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

  1. 逻辑回归 Logistic Regression

    逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...

  2. logistic regression与SVM

    Logistic模型和SVM都是用于二分类,现在大概说一下两者的区别 ① 寻找最优超平面的方法不同 形象点说,Logistic模型找的那个超平面,是尽量让所有点都远离它,而SVM寻找的那个超平面,是只 ...

  3. Logistic Regression - Formula Deduction

    Sigmoid Function \[ \sigma(z)=\frac{1}{1+e^{(-z)}} \] feature: axial symmetry: \[ \sigma(z)+ \sigma( ...

  4. SparkMLlib之 logistic regression源码分析

    最近在研究机器学习,使用的工具是spark,本文是针对spar最新的源码Spark1.6.0的MLlib中的logistic regression, linear regression进行源码分析,其 ...

  5. [OpenCV] Samples 06: [ML] logistic regression

    logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法 ...

  6. Stanford机器学习笔记-2.Logistic Regression

    Content: 2 Logistic Regression. 2.1 Classification. 2.2 Hypothesis representation. 2.2.1 Interpretin ...

  7. 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 ...

  8. 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 ...

  9. Logistic Regression逻辑回归

    参考自: http://blog.sina.com.cn/s/blog_74cf26810100ypzf.html http://blog.sina.com.cn/s/blog_64ecfc2f010 ...

随机推荐

  1. ORA-00346,借助_allow_resetlogs_corruption开库

    Mon Aug 06 10:15:08 2018Errors in file /data/app/oracle/diag/rdbms/prod/prod/trace/prod_ora_6831.trc ...

  2. mongoexport导出记录到csv文件

    root@service:~# mongoexport -d prod -c employees -f _id,platform,phone --csv -o /opt/employees.csv 2 ...

  3. 十一、python函数学习

    1.    定义函数 def   函数名(形参): 函数体 return  xxx--------其下面的内容不再执行 ---------------------------------------- ...

  4. 锐捷网络自动连接python脚本

    1 实现锐捷网络的连接,当断开后自动重连 import os import sys import time ip = 'www.baidu.com' print('开始ping百度') backinf ...

  5. winform项目中开发的一套UI控件库

    https://github.com/houyhea/winform-control-lib winform-control-lib 曾经在一个winform项目中开发的一套UI控件库 类图:  效果 ...

  6. 【Linux】limits.conf 不重启就生效或者不生效的原因

    前阵子,我要用到使LInux的文件打开数为65534个,而且需要永久生效,于是将配置写到了: vim /etc/security/limits.conf * soft nofile 65534* ha ...

  7. 自己挖的坑自己填--docker创建实例出现Waiting for SSH to be available…

    在之前使用Docker for Windows Installer.exe直接安装,通过docker-machine-driver-vmwareworkstation.exe实现docker和VM的共 ...

  8. SpringBoot 整合 MybatisPlus (项目的创建及简单的单表查询)

    添加依赖 <!--mybatis-plus的springboot支持--> <dependency> <groupId>com.baomidou</group ...

  9. 一键生成APK

    傻瓜式的生成APK网址:https://www.appbsl.com/ 第一步 第二步 第三步 第四步

  10. UI标签库专题十:JEECG智能开发平台 Form(form标签)

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhangdaiscott/article/details/30099121  1. Form(f ...