PytorchZerotoAll学习笔记(四)--线性回归
线性回归
# 导入 torch、torch.autograd的Variable模块
import torch
from torch.autograd import Variable
# 生成需要回归需要的tensor
x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]])) #定义模型类,继承自nn包的Module模块
class Model(torch.nn.Module):
# 初始化方法
def __init__(self):
"""
In the constructor we instantiate two nn.Linear module
"""
# 子类转换为父类对象并调用初始化方法
super(Model, self).__init__()
# 线性回归,一个输入,一个输出
self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x):
"""
In the forward function we accept a Variable of input data and we must return
a Variable of output data. We can use Modules defined in the constructor as
well as arbitrary operators on Variables.
"""
# y=K *x 返回结果
y_pred = self.linear(x)
return y_pred # our model # 调用模型类生成模型的对象
model = Model() # Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model. ##使用均方误差函数,在多个样本情况下,不计算平均值
criterion = torch.nn.MSELoss(size_average=False)
##使用随机梯度下降,学习率为0.01
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # Training loop
# 训练 500轮
for epoch in range(500):
# Forward pass: Compute predicted y by passing x to the model
# 前向推理模型
y_pred = model(x_data) # Compute and print loss
# 计算损失
loss = criterion(y_pred, y_data)
print(epoch, loss.data[0]) # Zero gradients, perform a backward pass, and update the weights.
# 由于使用多次训练,每轮结束之后要清零数据
optimizer.zero_grad()
# 反向传播求梯度值
loss.backward()
# 更新所有的参数
optimizer.step() # After training
hour_var = Variable(torch.Tensor([[4.0]]))
y_pred = model(hour_var)
print("predict (after training)", 4, model(hour_var).data[0][0])
PytorchZerotoAll学习笔记(四)--线性回归的更多相关文章
- C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻
前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...
- IOS学习笔记(四)之UITextField和UITextView控件学习
IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...
- java之jvm学习笔记四(安全管理器)
java之jvm学习笔记四(安全管理器) 前面已经简述了java的安全模型的两个组成部分(类装载器,class文件校验器),接下来学习的是java安全模型的另外一个重要组成部分安全管理器. 安全管理器 ...
- Learning ROS for Robotics Programming Second Edition学习笔记(四) indigo devices
中文译著已经出版,详情请参考:http://blog.csdn.net/ZhangRelay/article/category/6506865 Learning ROS for Robotics Pr ...
- Typescript 学习笔记四:回忆ES5 中的类
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- ES6学习笔记<四> default、rest、Multi-line Strings
default 参数默认值 在实际开发 有时需要给一些参数默认值. 在ES6之前一般都这么处理参数默认值 function add(val_1,val_2){ val_1 = val_1 || 10; ...
- muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制
目录 muduo网络库学习笔记(四) 通过eventfd实现的事件通知机制 eventfd的使用 eventfd系统函数 使用示例 EventLoop对eventfd的封装 工作时序 runInLoo ...
- python3.4学习笔记(四) 3.x和2.x的区别,持续更新
python3.4学习笔记(四) 3.x和2.x的区别 在2.x中:print html,3.x中必须改成:print(html) import urllib2ImportError: No modu ...
- Go语言学习笔记四: 运算符
Go语言学习笔记四: 运算符 这章知识好无聊呀,本来想跨过去,但没准有初学者要学,还是写写吧. 运算符种类 与你预期的一样,Go的特点就是啥都有,爱用哪个用哪个,所以市面上的运算符基本都有. 算术运算 ...
- 零拷贝详解 Java NIO学习笔记四(零拷贝详解)
转 https://blog.csdn.net/u013096088/article/details/79122671 Java NIO学习笔记四(零拷贝详解) 2018年01月21日 20:20:5 ...
随机推荐
- Redmine使用学习
注:陈刚在公司架设了 Redmine xx公司产品档案管理系统,并且与tortoisegit集成了在一起:真心不错!比如git:192.168.10.46,而redmine:192.168.10.46 ...
- iOS:位置相关(18-03-09更)
1.定位设置 2.定位页面逻辑 1.定位设置 2.定位页面逻辑 1).第一次进入该VC,在 viewDidLoad 调用刷新页面 refreshLocationView .这时用户还没决定,会刷出“正 ...
- P1015 回文数解题思路(非原创)
测试 #include<bits/stdc++.h> using namespace std; int n,m,step; string nn; int len,nex; bool dfs ...
- 大数据分析系统Hadoop的13个开源工具
Hadoop是由Apache基金会开发的一个大数据分布式系统基础架构,最早版本是2003年原Yahoo!DougCutting根据Google发布的学术论文研究而来. 用户可以在不了解分布式底层细节的 ...
- python3使用bencode库实现BT种子生成磁力链接
python3 需要使用 pip install py3-bencode安装py3-bencode库. pip install py3-bencode 这里使用当前目录下的 1.torrent 文件转 ...
- [转] JetBrains Products License Server,适用RubyMine、Goland等
原文:http://jetbrains.license.laucyun.com/ Working Server http://jetbrains.license.laucyun.com (Lower ...
- 使用ofstream输出unicode
void saveWideFileHead(std::ofstream& out)// 写入文件内容前,先写入BOM { char const* const utf16head = " ...
- BrightScript 3D test - Roku (4)
My initial attempt to port over an old Actionscript program, here it goes in main.brs. Library " ...
- 20155236 《Java程序设计》实验四(Android程序设计)实验报告
20155236 <Java程序设计>实验四(Android程序设计)实验报告 一.实验内容及步骤 第24章:初识Android 任务一:完成Hello World, 要求修改res目录中 ...
- C# Disable CTRL-ALT-DEL, ALT-TAB, ALT-F4, Start Menu and so on…
使用C#禁用系统的某些特定按键 原文地址:http://www.tamas.io/c-disable-ctrl-alt-del-alt-tab-alt-f4-start-menu-and-so-on/ ...