题目描述:
代码::
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 文件路径
path='ex1data1.txt'
# 读取文件
data=pd.read_csv(path,names=['Population','Profit'])
# 构造数据集
data.insert(0,'ones',1)
# 标签
X=data.iloc[:,0:-1]
X=X.values
# 真实值
y=data.iloc[:,-1]
y=y.values.reshape(97,1)
# 损失函数
def costfunction(X,y,theta):
inner=np.power(X@theta-y,2)
return np.sum(inner)/(2*len(X))
# theta初始化
theta=np.zeros((2,1))
# 梯度下降
def grandientDescent(X,y,theta,alpha,iters):
costs=[]
for i in range(iters):
theta=theta-(X.T@(X@theta-y))*alpha/len(X)
cost=costfunction(X,y,theta)
costs.append(cost)
return theta,costs
# 参数初始化
alpha=0.02
iters=2000