深度学习之 rnn 台词生成

深度学习之 rnn 台词生成

写一个台词生成的程序,用 pytorch 写的。

import os
def load_data(path):
    with open(path, 'r', encoding="utf-8") as f:
        data = f.read()
    return data

text = load_data('./moes_tavern_lines.txt')[81:]

train_count = int(len(text) * 0.6)
val_count = int(len(text) * 0.2)
test_count = int(len(text) * 0.2)

train_text = text[:train_count]
val_text = text[train_count: train_count + val_count]
test_text = text[train_count + val_count:]

view_sentence_range = (0, 10)

import numpy as np

print("data set State")
print("Roughly the number of unique words: {}".format(len({word: None for word in text.split()})))
scenes = text.split("\n\n")
print("number of scenes: {}".format(len(scenes)))
sentence_count_scene = [scene.count('\n') for scene in scenes]
print('Average number for sentences in each scene: {}'.format(np.average(sentence_count_scene)))

sentences = [sentence for scene in scenes for sentence in scene.split('\n')]
print("Number for lines: {}".format(len(sentences)))
word_count_sentence = [len(sentence.split()) for sentence in sentences]
print('Average number for words in each line: {}'.format(np.average(word_count_sentence)))

print()
print('The sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))

def token_lookup():
    return {
        '.': '||Period||',
        ',': '||Comma||',
        '"': '||Quotation_Mark||',
        ';': '||Semicolon||',
        '!': '||Exclamation_mark||',
        '?': '||Question_mark||',
        '(': '||Left_Parentheses||',
        ')': '||Right_Parentheses||',
        '--': '||Dash||',
        '\n': '||Return||',
    }

import os
import torch

class Dictionary(object):
    def __init__(self):
        self.word2idx = {}
        self.idx2word = []

    def add_word(self, word):
        if word not in self.word2idx:
            self.idx2word.append(word)
            self.word2idx[word] = len(self.idx2word) - 1
        return self.word2idx[word]

    def __len__(self):
        return len(self.idx2word)

class Corpus(object):
    def __init__(self, train, val, test):
        self.dictionary = Dictionary()
        self.train = self.tokenize(train)
        self.valid = self.tokenize(val)
        self.test = self.tokenize(test)

    def tokenize(self, text):
        words = text.split()
        tokens = len(words)
        token = 0
        ids = torch.LongTensor(tokens)
        for i, word in enumerate(words):
            self.dictionary.add_word(word)
            ids[i] = self.dictionary.word2idx[word]

        return ids

import numpy as np
import torch

i_dict = token_lookup()

def create_data(text):
    vocab_to_int = {}
    int_to_vocab = {}

    new_text = ""
    for t in text:
        if t in token_lookup():
            new_text += " {} ".format(i_dict[t])
        else:
            new_text += t

    return new_text

import torch
import torch.nn as nn
from torch.autograd import Variable

# 模型 RNN
class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, n_layers=1):
        super(RNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_layers = n_layers

        self.drop = nn.Dropout(0.5)

        self.encoder = nn.Embedding(input_size, hidden_size)

        self.gru = nn.GRU(hidden_size, hidden_size, n_layers)

        self.decoder = nn.Linear(hidden_size, output_size)

    def forward(self, input, hidden):
        input = self.encoder(input)
        output, hidden = self.gru(input, hidden)
        output = self.drop(output)
        decoded = self.decoder(output.view(output.size(0) * output.size(1), output.size(2)))
        return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden

    def init_hidden(self, batch_size):
        return Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size))

# batch 化
def batchify(data, bsz):
    # Work out how cleanly we can divide the dataset into bsz parts.
    nbatch = data.size(0) // bsz
    # Trim off any extra elements that wouldn't cleanly fit (remainders).
    data = data.narrow(0, 0, nbatch * bsz)
    # Evenly divide the data across the bsz batches.
    data = data.view(bsz, -1).t().contiguous()

    return data

n_epochs = 3500
print_every = 500
plot_every = 10
hidden_size = 100
n_layers = 1
lr = 0.005
chunk_len = 10
batch_size = 20
val_batch_size = 10

