《PyTorch深度学习实践》完结合集 · Hongpu Liu · logistic回归(+交叉熵)(4)

目录

6.logistic回归


6.logistic回归

 

  

 

在此,推荐大家去看一篇文章:

一文搞懂交叉熵在机器学习中的使用,透彻理解交叉熵背后的直觉

另外,我在这里记录文章里面一些重要的内容,如下:


扫描二维码关注公众号,回复: 13414582 查看本文章

 

 

 

 

 

 


 

 

 求不求平均值(size_average = False / True)影响梯度,影响学习率

 

 

#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
============================================
时间:2021.8.15
作者:手可摘星辰不去高声语
文件名:06-logistic回归.py
功能:
1、Ctrl + Enter      在下方新建行但不移动光标;
2、Shift + Enter     在下方新建行并移到新行行首;
3、Shift + Enter     任意位置换行
4、Ctrl + D          向下复制当前行
5、Ctrl + Y         删除当前行
6、Ctrl + Shift + V  打开剪切板
7、Ctrl + /          注释(取消注释)选择的行;
8、Ctrl + E       可打开最近访问过的文件
9、Double Shift + /  万能搜索
============================================
"""


import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.functional as F


x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])
# print(x_data.shape)


class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = F.sigmoid(self.linear(x))
        return y_pred


model = LinearModel()
criterion = torch.nn.BCELoss(size_average=False)
optimzer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(1000):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print("Epoch:{}\tBCE:{}".format(epoch, loss))
    optimzer.zero_grad()
    loss.backward()
    optimzer.step()


x = np.linspace(0, 10, 200)
x_t = torch.Tensor(x).view((200,1))
y_t = model(x_t)
y = y_t.data.numpy()

plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel("X")
plt.ylabel("Y")
plt.grid()
plt.show()

 

猜你喜欢

转载自blog.csdn.net/weixin_44917390/article/details/119707528