写一个python深度学习代码
时间: 2023-03-08 10:17:20 浏览: 128
《Python深度学习》配套源代码
我可以为你写一段深度学习代码:import numpy as np
import tensorflow as tf# 定义输入和输出
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]))# 定义模型
y_pred = tf.nn.softmax(tf.matmul(X, W) + b)# 定义损失函数和优化器
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(y_pred), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cost)# 初始化变量
init = tf.global_variables_initializer()# 开始训练
with tf.Session() as sess:
sess.run(init)
# 迭代训练
for epoch in range(1000):
_, c = sess.run([optimizer, cost], feed_dict={X: data.train.images, y: data.train.labels})
if (epoch+1) % 100 == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c)) print("Optimization Finished!") # 计算准确率
correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print ("Accuracy:", accuracy.eval({X: data.test.images, y: data.test.labels}))
阅读全文