机器学习-线性回归Python代码实现

线性回归简介

线性回归是机器学习中最简单和最常见的回归问题之一。它是一种用于预测连续数值输出的统计模型,它假设自变量(输入特征)与因变量(输出)之间存在线性关系。

在线性回归中,我们假设因变量与自变量之间的关系可以表示为一个直线方程:y=wx+b,其中w、b为模型的相关参数,x为输入特征,y为预测值。

训练线性回归模型的步骤包括以下几个关键步骤:

  1. 数据收集:收集包含自变量和因变量的样本数据。这些数据可以是实际观测值或者从其他来源获取的数据。

  2. 数据预处理:对数据进行预处理,包括数据清洗、缺失值处理、特征工程等步骤,以便为模型提供可用的数据。

  3. 特征选择:选择与因变量相关的自变量作为模型输入特征。通过研究特征之间的相关性和各自与因变量的关系,来决定哪些特征对预测较为重要。

  4. 模型训练:使用训练数据拟合线性模型,并找到最佳的斜率和截距。通常采用最小二乘法或者梯度下降等优化算法来最小化模型的残差。

  5. 模型评估:使用评估指标(例如均方误差、决定系数等)来评估模型的性能。一般来说,较低的均方误差和较高的决定系数表示模型预测效果较好。

  6. 模型应用:使用训练好的模型进行预测。给定新的自变量,模型可以通过线性方程预测相应的因变量。

代价函数

公式如下:

 代码:

import numpy as np
import matplotlib.pyplot as plt
from lab_utils_uni import plt_intuition, plt_stationary, plt_update_onclick, soup_bowl

plt.style.use('./deeplearning.mplstyle')

def compute_cost(x,y,w,b):
    """
    :param x: data,m examples
    :param y: target values
    :param w: model parameters
    :param b: model parameters
    :return: total_cost: The cost of using w,b as the paramters to fit the data points in x and y
    """
    m = x.shape[0]
    cost_sum = 0

    for i in range(m):
        f_wb = w * x[i] + b
        cost = (f_wb - y[i]) ** 2   #两个*表示平方
        cost_sum = cost_sum + cost
    total_cost = (1/(2*m))*cost_sum

    return total_cost


x_train = np.array([1.0, 1.7, 2.0, 2.5, 3.0, 3.2])
y_train = np.array([250, 300, 480,  430,   630, 730,])

plt.close('all')
fig, ax, dyn_items = plt_stationary(x_train, y_train)
updater = plt_update_onclick(fig, ax, x_train, y_train, dyn_items)

soup_bowl()

运行效果:

可以看到当cost(w,b)越靠近中间圆圈,预测值越接近于真实值

 

梯度下降代码

具体运算公式如下图

 代码:

import math, copy
import numpy as np
import matplotlib.pyplot as plt
from lab_utils_uni import plt_house_x, plt_contour_wgrad, plt_divergence, plt_gradients

# Load our data set 数据集
x_train = np.array([1.0, 2.0])   #features
y_train = np.array([300.0, 500.0])   #target value


# Function to calculate the cost 代价函数
def compute_cost(x, y, w, b):
    m = x.shape[0]
    cost = 0

    for i in range(m):
        f_wb = w * x[i] + b
        cost = cost + (f_wb - y[i]) ** 2
    total_cost = 1 / (2 * m) * cost

    return total_cost

# Function to calculate the gradient
def compute_gradient(x,y,w,b):
    """
    :param x: Data, m examples
    :param y: target values
    :param w: model parameter
    :param b: model parameter
    :returns
     dj_dw: The gradient of the cost w.r.t  The parameters w
     dj_db: The gradient of the cost w.r.t  The parameters b
    """

    m = x.shape[0]
    dj_dw = 0
    dj_db = 0

    for i in range(m):
        f_wb = w * x[i] + b
        dj_dw_i = (f_wb - y[i]) * x[i]
        dj_db_i = (f_wb - y[i])
        dj_dw = dj_dw + dj_dw_i
        dj_db = dj_db + dj_db_i
    dj_dw = dj_dw / m
    dj_db = dj_db / m

    return dj_dw, dj_db

plt_gradients(x_train,y_train, compute_cost, compute_gradient)
plt.show()


def gradient_descent(x, y, w_in, b_in, alpha, num_iters, cost_function, gradient_function):
    """
    :param x: Data, m examples
    :param y: target values
    :param w_in,b_in: initial values of model parameters
    :param alpha: Learning rate 学习率
    :param num_iters: number of iterations to run gradient descent 迭代次数
    :param cost_function: function to call to produce cost
    :param gradient_function: function to call to produce gradient

    :Returns:
        w (scalar): Updated value of parameter after running gradient descent
        b (scalar): Updated value of parameter after running gradient descent
        J_history (List): History of cost values
        p_history (list): History of parameters [w,b]
    """

    w = copy.deepcopy(w_in) #深复制避免赋值后原变量被修改
    J_history = []
    p_history = []
    b = b_in
    w = w_in

    for i in range(num_iters):
        #计算梯度
        dj_dw, dj_db = gradient_function(x,y,w,b)

        #更新参数
        b = b - alpha * dj_db
        w = w - alpha * dj_dw

        if i<100000:
            J_history.append(cost_function(x,y,w,b))
            p_history.append([w,b])

        # Print cost every at intervals 10 times or as many iterations if < 10
        if i % math.ceil(num_iters / 10) == 0:
            print(f"Iteration {i:4}: Cost {J_history[-1]:0.2e} ",
                f"dj_dw: {dj_dw: 0.3e}, dj_db: {dj_db: 0.3e}  ",
                f"w: {w: 0.3e}, b:{b: 0.5e}")

    return w,b,J_history,p_history

# initialize parameters
w_init = 0
b_init = 0
# some gradient descent settings
iterations = 10000
tmp_alpha = 1.0e-2 #学习率设置不宜过大也不宜过小
# run gradient descent
w_final, b_final, J_hist, p_hist = gradient_descent(x_train ,y_train, w_init, b_init, tmp_alpha,
                                                    iterations, compute_cost, compute_gradient)
print(f"(w,b) found by gradient descent: ({w_final:8.4f},{b_final:8.4f})")

#plot cost versus iteration
fig, (ax1, ax2) = plt.subplots(1, 2, constrained_layout=True, figsize=(12,4))
ax1.plot(J_hist[:100])
ax2.plot(1000 + np.arange(len(J_hist[1000:])), J_hist[1000:])
ax1.set_title("Cost vs. iteration(start)");  ax2.set_title("Cost vs. iteration (end)")
ax1.set_ylabel('Cost')            ;  ax2.set_ylabel('Cost')
ax1.set_xlabel('iteration step')  ;  ax2.set_xlabel('iteration step')
plt.show()

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值