一.实现简单的示例函数
在该部分练习中,将通过代码实现返回一个5*5的对角矩阵。输出与如下相同:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1.1解决方案及结果
二.单变量线性回归
在该部分练习中,将实现单变量线性回归并用来预测餐车的利润。
假设你是一家餐厅的领导,正在考虑在不同的城市开设新的分店。该连锁店已经在不同的城市有了餐车,并且你能够获得每个城市的人口和利润数据。
现在需要使用这些数据来帮助你选择下一个被扩展的城市。
文件ex1data1.txt包含线性回归问题的数据集。第一列数据对应城市人口,第二列数据对应那座城市的餐车的利润。利润为负时表示亏损。
2.1绘制数据
data.plot(kind='scatter', x='Population', y='Profit',c='red', figsize=(12,8))
结果展示:
2.2梯度下降
在该部分中,将使用梯度下降来选择合适的线性回归参数θ用以拟合给定数据集。
2.2.1 更新公式
2.2.2 实现
接下来,我们在数据中添加了一个维度来拟合截距项 𝜃0
。并将初始参数值设为0,学习率 𝛼 设为0.01。
2.2.3 计算成本J(θ)
在执行梯度下降最小化成本函数 𝐽(𝜃) 时,通过计算成本来监视收敛状态是有帮助的。在该部分练习任务中,你需要实现一个计算成本 𝐽(𝜃)的函数computeCost,用于检查梯度下降实现的收敛性。其中,X和y不是标量值,而是矩阵,其行代表训练集中的示例。
要点:完成该函数后,将 𝜃值初始化为0并进行成本的计算,将得到的成本值打印出来。如果结果为32.07,则计算通过。
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
theta = np.matrix(np.array([0,0]))
computeCost(X, y, theta)
结果:
2.2.4 梯度下降
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
g, cost = gradientDescent(X, y, theta, alpha, iterations)
g
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, 'b', label='Prediction')
ax.scatter(data.Population, data.Profit, c='red',label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
结果:
2.3 可视化成本函数
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iterations), cost_final, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
Text(0.5, 1.0, 'Error vs. Training Epoch')