请用python写一个神经网络
时间: 2023-03-16 21:44:27 浏览: 57
很高兴为您服务!Python中的神经网络可以使用TensorFlow或Keras库来实现。下面是一个简单的神经网络示例: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]))
pred = tf.nn.softmax(tf.matmul(x, W) + b)# 定义损失函数和优化器
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(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(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# 遍历所有的batch
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# 运行优化器
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
y: batch_ys})
# 计算平均损失
avg_cost += c / total_batch
# 显示训练中的详细信息
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) print("Optimization Finished!") # 测试模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# 计算准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))