import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim class RNN(nn.Module): def __init__(self,input_dim , hidden_dim , out_dim):
super(RNN,self).__init__()
self.linear_1 = nn.Linear(input_dim , hidden_dim)
self.linear_2 = nn.Linear(hidden_dim , hidden_dim)
self.linear_3 = nn.Linear(hidden_dim, out_dim) self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
self.hidden_size = hidden_dim def forward(self, input , hidden_input):
input = input.view(1, 1, -1)
hy = self.relu(self.linear_1(input) + self.linear_2(hidden_input))
output = self.sigmoid(self.linear_3(hy))
return output , hy def init_weight(self):
nn.init.normal_(self.linear_1.weight.data , 0 , np.sqrt(2 / 16))
nn.init.uniform_(self.linear_1.bias, 0, 0) nn.init.normal_(self.linear_2.weight.data, 0, np.sqrt(2 / 16))
nn.init.uniform_(self.linear_2.bias, 0, 0) nn.init.normal_(self.linear_3.weight.data , 0 , np.sqrt(2 / 16))
nn.init.uniform_(self.linear_3.bias, 0, 0)
def init_hidden(self):
return torch.zeros([1,1,self.hidden_size]) def train(input_seq , target, encoder , optim , criterion ,max_length):
optim.zero_grad()
hidden = encoder.init_hidden()
encoder_outputs = torch.zeros(max_length)
for ndx in range(max_length):
x_in = torch.Tensor([input_seq[0][ndx] , input_seq[1][ndx]])
output , hidden = encoder(x_in , hidden)
encoder_outputs[ndx] = output[0,0] target = torch.Tensor(target)
loss = criterion(encoder_outputs, target)
loss.backward()
optim.step() return loss , encoder_outputs def trainIter(batch_x , batch_y , encoder , max_length,learning_rate): encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
loss = 0
predict = np.zeros([batch_size , max_length])
for ndx in range(len(batch_x)):
loss_ , encoder_outputs = train(batch_x[ndx],batch_y[ndx], encoder ,encoder_optimizer,criterion, max_length)
loss += loss_
predict[ndx] = encoder_outputs.detach().numpy()
return loss , predict def getBinDict(bit_size = 16):
max = pow(2,bit_size)
bin_dict = {}
for i in range(max):
s = '{:016b}'.format(i)
arr = np.array(list(reversed(s)))
arr = arr.astype(int)
bin_dict[i] = arr
return bin_dict binary_dim = 16
int2binary = getBinDict(binary_dim) def getBatch( batch_size , binary_size):
x = np.random.randint(0,256,[batch_size , 2])
batch_x = np.zeros([batch_size , 2,binary_size] )
batch_y = np.zeros([batch_size , binary_size])
for i in range(0 , batch_size):
batch_x[i][0] = int2binary[x[i][0]]
batch_x[i][1] = int2binary[x[i][1]]
batch_y[i] = int2binary[x[i][0] + x[i][1]]
return batch_x , batch_y , [a + b for a,b in x] def getInt(y , bit_size):
arr = np.zeros([len(y)])
for i in range(len(y)):
for j in range(bit_size):
arr[i] += (int(y[i][j]) * pow(2 , j))
return arr if __name__ == '__main__':
input_size = 2
hidden_size = 8
batch_size = 100
net = RNN(input_size, hidden_size , 1)
net.init_weight()
print(net)
for i in range(100000):
net.zero_grad()
h0 = torch.zeros(1, batch_size, hidden_size)
x , y , t = getBatch(batch_size , binary_dim)
loss , outputs = trainIter(x , y , net , binary_dim , 0.01)
print('iterater:%d loss:%f' % (i, loss))
if i % 100== 0:
output2 = np.round(outputs)
result = getInt(output2,binary_dim)
print(t ,'\n', result) print('iterater:%d loss:%f'%(i , loss))

