日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

keras中lstm参数_如何使用Keras为自定义NER构建深度神经网络

發(fā)布時間:2025/7/14 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 keras中lstm参数_如何使用Keras为自定义NER构建深度神经网络 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在這篇文章中,我們將學(xué)習(xí)如何使用Keras創(chuàng)建一個簡單的神經(jīng)網(wǎng)絡(luò)來從非結(jié)構(gòu)化文本數(shù)據(jù)中提取信息(NER)。

模型架構(gòu)

在這里,我們將使用BILSTM + CRF層。LSTM層用于過濾不需要的信息,將僅保留重要的特征/信息,而CRF層用于處理序列數(shù)據(jù)。

BI-LSTM層

BI-LSTM用于為我們的單詞生成向量表示。 它以句子中的每個單詞作為輸入,并在兩個方向(即正向和反向)上生成每個單詞的向量表示,其中正向訪問過去的信息而反向訪問將來的信息。 然后將其與CRF層合并。

CRF層

CRF層是BI-LSTM層之上的優(yōu)化。它可用于基于過去的屬性標簽有效地預(yù)測當前標簽。

數(shù)據(jù)預(yù)處理

加載數(shù)據(jù)

在本文中,我使用機器學(xué)習(xí)數(shù)據(jù)集(https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus)。對于我們的機器學(xué)習(xí)模型,我們需要一個包含“ Sentence_id” /“ Sentence”列,“ word”列和“ tag”列的data frame。Python代碼如下:

import pandas as pddf = pd.read_csv("/kaggle/input/entity-annotated-corpus/ner.csv", encoding = "ISO-8859-1", error_bad_lines=False)data = df[['sentence_idx','word','tag']]data.head()

在SentenceGetter中包裝輸入數(shù)據(jù)

加載數(shù)據(jù)之后,我們將使用SentenceGetter類來檢索帶有標簽的句子。Python實現(xiàn)如下:

class SentenceGetter(object): def __init__(self, dataset): self.n_sent = 1 self.dataset = dataset self.empty = False agg_func = lambda s: [(w, t) for w,t in zip(s["word"].values.tolist(), s["tag"].values.tolist())] self.grouped = self.dataset.groupby("sentence_idx").apply(agg_func) self.sentences = [s for s in self.grouped] def get_next(self): try: s = self.grouped["Sentence: {}".format(self.n_sent)] self.n_sent += 1 return s except: return None getter = SentenceGetter(data)sentences = getter.sentencesprint(sentences[1:3])

這是三個句子的樣子:

單詞和標簽詞典

Keras(和大多數(shù)其他機器學(xué)習(xí)模型)期望所有id都是數(shù)字,這是節(jié)省內(nèi)存的優(yōu)化。我們將使用word2idx字典將每個單詞轉(zhuǎn)換為相應(yīng)的整數(shù)ID,并使用tag2idx將tag轉(zhuǎn)換為整數(shù)ID。

from math import nanwords = list(set(data["word"].values))n_words = len(words)tags = []for tag in set(data["tag"].values): if tag is nan or isinstance(tag, float): tags.append('unk') else: tags.append(tag)n_tags = len(tags)from future.utils import iteritemsword2idx = {w: i for i, w in enumerate(words)}tag2idx = {t: i for i, t in enumerate(tags)}idx2tag = {v: k for k, v in iteritems(tag2idx)}

Pad Sequence

BI-LSTM層期望所有文本/句子的長度相同。我們將填充大小選擇為最長句子的長度。Python代碼如下:

from keras.preprocessing.sequence import pad_sequencesfrom keras.utils import to_categoricalfrom sklearn.model_selection import train_test_splitmaxlen = max([len(s) for s in sentences])X = [[word2idx[w[0]] for w in s] for s in sentences]X = pad_sequences(maxlen=maxlen, sequences=X, padding="post",value=n_words - 1)y = [[tag2idx[w[1]] for w in s] for s in sentences]y = pad_sequences(maxlen=maxlen, sequences=y, padding="post", value=tag2idx["O"])y = [to_categorical(i, num_classes=n_tags) for i in y]# Split train and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

創(chuàng)建模型(并了解層參數(shù))

輸入層

輸入層采用形狀參數(shù),該參數(shù)是表示輸入數(shù)據(jù)維數(shù)的元組。

嵌入層

基本上,它是一個字典查找,它以整數(shù)作為輸入并返回關(guān)聯(lián)的向量。它包含三個參數(shù):

  • input_dim:文本數(shù)據(jù)中詞匯的大小,即n_words + 1
  • output_dim:嵌入的維數(shù)
  • input_length:輸入序列的長度,即最長句子的長度

BI-LSTM層

