print(x_train_all.shape, y_train_all.shape)
print(x_test.shape, y_test.shape)
#(60000, 28, 28) (60000,)
#(10000, 28, 28) (10000,)
#tf.keras.models.Sequential
"""
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"))
"""
#激活函数relu: y = max(0, x)
#激活函数softmax: 将向量变成概率分布:x = [x1, x2, x3],
# y = [e~x1/sum, e~x2/sum, e~x3/sum,], sum =e~x2+e~x1+e~x3
#将向量变成概率分布: e~x1/sum, e~x2/sum, e~x3/sum, 3个值均为0-1之间的数,且相加为1
#Flatten:展平,将28*28的二维矩阵展平成28*28的一维向量。
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]), #输入是28,28的二维矩阵展平成28*28的一维向量
keras.layers.Dense(300, activation='relu'),
keras.layers.Dense(100, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
#目的:将损失函数,优化方法,以及关心的其他metric加到图中,并且将图固化下来。
# loss中:reason for sparse: y->index. y->one_hot->[]
#if y 是一个向量,则用categorical_crossentropy
# else if y 是一个数,则用sparse_categorical_crossentropy
model.compile(loss="sparse_categorical_crossentropy",
optimizer= keras.optimizers.SGD(0.001),
metrics=["accuracy"])
#可以看到模型里有多少层
model.layers
#查看模型概况,参数情况
model.summary()
#参数量计算:[None样本数, 784] * W矩阵 + b偏置 -> [None, 300],则W.shape[784*300],b=[300]长度为300的向量
#epochs=10:训练集遍历10次
#每完成训练集上的一次遍历之后,就会在验证集上做一次验证。
history = model.fit(x_train, y_train, epochs = 10,
validation_data = (x_valid, y_valid))
#History是tensorflow的一个callback
#画图
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)
model.evaluate(x_test, y_test, verbose=0) #测试集验证
本文着眼于模型构建,采用keras.models.Sequential的方法,代码中用注释标记了两种建模方法,是等价的