深度学习cnn算法代码
时间: 2023-09-10 20:05:38 浏览: 73
以下是一个简单的 CNN 算法的 Python 代码示例:
```python
import numpy as np
import tensorflow as tf
# 定义超参数
learning_rate = 0.001
training_epochs = 10
batch_size = 100
# 定义输入和输出的占位符
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
Y = tf.placeholder(tf.float32, [None, 10])
# 定义卷积层和池化层的函数
def conv2d(x, W, b, strides=1):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
# 定义卷积神经网络的模型
def conv_net(x, weights, biases):
# 第一层卷积层
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
# 第一层池化层
conv1 = maxpool2d(conv1, k=2)
# 第二层卷积层
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
# 第二层池化层
conv2 = maxpool2d(conv2, k=2)
# 全连接层
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# 输出层
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
# 定义权重和偏置项
weights = {
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
'out': tf.Variable(tf.random_normal([1024, 10]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bd1': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([10]))
}
# 构建模型、损失函数和优化器
logits = conv_net(X, weights, biases)
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)
# 加载 MNIST 数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# 训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
avg_cost = 0.0
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
batch_x = batch_x.reshape((batch_size, 28, 28, 1))
_, c = sess.run([optimizer, cost], feed_dict={X: batch_x, Y: batch_y})
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.reshape((-1, 28, 28, 1)), Y: mnist.test.labels}))
```
以上代码中,首先定义了超参数,包括学习率、训练轮数和批次大小。然后定义了输入和输出的占位符 `X` 和 `Y`。
接下来定义了卷积层和池化层的函数 `conv2d` 和 `maxpool2d`。然后定义了一个包含两个卷积层和一个全连接层的卷积神经网络模型 `conv_net`。最后定义了权重和偏置项 `weights` 和 `biases`。
接着加载了 MNIST 数据集,并使用 Adam 优化器最小化损失函数。
最后在测试集上评估模型的准确率,并输出结果。
阅读全文
相关推荐


















