用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的更多相关文章

  1. 小白学习之pytorch框架(3)-模型训练三要素+torch.nn.Linear()

    模型训练的三要素:数据处理.损失函数.优化算法    数据处理(模块torch.utils.data) 从线性回归的的简洁实现-初始化模型参数(模块torch.nn.init)开始 from torc ...

  2. 0802_转载-nn模块中的网络层介绍

    0802_转载-nn 模块中的网络层介绍 目录 一.写在前面 二.卷积运算与卷积层 2.1 1d 2d 3d 卷积示意 2.2 nn.Conv2d 2.3 转置卷积 三.池化层 四.线性层 五.激活函 ...

  3. Darknet_Yolov3模型搭建

    Darknet_Yolov3模型搭建 YOLO(You only look once)是目前流行的目标检测模型之一,目前最新已经发展到V3版本了,在业界的应用也很广泛.YOLO的特点就是"快 ...

  4. 一周总结:AutoEncoder、Inception 、模型搭建及下周计划

    一周总结:AutoEncoder.Inception .模型搭建及下周计划   1.AutoEncoder: AutoEncoder: 自动编码器就是一种尽可能复现输入信号的神经网络:自动编码器必须捕 ...

  5. slf4j+logback搭建超实用的日志管理模块

    文章转自http://www.2cto.com/kf/201702/536097.html slf4j+logback搭建超实用的日志管理模块(对日志有编号管理):日志功能在服务器端再常见不过了,我们 ...

  6. torch7 安装 并安装 hdf5模块 torch模块 nn模块 (系统平台为 ubuntu18.04 版本)

    今年的CCF A会又要开始投稿了,实验室的师弟还在玩命的加实验,虽然我属于特殊情况是该从靠边站被老板扶正但是实验室的事情我也尽力的去帮助大家,所以师弟在做实验的时候遇到了问题也会来问问我,这次遇到的一 ...

  7. 孤荷凌寒自学python第八十四天搭建jTessBoxEditor来训练tesseract模块

    孤荷凌寒自学python第八十四天搭建jTessBoxEditor来训练tesseract模块 (完整学习过程屏幕记录视频地址在文末) 由于本身tesseract模块针对普通的验证码图片的识别率并不高 ...

  8. (子文章)Spring Boot搭建两个微服务模块

    目录 1. 创建工程和user-service模块 1.1 创建空工程 1.2 在空工程里新建Module 2. 配置文件 2.1 pom.xml 2.2 application.yml 3. 代码 ...

  9. 入门项目数字手写体识别:使用Keras完成CNN模型搭建(重要)

    摘要: 本文是通过Keras实现深度学习入门项目——数字手写体识别,整个流程介绍比较详细,适合初学者上手实践. 对于图像分类任务而言,卷积神经网络(CNN)是目前最优的网络结构,没有之一.在面部识别. ...

随机推荐

  1. Nodejs-模块化结构

    1.模块(一个文件就是一个模块) 获取当前脚本所在的路径 _ _dirname 文件路径 _ _filename (1)创建模块(module1.js) const fs=require('fs'); ...

  2. 单例模式【python】

    在python中,如需让一个类只能创建一个实例对象,怎么能才能做到呢? 思路:1.通过同一个类创建的不同对象,都让他们指向同一个方向.   2.让个类只能创建唯一的实例对象. 方法:用到 _ _new ...

  3. 分享一个文件查找、替换制定的字符或数字之CS程序、附带源码

    首先就上操作流程图: 图--登陆界面.登陆密码:alidoing.com 图--界面说明(一看就懂) 图--文件查找到再替换 图--文件替换成功 图--替换后的文件 代码开始: 登陆的代码就非常简单. ...

  4. 【Decode Ways】cpp

    题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: ' ...

  5. 最少的硬币数量组合出1到m之间的任意面值(贪心算法)

    题目描述: 你有n种不同面值的硬币,每种面值的硬币都有无限多个,为了方便购物,你希望带尽量少的硬币,并且要能组合出 1 到 m 之间(包含1和m)的所有面值. 输入描述: 第一行包含两个整数:m ,n ...

  6. Leetcode 630.课程表III

    课程表III 这里有 n 门不同的在线课程,他们按从 1 到 n 编号.每一门课程有一定的持续上课时间(课程时间)t 以及关闭时间第 d 天.一门课要持续学习 t 天直到第 d天时要完成,你将会从第 ...

  7. DFS和BFS遍历的问题

    来自https://github.com/soulmachine/leetcode 广度优先搜索 输入数据:没有什么特征,不像dfs需要有递归的性质.如果是树/图,概率更大. 状态转换图:数或者DAG ...

  8. 【bzoj2242】[SDOI2011]计算器 EXgcd+BSGS

    题目描述 你被要求设计一个计算器完成以下三项任务: 1.给定y,z,p,计算Y^Z Mod P 的值: 2.给定y,z,p,计算满足xy≡ Z ( mod P )的最小非负整数: 3.给定y,z,p, ...

  9. eclipse中 tomcat首页server Locations变灰无法编辑

    解决办法: 1.首先将Servers中部署的工程全部清空 2.然后对Tomcat v8.0 Server at localhost,点右键进行clean处理,再重新双击打开server服务即可.

  10. BZOJ2393 & 1853 [Scoi2010]幸运数字 【搜索 + 容斥】

    题目 在中国,很多人都把6和8视为是幸运数字!lxhgww也这样认为,于是他定义自己的"幸运号码"是十进制表示中只包含数字6和8的那些号码,比如68,666,888都是" ...