【机器学习】单变量线性回归

这篇具有很好参考价值的文章主要介绍了【机器学习】单变量线性回归。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

ML introduction

机器学习:从数据中学习,而不依赖于规则下编程的一种算法

Goal: \(min_{w,b}(J(w, b))\) - 提供一种衡量一组特定参数与训练数据拟合程度的方法

Supervised Learning

right answer && x -> y label

categories

  • Regression
  • Classification

Unsupervised Learning

structure || pattern

categories

  • Clustering
  • Anomaly detection 异常检测
  • Dimensionality reduction 降维

Liner Regression with One Variable

预测数字问题

这部分主要内容包括单变量线性回归的模型表示、代价函数、梯度下降法和使用梯度下降法求解代价函数的最小值。

线性回归模型

数学表达式

\[f_{w,b}(x^{(i)}) = wx^{(i)}+b \]

代码

ndarray:n维数组类对象

scalar:标量

# 迭代
def compute_model_output(x, w, b):
    """
    Computes the prediction of a linear model
    Args:
      x (ndarray (m,)): Data, m examples 
      w,b (scalar)    : model parameters  
    Returns
      y (ndarray (m,)): target values
    """
    m = x.shape[0]
    f_wb = np.zeros(m)
    for i in range(m):
        f_wb[i] = w * x[i] + b
        
    return f_wb
# 向量
def compute_model_output(x, w, b): 
    """
    single predict using linear regression
    Args:
      x (ndarray): Shape (n,) example with multiple features
      w (ndarray): Shape (n,) model parameters   
      b (scalar):             model parameter 
      
    Returns:
      p (scalar):  prediction
    """
    yhat = np.dot(x, w) + b     
    return yhat

Cost Function

数学表达式

\[J(w,b) = \frac{1}{2m}\sum_{i=1}^{m} (f_{w, b}(x^{(i)}) - y^{(i)})^2 \]
\[f_{w,b}(x^{(i)}) = wx^{(i)} + b \]

参数表:

m y error
训练样例 真值 \(f_{w, b}(x^{(i)}) - y^{(i)}\)

代码

# 迭代
def compute_cost(x, y, w, b): 
    """
    Computes the cost function for linear regression.
    
    Args:
      x (ndarray (m,)): Data, m examples 
      y (ndarray (m,)): target values
      w,b (scalar)    : model parameters  
    
    Returns
        total_cost (float): The cost of using w,b as the parameters for linear regression
               to fit the data points in x and y
    """
    # number of training examples
    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
# 向量
def compute_cost(X, y, theta):
    """
    Computes the cost function for linear regression.
    Args:
       X (ndarray (m,)): Data, m examples 
       y (ndarray (m,)): target values
       theta (b (ndarray (m,), w (ndarray (m,))): model parameters
    
     Returns
        total_cost (float): The cost of using theta as the parameters for linear regression
               to fit the data points in X and y
    """
    error = (X * theta.T) - y
    inner = np.power(error, 2)
    total_cost = np.sum(inner)/(2 * len(X))
    return total_cost

数学原理

求导:不同的w对应不同的J,对多个点拟合出的曲线求导,以期找到最小的J对应的w

function of w

function of w

function of w

function of w

Gradient Descent

(迭代)=> 极值点

大样本:每次梯度更新都抽部分样本

数学表达式

\[\begin{align*} \text{repeat}&\text{ until convergence:} \; \lbrace \newline \; w &= w - \alpha \frac{\partial J(w,b)}{\partial w} \; \newline b &= b - \alpha \frac{\partial J(w,b)}{\partial b} \newline \rbrace \end{align*} \]
\[\begin{align} \frac{\partial J(w,b)}{\partial w} &= \frac{1}{m} \sum\limits_{i = 0}^{m-1} (f_{w,b}(x^{(i)}) - y^{(i)})x^{(i)} \\ \frac{\partial J(w,b)}{\partial b} &= \frac{1}{m} \sum\limits_{i = 0}^{m-1} (f_{w,b}(x^{(i)}) - y^{(i)}) \\ \end{align} \]

