ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

线性回归补充练习

2022-05-30 05:00:07  阅读:228  来源: 互联网

标签:iters 回归 练习 cols np shape 线性 theta data2


巩固了线性回归的内容,练习了多变量的线性回归,对程序添加了一些详细的注释

import numpy as np#线性代数包
import pandas as pd#数据处理包
import matplotlib.pyplot as plt#画图包
path = 'ex1data2.txt'
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
#data2.head()
#特征归一化处理
data2 = (data2 - data2.mean()) / data2.std()
#data2.head()
#向量化处理
data2.insert(0, 'Ones', 1)#在第一列前加名字为ones的一列,其数值全为1
cols = data2.shape[1]#shape[0]是行数,shape[1]是列数,这里cols=4
X2 = data2.iloc[:,0:cols-1]#逗号前是行后是列, :就是选择全部行,cols-1是3,选取规则是左闭右开区间,[0,3)就是第1第2第3列
y2 = data2.iloc[:,cols-1:cols]#y是全部行,[3,4)是第4列 cols-1:cols就是最后一列
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta2 = np.matrix(np.array([0,0,0]))#初始化θ为(0,0)一行三列

######定义代价函数
def computeCost(X, y, theta):
# (X * theta.T) - y)就是所有的hθ(xi)-yi,是个列向量;np.power(x1,x2)就是对数组x1的元素分别求X2次方,x2可以是数组,但要求和x1列数相同
inner = np.power(((X * theta.T) - y), 2)#(X * theta.T) - y)中所有的元素求平方
return np.sum(inner) / (2 * len(X)) #np.sum就是对矩阵所有元素求和 len(X) X如果是矩阵,返回值是矩阵的行数;len(M[])返回列数

##梯度下降算法
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
#算法是批量梯度算法,parameters会自动适应变量数

alpha = 0.01
iters = 1000

g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters)

#computeCost(X2, y2, g2)
#绘制代价函数图
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost2, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()

标签:iters,回归,练习,cols,np,shape,线性,theta,data2
来源: https://www.cnblogs.com/zc-dn/p/16325533.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有