文本生成项目(基于tensorflow1.14版本)

news2024/9/16 20:35:03

项目下载链接:链接: https://pan.baidu.com/s/1OfICplwlEtRBz_ta7Nwyyg?pwd=yr5c 提取码: yr5c 复制这段内容后打开百度网盘手机App,操作更方便哦 
--来自百度网盘超级会员v4的分享

1.模型代码:model.py

# -*- coding: utf-8 -*-
# file: model.py
# author: JinTian
# time: 07/03/2017 3:07 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
import tensorflow as tf
import numpy as np


def rnn_model(model, input_data, output_data, vocab_size, rnn_size=128, num_layers=2, batch_size=64,
              learning_rate=0.01):
    """
    construct rnn seq2seq model.
    :param model: model class
    :param input_data: input data placeholder
    :param output_data: output data placeholder
    :param vocab_size:
    :param rnn_size:
    :param num_layers:
    :param batch_size:
    :param learning_rate:
    :return:
    """
    end_points = {}

    if model == 'rnn':
        cell_fun = tf.contrib.rnn.BasicRNNCell
    elif model == 'gru':
        cell_fun = tf.contrib.rnn.GRUCell
    elif model == 'lstm':
        cell_fun = tf.contrib.rnn.BasicLSTMCell

    cell = cell_fun(rnn_size, state_is_tuple=True)
    cell = tf.contrib.rnn.MultiRNNCell([cell] * num_layers, state_is_tuple=True)

    if output_data is not None:
        initial_state = cell.zero_state(batch_size, tf.float32)
    else:
        initial_state = cell.zero_state(1, tf.float32)

    with tf.device("/cpu"):
        embedding = tf.get_variable('embedding', initializer=tf.random_uniform(
            [vocab_size + 1, rnn_size], -1.0, 1.0))
        inputs = tf.nn.embedding_lookup(embedding, input_data)

    # [batch_size, ?, rnn_size] = [64, ?, 128]
    outputs, last_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)
    output = tf.reshape(outputs, [-1, rnn_size])

    weights = tf.Variable(tf.truncated_normal([rnn_size, vocab_size + 1])) # 产生一个正态分布
    bias = tf.Variable(tf.zeros(shape=[vocab_size + 1]))
    # 预测值h
    logits = tf.nn.bias_add(tf.matmul(output, weights), bias=bias)
    # [?, vocab_size+1]

    if output_data is not None:
        # output_data must be one-hot encode 真实标签
        labels = tf.one_hot(tf.reshape(output_data, [-1]), depth=vocab_size + 1)
        # should be [?, vocab_size+1]

        loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)
        # loss shape should be [?, vocab_size+1]
        total_loss = tf.reduce_mean(loss)
        train_op = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)
        # gvs = train_op.compute_gradients(total_loss) # gvs:[(10000,w1),(10,b1),(0.001,w2),(1,b2)]
        # new_gvs = []
        # for i,j in gvs:
        #     new_gvs.append((tf.clip_by_value(i,-10,10), j))
        # train_op = train_op.apply_gradients(new_gvs)梯度裁剪


        end_points['initial_state'] = initial_state
        end_points['output'] = output
        end_points['train_op'] = train_op
        end_points['total_loss'] = total_loss
        end_points['loss'] = loss
        end_points['last_state'] = last_state
    else:
        prediction = tf.nn.softmax(logits)

        end_points['initial_state'] = initial_state
        end_points['last_state'] = last_state
        end_points['prediction'] = prediction

    return end_points

2.模型保存

小知识:保存模型方式有两种:1.只保存模型参数;2.保存模型结构和参数。

        1.只保存参数:加载的时候一定要实例化模型,不然没有结构。

        2.保存参数和模型:保存的比较大,占用内存大,一般不太使用。

3.model里四个文件:

        1.checkpoint:模型保存路径

        2.第二个模型参数

        3.第三个基本没用

        3.第四个是模型的图(模型结构图)

 

2.主程序代码

# -*- coding: utf-8 -*-
# file: main.py
# author: JinTian
# time: 11/03/2017 9:53 AM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
import os
import numpy as np
import tensorflow as tf
from poems.model import rnn_model
from poems.poems import process_poems, generate_batch

tf.flags.DEFINE_integer('batch_size',64, help='batch size.')#批次带线啊哦
tf.flags.DEFINE_float('learning_rate', 0.01, 'learning rate.')
tf.flags.DEFINE_string('model_dir', os.path.abspath('./model'), 'model save path.')#模型路径
tf.flags.DEFINE_string('file_path', os.path.abspath('./data/poems.txt'), 'file name of poems.')#数据路径
tf.flags.DEFINE_string('model_prefix', 'poems', 'model save prefix.')
tf.flags.DEFINE_integer('epochs', 10, 'train how many epochs.')#训练次数

