对ANN_mnist.py进行了调试,把基于tensorflow1.0的代码改写为基于rensorflow2.0的格式,成功运行

This commit is contained in:
MuJ 2023-12-15 16:58:37 +08:00
parent a02e0184de
commit 28a33615e1
5 changed files with 60 additions and 2 deletions

View File

@ -2,7 +2,7 @@
# 训练简单的神经网络,并显示运行时间
# 数据集mnnist
#===============================================
from __future__ import absolute_import
"""from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
@ -48,4 +48,62 @@ accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
print(sess.run(accuracy,feed_dict={x:mnist_data.test.images,y:mnist_data.test.labels}))
endtime=datetime.datetime.now()
print('total time endtime-starttime:', endtime-starttime)
print('total time endtime-starttime:', endtime-starttime)"""
"""由于tensorflow更新至了2.0,1.0的方法许多已经被合并调整后弃用了,所以使用chatgpt更新了2.0版本的代码如下"""
# 导入 TensorFlow 和相关的 Keras 类和函数
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import SGD
import datetime
# 加载 MNIST 数据集,这是一个手写数字的图像数据集,用于训练和测试机器学习模型。
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 对数据进行归一化处理,将像素值从 [0, 255] 缩放到 [0, 1] 区间,这有助于模型的训练。
x_train, x_test = x_train / 255.0, x_test / 255.0
# 将图像数据从 28x28 的矩阵形式转换成 784 维的向量形式。
x_train = x_train.reshape(-1, 784)
x_test = x_test.reshape(-1, 784)
# 将标签转换为 one-hot 编码,这是将分类标签转换为仅在对应类的位置为 1其余为 0 的向量。
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 创建一个 Sequential 模型。这是一种线性堆叠的模型,您可以通过在列表中添加层来构建模型。
model = Sequential([
Dense(10, activation='softmax', input_shape=(784,))
])
# 编译模型。这一步设置了模型的优化器、损失函数和评估指标。
# - 使用 SGD随机梯度下降优化器。
# - 损失函数使用 categorical_crossentropy适用于多分类问题。
# - 评估指标使用准确率accuracy
model.compile(optimizer=SGD(lr=0.3),
loss='categorical_crossentropy',
metrics=['accuracy'])
# 记录训练开始时间。
starttime = datetime.datetime.now()
# 训练模型。这里使用 fit 方法对模型进行训练。
# - x_train 和 y_train 是训练数据和标签。
# - epochs=10 表示总共训练 10 个周期。
# - batch_size=100 指定每次梯度更新时使用的样本数量。
model.fit(x_train, y_train, epochs=10, batch_size=100)
# 记录训练结束时间。
endtime = datetime.datetime.now()
# 在测试集上评估模型性能。
# - x_test 和 y_test 是测试数据和标签。
# 这里返回的是模型在测试数据上的损失值和准确率。
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Accuracy: {accuracy}")
# 打印总的训练时间。
print('Total time (endtime - starttime):', endtime - starttime)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.