首页 > 其他分享 >循环神经网络--基于pytorch框架

循环神经网络--基于pytorch框架

时间:2023-09-05 21:01:51浏览次数:45  
标签:state -- torch 神经网络 pytorch num device net size

import matplotlib.pyplot as plt
import math
import torch
from torch import nn
from torch.nn import functional as f
from d2l import torch as d2l

batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)

print(f.one_hot(torch.tensor([0, 2]), len(vocab)))

x = torch.arange(10).reshape((2, 5))
print(f.one_hot(x.T, 28).shape)


# 初始化模型参数

def get_params(vocab_size, num_hidden, device):
    num_inputs = num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    # 隐藏层参数
    w_xh = normal((num_inputs, num_hidden))
    w_hh = normal((num_hidden, num_hidden))
    b_h = torch.zeros(num_hidden, device=device)

    # 输出层参数
    w_hq = normal((num_hidden, num_outputs))
    b_hq = torch.zeros(num_outputs, device=device)

    # 附加梯度
    params = [w_xh, w_hh, b_h, w_hq, b_hq]
    for param in params:
        param.requires_grad_(True)
    return params


# 构造网络

def init_rnn_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),)


def rnn(inputs, state, params):
    w_xh, w_hh, b_h, w_hq, b_q = params
    h, = state
    outputs = []

    # x的形状(批量大小,词表大小)
    for x in inputs:
        h = torch.tanh(torch.mm(x, w_xh) + torch.mm(h, w_hh) + b_h)
        y = torch.mm(h, w_hq) + b_q
        outputs.append((y))
    return torch.cat(outputs, dim=0), (h,)


class RNNModelScratch:  # @save
    """从零开始实现的循环神经网络模型"""

    def __init__(self, vocab_size, num_hidden, device,
                 get_params, init_state, forward_fn):
        self.vocab_size, self.num_hidden = vocab_size, num_hidden
        self.params = get_params(vocab_size, num_hidden, device)
        self.init_state, self.forward_fn = init_state, forward_fn

    def __call__(self, x, state):
        x = f.one_hot(x.T, self.vocab_size).type(torch.float32)
        return self.forward_fn(x, state, self.params)

    def begin_state(self, batch_size, device):
        return self.init_state(batch_size, self.num_hidden, device)


num_hidden = 512
net = RNNModelScratch(len(vocab), num_hidden, d2l.try_gpu(), get_params,
                      init_rnn_state, rnn)
state = net.begin_state(x.shape[0], d2l.try_gpu())
y, new_state = net(x.to(d2l.try_gpu()), state)

print(y.shape, len(new_state), new_state[0].shape)


# 训练预测

def predict_ch8(prefix, num_preds, net, vocab, device):
    """在prefix后面生成新字符"""
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix[0]]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))

    for y in prefix[1:]:  # 预热期
        _, state = net(get_input(), state)
        outputs.append(vocab[y])

    for _ in range(num_preds):  # 预测num_preds步
        y, state = net(get_input(), state)
        outputs.append(int(y.argmax(dim=1).reshape(1)))
    return ''.join([vocab.idx_to_token[i] for i in outputs])


print(predict_ch8('time traveller ', 10, net, vocab, d2l.try_gpu()))


def grad_clipping(net, theta):  # @save
    """裁剪梯度"""
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params
    norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm


# 训练

# @save
def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):
    """训练网络一个迭代周期(定义见第8章)"""
    state, timer = None, d2l.Timer()
    metric = d2l.Accumulator(2)  # 训练损失之和,词元数量
    for X, Y in train_iter:
        if state is None or use_random_iter:
            # 在第一次迭代或使用随机抽样时初始化state
            state = net.begin_state(batch_size=X.shape[0], device=device)
        else:
            if isinstance(net, nn.Module) and not isinstance(state, tuple):
                # state对于nn.GRU是个张量
                state.detach_()
            else:
                # state对于nn.LSTM或对于我们从零开始实现的模型是个张量
                for s in state:
                    s.detach_()

        y = Y.T.reshape(-1)
        X, y = X.to(device), y.to(device)
        y_hat, state = net(X, state)
        l = loss(y_hat, y.long()).mean()

        if isinstance(updater, torch.optim.Optimizer):
            updater.zero_grad()
            l.backward()
            grad_clipping(net, 1)
            updater.step()
        else:
            l.backward()
            grad_clipping(net, 1)
            # 因为已经调用了mean函数
            updater(batch_size=1)
        metric.add(l * y.numel(), y.numel())

    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()