FLAGS = tf.flags.FLAGS#实例化一下
#定义参数和路径

def run_training():
    if not os.path.exists(FLAGS.model_dir):
        os.makedirs(FLAGS.model_dir)

    poems_vector, word_to_int, vocabularies = process_poems(FLAGS.file_path)
    batches_inputs, batches_outputs = generate_batch(FLAGS.batch_size, poems_vector, word_to_int)

    input_data = tf.placeholder(tf.int32, [FLAGS.batch_size, None])
    output_targets = tf.placeholder(tf.int32, [FLAGS.batch_size, None])

    end_points = rnn_model(model='lstm', input_data=input_data, output_data=output_targets, vocab_size=len(
        vocabularies), rnn_size=128, num_layers=2, batch_size=64, learning_rate=FLAGS.learning_rate)

    saver = tf.train.Saver(tf.global_variables())
    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    with tf.Session() as sess:
        # sess = tf_debug.LocalCLIDebugWrapperSession(sess=sess)
        # sess.add_tensor_filter("has_inf_or_nan", tf_debug.has_inf_or_nan)
        sess.run(init_op)

        start_epoch = 0
        checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir)#间接训练,判断之前是否有模型,如果有就在之前基础进行训练
        if checkpoint:
            saver.restore(sess, checkpoint)#读出来模型
            print("## restore from the checkpoint {0}".format(checkpoint))
            start_epoch += int(checkpoint.split('-')[-1])
        print('## start training...')
        try:
            for epoch in range(start_epoch, FLAGS.epochs):
                n = 0
                n_chunk = len(poems_vector) // FLAGS.batch_size
                for batch in range(n_chunk):
                    loss, _, _ = sess.run([
                        end_points['total_loss'],
                        end_points['last_state'],
                        end_points['train_op']
                    ], feed_dict={input_data: batches_inputs[n], output_targets: batches_outputs[n]})
                    n += 1
                    print('Epoch: %d, batch: %d, training loss: %.6f' % (epoch, batch, loss))
                if epoch % 6 == 0:
                    saver.save(sess, os.path.join(FLAGS.model_dir, FLAGS.model_prefix), global_step=epoch)
        except KeyboardInterrupt:
            print('## Interrupt manually, try saving checkpoint for now...')
            saver.save(sess, os.path.join(FLAGS.model_dir, FLAGS.model_prefix), global_step=epoch)
            print('## Last epoch were saved, next time will start from epoch {}.'.format(epoch))


def main(_):
    run_training()


if __name__ == '__main__':
    tf.app.run()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/102657.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Qemu中SylixOS与VMware中Linux的通信链路搭建

1.适用范围 在与客户沟通交流后,ECSM管理Linux端docker及Linux与SylixOS间通信也成了客户比较关心的一部分。因此为了能够更好地给客户提供演示,必然需要搭建一套具有ECSM、SylixOS、linux的环境。 如果通过硬件搭建,一是携带麻烦&#xff0…

表哥推荐python自学书籍:从入门到精通,读这十本书就够了!

前言 人生苦短,我学python。 python编程语言在各种榜单上经常拿到前列位置,在全球范围内都非常受欢迎。 Python作为一种不受局限、跨平台的开源编程语言,其数据处理速度快、功能强大且简单易学。而且,Python采用解释运行的方式…

风电机组的预测性维护应该如何进行?

一、应用背景 风能是最重要的清洁能源之一,大力发展风电等清洁能源是实现国家可持续发展战略的必然选择。发展风电、光伏等新能源的高效运维技术已成为当前电力系统面临的重要问题之一。在风电机组单机容量较大、机组整体结构越来越复杂、各部件之间的耦合也愈加紧…

零基础入门智能射频——偶极子天线等效电路模型分析

1.前言 无人机的安全防范和管控,已经成为无人机行业的重点内容。无人机探测解决方案已经变得非常重要。前面系列文章给出了针对无人机侦察和干扰无人机的天线阵设计,上一期文章中,我们给出一种小型化的无人机侦测天线,每个阵元都…

GIS开发入坑(四)--QGIS导入POI数据并实现简单处理分析

POI数据,英文全称Point of Intersesting,中文的意思是兴趣点,指的是在地图上有意义的点:比如商店、酒吧、加油站、医院、车站等。POI数据能够赋能时空行为、城市规划、地理信息等研究,因此获取准而全的POI数据是开展科…

ChatGPT:你才是编译器!你全家都是编译器!

