美文网首页
线性回归练习

线性回归练习

作者: celine_zhou | 来源:发表于2020-02-15 02:23 被阅读0次

单输入线性回归练习

1.导入需要用的模块

# import packages and modules
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random

2.初始化参数

注意:初始化参数时要初始化为向量,例如初始化为x = torch.randn(n)就是错误的。

#初始化参数
n = 1000
x = torch.randn(n,1)
w = 3.4
b = 2
y = torch.zeros(n,1)

3.生成数据集

注意:生成数据集时,后面的随机生成的数字要为和y一样的随机向量,而不能是一个数字。

#2.生成数据集
y = w*x + b + torch.tensor(np.random.normal(0, 0.5, size=y.size()))
print(y[0:10])
print(x.shape,y.shape)
plt.scatter(x.numpy(), y.numpy(),1);

4.初始化参数

注意:w.requires_grad_(requires_grad=True) 默认的requires_grad=False(自动求导)

#初始化训练参数 / 读取数据
X = x
w = torch.randn(1)
b = torch.zeros(1)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
print(w,b,x_len)

5.分批次读取数据

注意:random.shuffle(indices) 函数表示打乱列表的循序。
torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) :构建多个(1*batch_size) Long类型的张量。

#分批次读取数据
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)  # random read 10 samples 打乱顺序函数
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
        yield  features.index_select(0, j), labels.index_select(0, j)

#前向传播
def forword(X,w,b):
    w=w.view(len(w),1) # 可以不加,目的是为了确保w为相对于的矩阵。
    b=b.view(len(b),1)
    return torch.mm(X, w) + b
    
#损失函数
def squared_loss(y_hat, y): 
    return (y_hat - y.view(y_hat.size())) ** 2 / 2
    
#反向传播
def sgd(params, lr, batch_size): 
    for param in params:
        param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track

# super parameters init
lr = 0.03
num_epochs = 5000

net = forword
loss = squared_loss

# training
for epoch in range(num_epochs):  # training repeats num_epochs times
    # in each epoch, all the samples in dataset will be used once
    
    # X is the feature and y is the label of a batch sample
    for X, y in data_iter(batch_size, X, y):
        #print(X.shape,w.shape,b)
        l = loss(net(X, w, b), y).sum()  
        # calculate the gradient of batch sample loss 
        l.backward()  
        # using small batch random gradient descent to iter model parameters
        sgd([w, b], lr, batch_size)  
        # reset parameter gradient
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(X, w, b), y)
    #print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(w,b)

相关文章

  • 线性回归练习

    单输入线性回归练习 1.导入需要用的模块 2.初始化参数注意:初始化参数时要初始化为向量,例如初始化为x = to...

  • Keras练习:线性回归

    Keras是高层神经网络API,后端可基于Tensorflow运行。 这里创建一个简单数据集,做线性回归,感受一下...

  • 机器学习实战——回归

    本章内容】 线性回归 局部加权线性回归 岭回归和逐步线性回归 例子 【线性回归】 wHat = (X.T*X).I...

  • 线性回归模型

    参考:1.使用Python进行线性回归2.python机器学习:多元线性回归3.线性回归概念 线性回归模型是线性模...

  • 通俗得说线性回归算法(二)线性回归实战

    前情提要:通俗得说线性回归算法(一)线性回归初步介绍 一.sklearn线性回归详解 1.1 线性回归参数 介绍完...

  • 第一次打卡

    线性回归主要内容包括: 线性回归的基本要素线性回归模型从零开始的实现线性回归模型使用pytorch的简洁实现线性回...

  • 2020-02-14

    线性回归:线性回归分为一元线性回归和多元线性回归,一元线性回归用一条直线描述数据之间的关系,多元回归是用一条曲线描...

  • 逻辑回归和线性回归对比

    简单说几点 线性回归和逻辑回归都是广义线性回归模型的特例。他们俩是兄弟关系,都是广义线性回归的亲儿子 线性回归只能...

  • 算法概述-02

    1.逻辑回归和线性回归的联系和区别: 逻辑回归和线性回归的都是广义的线性回归。 线性回归是根据最小二乘法来建模,逻...

  • 【机器学习实践】有监督学习:线性分类、回归模型

    线性模型 为线性模型 分类和回归的区别 分类:离散回归:连续本文主要关注线性回归模型 常用线性回归模型类型 OLS...

网友评论

      本文标题:线性回归练习

      本文链接:https://www.haomeiwen.com/subject/jposfhtx.html