东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

[TensorFlow2.0] 03、tf-keras与keras的相同和不同及实战案例

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
跳转到指定楼层
楼主
发表于 2019-10-28 19:28:54 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方耀 微信:dfy_88888'
  3. __date__ = '2019/10/28 下午3:37'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'tf_keras_classify_model'

  6. import os
  7. import sys
  8. import time
  9. import tensorflow as tf
  10. import matplotlib as mpl
  11. import matplotlib.pyplot as plt
  12. import numpy as np
  13. import pandas as pd
  14. import sklearn

  15. from tensorflow import keras
  16. # tf的keras 和 单独的keras
  17. # pip3 install keras
  18. import keras

  19. print(tf.__version__)
  20. print(sys.version_info)
  21. for module in mpl, np, pd, sklearn, tf, keras:
  22.     print(module.__name__, module.__version__)

  23. # https://tensorflow.google.cn/api_docs/python/tf/keras/datasets/fashion_mnist/load_data
  24. fashion_mnist = keras.datasets.fashion_mnist
  25. (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
  26. print(X_train.shape, y_train.shape)
  27. print('测试数据集:', X_test.shape, y_test.shape)
  28. X_valid, X_train = X_train[:5000], X_train[5000:]
  29. y_valid, y_train = y_train[:5000], y_train[5000:]
  30. print('验证数据集:', X_valid.shape, y_valid.shape)
  31. print('训练数据集:', X_train.shape, y_train.shape)


  32. def show_single_image(img_arr):
  33.     plt.imshow(img_arr, cmap='binary')
  34.     plt.show()

  35. # show_single_image(X_train[11])


  36. def show_multi_images(n_rows, n_cols, X_data, y_data, class_names):
  37.     assert len(X_data) == len(y_data), '样本的特征与标签长度一致'
  38.     assert n_rows*n_cols <= len(X_data)
  39.     # 使用plt的子图 width, height in inches
  40.     plt.figure(figsize=(n_cols*1.4, n_rows*1.6))
  41.     for i in range(n_rows):
  42.         for j in range(n_cols):
  43.             index = i*n_cols + j
  44.             plt.subplot(n_rows, n_cols, index+1)
  45.             plt.imshow(X_data[index], cmap='binary', interpolation='nearest')
  46.             plt.axis('off')
  47.             plt.title(label=class_names[y_data[index]])
  48.     plt.show()


  49. class_names = ['t-shirt', 'trouser', 'pullover', 'dress',
  50.                'coat', 'sandal', 'shirt', 'sneaker',
  51.                'bag', 'ankle boot']
  52. # show_multi_images(3, 5, X_train[:20], y_train[:20], class_names)

  53. # tf.keras.Sequential 构建模型结构
  54. # model = keras.Sequential(name='tf2.0_model')
  55. # model.add(keras.layers.Flatten(input_shape=(28, 28)))
  56. # model.add(keras.layers.Dense(units=300, activation='relu'))
  57. # model.add(keras.layers.Dense(units=100, activation='relu'))
  58. # model.add(keras.layers.Dense(10, activation='softmax'))

  59. model = keras.Sequential(layers=[
  60.     keras.layers.Flatten(input_shape=(28, 28)),
  61.     keras.layers.Dense(units=300, activation='relu'),
  62.     keras.layers.Dense(units=100, activation='relu'),
  63.     keras.layers.Dense(10, activation='softmax')
  64. ], name='tf2.0_model_2')

  65. model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001),
  66.               loss='sparse_categorical_crossentropy',
  67.               metrics=['accuracy', 'mse'])
  68. model.summary()
  69. # print(tf.test.is_gpu_available())

  70. # 开始训练
  71. # validation_freq 是根据epochs来的 每隔多少轮进行验证
  72. history = model.fit(x=X_train, y=y_train, epochs=10, verbose=1,
  73.                     validation_data=(X_valid, y_valid), validation_freq=1)
  74. print(type(history))
  75. # 模型训练过程中的历史数据指标
  76. print(history.history)
  77. # validation_freq=2 的情况:
  78. # {'loss': [2.276887303126942, 0.5237461835861206, 0.45976711897850037, 0.4327715507962487],
  79. # 'accuracy': [0.75996363, 0.8186182, 0.8376727, 0.8458727],
  80. # 'mse': [27.68526, 27.679394, 27.680891, 27.681673],
  81. # 'val_loss': [0.5112990405797958, 0.45343393814563754],
  82. # 'val_accuracy': [0.823199987411499, 0.843999981880188],
  83. # 'val_mse': [27.655563354492188, 27.657318115234375]}


  84. def plot_learning_curve(history):
  85.     # ValueError: arrays must all be same length
  86.     # 表格型数据 要求每一列的len一致 这里即:history.history字典里每个key对应的value长度一致
  87.     df_history = pd.DataFrame(data=history.history)
  88.     print(df_history)
  89.     print(df_history.index)
  90.     print(df_history.columns)
  91.     print(df_history.dtypes)
  92.     df_history.plot(figsize=(8, 5))
  93.     plt.grid(True)
  94.     # x就是DataFrame的索引
  95.     plt.ylim(0, 1.3)
  96.     plt.show()


  97. plot_learning_curve(history)



