AlwaysRunning / README.md
AdamBryan1995's picture
Update README.md
fa76837 verified
|
Raw History Blame Contribute Delete
12 kB

title: AlwaysRunning emoji: 👁 colorFrom: red colorTo: purple sdk: streamlit sdk_version: 1.32.0 app_file: app.py pinned: false license: creativeml-openrail-m ---from keras.models import Sequential from keras.layers import Dense

Create a sequential model - this is a linear stack of layers

model = Sequential()

Add an input layer to our model. In this case we will use a dense layer, which is a fully-connected neural layer. We have 10 inputs (features) and we want to use the ReLU activation function

model.add(Dense(10, activation='relu', input_shape=(10,)))

Add a hidden layer. This will also be a dense layer with 5 neurons and a ReLU activation

python dataset.py

Load the inputs and targets from separate files

X = np.load('inputs.npy') y = np.load('targets.npy')

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray() np.save('inputs.npy', X) np.save('targets.npy', y) python neural_network.py

import numpy as np from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import OneHotEncoder

Load the iris dataset

iris = load_iris() X = iris['data'] y = iris['target']

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray()

Split the data into training and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Define the model architecture

model = Sequential() model.add(Dense(64, activation='relu', input_dim=X_train.shape[1])) model.add(Dense(64, activation='relu')) model.add(Dense(y_train.shape[1], activation='softmax'))

Compile the model with the adam optimizer and categorical cross entropy loss

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Perform grid search to find the optimal hyperparameters

from sklearn.model_selection import GridSearchCV param_grid = {'batch_size': [10, 20, 30], 'epochs': [10, 20]} grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid_result = grid.fit(X_train, y_train)

Extract the best hyperparameters

best_batch_size = grid_result.best_params_['batch_size'] best_epochs = grid_result.best_params_['epochs']

Retrain the model using the best hyperparameters found

model.fit(X_train, y_train, batch_size=best_batch_size, epochs=best_epochs, verbose=1, validation_data=(X_test, y_test))

Evaluate the model on the test set

scores = model.evaluate(X_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])

Generate a classification report

y_pred = model.predict_classes(X_test) print(classification_report(np.argmax(y_test, axis=1), y_pred))

np.save('inputs.npy', X) np.save('targets.npy', y)

Load the inputs and targets from separate files

X = np.load('inputs.npy') y = np.load('targets.npy')

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray(

python simulation.py Train on 120 samples, validate on 30 samples Epoch 1/10 120/120 [==============================] - 0s 798us/step - loss: 1.1511 - accuracy: 0.3667 - val_loss: 1.1095 - val_accuracy: 0.3667 Epoch 2/10 120/120 [==============================] - 0s 53us/step - loss: 1.0961 - accuracy: 0.4833 - val_loss: 1.0573 - val_accuracy: 0.5333 ... Epoch 9/10 120/120 [==============================] - 0s 53us/step - loss: 0.7153 - accuracy: 0.8500 - val_loss: 0.7523 - val_accuracy: 0.8000 Epoch 10/10 120/120 [==============================] - 0s 53us/step - loss: 0.6701 - accuracy: 0.8833 - val_loss: 0.7155 - val_accuracy: 0.8333 Test loss: 0.715541832447052 Test accuracy: 0.8333333333333334 precision recall f1-score support 0 0.83 1.00 0.91 9 1 0.80 0.75 0.78 11 2 0.86 0.75 0.80 9 micro avg 0.83 0.83 0.83 29 macro avg 0.83 0.83 0.83 29 weighted avg 0.83 0.83 0.83 29

<keras.callbacks.History at 0x1a2b3c4d5e>

import numpy as np from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import OneHotEncoder

Load the iris dataset

iris = load_iris() X = iris['data'] y = iris['target']

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray()

Split the data into training and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Define the model architecture

model = Sequential() model.add(Dense(64, activation='relu', input_dim=X_train.shape[1])) model.add(Dense(64, activation='relu')) model.add(Dense(y_train.shape[1], activation='softmax'))

Compile the model with the adam optimizer and categorical cross entropy loss

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Perform grid search to find the optimal hyperparameters

from sklearn.model_selection import GridSearchCV param_grid = {'batch_size': [10, 20, 30], 'epochs': [10, 20]} grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid_result = grid.fit(X_train, y_train)

Extract the best hyperparameters

best_batch_size = grid_result.best_params_['batch_size'] best_epochs = grid_result.best_params_['epochs']

Retrain the model using the best hyperparameters found

model.fit(X_train, y_train, batch_size=best_batch_size, epochs=best_epochs, verbose=1, validation_data=(X_test, y_test))

Evaluate the model on the test set

scores = model.evaluate(X_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])

