0.1 Regression

本文通过使用Python的多种库,如NumPy、Pandas、Matplotlib、Seaborn、Scikit-learn和PyTorch,对线性回归模型进行了深入的实践与比较。从梯度下降法到正规方程,再到利用Sklearn和PyTorch实现线性回归,展示了不同方法的优劣。通过数据可视化,直观地呈现了模型的拟合效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
"""
Created on Sat Oct 27 18:59:53 2018

@author: Plenari
"""

import matplotlib.pyplot as plt
import numpy as np 
import pandas as pd
import scipy as sc
import seaborn as sns

x=np.arange(1,10)
x=np.array([np.ones_like(x),x,x**2]).T
y=np.dot(x,np.array([[1,2,3]]).T)

sns.set()

# normal
x0=np.mat(x)
w_normal=(x0.T*x0).I*(x0.T)*np.mat(y.reshape(-1,1))
plt.plot(y,'*')
plt.plot(x0*w_normal,'-')
plt.show()


#gradenscent  梯度下降

learn=1e-4#learning
'''
线性回归的梯度下降
'''

w=np.ones([len(x[0]),1])
m,n=x.shape
for i in range(100):
    hypo=np.dot(x,w)
    loss=hypo-y
    gradient=np.dot(x.T,loss)/m
    loss=np.sqrt(np.mean(loss**2))
    if i%50==0:
        
        print(i,loss)
    w=w-learn*gradient
    

'''
sklearn
'''
from sklearn.linear_model import LinearRegression
lr=LinearRegression()
lr.fit(x,y)
print(lr.coef_)
#>>> [[0. 2. 3.]]

#pytorch

import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

class LR(nn.Module):

    def __init__(self):
        super(LR, self).__init__()
        self.linear=nn.Linear(3,1,bias=False)
        
    def forward(self, x):
        x = self.linear(x)
        return x

'''
用pytorch实
'''
model = LR()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr = 0.0001)
x=torch.from_numpy(x.astype('float32'))
y=torch.from_numpy(y.astype('float32'))
loss0=1e9
for i in range(200000):    
    optimizer.zero_grad()   # 首先梯度清零(与 net.zero_grad() 效果一样)
    
    output = model(x)
    loss = criterion(output,y)        
    loss.backward()
    optimizer.step()    # 更新参数
    if np.abs(loss.item()-loss0)<1e-9:
        print(loss.item())
        break
    loss0=loss.item()

print(model.linear.state_dict())

plt.plot(y.data.numpy().flatten(),'*')
plt.plot(model(x).data.numpy().flatten())
plt.title('pytorch')
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值