tensorboard2.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import tensorflow as tf
  2. import numpy as np
  3. import os
  4. #这个脚本回到drive的利用率特别高,超出100%
  5. """
  6. def load_mnist(path):
  7. #加载本地下载好的mnist数据集
  8. f = np.load(path)
  9. x_train, y_train = f['x_train'], f['y_train']
  10. x_test, y_test = f['x_test'], f['y_test']
  11. f.close()
  12. return (x_train, y_train), (x_test, y_test)
  13. (x_train, y_train), (x_test, y_test) = load_mnist("mnist.npz")
  14. """
  15. mnist = tf.keras.datasets.mnist#从xx网站下载mnist到.kera,如果已经有了直接使用
  16. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  17. x_train, x_test = x_train / 255.0, x_test / 255.0 # 将样本从整数转换为浮点数
  18. # 利用tf.keras.Sequential容器封装网络层,前一层网络的输出默认作为下一层的输入
  19. model = tf.keras.models.Sequential([
  20. tf.keras.layers.Flatten(input_shape=(28, 28)),
  21. tf.keras.layers.Dense(128, activation='relu'), # 创建一层网络,设置输出节点数为128,激活函数类型为Relu
  22. tf.keras.layers.Dropout(0.2), # 在训练中每次更新时, 将输入单元的按比率随机设置为 0, 这有助于防止过拟合
  23. tf.keras.layers.Dense(10, activation='softmax')]) # Dense层就是所谓的全连接神经网络层
  24. model.summary()#显示模型的结构
  25. # 为训练选择优化器和损失函数:
  26. model.compile(optimizer='adam',
  27. loss='sparse_categorical_crossentropy',
  28. metrics=['accuracy'])
  29. if 'CLOUD_PROVIDER' in os.environ and os.environ['CLOUD_PROVIDER'] == 'Agit':
  30. log_dir = os.path.join('/root/.agit/logs') # this is the storage path in the Agit environment
  31. else:
  32. log_dir = os.path.join("logs") # this is the path when the program runs in other environments
  33. #log_dir = os.path.join("logs")
  34. # print(log_dir)
  35. if not os.path.exists(log_dir):
  36. os.mkdir(log_dir)
  37. # 定义TensorBoard对象.histogram_freq 如果设置为0,则不会计算直方图。
  38. tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
  39. # TensorBoard对象作为回调传给model.fit方法
  40. model.fit(x_train, y_train, epochs=8, validation_data=(x_test, y_test), callbacks=[tensorboard_callback])
  41. model.save_weights(log_dir + '/weight/my_weights', save_format='tf') # 保存模型*****直接引用对应的路径参数