原文链接:http://www.one2know.cn/nlp21/

根据已有文本LSTM自动生成文本

from __future__ import print_function
import numpy as np
import random
import sys path = r'shakespeare_final.txt'
text = open(path).read().lower() # 打开文档 读成字符串 然后都变小写
characters = sorted(list(set(text))) # 去掉重复字符 方便下面编码
print('corpus length:',len(text))
print('total chars:',len(characters)) char2indices = dict((c,i) for i,c in enumerate(characters)) # 字符(字母等)=>索引(数字)
indices2char = dict((i,c) for i,c in enumerate(characters)) # 索引(数字)=>字符(字母等) maxlen = 40 # 40个字符长度预测下一个字符
step = 3 # 一次预测3个
sentences = []
next_chars = []
for i in range(0,len(text)-maxlen,step):
sentences.append(text[i:i+maxlen])
next_chars.append(text[i+maxlen])
print('nb sentences:',len(sentences)) # 40个字符串作为特征句子的个数 即训练数据大小 ## 构造数据集 类似one-hot编码
X = np.zeros((len(sentences),maxlen,len(characters)),dtype=np.bool)
y = np.zeros((len(sentences),len(characters)),dtype=np.bool)
for i,sentence in enumerate(sentences):
for t,char in enumerate(sentence):
X[i,t,char2indices[char]] = 1
y[i,char2indices[next_chars[i]]] = 1 # 构建神经网路
from keras.models import Sequential
from keras.layers import Dense,LSTM,Activation,Dropout
from keras.optimizers import RMSprop
model = Sequential()
model.add(LSTM(128,input_shape=(maxlen,len(characters))))
model.add(Dense(len(characters)))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',optimizer=RMSprop(lr=0.01))
print(model.summary()) def pred_indices(preds,metric=1.0):
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / metric
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probs = np.random.multinomial(1,preds,1)
return np.argmax(probs) for iteration in range(1,30): # 便于观察每一轮的训练结构
print('-' * 40)
print('Iteration',iteration)
model.fit(X,y,batch_size=128,epochs=1)
start_index = random.randint(0,len(text)-maxlen-1)
for diversity in [0.2,0.7,1.2]:
print('\n----- diversity:',diversity)
generated = ''
sentence = text[start_index:start_index+maxlen]
generated += sentence
print('----- Generating with seed: "'+sentence+'"')
sys.stdout.write(generated)
for i in range(400):
x = np.zeros((1,maxlen,len(characters)))
for t,char in enumerate(sentence): # 数字索引=>字母
x[0,t,char2indices[char]] = 1
preds = model.predict(x,verbose=0)[0]
next_index = pred_indices(preds,diversity)
pred_char = indices2char[next_index]
generated += pred_char
sentence = sentence[1:] + pred_char
sys.stdout.write(pred_char)
sys.stdout.flush()
print('\nOne combination completed \n')

输出:

corpus length: 581432
total chars: 61
nb sentences: 193798
Using TensorFlow backend.
WARNING:tensorflow:From D:\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (None, 128) 97280
_________________________________________________________________
dense_1 (Dense) (None, 61) 7869
_________________________________________________________________
activation_1 (Activation) (None, 61) 0
=================================================================
Total params: 105,149
Trainable params: 105,149
Non-trainable params: 0
_________________________________________________________________
None
----------------------------------------
Iteration 1
WARNING:tensorflow:From D:\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Epoch 1/1
2019-07-15 17:04:03.721908: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2019-07-15 17:04:04.438003: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: GeForce GTX 950M major: 5 minor: 0 memoryClockRate(GHz): 1.124
pciBusID: 0000:01:00.0
totalMemory: 2.00GiB freeMemory: 1.64GiB
2019-07-15 17:04:04.438676: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-07-15 17:04:07.352274: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-07-15 17:04:07.352543: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0
2019-07-15 17:04:07.352701: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0: N
2019-07-15 17:04:07.357455: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1386 MB memory) -> physical GPU (device: 0, name: GeForce GTX 950M, pci bus id: 0000:01:00.0, compute capability: 5.0)
2019-07-15 17:04:08.415227: I tensorflow/stream_executor/dso_loader.cc:152] successfully opened CUDA library cublas64_100.dll locally 128/193798 [..............................] - ETA: 2:16:56 - loss: 4.1095
256/193798 [..............................] - ETA: 1:09:23 - loss: 3.6938
384/193798 [..............................] - ETA: 46:52 - loss: 3.8312
。。。

