实战分类模型之模型构建

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的方法,代码中用注释标记了两种建模方法,是等价的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值