# 数据生成
train_data = create_data(train_text)
test_data = create_data(test_text)
val_data = create_data(val_text)

corpus = Corpus(train_data, val_data, test_data)

train_source = batchify(corpus.train, batch_size)
test_source = batchify(corpus.test, batch_size)
val_source = batchify(corpus.valid, batch_size)

n_tokens = len(corpus.dictionary)

# 模型
model = RNN(n_tokens, hidden_size, n_tokens, n_layers)

# 优化器
optimizer = torch.optim.Adam(model.parameters(), lr=lr)

# 损失函数
criterion = nn.CrossEntropyLoss()

#
def get_batch(source, i , evaluation = False):
    seq_len = min(chunk_len, len(source) - 1 - i)
    data = Variable(source[i:i+seq_len], volatile=evaluation)
    target = Variable(source[i+1:i+1+seq_len].view(-1))
    return data,target

def repackage_hidden(h):
    if type(h) == Variable:
        return Variable(h.data)
    else:
        return tuple(repackage_hidden(v) for v in h)

# 训练
def train():
    model.train()
    total_loss = 0

    ntokens = len(corpus.dictionary)
    hidden = model.init_hidden(batch_size)
    for batch, i in enumerate(range(0, train_source.size(0) - 1, chunk_len)):
        data, targets = get_batch(train_source, i)

        hidden = repackage_hidden(hidden)
        optimizer.zero_grad()
        output, hidden = model(data, hidden)
        loss = criterion(output.view(-1, ntokens), targets)
        loss.backward()
        optimizer.step()

        total_loss += loss.data

        if batch % 10 == 0:
            print('epoch {}/{} {}'.format(epoch, batch, loss.data))

# 验证
def evaluate(data_source):
    model.eval()
    total_loss = 0

    ntokens = len(corpus.dictionary)
    hidden = model.init_hidden(batch_size)
    for i in range(0, data_source.size(0) - 1, chunk_len):
        data, targets = get_batch(data_source, i, evaluation=True)

        output, hidden = model(data, hidden)
        output_flat = output.view(-1, ntokens)
        total_loss += len(data) * criterion(output_flat, targets).data
        hidden = repackage_hidden(hidden)

    return total_loss[0] / len(data_source)

import time, math

# 开始训练
for epoch in range(1, n_epochs + 1):
    train()
    val_loss = evaluate(val_source)
    print("epoch {} {} {}".format(epoch, val_loss, math.exp(val_loss)))

# 生成一段短语
def gen(n_words):
    model.eval()
    ntokens = len(corpus.dictionary)
    hidden = model.init_hidden(1)

    input = Variable(torch.rand(1, 1).mul(ntokens).long(), volatile=True)

    words = []
    for i in range(n_words):
        output, hidden = model(input, hidden)
        word_weights = output.squeeze().data.exp().cpu()
        word_idx = torch.multinomial(word_weights, 1)[0]
        input.data.fill_(word_idx)

        word = corpus.dictionary.idx2word[word_idx]

        isOk = False
        for w,s in i_dict.items():
            if s == word:
                isOk = True
                words.append(w)
                break

        if not isOk:
            words.append(word)

    return words

words = gen(1000)
print(" ".join(words))

总结

rnn 总是参数不怎么对,耐心调整即可。

原文地址:https://www.cnblogs.com/htoooth/p/8663618.html

时间: 2024-08-27 08:07:55

深度学习之 rnn 台词生成的相关文章

用深度学习技术FCN自动生成口红