复制代码



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

01.png (226.43 KB, 下载次数: 81)

01.png

02.png (313.73 KB, 下载次数: 85)

02.png

03.png (199.38 KB, 下载次数: 82)

03.png

04.png (223.92 KB, 下载次数: 88)

04.png

05.png (255.58 KB, 下载次数: 84)

05.png

06.png (259.61 KB, 下载次数: 84)

06.png

07.png (119.84 KB, 下载次数: 89)

07.png

08.png (92.93 KB, 下载次数: 86)

08.png

屏幕截图.png (33.01 KB, 下载次数: 85)

屏幕截图.png

01.png (218.32 KB, 下载次数: 89)

01.png

02.png (112.03 KB, 下载次数: 86)

02.png

03.png (257.55 KB, 下载次数: 86)

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

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
沙发
 楼主| 发表于 2019-10-28 20:01:18 | 只看该作者
  1. from sklearn.preprocessing import StandardScaler, MinMaxScaler
  2. # 数据的归一化处理
  3. std_scaler = StandardScaler()
  4. # print('训练数据集0:', X_train[0])
  5. X_train_std = std_scaler.fit_transform(X_train.reshape(-1, 28*28))
  6. X_train_std = X_train_std.reshape(-1, 28, 28)
  7. print(X_train_std.shape)
  8. X_valid_std = std_scaler.transform(X_valid.reshape(-1, 28*28))
  9. X_valid_std = X_valid_std.reshape(-1, 28, 28)
  10. print(X_valid_std.shape)
  11. X_test_std = std_scaler.transform(X_test.reshape(-1, 28*28))
  12. X_test_std = X_test_std.reshape(-1, 28, 28)
复制代码
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
板凳
 楼主| 发表于 2019-10-28 20:08:20 | 只看该作者
  1. # 测试模型
  2. test_loss, test_accuracy, test_mse = model.evaluate(X_test_std, y_test)
  3. print(test_loss, test_accuracy, test_mse)
  4. y_test_predict = model.predict(X_test_std, verbose=1)
  5. print(y_test_predict.shape)
  6. print(y_test_predict[:2])
复制代码
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
地板
 楼主| 发表于 2019-10-28 20:36:36 | 只看该作者
  1. # Callbacks: utilities called at certain points during model training.
  2. # 实战回调函数
  3. logdir = './callbacks'
  4. if not os.path.exists(logdir):
  5.     os.mkdir(logdir)
  6. output_model_file = os.path.join(logdir, 'fashion_mnist_model.h5')
  7. callbacks = [
  8.     keras.callbacks.TensorBoard(logdir),
  9.     keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5),
  10.     keras.callbacks.ModelCheckpoint(output_model_file, save_best_only=True)
  11. ]
  12. history = model.fit(x=X_train_std, y=y_train, epochs=10, verbose=1,
  13.                     validation_data=(X_valid_std, y_valid), validation_freq=1, callbacks=callbacks)
  14. print(type(history))
  15. # 模型训练过程中的历史数据指标
  16. print(history.history)
复制代码
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
5#
 楼主| 发表于 2019-10-28 22:12:01 | 只看该作者
自带归一化功能的激活函数activation='selu'  Scaled Exponential Linear Unit (SELU)

model.add(keras.layers.Dropout(rate=0.5))
model.add(keras.layers.AlphaDropout(rate=0.5)) 更强大:1、均值和方差不变 2、归一化的性质不变
model.add(keras.layers.GaussianDropout(rate=0.5))
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-5 16:27 , Processed in 0.192875 second(s), 22 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

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