Keras 服饰图片分类2——数据归一化与回调函数

将数据集拿来

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/
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值