110 lines
4.6 KiB
Python
110 lines
4.6 KiB
Python
#===============================================
|
||
# 训练简单的神经网络,并显示运行时间
|
||
# 数据集:mnnist
|
||
#===============================================
|
||
"""from __future__ import absolute_import
|
||
from __future__ import division
|
||
from __future__ import print_function
|
||
|
||
import datetime
|
||
starttime = datetime.datetime.now()
|
||
|
||
import tensorflow as tf
|
||
import numpy as np
|
||
|
||
# Import data
|
||
from tensorflow.examples.tutorials.mnist import input_data
|
||
flags = tf.app.flags
|
||
FLAGS = flags.FLAGS
|
||
flags.DEFINE_string('data_dir', '/learn/tensorflow/python/data/', 'Directory for storing data') # 把数据放在/data文件夹中
|
||
mnist_data = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) # 读取数据集
|
||
|
||
# 建立抽象模型
|
||
x = tf.placeholder(tf.float32, [None, 784]) # 占位符
|
||
y = tf.placeholder(tf.float32, [None, 10])
|
||
W = tf.Variable(tf.zeros([784, 10]))
|
||
b = tf.Variable(tf.zeros([10]))
|
||
a = tf.nn.softmax(tf.matmul(x, W) + b)
|
||
|
||
# 定义损失函数和训练方法
|
||
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1])) # 损失函数为交叉熵,学习速率要设为0.3量级
|
||
#cross_entropy = -tf.reduce_sum(y * tf.log(a)) # 损失函数为交叉熵
|
||
optimizer = tf.train.GradientDescentOptimizer(0.3) # 梯度下降法,学习速率要设为0.001量级
|
||
train_next = optimizer.minimize(cross_entropy) # 训练目标:最小化损失函数
|
||
|
||
# Train
|
||
sess = tf.InteractiveSession() # 建立交互式会话
|
||
# tf.global_variables_initializer().run()
|
||
sess.run(tf.global_variables_initializer())
|
||
for i in range(1000):
|
||
batch_xs, batch_ys = mnist_data.train.next_batch(100) # 随机抓取100个数据
|
||
# train_next.run({x: batch_xs, y: batch_ys})
|
||
sess.run(train_next, feed_dict={x: batch_xs, y: batch_ys})
|
||
|
||
#测试
|
||
correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1))
|
||
# tf.cast先将数据转换成float,防止求平均不准确:比如 tf.float32就是正确,写成tf.float16导致不准确,超出范围。
|
||
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)"""
|
||
|
||
"""由于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)
|