File size: 12,034 Bytes
467d46f
 
 
 
 
 
 
 
 
 
fa76837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467d46f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
---
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)