线性回归练习1

上周二居家隔离到周六,进度很慢,对之前一部分的课程进行一些笔记总结;
整体算法原理,框架结构已经理解,但是还有一些语句理解的不是很透彻。


#导入数据并绘图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
path = 'ex1data1.txt'

data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
print(data.head())
data.describe()
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
plt.show()

 

 



######定义代价函数
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))

data.insert(0, 'Ones', 1)#加一行用向量计算
#变量初始化
cols = data.shape[1]
X = data.iloc[:, 0:cols - 1] # X是所有行,去掉最后一列
y = data.iloc[:, cols - 1:cols] # X是所有行,最后一列
print(X.head()) # head()是观察前5行
print(y.head())
#转换X,y为numpy矩阵
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0, 0]))#初始化为(0,0)


##梯度下降算法
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
#初始化迭代步数和学习率
alpha = 0.01
iters = 1000

g, cost = gradientDescent(X, y, theta, alpha, iters)#开始迭代

computeCost(X, y, g)#寻找到合适参数后的代价函数值
#绘制拟合图
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()、

 

 


#代价函数随迭代次数的变化图
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()

 

posted on   zc-DN  阅读(55)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示