天天看点

机器学习-线性回归课后笔记

前言:

 ​

过完理论学习,还是要动手实践,吴恩达老师的布置的课后作业可在courses上报名就可以看 ​

练习题目:

预测房价,内容参照ex1.pdf

实现代码+注释:

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())
print(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)

# set X (training data) and y (target variable)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]#X是所有行,去掉最后一列
y = data.iloc[:,cols-1:cols]#X是所有行,最后一列

print(X.head())#head()是观察前5行

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

#看一下維度
print(X.shape,theta.shape,y.shape)

#计算代价函数 (theta初始值为0).
print(computeCost(X, y, theta))

# batch gradient decent(批量梯度下降)
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)
print(g)

# 最后,我们可以使用我们拟合的参数计算训练模型的代价函数(误差)。
print(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()


path =  'ex1data2.txt'
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
print(data2.head())

# 特征归一化
data2 = (data2 - data2.mean())/ data2.std()
print(data2.head())

# 现在我们重复第1部分的预处理步骤,并对新数据集运行线性回归程序。
# 添加ones 一列
data2.insert(0,'Ones',1)

# 设置 X(训练的数据),y是目标变量
cols = data2.shap[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]

# 转换为矩阵并初始化
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta = np.matrix(np.array([0,0,0]))

# 对数据集执行线性回归
g2 , cost2 = gradientDescent(X2,y2,theta,alpha,iters)

#得到模型的成本(误差)
computeCost(X2)      

结果分析:

机器学习-线性回归课后笔记

拟合直线

机器学习-线性回归课后笔记

梯度下降算法的拟合图示

机器学习-线性回归课后笔记

正规方程算法的拟合图示

总的来说,只要特征变量的数目并不大,正规方程是一个很好的计算参数的替代方法。具体地说,只要特征变量数量小于1w,通常使用正规方程法,而不是用梯度下降法。

线性回归方程是非常重要的一个基础知识,后面需要重点回顾。