Created
August 27, 2022 17:34
-
-
Save elowy01/bd3c50c9b88ee98537d60369207fb7bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import keras | |
import pdb | |
from keras.datasets import mnist | |
from keras.models import Sequential | |
from keras.layers import Dense, Dropout | |
from keras.optimizers import RMSprop | |
import numpy as np | |
# Load mnist data | |
(x_train, y_train), (x_test, y_test) = mnist.load_data() | |
# Process the data | |
x_train = x_train.reshape(60000, 784) # reshape the input from (28, 28) tuple to (784, ) | |
x_test = x_test.reshape(10000, 784) | |
x_train = x_train.astype('float32') | |
x_test = x_test.astype('float32') | |
x_train /= 255 | |
x_test /= 255 | |
y_train = keras.utils.to_categorical(y_train, 10) # is used to convert vector to binary matrix | |
y_test = keras.utils.to_categorical(y_test, 10) | |
# Create the model | |
model = Sequential() | |
model.add(Dense(512, activation = 'relu', input_shape = (784,))) | |
model.add(Dropout(0.2)) | |
model.add(Dense(512, activation = 'relu')) | |
model.add(Dropout(0.2)) | |
model.add(Dense(10, activation = 'softmax')) | |
# Compile the model | |
model.compile(loss = 'categorical_crossentropy', | |
optimizer = RMSprop(), | |
metrics = ['accuracy']) | |
# Train the model | |
history = model.fit( | |
x_train, y_train, | |
batch_size = 128, | |
epochs = 20, | |
verbose = 1, | |
validation_data = (x_test, y_test) | |
) | |
# evaluate the model | |
score = model.evaluate(x_test, y_test, verbose = 0) | |
# let's predict now | |
pred = model.predict(x_test) | |
pred = np.argmax(pred, axis = 1)[:5] | |
label = np.argmax(y_test,axis = 1)[:5] | |
print(pred) # outputs: [7 2 1 0 4] | |
print(label) # outputs: [7 2 1 0 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment