您当前的位置: 首页 > 

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

用LSTM实现英文写作

IT之一小佬 发布时间:2021-05-02 23:32:47 ,浏览量:0

用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
raw_txt = pd.read_csv('../data/r&j.txt', sep='aaaaa', names=['txt'], engine='python')
raw_txt

raw_txt.txt[1]
#  处理大小写,末尾增加空格
def m_perproc(tmp_str):
    return (tmp_str + ' ').lower()

raw_txt.txt = raw_txt.txt.apply(m_perproc)
raw_txt.txt[1]
raw_txt = raw_txt.txt.agg('sum')  # 数字的汇总,如果是字符串的话就是拼接
raw_txt

#  将字符串转换为数值代码以便处理
chars =  sorted(list(set(raw_txt)))  # 生成字符list
print(len(chars))
char_to_int = dict((c, i) for i, c in enumerate(chars))  # 字符-数值对应字典
int_to_char = dict((i, c) for i, c in enumerate(chars))  # 数值-字符对应字典
int_to_char

#  构造训练测试集
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])
print(len(x[:3][1]))
x[:3]

y[:3]
#  将文本的数值表达转换为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]

#  将因变量的类型正确指定为类别
y = np_utils.to_categorical(y)
y[0]
#  建立LSTM模型
model = Sequential()
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为分批量将数据用于训练,以减少计算资源的需求
#  epoch次数越多,模型训练的效果越好,但所需要的时间也线性增加
model.fit(x, y, epochs=2, batch_size=64)

#  进行文本预测
def predict_next(input_array):  # 进行下一个字符的预测
    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 string_to_index(raw_input):  # 将输入的字符串转换为索引值
    res = []
    for c in raw_input[len(raw_input) - seq_length:]:
        res.append(char_to_int[c])
    return res

def y_to_char(y):  # 将预测结果由索引值转换回字符
    largest_index = y.argmax()  # 取最大数值对应的索引值
    c = int_to_char[largest_index]
    return c
def generage_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 = generage_article(init)
article

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0401s