pytorch rnn 2的更多相关文章

  1. pytorch rnn

    温习一下,写着玩. import torch import torch.nn as nn import numpy as np import torch.optim as optim class RN ...

  2. [PyTorch] rnn,lstm,gru中输入输出维度

    本文中的RNN泛指LSTM,GRU等等 CNN中和RNN中batchSize的默认位置是不同的. CNN中:batchsize的位置是position 0. RNN中:batchsize的位置是pos ...

  3. pytorch --Rnn语言模型(LSTM,BiLSTM) -- 《Recurrent neural network based language model》

    论文通过实现RNN来完成了文本分类. 论文地址:88888888 模型结构图: 原理自行参考论文,code and comment: # -*- coding: utf-8 -*- # @time : ...

  4. pytorch RNN层api的几个参数说明

    classtorch.nn.RNN(*args, **kwargs) input_size – The number of expected features in the input x hidde ...

  5. 机器翻译注意力机制及其PyTorch实现

    前面阐述注意力理论知识,后面简单描述PyTorch利用注意力实现机器翻译 Effective Approaches to Attention-based Neural Machine Translat ...

  6. PyTorch专栏(六): 混合前端的seq2seq模型部署

    欢迎关注磐创博客资源汇总站: http://docs.panchuang.net/ 欢迎关注PyTorch官方中文教程站: http://pytorch.panchuang.net/ 专栏目录: 第一 ...

  7. 混合前端seq2seq模型部署

    混合前端seq2seq模型部署 本文介绍,如何将seq2seq模型转换为PyTorch可用的前端混合Torch脚本.要转换的模型来自于聊天机器人教程Chatbot tutorial. 1.混合前端 在 ...

  8. “你什么意思”之基于RNN的语义槽填充(Pytorch实现)

    1. 概况 1.1 任务 口语理解(Spoken Language Understanding, SLU)作为语音识别与自然语言处理之间的一个新兴领域,其目的是为了让计算机从用户的讲话中理解他们的意图 ...

  9. Pytorch系列教程-使用字符级RNN生成姓名

    前言 本系列教程为pytorch官网文档翻译.本文对应官网地址:https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutor ...

随机推荐

  1. 重新=》easyui DataGrid是否可以动态的改变列显示的顺序

    $.extend($.fn.datagrid.methods,{ columnMoving: function(jq){ return jq.each(function(){ var target = ...

  2. C++ 匿名对象产生场景

    //匿名对象产生的三种场景 #include<iostream> using namespace std; class Point{ public: Point(int a,int b){ ...

  3. 【BZOJ】1028: [JSOI2007]麻将(贪心+暴力)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1028 表示不会贪心QAQ 按顺序枚举,如果能形成刻子那么就形成刻子,否则形成顺子.orz 证明?:因 ...

  4. Elasticsearch JVM Heap Size大于32G,有什么影响?

    0.引言 在规划ES部署的时候,会涉及到data node的分配堆内存大小,而Elasticsearch默认安装后设置的内存是1GB,对于任何一个业务部署来说,这个都太小了. 设置Heap Size的 ...

  5. Struts2_day02--Struts2封装获取表单数据方式

    Struts2封装获取表单数据方式 原始方式获取表单封装到实体类对象 属性封装(会用) 1 直接把表单提交属性封装到action的属性里面 2 实现步骤 (1)在action成员变量位置定义变量 - ...

  6. C#,C++Dll文件调用心得

    C#下: 1.新建-->项目-->控制台应用程序:填写各种名称之后项目新建成功:一下为默认生成方式. 2.如下,在Program.cs中添加如下代码: using System;using ...

  7. js中什么是闭包?

    闭包是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分.

  8. JAVA上百实例源码网站

    JAVA源码包1JAVA源码包2JAVA源码包3JAVA源码包4 JAVA开源包1 JAVA开源包2 JAVA开源包3 JAVA开源包4 JAVA开源包5 JAVA开源包6 JAVA开源包7 JAVA ...

  9. Redesign Your App for iOS 7 之 页面布局

    Redesign Your App for iOS 7 之 页面布局 http://www.vinqon.com/codeblog/?detail/11109

  10. JS内存泄漏排查方法-Chrome Profiles

    原文链接:http://caibaojian.com/chrome-profiles.html 一.概述 Google Chrome浏览器提供了非常强大的JS调试工具,Heap Profiling便是 ...