1 这个是什么? ???????基于全卷积神经网络(FCN)的自动生成口红Python程序. 图1 FCN生成口红的效果(注:此两张人脸图来自人脸公开数据库LFW) 2 怎么使用了? ???????首先能从这个Github (https://github.com/Kalafinaian/ai_lips_makeup) 中下载这个python项目.下载解压后你得到这样一个程序. 图2 口红Python程序 ???????本项目的运行环境为Python3.6,需要的深度学习包tensorflow ,

斯坦福大学深度学习与自然语言处理第一讲:引言

斯坦福大学在三月份开设了一门"深度学习与自然语言处理"的课程:CS224d: Deep Learning for Natural Language Processing ,授课老师是青年才俊Richard Socher,他本人是德国人,大学期间涉足自然语言处理,在德国读研时又专攻计算机视觉,之后在斯坦福大学攻读博士学位,拜师NLP领域的巨牛 Chris Manning和Deep Learning 领域的巨牛 Andrew Ng ,其博士论文是< Recursive Deep Le

斯坦福大学深度学习与自然语言处理第一讲

我学习自然语言是从Christopher D.Manning的统计自然语言处理基础这本书开始的,很多文本分析也是应用统计方法,或者机器学习的方法,而近年来深度学习逐渐渗入各个领域,其在自然语言处理领域中也取得了令人惊叹的效果,这成功的引起了我的重视,决定学习一下.何其所幸,让我找到了斯坦福大学深度学习与自然语言的课程,深得我心啊,所以打算好好学习一下,鉴于我爱自然语言处理中有相关课程的slides,我就直接复制粘贴了,接下来打算做的工作是对该课程中推荐阅读的部分论文做一些笔记.本人才疏学浅,专业

机器学习和深度学习资料合集

机器学习和深度学习资料合集 注:机器学习资料篇目一共500条,篇目二开始更新 希望转载的朋友,你可以不用联系我.但是一定要保留原文链接,因为这个项目还在继续也在不定期更新.希望看到文章的朋友能够学到更多.此外:某些资料在中国访问需要梯子. <Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost到随机森林.Deep Learning. <Deep Learning in

[转]机器学习和深度学习资料汇总【01】

本文转自:http://blog.csdn.net/sinat_34707539/article/details/52105681 <Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost到随机森林.Deep Learning. <Deep Learning in Neural Networks: An Overview> 介绍:这是瑞士人工智能实验室Jurgen

机器学习与深度学习资料

<Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost到随机森林.Deep Learning. <Deep Learning in Neural Networks: An Overview> 介绍:这是瑞士人工智能实验室Jurgen Schmidhuber写的最新版本<神经网络与深度学习综述>本综述的特点是以时间排序,从1940年开始讲起,到60-80

CNCC2017中的深度学习与跨媒体智能

转载请注明作者:梦里茶 目录 机器学习与跨媒体智能 传统方法与深度学习 图像分割 小数据集下的深度学习 语音前沿技术 生成模型 基于贝叶斯的视觉信息编解码 珠算:基于别噎死推断的深度生成模型库 图像与视频生成的规则约束 景深风景生成 骨架约束的人体视频生成 跨媒体智能 视频检索的哈希学习 多媒体与知识图谱 基于锚图的视觉数据分析 视频问答 细粒度分类 跨媒体关联与检索(待补充) 正片开始 传统方法与深度学习 图像分割 图像分割是医疗图像中一个很重要的任务,通常分为分割,配准,可视化几个子任务.这

深度学习攻防对抗(JCAI-19 阿里巴巴人工智能对抗算法竞赛)

最近在参加IJCAI-19阿里巴巴人工智能对抗算法竞赛(点击了解),初赛刚刚结束,防御第23名,目标攻击和无目标攻击出了点小问题,成绩不太好都是50多名,由于找不到队友,只好一个人跟一群大佬PK,双拳难敌四手,差点自闭放弃比赛了.由于知道对抗攻击的人很少,于是抽空写篇博客,简单科普一下人工智能与信息安全的交叉前沿研究领域:深度学习攻防对抗. 然后简单介绍一下IJCAI-19 阿里巴巴人工智能对抗算法竞赛 目前,人脸识别.自动驾驶.刷脸支付.抓捕逃犯.美颜直播……人工智能与实体经济深度结合,彻底改

深度学习与自然语言处理(7)_斯坦福cs224d 语言模型,RNN,LSTM与GRU

翻译:@胡杨([email protected]) && @胥可([email protected]) 校对调整:寒小阳 && 龙心尘 时间:2016年7月 出处: http://blog.csdn.net/han_xiaoyang/article/details/51932536 http://blog.csdn.net/longxinchen_ml/article/details/51940065 说明:本文为斯坦福大学CS224d课程的中文版内容笔记,已得到斯坦福大学