神经网络代码
时间: 2023-07-08 14:15:59 浏览: 98
神经网络的代码通常使用深度学习框架来实现,比如TensorFlow、PyTorch、Keras等。以下是一个使用TensorFlow实现的简单的全连接神经网络的代码示例:
```python
import tensorflow as tf
# 定义神经网络结构
n_inputs = 28*28 # MNIST图像像素点数
n_hidden1 = 300
n_hidden2 = 100
n_outputs = 10 # 10个数字分类
# 定义输入输出占位符
X = tf.placeholder(tf.float32, shape=(None, n_inputs), name="X")
y = tf.placeholder(tf.int64, shape=(None), name="y")
# 定义神经网络层
with tf.name_scope("dnn"):
hidden1 = tf.layers.dense(X, n_hidden1, name="hidden1",
activation=tf.nn.relu)
hidden2 = tf.layers.dense(hidden1, n_hidden2, name="hidden2",
activation=tf.nn.relu)
logits = tf.layers.dense(hidden2, n_outputs, name="outputs")
# 定义损失函数和优化器
with tf.name_scope("loss"):
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)
loss = tf.reduce_mean(xentropy, name="loss")
with tf.name_scope("train"):
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
training_op = optimizer.minimize(loss)
# 定义评估指标
with tf.name_scope("eval"):
correct = tf.nn.in_top_k(logits, y, 1)
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
# 训练模型
n_epochs = 40
batch_size = 50
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(n_epochs):
for iteration in range(mnist.train.num_examples // batch_size):
X_batch, y_batch = mnist.train.next_batch(batch_size)
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})
acc_test = accuracy.eval(feed_dict={X: mnist.test.images, y: mnist.test.labels})
print(epoch, "Train accuracy:", acc_train, "Test accuracy:", acc_test)
```
以上代码实现了一个有两个隐藏层的全连接神经网络,用于对MNIST手写数字进行分类。代码中使用了TensorFlow提供的高层API,如`tf.layers.dense`实现了全连接层的定义,`tf.train.GradientDescentOptimizer`实现了梯度下降优化器的定义等。
阅读全文