吴恩达线性回归

线性回归

导入必须的包

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

导入数据

data=pd.read_csv(‘ex1data1.txt’,names=[‘population’,‘profit’])

查看信息

data.head()
在这里插入图片描述

插入1

data.insert(0,‘one’,1)
data.head()
在这里插入图片描述

切割数据获取X,y值

cols=data.shape[1]
X=data.iloc[:,0:cols-1]
y=data.iloc[:,cols-1:cols]

查看X

X.head()
在这里插入图片描述
y.head()
在这里插入图片描述

转换为矩阵形式

X=np.matrix(X.values)
y=np.matrix(y.values)
theta=np.matrix(np.array([0,0]))

查看维度信息

X.shape
在这里插入图片描述
y.shape
在这里插入图片描述
theta.shape
在这里插入图片描述

建立代价函数

在这里插入图片描述
def computeCost(X,y,theta):
inner=np.power(((Xtheta.T)-y),2)
return np.sum(inner)/(2
len(X))

计算代价值,未调整参数

computeCost(X,y,theta)
在这里插入图片描述

设置学习率 迭代次数

alpha=0.01
iters=1000
在这里插入图片描述

批量梯度下降

def gradientDescent(X,y,theta,alpha,iters):
temp=np.matrix(np.zeros(theta.shape))
parameters=int(theta.ravel().shape[1])
cost=np.zeros(iters)
for i in range(iters):
error=(X*theta.T)-y
for j in range(parameters):
term=np.multiply(error,X[:,j])
temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term))
theta=temp
cost[i]=computeCost(X,y,theta)
return theta,cost

计算批量梯度下降后代价函数值

g,cost=gradientDescent(X,y,theta,alpha,iters)
computeCost(X,y,g)
在这里插入图片描述

特征变量小于1W也可以使用正规方程计算参数值

在这里插入图片描述
def normalEpn(X,y):
theta=np.linalg.inv(X.T@X)@X.T@y
return theta

final_theta2=normalEpn(X,y)

计算代价函数值

computeCost(X,y,final_theta2.T)
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值