数据分析python,线性回归

举报
the-order 发表于 2022/05/02 21:37:31 2022/05/02
【摘要】 数据分析python,线性回归

本节是python实现一元回归的代码部分,理论参考链接: link.
代码下载地址link.
代码可直接赋值运行,如有问题请留言

1 环境准备

import numpy as np
import matplotlib.pyplot as pl
import matplotlib
matplotlib.rcParams['font.sans-serif']='SimHei'
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus']=False

这些是需要的python组件和画图需要的包,matplotlib是画图的设置

2 读取文件方法设置

def loadDataset(filename):
    X=[]
    Y=[]
    with open(filename,'rb') as f:
        for idx,line in enumerate(f):
            line=line.decode('utf-8').strip()
            if not line:
                continue
                
            eles=line.split(',')
            
            if idx==0:
                numFea=len(eles)
                
            eles=list(map(float,eles))#map返回一个迭代对象
            
            X.append(eles[:-1])
            Y.append([eles[-1]])
    return np.array(X),np.array(Y)
    ```

# 3 预测值方法
def h(theta,X):
    return np.dot(X,theta)

# 4 完成方法设计

def J(theta,X,Y):
    return np.sum(np.dot((h(theta,X)-Y).T,(h(theta,X)-Y))/(2*m))

# 5 梯度下降方法

def bgd(alpha,maxloop,epsilon,X,Y):
m,n=X.shape

theta=np.zeros((2,1))

count=0
converged=False
error=np.inf
errors=[]
thetas={0:[theta[0,0]],1:[theta[1,0]]}

while count<=maxloop:
    if(converged):
        break
    
    count=count+1
    temp1=theta[0,0]-alpha/m*(h(theta,X)-Y).sum()
    temp2=theta[1,0]-alpha/m*(np.dot(X[:,1][:,np.newaxis].T,(h(theta,X)-Y))).sum()
    
    #同步更新
    theta[0,0]=temp1
    theta[1,0]=temp2
    thetas[0].append(temp1)
    thetas[1].append(temp2)
    
    error=J(theta,X,Y)
    errors.append(error)
    
    if(error<epsilon):
        converged=True
return theta,errors,thetas
```

6 读取文件

先预览下读取的数据,这里用的一组不太好的数据
在这里插入图片描述

X,Y=loadDataset('./data/price_diff.csv')
print(X.shape)
print(Y.shape)

(243, 1)
(243, 1)

m,n=X.shape
X=np.concatenate((np.ones((m,1)),X),axis=1)
X.shape

(243, 2)

7 模型参数设置

alpha=0.000000000000000003
maxloop=3000
epsilon=0.01
result=bgd(alpha,maxloop,epsilon,X,Y)
theta,errors,thetas=result

xCopy=X.copy()
xCopy.sort(0)
yHat=h(theta,xCopy)
xCopy[:,1].shape,yHat.shape,theta.shape

((243,), (243, 1), (2, 1))

8 结果绘图

pl.xlabel(u'1')
pl.ylabel(u'2')
pl.plot(xCopy[:,1],yHat,color='red')
pl.scatter(X[:,1].flatten(),Y.T.flatten())
pl.show()

在这里插入图片描述
误差与迭代次数绘图

pl.xlim(-1,3000)

pl.xlabel(u'迭代次数')
pl.ylabel(u'代价函数')
pl.plot(range(len(errors)),errors)
pl.show()

在这里插入图片描述

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200