美文网首页
RNN for mnist

RNN for mnist

作者: VaultHunter | 来源:发表于2017-09-01 15:52 被阅读0次
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

相关文章

网友评论

      本文标题:RNN for mnist

      本文链接:https://www.haomeiwen.com/subject/mhkkjxtx.html