一、首先,简单来说CNN卷积神经网络与BP神经网络主要区别在于:
1、网络的层数的多少(我这里的CNN是比较简单的,层数较少,真正应用的话,层数是很多的)。
2、CNN名称来说,具有卷积运算的特点,对于大型的图片或者数量多的图片,卷积运算可以大量提高计算性能,而BP神经网络大都为全连接层,计算量本身就大,输入大量的图片,性能就不好了。
二、新建CNN文件
import tensorflow as tf
def inference(images, batch_size, n_classes):
# 一个简单的卷积神经网络,卷积+池化层x2,全连接层x2,最后一个softmax层做分类。
# 卷积层1
# 64个3x3的卷积核(3通道),padding=’SAME’,表示padding后卷积的图与原图尺寸一致,激活函数relu()
with tf.variable_scope('conv1') as scope:
weights = tf.Variable(tf.truncated_normal(shape=[3, 3, 3, 64], stddev=1.0, dtype=tf.float32),
name='weights', dtype=tf.float32)
biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[64]),
name='biases', dtype=tf.float32)
conv = tf.nn.conv2d(images, weights, strides=[1, 1, 1, 1], padding='SAME')
pre_activation = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(pre_activation, name=scope.name)
# 池化层1
# 3x3最大池化,步长strides为2,池化后执行lrn()操作,局部响应归一化,对训练有利。
with tf.variable_scope('pooling1_lrn') as scope:
pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pooling1')
norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
# 卷积层2
# 16个3x3的卷积核(16通道),padding=’SAME’,表示padding后卷积的图与原图尺寸一致,激活函数relu()
with tf.variable_scope('conv2') as scope:
weights = tf.Variable(tf.truncated_normal(shape=[