Spaces:
Sleeping
Sleeping
File size: 1,604 Bytes
c37e02d | 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 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Load Fashion MNIST dataset (built-in)
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# Class names in the dataset
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Normalize pixel values to [0,1]
train_images = train_images / 255.0
test_images = test_images / 255.0
# Build a simple neural network model
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10)
])
# Compile the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the model
model.fit(train_images, train_labels, epochs=10)
# Evaluate on test data
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
# Save the model
model.save('fashion_mnist_model.h5')
# Optional: Test prediction and plot one image
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print("Predicted label for first test image:", class_names[np.argmax(predictions[0])])
import matplotlib.pyplot as plt
plt.figure()
plt.imshow(test_images[0], cmap=plt.cm.binary)
plt.title(class_names[test_labels[0]])
plt.show()
|