模型搭建练习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)是目前最优的网络结构,没有之一.在面部识别. ...
随机推荐
- Android 自定义 radiobutton
<RadioButton android:id="@+id/radiobutton_pay_method" android:layout_width="30dp&q ...
- 【Median of Two Sorted Arrays】cpp
题目: There are two sorted arrays A and B of size m and n respectively. Find the median of the two sor ...
- CentOS6.4编译Hadoop-2.4.0
因为搭建Hadoop环境的时候,所用的系统镜像是emi-centos-6.4-x86_64,是64位的,而hadoop是默认是32的安装包.这导致我们很多操作都会遇到这个问题(Java HotSp ...
- 理解机器为什么可以学习(三)---Theory of Generalization
前边讨论了我们介绍了成长函数和break point,现在继续讨论m是否成长很慢,是否能够取代M. 成长函数就是二分类的排列组合的数量.break point是第一个不能shatter(覆盖所有情形) ...
- [转]Ubuntu下添加开机启动脚本
作者: 王恒 发表于 2012年 11月 5日 1.方法一,编辑rc.loacl脚本 Ubuntu开机之后会执行/etc/rc.local文件中的脚本, 所以我们可以直接在/etc/rc.local中 ...
- var和function定义方法的区别
在JS中有两种定义函数的方式,1是var aaa=function(){...}2是function aaa(){...}var 方式定义的函数,不能先调用函数,后声明,只能先声明函数,然后调用.fu ...
- [URAL1519] Formula 1 [插头dp入门]
题面: 传送门 思路: 插头dp基础教程 先理解一下题意:实际上就是要你求这个棋盘中的哈密顿回路个数,障碍不能走 看到这个数据范围,还有回路处理,就想到使用插头dp来做了 观察一下发现,这道题因为都是 ...
- redis学习(三)五种数据结构
Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合). 1.string string类型是Redis最基 ...
- pdo防sql注入
http://blog.csdn.net/qq635785620/article/details/11284591
- 【转】 Linux中记录终端输出到txt文本文件
转载: http://blog.csdn.net/tengh/article/details/41823883 一,把命令运行的结果保存到文件当中:用 > 把输出转向就可以了 例子: $ ls ...