tensorflow2全连接网络的扩展功能

tensorflow笔记系列文章均参考自中国大学Mooc上北京大学软件与微电子学院曹建老师的《Tensorflow笔记2》课程。曹建老师讲的非常棒,受益良多,强烈建议tensorflow初学者学习。

自制数据集

一般来说,tensorflowkeras框架中datasets模块提供的数据集足够我们玩了,但有时我们也需要使用已有数据来制作自己的数据集。下面提供一个generated函数来实现自制数据集的生成,代替load_data()

"""
    :parameter
        - path: 数据文件路径
        - txt: 数据文件的文本描述,通常由两列组成,第一列表示文件名(和文件路径组合可以得到完整路径),
                第二列为这一数据对应的标签值
    :returns
        - x: 特征值
        - y_: 标签值
"""
def generateds(path, txt):
    f = open(txt, 'r')
    contents = f.readlines()  # 按行读取
    f.close()
    x, y_ = [], []
    for content in contents:
        value = content.split()  # 以空格分开,存入数组
        img_path = path + value[0]
        img = Image.open(img_path)
        img = np.array(img.convert('L'))  # 转换为灰度图
        img = img / 255.  # 归一化数值
        x.append(img)
        y_.append(value[1])
        print('loading : ' + content)
​
    x = np.array(x)
    y_ = np.array(y_)
    y_ = y_.astype(np.int64)
    return x, y_

数据增强

数据增强可以帮助我们增大数据量,tensorflow提供了数据增强方法ImageDataGenerator(),使用方法如下:

image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(
        rescale=所有数据将乘以该数值,
        rotation_range=随机旋转角度数范围,
        width_shift_range=随机宽度偏移量,
        height_shift_range=随机高度偏移量,
        水平翻转: horizontal_flip=是否随机水平翻转.
        随机缩放: zoom_range=随机缩放的范围[1-n,1+n])
image_gen_train.fit(x_train)

下面给出一个具体实例:

image_gen_train = ImageDataGenerator(
    rescale=1./1.,  # 如为图像,分母为255时,可归至0-1
    rotation_range=45,  # 随机45度旋转
    width_shift_range=.15,  # 宽度偏移
    height_shift_range=.15,  # 高度偏移
    horizontal_flip=False,  # 水平翻转
    zoom_range=0.5  #将图像随机随访阈量)
image_gen_train.fit(x_train)

需要注意的是这里的x_train需要是一个四维数据,因此需要对数据进行reshape(),同时model.fit()也需要变为

model.fit(image_gen_train.flow(x_train,y_train,batch_size=32),...)

断点续训

断点续训分为保存模型和读取模型

读取模型的操作可以使用model.load_weight()函数,一般操作如下:

checkpoint_save_path = "./checkpoint/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print("-----------load the model-----------")
    model.load_weights(checkpoint_save_path)

保存模型

cp_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=路径文件名,
save_weights_only=True/False,
save_best_only=True/False
)
history = model.fit(callbacks=[cp_callback])

 

参数提取

model.trainable_variables返回模型中可训练的参数

设置print输出格式:np.set_printoptions(threshold=超过多少省略显示),例如:

np.set_printoptions(threshold=np.inf)
print(model.trainable_variables)

model.trainable_variables里有各个参数name值,shape值和numpy()值,可以通过for循环遍历打印出来

acc/loss可视化

在前面的model.fit中除了训练模型,还同步记录了训练集loss,测试集val_loss,训练集准确率sparse_categorical_accuracy以及测试集准确率val_sparse_categorical_accuracy,我们在前面的代码中将其存在了histrory中,通过以下方式可以取得:

acc = histrory.histrory['sparse_categorical_accuracy']
val_acc = histrory.histrory['val_sparse_categorical_accuracy']
loss = histrory.histrory['loss']
val_loss = histrory.histrory['val_loss']

用以下代码可以实现画图,将数据可视化:

plt.subplot(1,2,1)
plt.plot(acc,label='训练集准确率')
plt.plot(val_acc,label='测试集准确率')
plt.title('训练集和测试集准确率')
plt.legend()

plt.subplot(1,2,2)
plt.plot(loss,label='训练集损失函数')
plt.plot(val_loss,label='测试集损失函数')
plt.title('训练集和测试集损失函数')
plt.legend()
plt.show()

前向传播实现应用

前向传播实现给图识物的应用通常需要三步:

  • 复现模型:model = tf.keras.models.Sequential([...])

  • 加载参数:model.load_weights(model_save_path)

  • 预测结果:result = model.predict(x_predict)

注意的是,根据训练的模型,要对给出的图片进行一定的修改:

img = Image.open(image_path)
img = img.resize((28,28), Image.ANTIALIAS)  # 将图片转换成28行28列的尺寸
img_arr = np.arry(img.convert('L'))  #  转换为灰度图

img_arr = 255 - imf_arr  # 颜色取反,这步根据输入图片和训练图片来决定是否需要
img_Arr = img_Arr / 255.0
x_predict = img_arr[tf.newaxis, ...]  # 由于训练时候是按照batch送入网络,因此要加一个维度,变为(1,28,28)
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
tf.print(pred)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值