当前位置:   article > 正文

吴恩达机器学习作业(1):线性回归_由于梯度方程式函数也在每个训练迭代中输出一个代价的向量,所以我们也可以绘制。

由于梯度方程式函数也在每个训练迭代中输出一个代价的向量,所以我们也可以绘制。

目录

1)导入相关库和数据

2)代价函数

3)批量梯度下降

4)绘制线性模型

前阵子在网易云课堂学习了吴恩达老师的机器学习课程,今天结合网上资料,用Python实现了线性回归作业,共勉。建议大家使用Jupyter notebook来编写程序。

1)导入相关库和数据

导入相关库:numpy, pandas, matplotlib

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
'
运行

拿到数据之后,建议大家先看看数据长什么样子,这样有助于我们进行之后的分析:

  1. path = 'ex1data1.txt'
  2. #指定了列名,header=None
  3. data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
  4. data.head()
  5. data.describe()
  6. data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
  7. plt.show()

2)代价函数J(θ)

现在我们使用梯度下降来实现线性回归,以最小化成本函数。

首先,我们将创建一个以参数\theta为特征的代价函数:

                                              J(\theta)=\frac{1}{2m}\sum_{i=1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})^2

其中:

                                           hθ(x)=θTX=θ0x0+θ1x1+...+θnxn

  1. def computeCost(X, y, theta):
  2. inner = np.power(((X * theta.T) - y), 2)
  3. return np.sum(inner) / (2 * len(X))
'
运行

我们需要在训练集中添加一列,以便我们可以使用向量化解决方案来计算大家函数:

  1. #在第0列插入1,列名为“Ones”
  2. data.insert(0, 'Ones', 1)
  3. # set X (training data) and y (target variable)
  4. #cols = 3
  5. cols = data.shape[1]
  6. X = data.iloc[:,0:cols-1] #X选取所有行,去掉最后一列,第一个分号前为行。
  7. y = data.iloc[:,cols-1:cols]#y选取所有行,最后一列

代价函数应该是numpy矩阵,所以我们需要转换X和y,然后才能使用它们。我们还需要初始化参数theta。

  1. X = np.matrix(X.values)
  2. y = np.matrix(y.values)
  3. #我们这里是单变量线性回归,故只需要两个参数
  4. theta = np.matrix(np.array([0,0]))

现在我们计算代价函数(theta初始值为0)

computeCost(X, y, theta)
32.072733877455676

3)批量梯度下降

我们前面只是计算了初试theta为0时代价函数的值,我们现在要使用梯度下降算法来求我们的参数θ

\dpi200θj:=θjαθjJ(θ)

\theta_0:=\theta_0-\alpha\frac{1}{m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})

θ1:=θ1α1mi=1m(hθ(x(i))y(i))x(i)

  1. def gradientDescent(X, y, theta, alpha, iters):
  2. temp = np.matrix(np.zeros(theta.shape)) #theta.shape=(1,2)
  3. parameters = int(theta.ravel().shape[1]) #ravel()降维,parameters=2
  4. cost = np.zeros(iters) #iter维零向量
  5. for i in range(iters): #迭代iters次
  6. error = (X * theta.T) - y
  7. for j in range(parameters): #2个参数
  8. term = np.multiply(error, X[:,j])
  9. temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
  10. theta = temp
  11. cost[i] = computeCost(X, y, theta) #保存每次迭代后的cost值
  12. return theta, cost
  13. alpha = 0.01
  14. iters = 1000
'
运行

现在我们运行梯度下降算法来求我们的参数theta并求出拟合后的代价函数值。

  1. g, cost = gradientDescent(X, y, theta, alpha, iters)
  2. computeCost(X, y, g)
4.5159555030789118

4)绘制线性模型

现在我们来绘制线性模型以及数据,直观地看出它的拟合。

  1. x = np.linspace(data.Population.min(), data.Population.max(), 100)
  2. f = g[0, 0] + (g[0, 1] * x)
  3. fig, ax = plt.subplots(figsize=(12,8))
  4. ax.plot(x, f, 'r', label='Prediction')
  5. ax.scatter(data.Population, data.Profit, label='Traning Data')
  6. ax.legend(loc=2)
  7. ax.set_xlabel('Population')
  8. ax.set_ylabel('Profit')
  9. ax.set_title('Predicted Profit vs. Population Size')
  10. plt.show()

由于梯度方程式函数也在每个训练迭代中输出一个代价的向量,所以我们也可以绘制。 请注意,代价总是降低 - 这是凸优化问题的一个例子。

  1. fig, ax = plt.subplots(figsize=(12,8))
  2. ax.plot(np.arange(iters), cost, 'r')
  3. ax.set_xlabel('Iterations')
  4. ax.set_ylabel('Cost')
  5. ax.set_title('Error vs. Training Epoch')
  6. plt.show()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/807450
推荐阅读
相关标签
  

闽ICP备14008679号