深度學習 Keras情感分析實戰

2021-09-11 05:47:21 字數 1794 閱讀 7202

from keras.preprocessing import sequence  # 句子序列

from keras.models import sequential # ai模型

from keras.layers import dense, embedding # 控制層

from keras.layers import lstm # rnn神經網路的一種

from keras.datasets import imdb # 資料集

max_feature =

20000

# 特徵數量. 最大的單詞數量

max_length =

80# 最大長度

batch_size =

32# 批量的大小

(x_train, y_train)

,(x_test, y_test)

= imdb.load_data(num_words=max_feature)

# 載入資料

print

(len

(x_train)

,len

(x_test)

)print

(x_train.shape, x_test.shape)

# 形狀

print

("資料填充以後"

)x_train = sequence.pad_sequences(x_train, maxlen=max_length)

# 資料填充

x_test = sequence.pad_sequences(x_test, maxlen=max_length)

# 資料填充

print

(x_train.shape, x_test.shape)

# 形狀

print

(y_train.shape, y_test.shape)

model = sequential(

)model.add(embedding(max_feature,

128)

)# 嵌入層

model.add(lstm(

128, dropout=

0.2, recurrent_dropout=

0.2)

)model.add(dense(

1, activation=

"sigmoid"))

# 輸出結果, 0 1

model.

compile

(loss=

"binary_crossentropy"

,# 損失最小

optimizer=

"adam"

,# 優化

metrics=

["accuracy"])

# 精確

print

("train---------------"

)model.fit(x_train, y_train,

batch_size=batch_size,

epochs=5,

validation_data=

(x_test, y_test)

)score = model.evaluate(x_test, y_test, batch_size=batch_size)

print

("loss函式"

, score[0]

,"識別率"

, score[1]

)print

(model.predict(x_test[1]

))# **的範例

IMDB情感分析例子 keras

載入imdb資料集 x train 0 1,14,22,32 長度為228 x train sequence.pad sequences x train,maxlen 500 x train 0 變為 0,0,0.1,14,22,32 長度為500 import numpy from keras.d...

keras深度學習(二)

上一次,我學到了感知機,多層感知機,啟用函式等 寫出了第乙個keras 例項 import keras.models import sequential model sequential model.add dense 12,input dim 8,kernel initializer random...

Keras深度學習(四)

今天測試前幾天所提到的演算法 1.使用keras定義簡單的神經網路 from future import print function import numpy as np from keras.datasets import mnist from keras.models import seque...