我是不是再也不需要编译器了?!这个故事的灵感来自一个类似的文章:在 ChatGPT 中构建虚拟机。我印象深刻并决定尝试类似的东西,但这次不是 Linux 命令行工具,而是让 ChatGPT 成为我们的 Python 编译器。这是初始化 Chat…

论文投稿指南——中文核心期刊推荐(数学)

【前言】 🚀 想发论文怎么办?手把手教你论文如何投稿!那么,首先要搞懂投稿目标——论文期刊 🎄 在期刊论文的分布中,存在一种普遍现象:即对于某一特定的学科或专业来说,少数期刊所含…

如何制作HTML网页设计【体育运动主题网站——中国篮球NBA】

🎉精彩专栏推荐 💭文末获取联系 ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 💂 作者主页: 【主页——🚀获取更多优质源码】 🎓 web前端期末大作业: 【📚毕设项目精品实战案例 (10…

中文社区面对面|明晚8点,CTO带你上手Jina产品!

文章导读 中文社区面对面是 Jina AI 在今年7月首次推出的栏目,旨在为社区用户提供支持并倾听用户的反馈,以帮助开发者更快速地了解 Jina 生态,更轻松地构建和部署自己的多模态应用,同时也帮助我们更好地提升产品的使用体验。第五期…

【Python机器学习】全连接层与非线性回归、防止过拟合方法的讲解及实战( 附源码)

需要全部代码请点赞关注收藏后评论区留言私信~~~ 全连接层与非线性回归 基于全连接层构建的多层神经网络能够用来完成回归和分类人物,在神经网络中一般用下图所示画法来表示神经元模型,神经元由输入层和输出层组成&am…

SPI协议详解

SPI协议详解前言一、SPI简介二、接口三、SPI总线个特点:(一)主从模式(二)同步传输(三)全双工串行通信(数据传输高位在前,低位在后)四、SPI总线传输的4种模式&…

[附源码]计算机毕业设计Python贵港高铁站志愿者服务平台(程序+源码+LW文档)

该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程 项目运行 环境配置: Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术: django python Vue 等等组成,B/S模式 pychram管理等…

分词并显示词性jieba.posseg.cut()

【小白从小学Python、C、Java】【计算机等级考试500强双证书】 【Python-数据分析】 分词并显示词性 jieba.posseg.cut() [太阳]选择题 以下python代码结果错误的一项是? import jieba.posseg as pseg words pseg.cut("我爱北京天安门") for word, flag in words: …

【docker】Comopse安装

Compose安装 1、下载 2、授权 Compose初体验 地址:Try Docker Compose | Docker Documentation 1、应用app.py 2、DockerFile 应用打包为镜像 3、Docker-compose yaml文件(定义整个服务,需要的环境,web、redis)完…

从输入URL到渲染的完整过程

浏览器有一个重要的安全策略,称之为「同源策略」 其中,源协议主机端口,**两个源相同,称之为同源,两个源不同,称之为跨源或跨域 同源策略是指,若页面的源和页面运行过程中加载的源不一致时&…

[附源码]Nodejs计算机毕业设计江西婺源旅游文化推广系统Express(程序+LW)

该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程。欢迎交流 项目运行 环境配置: Node.js Vscode Mysql5.7 HBuilderXNavicat11VueExpress。 项目技术: Express框架 Node.js Vue 等等组成,B/S模式 Vscode管理前后端分…

Spring面试基础

目录1. 你认为Spring的核心是什么2. 如何理解约定优于配置3. spring boot starter有什么用4. Spring用到了哪些设计模式5. Springboot的启动流程6. Spring Boot自动装配的过程7. Spring Boot注解7.1. SpringBootApplication注解7.2 Import注解7.3 Conditional注解8. Spring的核…

栈和队列面试题讲解(有效的括号、用队列实现栈、用栈实现队列、设计循环队列)

今天,我将带来栈和队列的面试题讲解。 目录有效的括号:[链接](https://leetcode.cn/problems/valid-parentheses/)用队列实现栈:[链接](https://leetcode.cn/problems/implement-stack-using-queues/)用栈实现队列:[链接](https:/…

电脑重装系统之后风扇一直很响如何优化

​在电脑温度升高时,风扇就会开始转动散热,但是如果电脑根本没有运行什么程序,风扇也一直转,那可能就是设置问题了,下面小编教大家Win11笔记本风扇一直转的解决方法。 工具/原料: 系统版本:wi…

传统制造业数字化转型6大关键

在当今的数字时代,“云移动”深刻影响着每个人的生活方式和每个企业的运营模式。随着互联网的日益普及,计算和存储能力的快速发展,物联网和传感器技术的广泛应用,以及工业软件的不断演进,数据采集、存储、传输、显示、…