东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 8899|回复: 2
打印 上一主题 下一主题

[课堂笔记] 02、数据集与模型train代码(基于Keras)实现

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
跳转到指定楼层
楼主
发表于 2019-11-6 20:22:58 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

02、数据集与模型train代码(基于Keras)实现


使用数据集:mnist


  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方耀 微信:dfy_88888'
  3. __date__ = '2019/11/6 14:30'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'train_model'
  6. from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, ZeroPadding2D
  7. from keras.models import Model
  8. from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
  9. # from keras.datasets import mnist
  10. import numpy as np
  11. import pandas as pd
  12. import matplotlib.pyplot as plt
  13. from tensorflow.examples.tutorials.mnist import input_data


  14. # (x_train, y_train), (x_test, y_test) = mnist.load_data()
  15. mnist = input_data.read_data_sets(train_dir='mnist_data', one_hot=False)
  16. # (55000, 784) 已经归一化到0-1之间了 dtype=float32
  17. x_train = mnist.train.images
  18. # (10000, 784) 已经归一化到0-1之间了 dtype=float32
  19. x_test = mnist.test.images

  20. # 归一化 (0, 1)  MinMaxScaler
  21. # x_train = x_train.astype('float32') / 255.
  22. # x_test = x_test.astype('float32') / 255.

  23. x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
  24. x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))


  25. noise_factor = 0.5
  26. x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
  27. x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
  28. # 加了噪音后 不要越界
  29. x_train_noisy = np.clip(x_train_noisy, 0., 1.)
  30. x_test_noisy = np.clip(x_test_noisy, 0., 1.)


  31. def plot_learning_curve(history):
  32.     # ValueError: arrays must all be same length
  33.     # 表格型数据 要求每一列的len一致 这里即:history.history字典里每个key对应的value长度一致
  34.     df_history = pd.DataFrame(data=history.history)
  35.     print(df_history)
  36.     # print(df_history.index)
  37.     print(df_history.columns)
  38.     # print(df_history.dtypes)
  39.     df_history.plot(figsize=(8, 5))
  40.     plt.grid(True)
  41.     # x就是DataFrame的索引
  42.     plt.ylim(0, 0.5)
  43.     plt.show()


  44. def train_model():
  45.     input_img = Input(shape=(28, 28, 1))
  46.     x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
  47.     x = MaxPooling2D((2, 2), padding='same')(x)
  48.     x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  49.     x = MaxPooling2D((2, 2), padding='same')(x)
  50.     x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  51.     encoded = MaxPooling2D((2, 2), padding='same', name='encoder')(x)

  52.     # at this point the representation is (4, 4, 8) i.e. 128-dimensional 特征向量

  53.     x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
  54.     x = UpSampling2D((2, 2))(x)
  55.     x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  56.     x = UpSampling2D((2, 2))(x)
  57.     x = Conv2D(16, (3, 3), activation='relu', padding='valid')(x)
  58.     x = UpSampling2D((2, 2))(x)
  59.     # 这里激活为何用sigmoid? 0-1之间的  自身也是0-1之间的
  60.     decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

  61.     autoencoder = Model(inputs=input_img, outputs=decoded)
  62.     autoencoder.summary()
  63.     # 损失函数为何用binary_crossentropy?  图片之间的相似度越小越好?
  64.     # binary_crossentropy 与  category_crossentropy 有何区别?
  65.     autoencoder.compile(optimizer='adam', loss='binary_crossentropy', metrics=['mse', 'mae'])

  66.     cb_tensorboard = TensorBoard(log_dir='./train_log')
  67.     cb_earlystop = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5)
  68.     cb_save_best_model = ModelCheckpoint(filepath='./autoencoder_dfy.h5', monitor='val_loss', save_best_only=True)
  69.     callbacks = [cb_tensorboard, cb_earlystop, cb_save_best_model]
  70.     # 注意:X = x_train_noisy Y = x_train  就是无监督学习了 只是自动加了噪音数据noise
  71.     # 5.5w =  55 000    1w = 1000 * 10
  72.     # ValueError: If steps_per_epoch is set, the `batch_size` must be None.
  73.     history = autoencoder.fit(x_train_noisy, x_train,
  74.                     epochs=55,
  75.                     batch_size=256,
  76.                     # steps_per_epoch=55,
  77.                     shuffle=True,
  78.                     validation_data=(x_test_noisy, x_test),
  79.                     # validation_steps=10,
  80.                     validation_freq=1,
  81.                     callbacks=callbacks)
  82.     # list all data in history
  83.     print(history.history.keys())
  84.     fig, ax_array = plt.subplots(1, 2)
  85.     ax1, ax2 = ax_array

  86.     ax1.set_title('model mse')
  87.     ax1.plot(history.history['mse'])
  88.     ax1.plot(history.history['val_mse'])
  89.     ax1.set_xlabel('epoch')
  90.     ax1.set_ylabel('mse')
  91.     ax1.legend(['train', 'validation'], loc='upper left')

  92.     ax2.set_title('model loss')
  93.     ax2.plot(history.history['loss'])
  94.     ax2.plot(history.history['val_loss'])
  95.     ax2.set_xlabel('epoch')
  96.     ax2.set_ylabel('loss')
  97.     ax2.legend(['train', 'validation'], loc='upper left')

  98.     plt.show()
  99.     plot_learning_curve(history)


  100. train_model()
复制代码




东方老师AI官网:http://www.ai111.vip
有任何问题可联系东方老师微信:dfy_88888
【微信二维码图片】

让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

0

主题

117

帖子

258

积分

中级会员

Rank: 3Rank: 3

积分
258
QQ
沙发
发表于 2020-2-3 15:54:09 | 只看该作者
谢谢老师提供的资料。
回复

使用道具 举报

0

主题

3

帖子

10

积分

新手上路

Rank: 1

积分
10
板凳
发表于 2020-4-20 22:47:54 | 只看该作者
提供这些很不容易
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-5-3 18:34 , Processed in 0.184710 second(s), 19 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表