Spaces:
Sleeping
Sleeping
| 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() | |