TensorFlow训练代码
TensorFlow是一个广泛使用的深度学习框架,以下是一个简单的TensorFlow训练代码示例:
import tensorflow as tf
# 定义输入和输出
x = tf.placeholder(tf.float32, shape=[None, input_size])
y_ = tf.placeholder(tf.float32, shape=[None, num_classes])
# 定义模型
W = tf.Variable(tf.zeros([input_size, num_classes]))
b = tf.Variable(tf.zeros([num_classes]))
y = tf.matmul(x, W) + b
# 定义损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# 定义优化器
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
# 定义准确率计算节点
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 开始训练
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(num_steps):
batch = mnist.train.next_batch(batch_size)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1]})
print('Step %d, training accuracy %g' % (i, train_accuracy))
print('Test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
此代码使用了TensorFlow的Placeholder和Variable来定义输入、输出和模型参数。使用了softmax交叉熵作为损失函数,使用梯度下降优化器进行模型训练。在训练过程中,通过计算正确率来评估模型性能。最后,使用测试集评估模型的准确率。
原文地址: https://www.cveoy.top/t/topic/yvA 著作权归作者所有。请勿转载和采集!