Machine Leaning ex1:Linear Regression
Python实现了ex1线性回归
线性回归的核心函数是第2章。其余函数均为调用这章的函数来实现计算。
1. 简单练习
1.1 输出一个5*5的单位矩阵
a = np.eye(5, dtype=int)
2. 梯度下降:训练线性回归的参数θ
2.1 计算代价损失函数Cost
def computeCost(X, y, theta):
m = len(X) # m: 数据集规模
h_theta_x = X * theta.T # h_theta_x: 假设函数, 向量
inner = np.power((h_theta_x - y), 2)
J_theta = np.sum(inner) / (2 * m)
return J_theta
2.2 梯度下降函数
def gradientDescent(X, y, theta, alpha, num_iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.shape[1]) # theta的列数,用于更新每代的全部theta
cost = np.zeros(num_iters) # 形成iter次数相同的数组,记录损失函数J_theta
all_theta = np.zeros((num_iters, parameters))
for i in range(num_iters):
cost[i] = computeCost(X, y, theta)
all_theta[i] = theta
hx_Sub_y = X * theta.T - y # 假设函数-y
for j in range(parameters):
diff = np.multiply(hx_Sub_y, X[:, j]) # 计算偏导数(hxi-yi)*xi
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(diff))
theta = temp
return cost, all_theta
2.3 正规方程 normal equation
def normalequation(X, y):
theta = (X.T * X)**-1 * X.T * y
# computeCost的返回值theta形状统一
return theta.T
3 线性回归
3.1 单变量线性回归
在本次练习中,需要实现一个单变量的线性回归。
假设有一组历史数据<城市人口,开店利润>,现需要预测在哪个城市中开店利润比较好?
历史数据如下:第一列表示城市人口数,单位为万人;第二列表示利润,单位为10,000$
3.1.1 读取数据,然后展示数据
data_path = 'ex1data1.txt'
data = pd.read_csv(data_path, header=None, names=['Population', 'Profit'])
# 增加θ0
data.insert(0, 'Theta0', 1)
# 使用pd的绘图,预览原始数据
data.plot(kind='scatter', x='Population', y='Profit')
3.1.2 线性回归函数
def liner_regression():
return
3.2 多变量的线性回归函数
ex1data2.txt里的数据,第一列是房屋大小,第二列是卧室数量,第三列是房屋售价
根据已有数据,建立模型,预测房屋的售价
def multi_liner_regression():
return
4 绘图
4.1 绘制线性回归
def plotLinerRegression(data, theta):
X = np.linspace(