import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)
lr = 0.001
training_iters = 100000
batch_size = 128
#display_step = 10
n_inputs = 28
n_steps = 28
n_hidden_units = 128
n_classes = 10
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])
X_in = tf.matmul(X,weights['in'])+biases['in']
X_in = tf.reshape(X_in,[-1,n_steps,n_hidden_units])
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units,forget_bias=1.0,state_is_tuple=True)
_init_state = lstm_cell.zero_state(batch_size,dtype=tf.float32)
with tf.variable_scope("rcnn",reuse=True): //声明作用域,否则报错
outputs,states = tf.nn.dynamic_rnn(lstm_cell,X_in,initial_state = _init_state,time_major = False)
//time_major若为true 则step 为X_in中的第一个,false 则为次要维度
results = tf.matmul(states[1],weights['out'])+biases['out']
//tf.nn.dynamic_rnn 返回的output ,[batch_size,n_step,cell.output_size]
//可以 tf.unstack(tf.transpose(outputs,[1,0,2]))先转成[n_step,batch_size,cell.output_size ],转成list
//在解成[batch_size,cell.output_size]] list中有28个 每一步的output都存在里面,所以output[-1] = state[1] 所以output是个list 包含28步的cell的输出,state是个元组,包含c 和m
return results
pred = RNN(x,weights,biases) //不能反
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=pred))
//reduce_mean求loss reduce_sum求交叉熵
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
step = 0
while step*batch_size < training_iters:
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
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(accuracy,feed_dict={
x:batch_xs,
y:batch_ys,
}))
step +=1
RNN for mnist
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 论文地址 2015 CVPR-2014.12.7 submitted 摘要 该文提出了一个给定图片或区域,生成对应...
- Note: 本文只是个草稿,备份用,后续会整理好。 官方安装完所有环境,用最新版的magenta搭配tensorf...
- 摘要:结合recursive neural networks和CRF。该模型学习了high-level discr...
- 自然语言处理 (NLP)问题都是序列化的。前馈神经网络,在单次前馈中对到来数据处理,假定所有输入独立,模式丢失。循...
- 这篇是 The Unreasonable Effectiveness of Recurrent Neural Ne...