将数据集拿来
from tensorflow import keras
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(np.max(x_train), np.min(x_train))
#输出:255 0
原数据:最大值—255,最小值— 0
数据归一化:
x = (x - u) / std
u:平均值,std:方差 ——将数据变为,均值是零,方差是1的正态分布
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train_scaler = scaler.fit_transform(
x_train.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_valid_scaler = scaler.transform(
x_valid.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_test_scaler = scaler.transform(
x_test.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_train(图片)是三维数据[None,28,28],训练归一化,需要输入二位数据,用reshape转成[None,784],训练完成再转回三维数据。
reshape(-1,1)中的-1代表无意义
reshape(-1,1)代表将二维数组重整为一个一列的二维数组
reshape(1,-1)代表将二维数组重整为一个一行的二维数组
reshape(-1,n)代表将二维数组重整为n列的二维数组
reshape(n,-1)代表将二维数组重整为n行的二维数组
fit_transform,fit可以保留训练数据集上的均值和方差,并应用到测试集与验证集上。
print(np.max(x_train_scaler), np.min(x_train_scaler))
#输出 2.023144 -0.8105139
数据归一化完成
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"])
回调函数:
Keras.callbacks模块
Tensorboard:
创建文件夹记录模型数据,常用参数:
1、log_dir: 用来保存Tensorboard的日志文件等内容的位置
2、histogram_freq: 对于模型中各个层计算激活值和模型权重直方图的频率。
3、write_graph: 是否在 TensorBoard 中可视化图像。
4、write_grads: 是否在 TensorBoard 中可视化梯度值直方图。
5、batch_size: 用以直方图计算的传入神经元网络输入批的大小。
6、write_images: 是否在 TensorBoard中将模型权重以图片可视化。
7、update_freq: 常用的三个值为’batch’ 、 ‘epoch’ 或 整数。当使用 ‘batch’ 时,在每个 batch 之后将损失和评估值写入到 TensorBoard 中。 ‘epoch’ 类似。如果使用整数,会在每一定个样本之后将损失和评估值写入到 TensorBoard 中。
modelcheckpoint:
在每个epoch后保存模型到filepath,常用参数:
1、filepath: 保存模型的路径。
2、monitor: 被监测的数据。val_acc或val_loss。
3、verbose: 详细信息模式,0 或者1。0为不打印输出信息,1为打印。
4、save_best_only: 如果save_best_only=True,将只保存在验证集上性能最好的模型mode: {auto, min, max} 的其中之一。 如果save_best_only=True,那么是否覆盖保存文件的决定就取决于被监测数据的最大或者最小值。 对于val_acc,模式就会是max;而对于 val_loss,模式就需要是min。在auto模式中,方式会自动从被监测的数据的名字中判断出来。
5、save_weights_only: 如果 True,那么只有模型的权重会被保存 (model.save_weights(filepath)), 否则的话,整个模型会被保存 (model.save(filepath))。
6、period: 每个检查点之间的间隔(训练轮数)。
EarlyStopping:
loss函数不再下降的时候提前停止,常用参数:
1、monitor:关注指标的值,一般关注’acc’,’val_acc’,’loss’,’val_loss’等
2、min_delta:阈值,两次训练的差距小于阈值,训练提前停止
3、patience:连续训练几次差距都比阈值小,训练提前关闭
import os
logdir = "./callbacks" #创建文件夹callbacks
if not os.path.exists(logdir):
os.mkdir(logdir)
output_model_file = os.path.join(logdir,
"fashin_mnist_model.h5")#创建文件
callbacks = [
keras.callbacks.TensorBoard(logdir),
keras.callbacks.ModelCheckpoint(output_model_file,
save_best_only = True),
keras.callbacks.EarlyStopping(patience=5, min_delta=1e-3),
]
history = model.fit(x_train_scaler, y_train, epochs=100,
validation_data=(x_valid_scaler, y_valid),
callbacks = callbacks)
print(model.evaluate(x_test_scaler, y_test))
输出:[0.3211212158203125, 0.88919997215271]
损失函数和准确率
在Terminal上输入ls查询,tree查看文件夹
输入:tensorboard --logdir=callbacks
得到6006端口,在浏览器上http://localhost:6006/