LSTM最基本的應用(07 3)

2022-05-04 13:42:07 字數 2411 閱讀 2785

**實現

#

-*- coding: utf-8 -*-

import

tensorflow as tf

from tensorflow.examples.tutorials.mnist import

input_data

#載入資料集

mnist = input_data.read_data_sets("

mnist_data/

",one_hot=true)

#輸入的是28*28

n_inputs=28 #

輸入一行,一行有28個資料

max_time=28 #

一共28行

lstm_size=100 #

隱層單元

n_classes=10 #

10個分類

batch_size=50 #

每批次50個樣本

n_batch=mnist.train.num_examples // batch_size #

計算一共有多少批次

#這裡的none表示第一維度可以是任意的長度

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=[n_classes]))

#定義rnn網路

defrnn(x,weight,biases):

#inputs=[batch_size,max_time,n_inputs]

inputs=tf.reshape(x,[-1,max_time,n_inputs])

#定義lstm基本cell

lstm_cell=tf.contrib.rnn.basiclstmcell(lstm_size)

#final_state[0]是cell state

#final_state[1]是hidden_state

outputs,final_state=tf.nn.dynamic_rnn(lstm_cell, inputs,dtype=tf.float32)

results=tf.nn.softmax(tf.matmul(final_state[1], weights) + biases)#

最後神經網路的輸出

return

results

#計算rnn的返回結果

prediction=rnn(x, weights, biases)

#損失函式

cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))

#使用adamoptimizer進行優化

trian_step=tf.train.adamoptimizer(1e-4).minimize(cross_entropy)

#結果存放在乙個布林型列表中

correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #

argmax返回一維張量中最大的值所在的位置

#求準確率

accuarcy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #

把correct_prediction變為float32型別

#初始化

init=tf.global_variables_initializer()

with tf.session() as sess:

sess.run(init)

for epoch in range(6):

for batch in

range(n_batch):

batch_xs,batch_ys=mnist.train.next_batch(batch_size)

sess.run(trian_step, feed_dict=)

acc=sess.run(accuarcy, feed_dict=)

print ("

iter

"+str(epoch)+"

, testing accuarcy=

" + str(acc))

執行結果:(此**還可以進行優化)

最基本的委託

有些教材,部落格說到委託都會提到事件,雖然事件是委託的乙個例項,但是為了理解起來更簡單,今天只談委託不談事件。先上一段 下邊的 完成了乙個委託應用的演示。乙個委託分三個步驟 public partial class webform3 system.web.ui.page step02 宣告乙個方法來...

最基本的操作

關於目錄的獲取 獲取沙盒目錄 算是跟目錄吧 nshomedirectory 獲取document目錄 常用 let paths nssearchpathfordirectoriesindomains documentdirectory,userdomainmask,true first 或者 fil...

GCC最基本的用法

在使用gcc編譯器的時候,我們必須給出一系列必要的呼叫引數和檔名稱。gcc編譯器的呼叫引數大約有100多個,其中多數引數我們可能根本就用不到,這裡只介紹其中最基本 最常用的引數。下面是man gcc的結果 gcc c s e std standard g pg olevel wwarn.pedant...