import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.set_random_seed(1)
#导入数据
mnist = input_data.read_data_sets('E:/Program Files/Machine Learning/node/MNIST_data',one_hot = True)
#hyperparameters
lr = 0.001 #学习率
training_iters = 100000
batch_size = 128
n_inputs = 28
n_steps = 28
n_hidden_units = 128
n_classes = 10
#定义x,y的placeholder和weights,biases的初始状况
x = tf.placeholder(tf.float32,[None,n_steps,n_inputs])
y = tf.placeholder(tf.float32,[None,n_classes])
#对weights biases初始化的定义
weight = {
#shape (28,128)
'in':tf.Variable(tf.random_normal([n_inputs,n_hidden_units])),
#shape (128,10)
'out':tf.Variable(tf.random_normal([n_hidden_units,n_classes]))
}
biases = {
#shape (128,)
'in':tf.Variable(tf.constant(0.1,shape=[n_hidden_units,])),
#shape (128,10)
'out':tf.Variable(tf.constant(0.1,shape=[n_classes,]))
}
#定义RNN的主体结构
def RNN(X,weight,biases):
#原始的X是3维数据,我们需要把它变成2维数据才能使用weight的矩阵乘法
#X ==> (128batchs*28steps,28 inputs)
X = tf.reshape(X,[-1,n_inputs])
#X_in = W * X +b
X_in = tf.matmul(X,weight['in']) + biases['in']
#X_in==> (128batchs,28steps,28 inputs)换回3维
X_in = tf.reshape(X_in,[-1,n_steps,n_hidden_units])
#cell
#使用basic LSTM Cell
lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units,forget_bias=1.0,state_is_tuple=True)
init_state = lstm_cell.zero_state(batch_size,dtype=tf.float32)#初始化全0 state
outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,X_in,initial_state=init_state,time_major=False)
#
results = tf.matmul(final_state[1],weight['out'])+biases['out']
return results
pred = RNN(x,weight,biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels =y ,logits=pred))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
#训练RNN
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
tensorflow--RNN解决mnist
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...