# @save
def train_ch8(net, train_iter, vocab, lr, num_epochs, device,
              use_random_iter=False):
    """训练模型(定义见第8章)"""
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
                            legend=['train'], xlim=[10, num_epochs])
    # 初始化
    if isinstance(net, nn.Module):
        updater = torch.optim.SGD(net.parameters(), lr)
    else:
        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
    predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
    # 训练和预测
    for epoch in range(num_epochs):
        ppl, speed = train_epoch_ch8(
            net, train_iter, loss, updater, device, use_random_iter)
        if (epoch + 1) % 10 == 0:
            print(predict('time traveller'))
            animator.add(epoch + 1, [ppl])
    print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
    print(predict('time traveller'))
    print(predict('traveller'))
    plt.show()

num_epochs, lr = 500, 1
train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())

 

标签:state,--,torch,神经网络,pytorch,num,device,net,size
From: https://www.cnblogs.com/o-Sakurajimamai-o/p/17680754.html

相关文章

  • Java中的多态
    多态使用注意事项(1) (2)通俗一点,就是重写后的优先级更高,记住这点就好。默认状态下还是父亲优先 (3) (4)类型强制转换操作ps.Dog和Cat继承于Animal 1 //Animala=newDog();  1Animala=newCat(); ainstanceofDog方法用于判断a是否是Dog类型(ps.Dog是个类)----如果......
  • 如何在Vue项目中引入富文本编辑器(wang-enduit)
    介绍官网https://www.wangeditor.com/安装yarnadd@wangeditor/editornpminstall@wangeditor/editor--saveyarnadd@wangeditor/editor-for-vue@nextnpminstall@wangeditor/editor-for-vue@next--save使用自定义上传图片,先转base64,转blob,上传服务器<divid="wa......
  • 第十六章 异常机制和File类
    16.1异常机制(重点)16.1.1基本概念异常就是"不正常"的含义,在Java语言中主要指程序执行中发生的不正常情况。java.lang.Throwable类是Java语言中错误(Error)和异常(Exception)的超类。其中Error类主要用于描述Java虚拟机无法解决的严重错误,通常无法编码解决,如:JVM挂掉了等。......
  • Go 语言请求DNS解析结果
    packageksyunwarningimport("context""fmt""net""time")//LookupDomainNameIp使用net包做DNS解析请求funcLookupDomainNameIp(domainString,nameServerstring)(dst[]string){r:=&net.Resolve......
  • obce_4
    #部署obcd/root/t-oceanbase-antmanvi3ecs-3ob-cluster.yamluser:user:rootpassword:Xg8Sp1Ex4V#key_file:yourssh-keyfilepathifneedport:22#timeout:sshconnectiontimeout(second),default30oceanbase:servers:-name:ob1#Please......
  • obce_5
    cd/root/t-oceanbase-antmanvi3ecs-3ob.yamluser:username:rootpassword:Ct1Wc9Jd3Poceanbase:servers:-name:ob1ip:172.16.1.27-name:ob2ip:172.16.1.28-name:ob3ip:172.16.1.29obproxy:depends:-oceanbaseservers:-name:obproxy1ip:172.......
  • MyBatisPlus翻新bug记录
    今天把老项目翻新成使用MyBatisPlus.偶遇bug.LambdaUpdateWrapper<AddressBook>wrapper=newLambdaUpdateWrapper<>();wrapper.set(AddressBook::getIsDefault,0);wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());addressBookMapper.update(null,wrapper)......
  • 梁继璋<<给孩子的一封信>>
    香港一位著名电台主持人梁继璋,给他儿子写过这样一封信,这封信就说到了爱和对儿子的责任。内容如下,首先写这封信是基于以下的三个原则。第一,人生祸福无常。谁也不知道可以活多久,有些事情还是早一点说好。这是我为什么给你写个备忘录。第二,我是你父亲,我不跟你说,没有人跟你说。......
  • 数据结构代码题-链表
    链表单链表单链表结构体的声明:typedefstructLink{ intdata;//代表数据域 structLink*next;//代表指针域,指向直接后继元素}link;//link为节点名,每个结点都是一个link结构体另一种:typedefstructLNode{ElemTypedata;structLNode*next;}LNode,*Link......
  • obce_6
    切换web-terminalcd/root/t-oceanbase-antmanvim1ecs-1ob-cluster.yamluser:username:rootpassword:password#这里请修改为ecs的登陆密码port:22……oceanbase:servers:-172.23.xxx.xx#修改为ecs分配的ip地址……obproxy:depends:-oceanbaseservers:-......