Skip to content

Instantly share code, notes, and snippets.

@plusangel
Last active July 15, 2023 13:26
Show Gist options
  • Save plusangel/5249e4062c0b16c7996dbfa3a28edca7 to your computer and use it in GitHub Desktop.
Save plusangel/5249e4062c0b16c7996dbfa3a28edca7 to your computer and use it in GitHub Desktop.
fashion mnist neural network approach
# To load the mnist data
from keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
# importing various types of hidden layers
from tensorflow.keras.layers import Conv2D, MaxPooling2D,\
Dense, Flatten, Softmax
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
import numpy as np
# Split the data into training and testing
(trainX, trainy), (testX, testy) = fashion_mnist.load_data()
# Print the dimensions of the dataset
print('Train: X = ', trainX.shape)
print('Test: X = ', testX.shape)
for i in range(1, 10):
# Create a 3x3 grid and place the
# image in ith position of grid
plt.subplot(3, 3, i)
# Insert ith image with the color map 'grap'
plt.imshow(trainX[i], cmap=plt.get_cmap('gray'))
# Display the entire plot
plt.show()
trainX = trainX/255.0
testX = testX/255.0
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10)
])
model.compile(optimizer='adam',
loss=SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
es = EarlyStopping(monitor='val_accuracy',
mode='max',
patience=5,
restore_best_weights=True)
history = model.fit(trainX, trainy, epochs=100, validation_split=0.1, callbacks=[es])
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Val'], loc='upper left')
plt.show()
test_loss, test_acc = model.evaluate(testX, testy)
print('\nTest accuracy:', test_acc)
probability_model = Sequential([
model,
Softmax()
])
predictions = probability_model.predict(testX)
np.argmax(predictions[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment