<jupyter_start><jupyter_text><jupyter_code>#import the libraries
import numpy as np
import pandas as pd
#from numpy import mean
#from numpy import std
#from numpy import dstack
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Dropout
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix
from keras.layers import GRU
from keras.utils import to_categorical
#opening the zip-file
from zipfile import ZipFile
file_name1="UCI HAR Dataset.zip"
with ZipFile(file_name1,'r') as zip:
  zip.extractall()
  print("DONE_1")

#those are separate normalised input features for the neural network
SIGNALS = [
    "body_acc_x",
    "body_acc_y",
    "body_acc_z",
    "body_gyro_x",
    "body_gyro_y",
    "body_gyro_z",
    "total_acc_x",
    "total_acc_y",
    "total_acc_z"
]
# Output classes to learn how to classify
LABELS = [
    "WALKING",
    "WALKING_UPSTAIRS",
    "WALKING_DOWNSTAIRS",
    "SITTING",
    "STANDING",
    "LAYING"
]
# Utility function to read the data from csv file
def _read_csv(filename):
    return pd.read_csv(filename, delim_whitespace=True, header=None)

# Utility function to load the load_signals
def load_signals(subset):
    signals_data = []

    for signal in SIGNALS:
        filename = f'/content/UCI HAR Dataset/{subset}/Inertial Signals/{signal}_{subset}.txt'
        #/content/UCI HAR Dataset/train/Inertial Signals
        #/content/UCI HAR Dataset/train/Inertial Signals/body_acc_x_train.txt
        signals_data.append(
            _read_csv(filename).to_numpy()
        ) 

    # Transpose is used to change the dimensionality of the output,
    # aggregating the signals by combination of sample/timestep.
    # Resultant shape is (7352 train/2947 test samples, 128 timesteps, 9 signals)
    return np.transpose(signals_data, (1, 2, 0))
def load_y(subset):
    filename = f'/content/UCI HAR Dataset/{subset}/y_{subset}.txt'
    y = _read_csv(filename)[0]

    return pd.get_dummies(y).to_numpy()
def load_data():
    """
    Obtain the dataset from multiple files.
    Returns: X_train, X_test, y_train, y_test
    """
    X_train, X_test = load_signals('train'), load_signals('test')
    y_train, y_test = load_y('train'), load_y('test')

    return X_train, y_train, X_test,  y_test
# Importing tensorflow
np.random.seed(42)
import tensorflow as tf
tf.random.set_seed(42)
# Initializing parameters
epochs = 45
batch_size = 16
n_hidden = 32
# Utility function to count the number of classes
def _count_classes(y):
    return len(set([tuple(category) for category in y]))
# Loading the train and test data
X_train, Y_train, X_test,  Y_test = load_data()
timesteps = len(X_train[0])
input_dim = len(X_train[0][0])
n_classes = _count_classes(Y_train)
#n_classes be 6
print(timesteps)
print(input_dim)
print(len(X_train))
print(n_classes)
# Initiliazing the sequential model
model = Sequential()
# Configuring the parameters
model.add(GRU(n_hidden, input_shape=(timesteps, input_dim)))
# Adding a dropout layer
model.add(Dropout(0.5))
# Adding a dense output layer with sigmoid activation
model.add(Dense(n_classes, activation='softmax'))
model.summary()
 #Compiling the model
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# Training the model
model.fit(X_train,Y_train,
          batch_size=batch_size,
          validation_data=(X_test, Y_test),
          epochs=epochs,shuffle=True)

Y_pred = model.predict(X_test)
pred = np.argmax(Y_pred,axis = 1) 
Y_actual = np.argmax(Y_test,axis = 1)
confusion_matrix(Y_actual, pred)
print(classification_report(Y_actual, pred))<jupyter_output>precision    recall  f1-score   support

           0       0.94      0.97      0.95       496
           1       0.91      0.94      0.92       471
           2       0.98      0.98      0.98       420
           3       0.82      0.82      0.82       491
           4       0.84      0.83      0.84       532
           5       1.00      0.95      0.97       537

    accuracy                           0.91      2947
   macro avg       0.91      0.91      0.91      2947
weighted avg       0.91      0.91      0.91      2947
{'fraction_non_alphanumeric': 0.09462616822429906, 'fraction_numerical': 0.034813084112149534, 'mean_word_length': 3.077142857142857, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '309657', 'license': 'MIT', 'n_tokens_mistral': 1536, 'n_tokens_neox': 1438, 'n_words': 380, 'path': 'GRU_RNN.ipynb', 'repo_name': 'purnimapatel/Comparing-of-Deep_learning-Neural-Network', 'size': '4280'}