LSTM 文本预测
LSTM
RNN对于前面的信息会有意外,LSTM可以基础相应的信息
code
#加载数据
data = open("LSTM_text.txt").read()
#移除换行
data = data.replace("\n","").replace("\r","")
print(data)
#分出字符
letters = list(set(data))
print(letters)
num_letters = len(letters)
print(num_letters)
#建立字典
int_to_char = {a:b for a,b in enumerate(letters)}
print(int_to_char)
char_to_int = {b:a for a,b in enumerate(letters)}
print(char_to_int)
#设置步长
time_step = 20
#批量字符数据预处理
import numpy as np
from tensorflow.keras.utils import to_categorical
#滑动窗口提取数据
def extract_data(data,slide):
x = []
y = []
for i in range(len(data) - slide):
x.append([a for a in data[i:i+slide]])
y.append(data[i+slide])
return x,y
#字符到数字的批量转换
def char_to_int_Data(x,y,char_to_int):
x_to_int = []
y_to_int = []
for i in range(len(x)):
x_to_int.append([char_to_int[char] for char in x[i]])
y_to_int.append([char_to_int[char] for char in y[i]])
return x_to_int,y_to_int
#实现输入字符文章的批量处理,输入整个字符,滑动窗口大小,转化字典
def data_preprocessing(data,slide,num_letters,char_to_int):
char_data = extract_data(data,slide)
int_data = char_to_int_Data(char_data[0],char_data[1],char_to_int)
Input = int_data[0]
Output = list(np.array(int_data[1]).flatten() )
Input_RESHAPED = np.array(Input).reshape(len(Input ),slide)
new = np.random.randint(0,10,size=[Input_RESHAPED.shape[0],Input_RESHAPED.shape[1],num_letters])
for i in range(Input_RESHAPED.shape[0]):
for j in range(Input_RESHAPED.shape[1]):
new[i,j,:] = to_categorical(Input_RESHAPED[i,j],num_classes=num_letters)
return new,Output
# 提取X y
X,y = data_preprocessing(data,time_step,num_letters,char_to_int)
print(X)
print(X.shape)
print(len(y))
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=10)
print(X_train.shape,X_test.shape,X.shape)
y_train_category = to_categorical(y_train,num_letters)
print(y_train_category)
print(y)
# set up the model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LSTM
model = Sequential()
# input_shape 看样本的
model.add(LSTM(units=20,input_shape=(X_train.shape[1],X_train.shape[2]),activation="relu"))
#输出层 看样本有多少页
model.add(Dense(units=num_letters ,activation="softmax"))
model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"])
model.summary()
#训练模型
model.fit(X_train,y_train_category,batch_size=1000,epochs=50)
#预测
y_train_predict = model.predict_classes(X_train)
#转换成文本
y_train_predict_char = [int_to_char[i] for i in y_train_predict ]
print(y_train_predict_char)
# 训练准确度
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_train,y_train_predict)
print(accuracy)
# 测试集准确率
y_test_predict = model.predict_classes(X_test)
accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)
y_test_predict_char = [int_to_char[i] for i in y_test_predict ]
new_letters = 'The United States continues to lead the world with more than '
X_new,y_new = data_preprocessing(new_letters,time_step,num_letters,char_to_int)
y_new_predict = model.predict_classes(X_new)
print(y_new_predict)
y_new_predict_char = [int_to_char[i] for i in y_new_predict ]
print(y_new_predict_char)
for i in range(0,X_new.shape[0]-20):
print(new_letters[i:i+20],'--predict next letter is --',y_new_predict_char[i])
参考链接
https://gitee.com/nickdlk/python_machine_learning
LSTM 文本预测的更多相关文章
- LSTM 文本情感分析/序列分类 Keras
LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/ neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...
- 时间序列深度学习:状态 LSTM 模型预测太阳黑子
目录 时间序列深度学习:状态 LSTM 模型预测太阳黑子 教程概览 商业应用 长短期记忆(LSTM)模型 太阳黑子数据集 构建 LSTM 模型预测太阳黑子 1 若干相关包 2 数据 3 探索性数据分析 ...
- Pytorch循环神经网络LSTM时间序列预测风速
#时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺序的,同样大 ...
- LSTM时间序列预测及网络层搭建
一.LSTM预测未来一年某航空公司的客运流量 给你一个数据集,只有一列数据,这是一个关于时间序列的数据,从这个时间序列中预测未来一年某航空公司的客运流量.数据形式: 二.实战 1)数据下载 你可以go ...
- Kesci: Keras 实现 LSTM——时间序列预测
博主之前参与的一个科研项目是用 LSTM 结合 Attention 机制依据作物生长期内气象环境因素预测作物产量.本篇博客将介绍如何用 keras 深度学习的框架搭建 LSTM 模型对时间序列做预测. ...
- keras-anomaly-detection 代码分析——本质上就是SAE、LSTM时间序列预测
keras-anomaly-detection Anomaly detection implemented in Keras The source codes of the recurrent, co ...
- (数据科学学习手札40)tensorflow实现LSTM时间序列预测
一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...
- deepmoji:文本预测emoji
输入句子,预测emoji demo: https://deepmoji.mit.edu/ github: https://github.com/bfelbo/DeepMoji 能够被预测的emoji ...
- Keras lstm 文本分类示例
#基于IMDB数据集的简单文本分类任务 #一层embedding层+一层lstm层+一层全连接层 #基于Keras 2.1.1 Tensorflow 1.4.0 代码: '''Trains an LS ...
- 使用keras的LSTM进行预测----实战练习
代码 import numpy as np from keras.models import Sequential from keras.layers import Dense from keras. ...
随机推荐
- mybatis插入数据返回id的实现方式
一. useGeneratedKeys="true" <insert id="saveUser" parameterType="com.apcs ...
- zookeeper选主测试
Zookeeper 会维护一个具有层次关系的数据结构,它非常类似于一个标准的文件系统 zookeeper基于目录监听机制来选主,多个客户端节点都可以来对zookeeper上某个目录节点进行监听和注册, ...
- 根据返回值,判断是否执行下一步的方法(Run Keyword And Return Status指令的使用)
场景分析: 上图"通用模版测试"内容 满足,如果当前页面存在这条数据,即结束执行本条用例,自动执行下一条.如果没有,则调用新建模版关键字,执行新建模版. 脚本如下 1配置运费模版 ...
- eolinker请求预处理:配置全局环境变量后,步骤内去掉请求头信息
特别注意:需要使用全局变量或者预处理前务必阅读本链接https://www.cnblogs.com/becks/p/13713278.html 1.描述,用例配置环境变量后会在请求前自动加上域名和请求 ...
- kette介绍-Step之Merge Join
Merge Join介绍 需要配合Sort rows使用,对关联字段进行排序 关联两个step数据,可以是两个不同的数据库表数据,也可以是一张表,一个文件,输出字段为两张表所有字段 注意将小数据集作为 ...
- 【工具】you-get + ffmpeg|视频下载+音频提取
一.原理: you-get下载,ffmpeg音视频分离. 这两个都是命令行工具. you-get安装(无python环境请参考python详细安装教程): pip3 install --upgrade ...
- 使用win10 wsl子系统将 rust 程序静态编译为linux可执行文件
chapter Ⅰ 事情起因 最近在学习rust, 想把一部分java服务迁移至rust编写,但由于公司服务器都是linux系统,所以在找windows下交叉编译为linux可执行文件的方法,把bin ...
- 用AI做了个动态下发微信群二维码应用
微信群的二维码每周都要更新一次,比较麻烦.于是搞了个简单的上传/下发的 Web 应用. 下面是优化前后流程,虽然看似步骤少了一步,但大大节省了时间. 主要功能 常见类型图片上传,支持删除,提供外链访问 ...
- codeup之打印日期
Description 给出年分m和一年中的第n天,算出第n天是几月几号. Input 输入包括两个整数y(1<=y<=3000),n(1<=n<=366). Output 可 ...
- C# 在Excel中设置文本的对齐方式、换行、旋转
在 Excel 中,对齐.换行和旋转是用于设置单元格内容显示方式的功能.合理的设置这些文本选项可以帮助用户更好地组织和展示 Excel 表格中的数据,使表格更加清晰.易读,提高数据的可视化效果.本文将 ...