NLP(二十一)根据已有文本LSTM自动生成文本的更多相关文章

  1. GZFramwork数据库层《二》单据表增删改查(自动生成单据号码)

    运行效果: 使用代码生成器(GZCodeGenerate)生成tb_EmpLeave的Model 生成器源代码下载地址: https://github.com/GarsonZhang/GZCodeGe ...

  2. 利用RNN(lstm)生成文本【转】

    本文转载自:https://www.jianshu.com/p/1a4f7f5b05ae 致谢以及参考 最近在做序列化标注项目,试着理解rnn的设计结构以及tensorflow中的具体实现方法.在知乎 ...

  3. IT轮子系列(二)——mvc API 说明文档的自动生成——Swagger的使用(一)

    这篇文章主要介绍如何使用Swashbuckle插件在VS 2013中自动生成MVC API项目的说明文档.为了更好说明的swagger生成,我们从新建一个空API项目开始. 第一步.新建mvc api ...

  4. (二十二)SpringBoot之使用mybatis generator自动生成bean、mapper、mapper xml

    一.下载mybatis generator插件 二.生成generatorConfig.xml new一个generatorConfig.xml 三.修改generatorConfig.xml 里面的 ...

  5. TensorFlow从1到2(十一)变分自动编码器和图片自动生成

    基本概念 "变分自动编码器"(Variational Autoencoders,缩写:VAE)的概念来自Diederik P Kingma和Max Welling的论文<Au ...

  6. selenium如何向ueditor富文本中自动输入文本

    1.网上给出的方法在百度的富文本控件ueditor中不起作用切换框架失败 2.利用ueditor的api文档,通过js不使用框架切换即可实现轻松写入 eg:ue.setContent('hello')

  7. (二)一个很好用的自动生成工具——mybatis generator

    mybatis generator-自动生成代码 准备材料: 一个文件夹,一个数据库的驱动包,mybatis-generator-core-1.3.5.jar,一条生成语句 如图:(我用的是derby ...

  8. 前端(二十一)—— vue指令:文本类指令、避免页面闪烁、v-bind指令、v-on指令、v-model指令、条件渲染指令、列表渲染指令

    文本类指令.v-bind指令.v-on指令.v-model指令.条件渲染指令.列表渲染指令 一.文本操作 v-text:文本变量 <p v-text='msg'></p> &l ...

  9. 无废话ExtJs 入门教程二十一[继承:Extend]

    无废话ExtJs 入门教程二十一[继承:Extend] extjs技术交流,欢迎加群(201926085) 在开发中,我们在使用视图组件时,经常要设置宽度,高度,标题等属性.而这些属性可以通过“继承” ...

随机推荐

  1. Windows 使用 helm3 和 kubectl

    简介: 主要原因是,我不会 vim ,在 linux 上修改 charts 的很蹩脚,所以就想着能不能再 windows 上执行 helm 命令,将 charts install linux 上搭建的 ...

  2. 脱壳系列_2_IAT加密壳_详细版解法1(含脚本)

    1 查看壳程序信息 使用ExeInfoPe 分析: 发现这个壳的类型没有被识别出来,Vc 6.0倒是识别出来了,Vc 6.0的特征是 入口函数先调用GetVersion() 2 用OD找OEP 拖进O ...

  3. 入门MySQL——基础语句篇

    前言:  前面几篇文章,我们介绍了MySQL的基础概念及逻辑架构.相信你现在应该有了自己的一套MySQL环境,接下来我们就可以开始练习MySQL了.本文将从MySQL最基础的语句出发,为你展示出创建及 ...

  4. nginx 之负载均衡 :PHP session 跨多台服务器配置

    公司一个项目单点压力越来越大,考虑到稳定性和降压,使用nginx做负载均衡,将请求分发到多个docker上去,这里记录下PHP多服务器间的会话session共享问题,解决方案是把session单独存在 ...

  5. 6.源码分析---和dubbo相比SOFARPC是如何实现负载均衡的?

    官方目前建议使用的负载均衡包括以下几种: random(随机算法) localPref(本地优先算法) roundRobin(轮询算法) consistentHash(一致性hash算法) 所以我们接 ...

  6. Linux 常用命令及详解

    1.  type   :查询命令 是否属于shell解释器2.  help  : 帮助命令3.  man : 为所有用户提供在线帮助4.  ls  : 列表显示目录内的文件及目录-l    以长格式显 ...

  7. SpringMVC项目案例之---数据的获取与显示

    数据的获取与显示 (一)功能 1.对用户输入的数据进行获取 2.将获取的数据显示到页面 3.使用了SpringMVC技术的注解方式 4.使用了过滤器,处理中文乱码问题 5.在web.xml中设置了访问 ...

  8. luogu1220_关路灯 区间dp

    传送门 区间dp f[i][j][state] : [i, j]区间 state=0 当前选i state = 1 当前选j 注意枚举的顺序 转移的设计时 在同时刻不在[i,j]区间里的数也要考虑 不 ...

  9. Linux lsof工具介绍

    引言 在<Linux fuser工具介绍>一文中,与大家一起学习了fuser工具的使用方法."lsof"——list open files,lsof也是Linux下用于 ...

  10. 帝国CMS(EmpireCMS) v7.5后台getshell分析(CVE-2018-18086)

    帝国CMS(EmpireCMS) v7.5后台getshell分析(CVE-2018-18086) 一.漏洞描述 EmpireCMS 7.5版本及之前版本在后台备份数据库时,未对数据库表名做验证,通过 ...