\(\alpha\): 学习率,控制更新模型参数w和b时采取的步骤大小

代码

# 迭代
def compute_gradient(x, y, w, b): 
    """
    Computes the gradient for linear regression 
    Args:
      x (ndarray (m,)): Data, m examples 
      y (ndarray (m,)): target values
      w,b (scalar)    : model parameters  
    Returns
      dj_dw (scalar): The gradient of the cost w.r.t. the parameters w
      dj_db (scalar): The gradient of the cost w.r.t. the parameter b     
     """
    
    # Number of training examples
    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_db += dj_db_i
        dj_dw += dj_dw_i 
    dj_dw = dj_dw / m 
    dj_db = dj_db / m 
        
    return dj_dw, dj_db

def gradient_descent(x, y, w_in, b_in, alpha, num_iters, cost_function, gradient_function): 
    """
    Performs gradient descent to fit w,b. Updates w,b by taking 
    num_iters gradient steps with learning rate alpha
    
    Args:
      x (ndarray (m,))  : Data, m examples 
      y (ndarray (m,))  : target values
      w_in,b_in (scalar): initial values of model parameters  
      alpha (float):     Learning rate
      num_iters (int):   number of iterations to run gradient descent
      cost_function:     function to call to produce cost
      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) # avoid modifying global w_in
    # An array to store cost J and w's at each iteration primarily for graphing later
    J_history = []
    p_history = []
    b = b_in
    w = w_in
    
    for i in range(num_iters):
        # Calculate the gradient and update the parameters using gradient_function
        dj_dw, dj_db = gradient_function(x, y, w , b)     

        # Update Parameters using equation (3) above
        b = b - alpha * dj_db                            
        w = w - alpha * dj_dw                            

        # Save cost J at each iteration
        if i<100000:      # prevent resource exhaustion 
            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 #return w and J,w history for graphing
# 向量
def gradient_descent(X, y, theta, alpha, iters):
    """
    Performs gradient descent to fit w,b. Updates w,b by taking 
    num_iters gradient steps with learning rate alpha

    Args:
      X (ndarray (m,))    : Data, m examples 
      y (ndarray (m,))    : target values
      theta (ndarray (m,)): initial values of model parameters  
      alpha (float)       : Learning rate
      iters (scalar)      : number of interations 

    Returns:
      theta (ndarray (m,)): Updated parameter of parameter after running gradient descent
      cost (ndarray (m,)) : Record the cost after each iteration
    """
    tmp = np.matrix(np.zeros(theta.shape)) # 构造零值矩阵
    parameters = int(theta.ravel().shape[1]) # theta的列即参数的个数
    cost = np.zeros(iters) # 构建iters个()的数组
    # 迭代
    for i in range(iters):
        error = (X * theta.T) - y
        for j in range(parameters):
            term = np.multiply(error, X[:, j]) # 求内积 np.multiply
            tmp[0, j] = theta[0, j] - ((alpha / len(X) * np.sum(term)))
            
        theta = tmp
        cost[i] = computeCost(X, y, theta)
        
    return theta, cost

数学原理

(w和b要同时更新)

最小二乘法

形式:$$标函数 = sum(观测值 - 理论值)^2$$

解法:https://www.cnblogs.com/pinard/p/5976811.html文章来源地址https://www.toymoban.com/news/detail-615693.html

  • 代数法:偏导数求最值
  • 矩阵法:normal equation(有局限性)

到了这里,关于【机器学习】单变量线性回归的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

    [ 实验1 回归分析] 一、 预备知识 使用梯度下降法求解多变量回归问题 数据集 Iris 鸢尾花数据集是一个经典数据集,在统计学习和机器学习领域都经常被用作示例。数据集内包含 3 类共 150 条记录,每类各 50 个数据,每条记录都有 4 项特征:花萼长度、花萼宽度、花瓣长度、

    2023年04月13日
    浏览(73)
  • 机器学习——线性回归/岭回归/Lasso回归

    线性回归会用到python第三方库:sklearn.linear_model中的LinearRegression 导入第三方库的方法:from sklearn.linear_model import LinearRegression 使用LinearRegression(二维数据,一维数据)进行预测,其中数据类型可以是pandas中的DataFrame或者series,也可以是numpy中的array数据,但维度一定要正确输入。

    2024年02月10日
    浏览(29)
  • 机器学习~从入门到精通(二)线性回归算法和多元线性回归

    SimpleLinearRegression.py moduel_selection.py draft.py lin_fit(x,y) lin_fit2(x,y) x.shape y.shape MSE mean squared error 均方误差 R squared error

    2024年02月01日
    浏览(58)
  • Spark-机器学习(3)回归学习之线性回归

    在之前的文章中,我们了解我们的机器学习,了解我们spark机器学习中的特征提取和我们的tf-idf,word2vec算法。想了解的朋友可以查看这篇文章。同时,希望我的文章能帮助到你,如果觉得我的文章写的不错,请留下你宝贵的点赞,谢谢。 Spark-机器学习(2)特征工程之特征提

    2024年04月22日
    浏览(30)
  • 机器学习——线性回归

    基于Python实现线性回归、预测和建模评估。 1 模型设定 以Boston数据集为例,其中MEDV是标签,其余均为特征变量 CRIM per capita crime rate by town ZN proportion of residential land zoned for lots over 25,000 sq.ft. INDUS proportion of non-retail business acres per town CHAS Charles River dummy variable (= 1 if tract bounds

    2024年02月04日
    浏览(30)
  • 【机器学习】线性回归模型详解

    PS:本文有一定阅读门槛,如果有不明白的地方欢迎评论询问! 接下来我们将要学习我们的第一个模型——线性回归。比如说我需要根据数据预测某个面积的房子可以卖多少钱 接下来我们会用到以下符号: m:训练样本数量 x:输入值,又称为属性值 y:输出值,是我们需要的结果

    2024年02月03日
    浏览(52)
  • 【机器学习】线性回归(超详细)

    上一篇: 机器学习是什么? https://mp.csdn.net/mp_blog/creation/editor/122619296   目录 2.单变量线性回归 2.1 模型表示 2.2 代价函数 2.2.1 代价函数的直观理解I 2.2.2 代价函数的直观理解II 2.3 梯度下降 2.3.1 梯度下降的直观理解 2.3.2 梯度下降的线性回归 3.线性代数的回顾 3.1矩阵和向量 3

    2024年02月09日
    浏览(24)
  • 机器学习——线性回归、梯度下降

    监督学习 :学习数据带有标签 无监督学习 :没有任何的标签,或者有相同的标签 其他:强化学习、推荐系统等 还是房价预测的例子, 训练集如下: 定义各个变量的含义如下: m——代表训练集中实例的数量 x——代表特征/输入变量 y——代表目标变量/输出变量 (x,y)——代

    2024年02月07日
    浏览(36)
  • 机器学习——多元线性回归算法

    多元线性回归算法,即多特征量线性回归算法,用多个特征量来进行预测,如这里用多个特征量(房子面积、卧室数量、房屋楼层数、房子年龄)来预测房子的售价问题 假如有一个多特征量的机器学习问题,并且这个问题中的多个特征可以在一个相近的范围内取值,那么可以

    2024年02月22日
    浏览(36)
  • 【机器学习300问】11、多元线性回归模型和一元线性回归有什么不同?

            在之前的文章中,我们已经学习了一元线性回归模型,其中最关键的参数是w和b。机器学习的目的就是去得到合适w和b后能准确预测未知数据。但现实世界是复杂的,一个事情的发生绝大多数时候不会是一个原因导致。         因此多元线性回归模型区别与一元线

    2024年01月22日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包