深度学习cnn算法代码
时间: 2023-09-10 12:07:20 浏览: 82
以下是一个简单的CNN算法实现的示例代码:
```python
import numpy as np
import tensorflow as tf
# 定义超参数
learning_rate = 0.001
training_epochs = 10
batch_size = 100
# 导入MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 定义占位符
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])
X_image = tf.reshape(X, [-1, 28, 28, 1])
# 定义卷积层
W1 = tf.Variable(tf.random_normal([5, 5, 1, 32]))
b1 = tf.Variable(tf.random_normal([32]))
conv1 = tf.nn.conv2d(X_image, W1, strides=[1, 1, 1, 1], padding='SAME')
conv1 = tf.nn.relu(conv1 + b1)
pool1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义第二个卷积层
W2 = tf.Variable(tf.random_normal([5, 5, 32, 64]))
b2 = tf.Variable(tf.random_normal([64]))
conv2 = tf.nn.conv2d(pool1, W2, strides=[1, 1, 1, 1], padding='SAME')
conv2 = tf.nn.relu(conv2 + b2)
pool2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义全连接层
W3 = tf.Variable(tf.random_normal([7*7*64, 1024]))
b3 = tf.Variable(tf.random_normal([1024]))
flat = tf.reshape(pool2, [-1, 7*7*64])
fc = tf.nn.relu(tf.matmul(flat, W3) + b3)
# 定义输出层
W4 = tf.Variable(tf.random_normal([1024, 10]))
b4 = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(fc, W4) + b4
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 初始化变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
total_batch = int(mnist.train.num_examples/batch_size)
# 训练模型
for epoch in range(training_epochs):
avg_cost = 0.
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
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# 测试模型
correct_prediction = tf.equal(tf.argmax(logits, 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}))
```
以上代码采用TensorFlow框架实现了一个简单的CNN算法,用于对MNIST手写数字进行分类。
阅读全文