模型搭建练习2_实现nn模块、optim、two_layer、dynamic_net
用variable实现nn.module
import torch
from torch.autograd import Variable N, D_in, H, D_out = 64, 1000, 100, 10 x = Variable(torch.randn(N, D_in))
y = Variable(torch.randn(N, D_out), requires_grad=False) model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out),
) loss_fn = torch.nn.MSELoss(size_average=False) learning_rate = 1e-4
for t in range(2):
# Forward pass
y_pred = model(x) loss = loss_fn(y_pred, y)
# Zero the gradients before running the backward pass.
model.zero_grad()
# Backward pass: compute gradient of the loss with respect to all the learnable
# parameters of the model. Internally, the parameters of each Module are stored
# in Variables with requires_grad=True, so this call will compute gradients for
# all learnable parameters in the model.
loss.backward() # Update the weights using gradient descent. Each parameter is a Variable
for param in model.parameters():
param.data -= learning_rate * param.grad.data
实现optim
import torch
from torch.autograd import Variable N, D_in, H, D_out = 64, 1000, 100, 10
x = Variable(torch.randn(N, D_in))
y = Variable(torch.randn(N, D_out), requires_grad=False) model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out),
)
loss_fn = torch.nn.MSELoss(size_average=False) learning_rate = 1e-4
# Use the optim package to define an Optimizer that will update the weights of
# the model for us.
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(500):
# Forward pass: compute predicted y by passing x to the model.
y_pred = model(x)
loss = loss_fn(y_pred, y)
# Before the backward pass, use the optimizer object to zero all of the
# gradients for the variables it will update (which are the learnable weights
# of the model)
optimizer.zero_grad()
# Backward pass: compute gradient of the loss with respect to model
# parameters
loss.backward()
# Calling the step function on an Optimizer makes an update to its
# parameters
optimizer.step()
实现two_layer模型
import torch
from torch.autograd import Variable class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x):
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred N, D_in, H, D_out = 64, 1000, 100, 10
x = Variable(torch.randn(N, D_in))
y = Variable(torch.randn(N, D_out), requires_grad=False) model = TwoLayerNet(D_in, H, D_out)
criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
for t in range(2):
y_pred = model(x)
loss = criterion(y_pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
实现dynamic_net
import random
import torch
from torch.autograd import Variable class DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out) def forward(self, x):
h_relu = self.input_linear(x).clamp(min=0)
for _ in range(random.randint(0, 3)):
h_relu = self.middle_linear(h_relu).clamp(min=0)
y_pred = self.output_linear(h_relu)
return y_pred N, D_in, H, D_out = 64, 1000, 100, 10
x = Variable(torch.randn(N, D_in))
y = Variable(torch.randn(N, D_out), requires_grad=False)
model = DynamicNet(D_in, H, D_out) criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
for t in range(2):
y_pred = model(x)
loss = criterion(y_pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
模型搭建练习2_实现nn模块、optim、two_layer、dynamic_net的更多相关文章
- 小白学习之pytorch框架(3)-模型训练三要素+torch.nn.Linear()
模型训练的三要素:数据处理.损失函数.优化算法 数据处理(模块torch.utils.data) 从线性回归的的简洁实现-初始化模型参数(模块torch.nn.init)开始 from torc ...
- 0802_转载-nn模块中的网络层介绍
0802_转载-nn 模块中的网络层介绍 目录 一.写在前面 二.卷积运算与卷积层 2.1 1d 2d 3d 卷积示意 2.2 nn.Conv2d 2.3 转置卷积 三.池化层 四.线性层 五.激活函 ...
- Darknet_Yolov3模型搭建
Darknet_Yolov3模型搭建 YOLO(You only look once)是目前流行的目标检测模型之一,目前最新已经发展到V3版本了,在业界的应用也很广泛.YOLO的特点就是"快 ...
- 一周总结:AutoEncoder、Inception 、模型搭建及下周计划
一周总结:AutoEncoder.Inception .模型搭建及下周计划 1.AutoEncoder: AutoEncoder: 自动编码器就是一种尽可能复现输入信号的神经网络:自动编码器必须捕 ...
- slf4j+logback搭建超实用的日志管理模块
文章转自http://www.2cto.com/kf/201702/536097.html slf4j+logback搭建超实用的日志管理模块(对日志有编号管理):日志功能在服务器端再常见不过了,我们 ...
- torch7 安装 并安装 hdf5模块 torch模块 nn模块 (系统平台为 ubuntu18.04 版本)
今年的CCF A会又要开始投稿了,实验室的师弟还在玩命的加实验,虽然我属于特殊情况是该从靠边站被老板扶正但是实验室的事情我也尽力的去帮助大家,所以师弟在做实验的时候遇到了问题也会来问问我,这次遇到的一 ...
- 孤荷凌寒自学python第八十四天搭建jTessBoxEditor来训练tesseract模块
孤荷凌寒自学python第八十四天搭建jTessBoxEditor来训练tesseract模块 (完整学习过程屏幕记录视频地址在文末) 由于本身tesseract模块针对普通的验证码图片的识别率并不高 ...
- (子文章)Spring Boot搭建两个微服务模块
目录 1. 创建工程和user-service模块 1.1 创建空工程 1.2 在空工程里新建Module 2. 配置文件 2.1 pom.xml 2.2 application.yml 3. 代码 ...
- 入门项目数字手写体识别:使用Keras完成CNN模型搭建(重要)
摘要: 本文是通过Keras实现深度学习入门项目——数字手写体识别,整个流程介绍比较详细,适合初学者上手实践. 对于图像分类任务而言,卷积神经网络(CNN)是目前最优的网络结构,没有之一.在面部识别. ...
随机推荐
- play后面加the不加the如何分辨
play表示“参加(某种球类运动或棋牌类的活动)”时,不需要定冠词the,后面直接加球类运动名称或棋牌类活动名称,可根据实际情况翻译成“打,踢,下”等.例如: 1) He often plays fo ...
- Nodejs-内置核心模块&npm包管理工具
1.核心模块的意义 如果只是在服务器运行JavaScript代码,其实意义不大(浏览器就可以解决)因为无法实现功能(读写文件,访问网络) Node的用处在于本身还提供了一系列的功能模块,用于与操作系统 ...
- 如何在Linux下使用Rsync
如何在Linux下使用Rsync 吐槽 昨天对scp进行总结之后看到最后有说到Rsync,俗语有云:好奇心害死猫.抱着学习的态度将Rsync给找了出来,然后进行了一些简单的学习.下面介绍一些个常用的命 ...
- Python+Selenium基础篇之4-XPath的使用
开始写自动化脚本之前,我们先学习几个概念,在完全掌握了这几个概念之后,有助于我们快速上手,如何去编写自动化测试脚本. 元素,在这个教程系列,我们说的元素之网页元素(web element).在网页上面 ...
- python-侦测系统
大概就是这样 要求 告警需要一定之间内出现多次 然后才报警一次 如果恢复 必须发送恢复的信息
- linux命令之grep、cut
输入: ifconfig eth0 eth0表示主机的第一块网卡. 输出: eth0: flags=<UP,BROADCAST,RUNNING,MULTICAST> mtu inet 19 ...
- 浅谈JavaScript中的函数问题
前面的话:JavaScript可运行在所有主要平台的主流浏览器上,也可运行在每一个主流操作系统的服务器端上.所以呢,要想成为一名优秀的全栈工程师,必须懂得JavaScript语言.这是我整理的JS的部 ...
- BZOJ4002 [JLOI2015]有意义的字符串 【数学 + 矩乘】
题目链接 BZOJ4002 题解 容易想到\(\frac{b + \sqrt{d}}{2}\)是二次函数\(x^2 - bx + \frac{b^2 - d}{4} = 0\)的其中一根 那么就有 \ ...
- xtrabackup安装使用说明
软件介绍: Percona XtraBackup是一块开源且免费的对MySQL Innodb存储引擎备份数据的工具,使用此工具的时候不需停止MySQL,而且支持压缩备份,支持对Innodb存储引擎做增 ...
- 配置ubuntu16.04下Theano使用GPU运行程序的环境
ubuntu16.04默认安装了python2.7和python3.5 .本教程使用python3.5 第一步:将ubuntu16.04默认的python2修改成默认使用python3 . sudo ...