在VS2017上进行开发, 首先,个人问题不知道为什么无法下载mnist的资源,只能手动放在工程文件夹下
其中MNIST就是,百度云资源:点击打开链接
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST/',one_hot = True) #这里向文件夹读取资源
lr = 0.001 #设置训练步长
training_it = 100000 #这里依据的是样本数量
batch_size = 128
n_inputs = 28 #将图片分成28行
n_steps = 28 #时间步
n_hidden_units = 128 #神经元数量
n_classes = 10 #mnist 指0-9
x= tf.placeholder(tf.float32,[None,n_steps,n_inputs]) #定义输入
y= tf.placeholder(tf.float32,[None,n_classes])
weights = { #此处定义权重
'in':tf.Variable(tf.random_normal([n_inputs,n_hidden_units])),
'out':tf.Variable(tf.random_normal([n_hidden_units,n_classes]))
}
biases = { #此处定义偏移量
'in': tf.Variable(tf.constant(0.1,shape =[n_hidden_units, ])),
'out':tf.Variable(tf.constant(0.1,shape=[n_classes,]))
}
def RNN(X,weights,biases):
X = tf.reshape(X,[-1,n_inputs]) #输入一张图片的28行
X_in = tf.matmul(X,weights['in'])+biases['in'] #第一层layer
X_in = tf.reshape(X_in,[-1,n_steps,n_hidden_units]) #这里reshape准备传入cell
cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units) #这里采用RNN的 BasicLSTMCell方法
init_state = cell.zero_state(batch_size,dtype = tf.float32) #初始化RNN状态参数
outputs,final_state = tf.nn.dynamic_rnn(cell,X_in,initial_state = init_state ,time_major = False)
outputs= tf.unstack(tf.transpose(outputs,[1,0,2])) #这里进行矩阵转置并拆解一个维度
results = tf.matmul(outputs[-1],weights['out'])+biases['out'] #这里进行第二层layer
return results
prediction = RNN(x,weights,biases) #这里进行RNN
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = prediction,labels = y)) #这里计算损失
train_op = tf.train.AdamOptimizer(lr).minimize(cost) #这里采用Adam的方式进行优化
#这里把预测值中的最大可能和实际值进行对比 输出为0和1数组,0为不同,1为相同
correct_pred = tf.equal(tf.arg_max(prediction,1),tf.arg_max(y,1))
#这里计算上述对比数组中1所占的比例
accuary = tf.reduce_mean(tf.cast(correct_pred,tf.float32))
with tf.Session() as sess:
#这里初始化变量
init = tf.global_variables_initializer()
#这里进行初始化 常规套路
sess.run(init)
step =0
while step*batch_size <training_it:
#获取一个batch的图片及对应标签
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
#对一个batch的图片进行reshape
batch_xs = batch_xs.reshape(batch_size,n_steps,n_inputs)
#开始训练
sess.run(train_op,feed_dict={x:batch_xs,y:batch_ys})
if step %20 ==0: #这里隔一段训练样本 计算一次 准确率
print(sess.run(accuary,feed_dict = {
x:batch_xs,y:batch_ys
}))
step+=1
以上RNN的时间序列是以图片行为标准。