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 文本预测的更多相关文章

  1. LSTM 文本情感分析/序列分类 Keras

    LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/   neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...

  2. 时间序列深度学习:状态 LSTM 模型预测太阳黑子

    目录 时间序列深度学习:状态 LSTM 模型预测太阳黑子 教程概览 商业应用 长短期记忆(LSTM)模型 太阳黑子数据集 构建 LSTM 模型预测太阳黑子 1 若干相关包 2 数据 3 探索性数据分析 ...

  3. Pytorch循环神经网络LSTM时间序列预测风速

    #时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺序的,同样大 ...

  4. LSTM时间序列预测及网络层搭建

    一.LSTM预测未来一年某航空公司的客运流量 给你一个数据集,只有一列数据,这是一个关于时间序列的数据,从这个时间序列中预测未来一年某航空公司的客运流量.数据形式: 二.实战 1)数据下载 你可以go ...

  5. Kesci: Keras 实现 LSTM——时间序列预测

    博主之前参与的一个科研项目是用 LSTM 结合 Attention 机制依据作物生长期内气象环境因素预测作物产量.本篇博客将介绍如何用 keras 深度学习的框架搭建 LSTM 模型对时间序列做预测. ...

  6. keras-anomaly-detection 代码分析——本质上就是SAE、LSTM时间序列预测

    keras-anomaly-detection Anomaly detection implemented in Keras The source codes of the recurrent, co ...

  7. (数据科学学习手札40)tensorflow实现LSTM时间序列预测

    一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...

  8. deepmoji:文本预测emoji

    输入句子,预测emoji demo: https://deepmoji.mit.edu/ github: https://github.com/bfelbo/DeepMoji  能够被预测的emoji ...

  9. Keras lstm 文本分类示例

    #基于IMDB数据集的简单文本分类任务 #一层embedding层+一层lstm层+一层全连接层 #基于Keras 2.1.1 Tensorflow 1.4.0 代码: '''Trains an LS ...

  10. 使用keras的LSTM进行预测----实战练习

    代码 import numpy as np from keras.models import Sequential from keras.layers import Dense from keras. ...

随机推荐

  1. hybrid应用自动化

    一.hybrid介绍 hybrid是一种混合app,将h5页面嵌入native原生页面. 基于uiautomator+chromedriver.native部分走uiautomator,web部分走c ...

  2. C#——基于CancellationTokenSource实现Task的取消

    参照:第七节:利用CancellationTokenSource实现任务取消和利用CancellationToken类检测取消异常. - Yaopengfei - 博客园 (cnblogs.com) ...

  3. rider的xamarin环境安装

    自从用上rider后,vs就再也没有安装过了.最近要做apk开发,就安装xamarin环境,但是总是报错: Show Log->idea.log 发现下面错误: ERROR | Environm ...

  4. js--弹出对话框、改变控件内容、验证输入邮箱的合法性

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  5. API接口调用--历史上的今天(v1.0)

    历史上的今天 参考(聚合数据):https://www.juhe.cn/docs/api/id/63 事件列表(v1.0) 接口地址: http://api.juheapi.com/japi/toh ...

  6. 【工具】you-get + ffmpeg|视频下载+音频提取

    一.原理: you-get下载,ffmpeg音视频分离. 这两个都是命令行工具. you-get安装(无python环境请参考python详细安装教程): pip3 install --upgrade ...

  7. Web前端入门第 48 问:纯 CSS 使用 column 属性实现瀑布流布局

    什么是瀑布流? 看一张图,以下图片来源于花瓣网截图: 如上图所示,瀑布流就是让内容按列显示,自动填充空白. 使用 column 实现瀑布流 源码: <div class="masonr ...

  8. Linux C 获取本机IPV4和IPV6地址列表

    有时候设备网卡上有多个IPv6,其中只有一个是可用的,另外一个是内网地址,无法使用,如果程序需要绑定一个V6地址的时候,需要获取网卡上的V6地址,并且要求是可用的. 通过ifconfig可用看到,et ...

  9. c++并发编程实战-第1章 c++并发世界

    前言 c++11开始支持多线程,使得编写c++多线程程序无需依赖特定的平台,使开发者能够编写可移植的.行为确定的多线程程序代码. 什么是并发 所谓并发,是两个或多个同时独立进行的活动.而计算机中的并发 ...

  10. 【晴神宝典刷题路】codeup+pat 题解索引(更新ing

    记录一下每天的成果,看多久能刷完伐 c2 c/c++快速入门 <算法笔记>2.3小节--C/C++快速入门->选择结构 习题4-10-1 奖金计算 <算法笔记>2.4小节 ...