導讀:在NLP基礎(chǔ):NNLM模型介紹中建钥,已經(jīng)介紹了NNLM模型原理藤韵,通過對網(wǎng)上已發(fā)布的代碼進行完善并標注熊经,進行模型代碼示例展示欲险。
Keras實現(xiàn)
代碼主要部分如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from keras.models import Sequential
import numpy as np
import tensorflow as tf
import re
sentences = [ "我渴了", "你真好", "他的錯", "對不起" , "他走了"]
# NNLM Parameter
n_step = len(sentences[0])-1 # number of steps ['我 渴', '你 真', '他 的', '對 不', '他 走']
#分字
def seg_char(sent):
? ? pattern = re.compile(r'([\u4e00-\u9fa5])')
? ? chars = pattern.split(sent)
? ? chars =[w for w in chars if len(w.strip()) > 0]
? ? return chars
#得到每個句子前n-1個詞和目標詞
chars=np.array([seg_char(i)for i in sentences])
chars=chars.reshape(1,-1)
word_list=np.squeeze(chars)
#['我' '渴' '了' '你' '真' '好' '他' '的' '錯' '對' '不' '起' '他' '走' '了']
word_list = list(set(word_list))
word_dict = {w: i for i, w in enumerate(word_list)}
#{'渴': 0, '錯': 1, '不': 2, '好': 3, '起': 4, '他': 5, '對': 6, '你': 7, '走': 8, '我': 9, '了': 10, '的': 11, '真': 12}
number_dict = {i: w for i, w in enumerate(word_list)}
#{0: '渴', 1: '錯', 2: '不', 3: '好', 4: '起', 5: '他', 6: '對', 7: '你', 8: '走', 9: '我', 10: '了', 11: '的', 12: '真'}
n_class = len(word_dict) # number of Vocabulary
#這里通過one-hot進行詞向量生成
#one-hot轉(zhuǎn)換
def make_batch(sentences):
? ? input_batch = []
? ? target_batch = []
? ? for sen in sentences:
? ? ? ? #將每個句子中的字轉(zhuǎn)化為下標表示
? ? ? ? word = seg_char(sen)
? ? ? ? input = [word_dict[n] for n in word[:-1]]
? ? ? ? target = word_dict[word[-1]]
? ? ? ? #one-hot轉(zhuǎn)換
? ? ? ? input_batch.append(np.eye(n_class)[input])
? ? ? ? target_batch.append(np.eye(n_class)[target])
? ? return input_batch, target_batch
input_batch, target_batch=make_batch(sentences)
input_batch=np.array(input_batch)
#將輸入詞向量進行首尾拼接
input_batch=input_batch.reshape(-1,n_step*n_class)
target_batch=np.array(target_batch)
target_batch=target_batch.reshape(-1,n_class)
from keras.layers import Dense
import keras
#建立模型天试,本模型暫不包含直連邊
def define_model():
? ? model = Sequential()
? ? #Dense為全連接網(wǎng)絡(luò)
? ? model.add(Dense(2,activation='tanh',input_shape=(n_step*n_class,))) # 輸入層
? ? model.add(Dense(n_class, activation='softmax'))? # 輸出層
? ? model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
? ? model.summary()
? ? return model
#訓練模型
model=define_model()
model.fit(input_batch, target_batch, epochs=2000)#訓練2000輪焕盟,數(shù)據(jù)少啦,一兩輪沒效果
#預測測試
predict=model.predict(input_batch)
predict=np.argmax(predict,1)#求取最大值索引
print('輸入的是:',[seg_char(sen)[:2] for sen in sentences])
print('預測得到:',[number_dict[n] for n in predict])
得到結(jié)果如下:
點擊原文:NLP基礎(chǔ):NNLM模型代碼示例灼卢,回復“NNLM”可獲取全部代碼