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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
| import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline
import numpy as np import sklearn
import pandas as pd import os,sys,time import tensorflow as tf
from tensorflow import keras
print(tf.__version__) print(sys.version_info)
for module in mpl,np,pd,sklearn,tf,keras: print(module.__name__,module.__version__)
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("====================训练集======================") print(x_train.shape,y_train.shape) print("====================验证集======================") print(x_valid.shape,y_valid.shape) print("====================测试集======================") print(x_test.shape,y_test.shape)
def show_single_image(img_array): plt.imshow(img_array,cmap="binary") plt.show()
show_single_image(x_train[0])
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
def show_all_images(n_rows,n_cols,x_data,y_data,class_names): assert len(x_data) == len(y_data) assert n_rows * n_cols < len(x_data) plt.figure(figsize = (n_rows*5,n_cols *1.2)) 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()
show_all_images(3,6,x_train,y_train,class_names)
""" # 模型添加层的第一种方法 model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) model.add(keras.layers.Dense(300, activation="relu")) model.add(keras.layers.Dense(100, activation="relu")) model.add(keras.layers.Dense(10, activation="softmax")) """
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.layers
model.summary()
history=model.fit(x_train,y_train, epochs = 10, validation_data=(x_valid,y_valid))
type(history)
history.history
def plot_learning_curves(history): pd.DataFrame(history.history).plot(figsize=(8,5)) plt.grid(True) plt.gca().set_ylim(0,1) plt.show()
plot_learning_curves(history)
|