一、问题描述 给定一组数据(如下图所示),格式为a, b。a表示该城市的人口,b表示卖食品的卡车在该城市的利润。通俗理解,a越大,b也越大,所以本问题是告知一城市的人口,请预测卖食品的卡车在该城市的利润。属于单边变量线性回归问题(文件ex1data1.txt包含线性回归问题的数据集)。
二、Jupyter解决此问题的过程 1.导入数据分析所需要的库1
import numpy as np import pandas as pd from matplotlib import pyplot as plt2.导入数据并查看
path = 'D:\Code\DataSets\ML_data_sets\ex1data1.txt' data = pd.read_csv(path, header = None, names = ['Population', 'Profit']) data.head()注解: ①逗号分隔值文件(Comma-Separated Values,CSV) ②names添加列名,header用指定的行来作为标题,若原无标题且指定标题则设为None ③可视化效果如下图所示 3.绘制数据的散点图
data.plot(kind = 'scatter', x = 'Population', y = 'Profit', figsize = (8, 6)) #figsize设置figure的size plt.show()4.根据公式描述,建立X, y, theta矩阵 公式:
不知道列向量的Markdown格式
(1)新增一列,值为1
data.insert(0, 'Ones', 1)(2)建立X, y, theta矩阵
cols = data.shape[1] #列数 X = data.iloc[:,0:cols-1] #前2列的数据 y = data.iloc[:,cols-1:] #最后一列的数据 X = np.matrix(X.values) y = np.matrix(y.values) theta = np.matrix([0,0])5.代价函数
# 代价函数 len(X)行数 def computeCost(X, y, theta): inner = np.power((X * theta.T) - y, 2) return np.sum(inner) / (2 * len(X))6.梯度下降算法
#批量梯度下降算法 def gradientDescent(X, y, theta, alpha, epoch): temp = np.matrix(np.zeros(theta.shape)) cost = np.zeros(epoch) m = X.shape[0] for i in range(epoch): temp = theta - (alpha / m) * (X * theta.T - y).T * X theta = temp cost[i] = computeCost(X, y, theta) return theta, cost7.验证结果 (1)计算
alpha = 0.01 epoch = 1000 final_theta, cost = gradientDescent(X, y, theta, alpha, epoch)(2)线性回归可视化
x = np.linspace(data.Population.min(), data.Population.max(), 100) # 横坐标 f = final_theta[0, 0] + (final_theta[0, 1] * x) # 纵坐标,利润 fig, ax = plt.subplots(figsize=(6,4)) ax.plot(x, f, 'r', label='Prediction') ax.scatter(data['Population'], data.Profit, label='Traning Data') ax.legend(loc=2) # 2表示在左上角 ax.set_xlabel('Population') ax.set_ylabel('Profit') ax.set_title('Predicted Profit vs. Population Size') plt.show()(3)代价可视化
fig, ax = plt.subplots(figsize=(8,4)) ax.plot(np.arange(epoch), cost, 'r') # np.arange()返回等差数组 ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title('Error vs. Training Epoch') plt.show()三、参考文献 1.吴恩达机器学习作业Python实现(一):线性回归
数据分析所需库的安装,pandas的安装与numpy一样 ↩︎