作业2-多变量线性回归
ex1data2.txt里的数据,第一列是房屋大小,第二列是卧室数量,第三列是房屋售价
根据已有数据,建立模型,预测房屋的售价
数据资源:
链接:https://pan.baidu.com/s/1Qfh04OU3XrxRWoAzZORMzg
提取码:ywlm
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 = (data2 - data2.mean()) / data2.std()
# J(θ)=1/2m ∑1_(i=1)^m▒(h_θ (x^((i)) )−y^((i)) )^2
# 计算机代价函数 X 为m * (n+1) 的矩阵,theta 为 1 * (n+1)的行向量,y为 m * 1的向量。
# x * theta.T = 预测值 y 为实际值。
def computeCost(X, y, theta):
inner = np.power((X*theta.T - y),2)
# np.sum(inner) inner中所有元素的累加和
return np.sum(inner) / (2*len(X))
# 梯度下降 这个部分实现了Ѳ的更新 alpha为学习率 iters为迭代次数
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
# theta.ravel() 对theta矩阵做扁平化处理
parameters = int(theta.ravel().shape[1]) # 参数的数量
cost = np.zeros(iters)
for i in range(iters):
error = (X * theta.T) - y # m * 1
# 对每个参数 进行更新 先存储到临时变量temp中,然后一起更新theta来实现同步更新
for j in range(parameters):
# np.multiply(A,B) 同型矩阵对应元素相乘
# 公式 :θ_1:=θ_1− a/m ∑1_(i=1)^m▒〖(h_θ (x^((i)))−y^((i)))〗 x_1^((i))
term = np.multiply(error, X[:, j]) # m * 1
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))
theta = temp
# 每次迭代 记录一下代价函数的值
cost[i] = computeCost(X, y, theta)
return theta, cost
# 加一列常数项
data2.insert(0, 'Ones', 1)
# 初始化X和y
cols = data2.shape[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]
# 转换成matrix格式,初始化theta
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta2 = np.matrix(np.array([0,0,0]))
# 初始化 学习率和迭代次数
alpha = 0.01
iters = 1500
# 运行梯度下降算法
g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters)
print(g2)
浙公网安备 33010602011771号