Task3.PyTorch实现Logistic regression
1.PyTorch基础实现代码
import torch
from torch.autograd import Variable torch.manual_seed(2)
x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0], [4.0]]))
y_data = Variable(torch.Tensor([[0.0], [0.0], [1.0], [1.0]])) #初始化
w = Variable(torch.Tensor([-1]), requires_grad=True)
b = Variable(torch.Tensor([0]), requires_grad=True)
epochs = 100
costs = []
lr = 0.1
print("before training, predict of x = 1.5 is:")
print("y_pred = ", float(w.data*1.5 + b.data > 0)) #模型训练
for epoch in range(epochs):
#计算梯度
A = 1/(1+torch.exp(-(w*x_data+b))) #逻辑回归函数
J = -torch.mean(y_data*torch.log(A) + (1-y_data)*torch.log(1-A)) #逻辑回归损失函数
#J = -torch.mean(y_data*torch.log(A) + (1-y_data)*torch.log(1-A)) +alpha*w**2
#基础类进行正则化,加上L2范数
costs.append(J.data)
J.backward() #自动反向传播 #参数更新
w.data = w.data - lr*w.grad.data
w.grad.data.zero_()
b.data = b.data - lr*b.grad.data
b.grad.data.zero_() print("after training, predict of x = 1.5 is:")
print("y_pred =", float(w.data*1.5+b.data > 0))
print(w.data, b.data)
2.用PyTorch类实现Logistic regression,torch.nn.module写网络结构
import torch
from torch.autograd import Variable x_data = Variable(torch.Tensor([[0.6], [1.0], [3.5], [4.0]]))
y_data = Variable(torch.Tensor([[0.], [0.], [1.], [1.]])) class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(1, 1)
self.sigmoid = torch.nn.Sigmoid() ###### **sigmoid** def forward(self, x):
y_pred = self.sigmoid(self.linear(x))
return y_pred model = Model() criterion = torch.nn.BCELoss(size_average=True) #损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 随机梯度下降 for epoch in range(500):
# Forward pass
y_pred = model(x_data) loss = criterion(y_pred, y_data)
if epoch % 20 == 0:
print(epoch, loss.item()) #梯度归零
optimizer.zero_grad()
# 反向传播
loss.backward()
# update weights
optimizer.step() hour_var = Variable(torch.Tensor([[0.5]]))
print("predict (after training)", 0.5, model.forward(hour_var).data[0][0])
hour_var = Variable(torch.Tensor([[7.0]]))
print("predict (after training)", 7.0, model.forward(hour_var).data[0][0])
参考:https://blog.csdn.net/ZZQsAI/article/details/90216593
Task3.PyTorch实现Logistic regression的更多相关文章
- 逻辑回归 Logistic Regression
逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...
- logistic regression与SVM
Logistic模型和SVM都是用于二分类,现在大概说一下两者的区别 ① 寻找最优超平面的方法不同 形象点说,Logistic模型找的那个超平面,是尽量让所有点都远离它,而SVM寻找的那个超平面,是只 ...
- Logistic Regression - Formula Deduction
Sigmoid Function \[ \sigma(z)=\frac{1}{1+e^{(-z)}} \] feature: axial symmetry: \[ \sigma(z)+ \sigma( ...
- SparkMLlib之 logistic regression源码分析
最近在研究机器学习,使用的工具是spark,本文是针对spar最新的源码Spark1.6.0的MLlib中的logistic regression, linear regression进行源码分析,其 ...
- [OpenCV] Samples 06: [ML] logistic regression
logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法 ...
- Stanford机器学习笔记-2.Logistic Regression
Content: 2 Logistic Regression. 2.1 Classification. 2.2 Hypothesis representation. 2.2.1 Interpretin ...
- Logistic Regression vs Decision Trees vs SVM: Part II
This is the 2nd part of the series. Read the first part here: Logistic Regression Vs Decision Trees ...
- Logistic Regression Vs Decision Trees Vs SVM: Part I
Classification is one of the major problems that we solve while working on standard business problem ...
- Logistic Regression逻辑回归
参考自: http://blog.sina.com.cn/s/blog_74cf26810100ypzf.html http://blog.sina.com.cn/s/blog_64ecfc2f010 ...
随机推荐
- ORACLE查询隐含参数
查询隐含参数:col name for a30col VALUE for a10col DESCRIB for a40set lines 200SELECT x.ksppinm NAME, y.ksp ...
- 洛谷P2657 windy数
传送 裸的数位dp 看这个题面,要求相邻两个数字之差至少为2,所以我们记录当前填的数的最后一位 同时要考虑毒瘤的前导0.如果填的数前面都是0,则这一位填0是合法的. emmm具体的看代码叭 #incl ...
- LeetCode 46——全排列
1. 题目 2. 解答 给定一个序列,序列中的任意一个数字都可以作为全排列的最后一位.然后,其余位置元素的确定便是剩余元素的一个全排列,也就是一个子问题. 例子中 [1, 2, 3] 的全排列,最后一 ...
- jdbcTemplate和namedParameterJdbcTemplate
jdbcTemplatejdbcTemplate配置<!-- 注入jdbcTemplate 官方工具包 --> <bean id="jdbc" class=&qu ...
- Ngix 配置与部署(wsgi,uwsgi,uWSGI)
1. WSGI 是一种协议接口,他是描述web服务器如何与web应用程序(Django ,Flask ) 通讯的规范. 2. uwsgi 与WSGI协议一样,是uWSGI服务器的独占协议,用于定义传输 ...
- linux系统镜像iso文件下载
linux系统镜像iso文件下载 首先你要选择你想要的linux版本,常见版本有CentOS,Ubuntu.选择一个你需要的. 有两个镜像站推荐: 网易镜像站:http://mirrors.163.c ...
- Makefile之patsubst
经常要手写项目的Makefile,或者看其他项目的遗留项目的Makefile,有些makefile内置函数常用, 却用完就忘记了,最近项目中使用patsubst,感觉挺好用的 格式:$(pa ...
- oracle--事物特性、锁、
update emp set comm = 100 where empno = 7369; 使用dba用户查看事务 ADDR XIDUSN XIDSLOT XIDSQN UBAFIL UBABLK U ...
- oracle--高级使用(merge)(递归START WITH)分析函数over
1.俩种表复制语句 SELECT INTO和INSERT INTO SELECT两种表复制语句 CT: create table <new table> as select * from ...
- HDU 5094 题解(状压BFS)
题面: Maze 题目中文大意: 这个故事发生在“星际迷航”的背景下. “星际争霸”的副队长史波克落入克林贡的诡计中,被关押在他们的母亲星球Qo’noS上. 企业的上尉詹姆斯·T·柯克(James T ...