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
| import matplotlib as mpl import matplotlib.pyplot as plt
import tensorflow as tf from tensorflow import keras
from sklearn.preprocessing import StandardScaler import numpy as np
fashion_mnist = keras.datasets.fashion_mnist (x_train_all, y_train_all), (x_test, y_test) = fashion_mnist.load_data()
x_valid, x_train = x_train_all[:5000], x_train_all[5000:] y_valid, y_train = y_train_all[:5000], y_train_all[5000:]
print(x_valid.shape, y_valid.shape) print(x_train.shape, y_train.shape) print(x_test.shape, y_test.shape)
scaler = StandardScaler() x_train_scaled = scaler.fit_transform( x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_valid_scaled = scaler.transform( x_valid.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_test_scaled = scaler.transform( x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28) print(np.max(x_train_scaled), np.min(x_train_scaled))
def show_single_image(img_arr): plt.imshow(img_arr, cmap="binary") plt.show()
show_single_image(x_train[0])
def show_imgs(n_rows, n_cols, x_data, y_data, class_names): plt.figure(figsize = (n_cols * 1.4, n_rows * 1.6)) for row in range(n_rows): for col in range(n_cols): index = n_cols * row + col plt.subplot(n_rows, n_cols, index + 1) plt.imshow(x_data[index], cmap = "binary", interpolation = "nearest") plt.axis('off') plt.title(class_names[y_data[index]]) plt.show() class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
show_imgs(3, 5, x_train, y_train, class_names)
model = keras.models.Sequential([ keras.layers.Flatten(input_shape = [28, 28]), keras.layers.Dense(300, activation = 'relu'), keras.layers.Dense(100, activation = 'relu'), keras.layers.Dense(10, activation = 'softmax') ])
model.compile(loss = 'sparse_categorical_crossentropy', optimizer = "sgd", metrics=["accuracy"])
model.summary()
history = model.fit(x_train, y_train, epochs = 10, validation_data = (x_valid, y_valid))
history.history import pandas as pd def plot_learning_curves(history): pd.DataFrame(history.history).plot(figsize=(8,5)) plt.grid(True) plt.gca().set_ylim(0, 5) plt.show()
plot_learning_curves(history)
|