16-2-RNN-recognise-images-LSTM.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import tensorflow as tf
  2. from sklearn.model_selection import train_test_split
  3. def main():
  4. # 导入数据
  5. (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
  6. # 转onehot
  7. y_train_onehot = tf.keras.utils.to_categorical(y_train)
  8. y_test_onehot = tf.keras.utils.to_categorical(y_test)
  9. # 归一化
  10. x_train = x_train / 255.0
  11. x_test = x_test / 255.0
  12. # 顺序模型(层直接写在里面,省写add)
  13. model = tf.keras.Sequential([
  14. tf.keras.layers.Input(shape=(28, 28)), # 输入层 28 * 28的向量
  15. tf.keras.layers.LSTM(128, return_sequences=True),
  16. tf.keras.layers.LSTM(128),
  17. # tf.keras.layers.Dropout(0.5), # 丢弃50%,防止过拟合
  18. tf.keras.layers.Dense(10, activation="softmax"), # 输出层 有10个类,用 softmax 概率分布
  19. ])
  20. # 编译模型
  21. model.compile(
  22. optimizer="adam", # 优化器
  23. loss="categorical_crossentropy", # 损失函数
  24. metrics=["acc"], # 观察值, acc正确率
  25. )
  26. # 训练
  27. model.fit(
  28. x_train, y_train_onehot,
  29. batch_size=32, # 一次放入多少样本
  30. epochs=10,
  31. validation_data=(x_test, y_test_onehot),
  32. )
  33. # loss: 0.2157 - acc: 0.9183 - val_loss: 0.2799 - val_acc: 0.8984
  34. if __name__ == "__main__":
  35. main()