###CNN###
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
'''这些是tf1.*版本,现在我已经升级到2.0版本,上方数据集都用不了了...'''
'''黑白图片,因此这里使用的是2D'''
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
batch_size=100
n_batch=mnist.train.num_examples//batch_size
tf=tf.compat.v1
#初始化权值(这样初始化真的很重要)
def weight_variable(shape):
initial=tf.truncated_normal(shape=shape,stddev=0.1)#生成一个截断的正态分布
return tf.Variable(initial)
#初始化偏置值
def bias_variable(shape):
initial=tf.constant(0.1,shape=shape)
return tf.Variable(initial)
#卷积层
def conv2d(x,W):
#x:输入 【batch,in_height,in_width,in_channels(通道数)】
#W:滤波器
#strides:步长
#padding:个人选择:SAME/VALID
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
#池化层
def max_pool_2x2(x):
#ksize=[1 x y 1] #步长2
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')#用max_pool2d也是可以的
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
#改变x的格式转为4D的向量[batch,in_height,in_width,in_channels]
x_image=tf.reshape(x,[-1,28,28,1])#-1还是那个意思,就是输入的个数不确定,让它自行计算是多少
#初始化第一个卷积层的权值和偏置
W_conv1=weight_variable([5,5,1,32])#5*5采样窗口,32个卷积核从1个平面抽取特征(从一个平面提取32个特征平面)【就是生成1D的32个卷积核,分别进行卷积,从而1个平面得到32个卷积特征平面】
b_conv1=bias_variable([32])#给这个卷积核设置一个偏置值
#把x_image和权值向量进行卷积,再加上偏置值,然后应用relu激活函数
h_cov1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#利用平面(2D)卷积进行卷积,并加一个偏置,得到批次*32个平面的
h_pool1=max_pool_2x2(h_cov1)#进行max-pooling
#初始化第二个卷积层的权值和偏置
W_conv2=weight_variable([5,5,32,64])#5*5采样窗口,64个卷积核从32个平面抽取特征(从32个平面提取64个特征平面)【生成32D的64个卷积核,分别进行卷积,从而得到1个包含64个卷积平面】
b_conv2=bias_variable([64])#么个卷积核设置一个偏置值
#把h_pool1和权值向量进行卷积,再加上偏置值,然后应用relu激活函数
h_cov2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_cov2)#进行max-pooling
#28*28的图片第一次卷积后还是28*28,第一次初花后变成14*14
#第二次卷积后14*14,第二次池化后变成7*7
#上方操作完后的得到64张7*7的平面
'''下方就是正常的神经网络(全连接)'''
#初始化第一个全连接层的权值
W_fc1=weight_variable([7*7*64,1024])#上一层有7*7*64个神经元,全连接层有1024个神经元
b_cf1=bias_variable([1,1024])
#将池化层2的输出扁平化为1维
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])#100,7*7*64
#求第一个全连接层的输出
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_cf1)
#keep_prob用来表示神经元的输出概率
keep_prob=tf.placeholder(tf.float32)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
#初始化第二个全连接层
W_fc2=weight_variable([1024,10])
b_cf2=bias_variable([1,10])
#计算输出
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_cf2)
#交叉熵代价函数
cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#优化器
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存放在一个布尔列表中
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
acc=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(21):
for batch in range(n_batch):
batch_x,batch_y=mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_x,y:batch_y,keep_prob:0.7})
accuracy=sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
print("第"+str(i+1)+"次迭代准确率为:"+str(accuracy))
###RNN###
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
tf=tf.compat.v1
#输入图片是28*28
n_input=28#输入一行,一行有28个数据
max_time=28#一共28行
lstm_size=100#隐藏单元
n_classes=10#10个分类
batch_size=50#m每个批次50个样本
n_batch=mnist.train.num_examples//batch_size#一共有多少个批次
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
'''下方权重是隐藏层和输出层之间的权重和偏置'''
#初始化权值
weights=tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1))
#初始化偏置值
biases=tf.Variable(tf.constant(0.1,shape=[1,n_classes]))
#定义RNN网络
def RNN(x,weights,biases):
#inputs=[batch_size,max_time,n_input]>>[batch_size,in_height,in_width]
inputs=tf.reshape(x,[-1,max_time,n_input])
#定义LSTM基本CELL
lstm_Cell=tf.nn.rnn_cell.BasicLSTMCell(lstm_size)#每个隐藏层中都会有一个cell
#final_state[0]是cell_state
#final_state[1]是hidden_state 由34行可见该形状为 ?*100(隐藏单元个数) 由返回值prediction可知results它与y形状相同(50,10) 所以他的形状为50(batch_size)*100(隐藏单元个数)
outputs,final_state=tf.nn.dynamic_rnn(lstm_Cell,inputs,dtype=tf.float32)
results=tf.nn.softmax(tf.matmul(final_state[1],weights)+biases)#经过softmax转化为概率显示
return results
#计算RNN返回结果
prediction=RNN(x,weights,biases)
#损失函数
cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
#使用Adam优化器
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(21):
for j in range(n_batch):
batch_x,batch_y=mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_x,y:batch_y})
acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("第"+str(i+1)+"次迭代准确率为:"+str(acc))