它包含五個參數(shù):

  • units:輸出空間的維數(shù)
  • return_sequences:如果return_sequence = True,則返回完整的輸出序列,否則,返回輸出序列中的最后一個輸出。
  • dropout:輸入線性轉(zhuǎn)換要下降的單位的分數(shù)。它介于0和1之間。
  • recurrent_dropout:recurrent狀態(tài)的線性轉(zhuǎn)換要下降的單位的分數(shù)。它介于0和1之間。
  • kernel_initializer:核權(quán)重矩陣的初始化程序,用于輸入的線性轉(zhuǎn)換。

TimeDistributed層

它是一個包裝器,允許我們對序列中的每個元素獨立地應(yīng)用一個層。它用于序列分類,以保持輸入和輸出的一對一關(guān)系。

CRF層

我們沒有應(yīng)用任何自定義的CRF層。我們已經(jīng)將輸出類的數(shù)量傳遞給了CRF層。

機器學(xué)習(xí)模型Python代碼

from keras.models import Model, Inputfrom keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectionalimport keras as kfrom keras_contrib.layers import CRFinput = Input(shape=(140,))word_embedding_size = 150# Embedding Layermodel = Embedding(input_dim=n_words, output_dim=word_embedding_size, input_length=140)(input)# BI-LSTM Layermodel = Bidirectional(LSTM(units=word_embedding_size, return_sequences=True, dropout=0.5, recurrent_dropout=0.5, kernel_initializer=k.initializers.he_normal()))(model)model = LSTM(units=word_embedding_size * 2, return_sequences=True, dropout=0.5, recurrent_dropout=0.5, kernel_initializer=k.initializers.he_normal())(model)# TimeDistributed Layermodel = TimeDistributed(Dense(n_tags, activation="relu"))(model) # CRF Layercrf = CRF(n_tags)out = crf(model) # outputmodel = Model(input, out)

擬合和評估模型

編譯模型

在訓(xùn)練模型之前,我們需要配置學(xué)習(xí)過程。它包含三個參數(shù):

  • 優(yōu)化器:它將根據(jù)看到的數(shù)據(jù)及其損失函數(shù)進行自我更新
  • 損失:它將能夠根據(jù)訓(xùn)練數(shù)據(jù)衡量其性能。
  • 指標:機器學(xué)習(xí)模型在訓(xùn)練和測試期間要評估的指標列表。

回調(diào)列表

當且僅當驗證精度提高時,它才用于將模型權(quán)重更新/保存到模型文件。它包含五個參數(shù):

  • filepath:目標模型文件的路徑
  • monitor:監(jiān)視模型的驗證準確性
  • verbose:如果verbose = 1,它將顯示進度條和每個epoch一行,如果verbose = 0,它將不顯示任何內(nèi)容,如果verbose = 2,它將只顯示每個epoch一行。
  • save_best_only:如果save_best_only = True,則根據(jù)監(jiān)視數(shù)量的最新最佳模型將不會被覆蓋。
  • mode:如果我們希望將其最小化,則將監(jiān)視值設(shè)為val_loss,將mode ='min'設(shè)置;如果我們要將其最大化,將set _ ='max'進行監(jiān)視,將其設(shè)為val_acc。

擬合模型

它包含七個參數(shù):

  • X:輸入數(shù)據(jù)
  • y:目標數(shù)據(jù)
  • batch_size:每個梯度更新的樣本數(shù),batch_size將默認為32。
  • epochs:epoch是對所提供的整個x和y數(shù)據(jù)的迭代。訓(xùn)練模型的epochs數(shù)。
  • validate_split:將訓(xùn)練數(shù)據(jù)的一部分用作驗證數(shù)據(jù)。
  • verbose:如果verbose = 0,它將不顯示任何內(nèi)容,如果verbose = 1,它將顯示進度條和每個epoch一行,如果verbose = 2,它將只顯示每個epoch一行。
  • callbacks:評估期間要應(yīng)用的回調(diào)列表。
from keras.callbacks import ModelCheckpointimport matplotlib.pyplot as plt#Optimiser adam = k.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999)# Compile modelmodel.compile(optimizer=adam, loss=crf.loss_function, metrics=[crf.accuracy, 'accuracy'])model.summary()# Saving the best model onlyfilepath="ner-bi-lstm-td-model-{val_accuracy:.2f}.hdf5"checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')callbacks_list = [checkpoint]# Fit the best modelhistory = model.fit(X, np.array(y), batch_size=256, epochs=10, validation_split=0.2, verbose=1, callbacks=callbacks_list)# Plot the graph plt.style.use('ggplot')def plot_history(history): accuracy = history.history['accuracy'] val_accuracy = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] x = range(1, len(accuracy) + 1) plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(x, accuracy, 'b', label='Training acc') plt.plot(x, val_accuracy, 'r', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(x, loss, 'b', label='Training loss') plt.plot(x, val_loss, 'r', label='Validation loss') plt.title('Training and validation loss') plt.legend()plot_history(history) 《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的keras中lstm参数_如何使用Keras为自定义NER构建深度神经网络的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。