Generate a classification report

y_pred = model.predict_classes(X_test) print(classification_report(np.argmax(y_test, axis=1), y_pred)) from keras.models import Sequential from keras.layers import Dense

Create a sequential model - this is a linear stack of layers

model = Sequential()

Add an input layer to our model. In this case we will use a dense layer, which is a fully-connected neural layer. We have 10 inputs (features) and we want to use the ReLU activation function

model.add(Dense(10, activation='relu', input_shape=(10,))) import numpy as np from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import OneHotEncoder

Load the iris dataset

iris = load_iris() X = iris['data'] y = iris['target']

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray()

Split the data into training and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Define the model architecture

model = Sequential() model.add(Dense(64, activation='relu', input_dim=X_train.shape[1])) model.add(Dense(64, activation='relu')) model.add(Dense(y_train.shape[1], activation='softmax'))

Compile the model with the adam optimizer and categorical cross entropy loss

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Perform grid search to find the optimal hyperparameters

from sklearn.model_selection import GridSearchCV param_grid = {'batch_size': [10, 20, 30], 'epochs': [10, 20]} grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid_result = grid.fit(X_train, y_train)

Extract the best hyperparameters

best_batch_size = grid_result.best_params_['batch_size'] best_epochs = grid_result.best_params_['epochs']

Retrain the model using the best hyperparameters found

model.fit(X_train, y_train, batch_size=best_batch_size, epochs=best_epochs, verbose=1, validation_data=(X_test, y_test))

Evaluate the model on the test set

scores = model.evaluate(X_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])

Generate a classification report

y_pred = model.predict_classes(X_test) print(classification_report(np.argmax(y_test, axis=1), y_pred)) pi3

import numpy as np from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import OneHotEncoder

Load the iris dataset

iris = load_iris() X = iris['data'] y = iris['target']

Convert categorical labels to one-hot encoding

enc = OneHotEncoder() y = enc.fit_transform(y[:,np.newaxis]).toarray()

Split the data into training and test sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Define the model architecture

model = Sequential() model.add(Dense(64, activation='relu', input_dim=X_train.shape[1])) model.add(Dense(64, activation='relu')) model.add(Dense(y_train.shape[1], activation='softmax'))

Compile the model with the adam optimizer and categorical cross entropy loss

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Perform grid search to find the optimal hyperparameters

from sklearn.model_selection import GridSearchCV param_grid = {'batch_size': [10, 20, 30], 'epochs': [10, 20]} grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid_result = grid.fit(X_train, y_train)

Extract the best hyperparameters

best_batch_size = grid_result.best_params_['batch_size'] best_epochs = grid_result.best_params_['epochs']

Retrain the model using the best hyperparameters found

model.fit(X_train, y_train, batch_size=best_batch_size, epochs=best_epochs, verbose=1, validation_data=(X_test, y_test))

Evaluate the model on the test set

scores = model.evaluate(X_test, y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1])

Generate a classification report

y_pred = model.predict_classes(X_test) print(classification_report(np.argmax(y_test, axis=1), y_pred))

Define the model architecture

model = Sequential() model.add(Dense(64, activation='relu', input_dim=input_dim)) model.add(Dense(64, activation='relu')) model.add(Dense(output_dim, activation='softmax'))

Specify the ranges for the hyperparameters to explore

batch_sizes = [10, 20, 30, 40, 50] learning_rates = [0.001, 0.01, 0.1] regularizations = [0.0, 0.001, 0.01]

Use GridSearchCV to find the optimal hyperparameters

from sklearn.model_selection import GridSearchCV param_grid = dict(batch_size=batch_sizes, learning_rate=learning_rates, regularization=regularizations) grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=3) grid_result = grid.fit(X_train, y_train)

Print the best hyperparameters and corresponding score

print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))

Import necessary modules from Keras

from keras.models import Sequential from keras.layers import Dense

Create a sequential model

model = Sequential()

Add an input layer with 10 neurons and the ReLU activation function

model.add(Dense(10, activation='relu', input_shape=(10,)))

Add a hidden layer with 5 neurons and the ReLU activation function

model.add(Dense(5, activation='relu'))

Add an output layer with 1 neuron and the sigmoid activation function

model.add(Dense(1, activation='sigmoid'))

Compile the model by specifying the loss function and optimizer

model.compile(loss='binary_crossentropy', optimizer='adam')

Train the model using the fit method

Pass the training data (X_train, y_train), specify the number of epochs (10), and the batch size (32)

model.fit(X_train, y_train, epochs=10, batch_size=32)