深度學習16—LSTM擬合IMDB案例案例+實現英文自動寫作

LSTM相關的網絡層定義

keras.layers.LSTM( # 長短期記憶網絡層

units : 正整數,輸出空間的維度。

activation = 'tanh' : 要使用的激活函數。
recurrent_activation = 'hard_sigmoid' : 用於循環時間步的激活函數。

use_bias = True : 布爾值,該層是否使用偏置向量。
kernel_initializer = 'glorot_uniform'
recurrent_initializer = 'orthogonal'
bias_initializer = 'zeros', unit_forget_bias = True
kernel_regularizer = None, recurrent_regularizer = None
bias_regularizer = None, activity_regularizer = None
kernel_constraint = None, recurrent_constraint = None
bias_constraint = None

dropout = 0.0 : 0~1,單元的丟棄比例,用於輸入的線性轉換。
recurrent_dropout = 0.0 : 0~1,單元的丟棄比例,用於循環層狀態的線性轉換。

implementation = 1 : 實現模式,12。
    模式1:將把它的操作結構化爲更多的小的點積和加法操作。
    模式2:將把它們分批到更少,更大的操作中。
return_sequences = False : 是返回輸出序列中的最後一個輸出,還是全部序列。

return_state = False : 除了輸出之外是否返回最後一個狀態(cell state)。 
go_backwards = False : 是否向後處理輸入序列並返回相反的序列。 
stateful = False : 是否將批次中索引i樣品的最後狀態用作下一批次i樣品初始狀態。 
unroll = False : 如果爲True,網絡將展開,否則將使用符號循環。
    展開可以加速RNN,但它往往會佔用更多的內存。展開只適用於短序列。
)

其餘LSTM函數:

LSTMCell : LSTM層的單元類。
ConvLSTM2D : 卷積LSTM,它類似於LSTM層,但輸入變換和循環變換都是卷積的。
CuDNNLSTM : 由CuDNN支持的快速LSTM 實現,只能以TensorFlow後端運行在GPU上。

用LSTM擬合IMDB案例

from keras.models import Sequential
from keras.layers import Input, Dense, Embedding, LSTM,Dropout
from keras.models import Model 

model = Sequential() 
# LSTM層指定爲32個神經元
model.add(Embedding(input_dim = 10000, output_dim = 64)) 
model.add(LSTM(32, activation = 'tanh')) # 注意設定適當的激活函數
model.add(Dropout(0.2)) # 拋棄20%的結果,防止過擬合
model.add(Dense(2, activation = 'softmax')) 

model.summary()

在這裏插入圖片描述

model.compile(loss = 'categorical_crossentropy', 
              optimizer = 'rmsprop', 
              metrics = ['accuracy']) 

from keras.datasets import imdb
# 首次使用時會在線進行數據集下載
# 只保留數據集中最常出現的前10000個詞
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words = 10000) 
from keras.preprocessing.sequence import pad_sequences
# 將所有的序列均補齊或截斷爲統一長度
max_word = 300
X_train = pad_sequences(X_train, maxlen = max_word)
X_test = pad_sequences(X_test, maxlen = max_word)
print(len(X_train[0]))
X_train[0][:100]
from keras.utils import to_categorical
# 將因變量轉換爲啞變量組
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model.fit(X_train, y_train, batch_size = 200, epochs = 10)

score = model.evaluate(X_test, y_test, batch_size = 200, verbose = 1)
print("測試集損失函數:%f,預測準確率:%2.2f%%" % (score[0], score[1] * 100))

預測效果
在這裏插入圖片描述

用LSTM實現英文自動寫作

文本預處理

# 載入所需工具包
import numpy as np
import pandas as pd

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

rawtxt = pd.read_csv(r"F:\learning_kecheng\deenlearning\NEW\r&j.txt", sep = 'aaaaa', 
                     names = ['txt'], engine = 'python')
print(rawtxt.head())
rawtxt.txt[1]

原數據,這是文本原來的格式:前五行
在這裏插入圖片描述
這是第二行
在這裏插入圖片描述
在這裏插入圖片描述
用sun函數將所有字符連接在一起:

raw_txt = rawtxt.txt.agg("sum")
raw_txt

在這裏插入圖片描述
** 將字符轉換爲數值代碼以便處理**
首先創建字典:其中chars 是文本中所有的字符類型。

chars = sorted(list(set(raw_txt))) # 生成字符list  sorted排序
char_to_int = dict((c, i) for i, c in enumerate(chars)) # 字符-數值對應字典
int_to_char = dict((i, c) for i, c in enumerate(chars)) # 數值-字符對應字典
char_to_int

在這裏插入圖片描述

構造訓練測試集

利用循環生成訓練集測試集

seq_length = 100
x = []; y = []
for i in range(0, len(raw_txt) - seq_length):
    given = raw_txt[i:i + seq_length] # 將前seq_length個字符作爲預測用變量
    predict = raw_txt[i + seq_length] # 將當前字符作爲因變量
    x.append([char_to_int[char] for char in given])
    y.append(char_to_int[predict])

處理後的x:長度爲設定的seq_length = 100
在這裏插入圖片描述
因變量
在這裏插入圖片描述
將文本的數值表達轉換爲LSTM需要的數組格式:[樣本數,時間步伐,特徵]

n_patterns = len(x)
n_vocab = len(chars)

# 把x變成LSTM需要的格式,reshape最後的1表示每個數值均爲單獨一個向量(代表一個字母輸入)
x = np.reshape(x, (n_patterns, seq_length, 1)) 
x = x / float(n_vocab) # 轉換爲0-1之間的數值以方便計算
x[0]

處理後的x:
在這裏插入圖片描述

# 將因變量的類型正確指定爲類別
y = np_utils.to_categorical(y) 
y[0]

處理後的y
在這裏插入圖片描述

建立LSTM模型

model = Sequential() 
# LSTM層指定爲128個神經元
model.add(LSTM(128, input_shape = (x.shape[1], x.shape[2]))) 
model.add(Dropout(0.2)) # 拋棄20%的結果,防止梯度飽和
model.add(Dense(y.shape[1], activation = 'softmax')) # 使用標準的NN作爲內核
# 指定損失函數
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam') 

# batch_size爲分批量將數據用於訓練,以減小計算資源的需求
# epochs次數越多,模型訓練效果越好,但所需時間也線性增加
model.fit(x, y, epochs = 2, batch_size = 64) 

進行文本預測

def string_to_index(raw_input): # 將輸入的字符轉換爲索引值
#    raw_input = in_string
    res = []
    for c in raw_input[(len(raw_input) - seq_length):]:
#        print(c)#長度爲seq_length100 
        res.append(char_to_int[c])
    return res
    

def predict_next(input_array): # 進行下一個字符的預測
#    input_array = res
    x = np.reshape([0 for i in range(seq_length - len(input_array))]
                   + input_array, (1, seq_length, 1)) # 生成預測用的x序列
    x = x / float(n_vocab)
    y = model.predict(x)
    return y


def y_to_char(y): # 將預測結果由索引值轉換回字符
    largest_index = y.argmax() # 取最大數值對應的索引值
    c = int_to_char[largest_index]
    return c


def generate_article(init, rounds = 50): # 按照指定的字符長度進行預測
    in_string = init.lower()
    for i in range(rounds):
        n = y_to_char(predict_next(string_to_index(in_string)))
        in_string += n # 將預測到的新字符合並,用於下一步預測
    return in_string


# 進行字母預測
init = 'We produce about two million dollars for each hour we work. The fifty hours is one conservative estimate for how long'
article = generate_article(init)
article

從long後面的預測到的
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章