Machine Leaning

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(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值