首页 > 其他分享 >【机器学习】单变量线性回归

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

时间:2023-07-30 20:56:34浏览次数:38  
标签:dj 变量 parameters gradient cost theta 线性 机器 ndarray

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

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

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

标签:dj,变量,parameters,gradient,cost,theta,线性,机器,ndarray
From: https://www.cnblogs.com/MrFeng2997/p/17592008.html

相关文章

  • Java学习6-面向对象基础 成员变量、成员方法、构造方法、this关键字、静态字段、静态
    一、面向对象概述面向过程开发,其实就是面向着具体的每一个步骤和过程,把每一个步骤和过程完成,然后由这些功能方法相互调用,完成需求。面向过程的代表语言:C语言当需求单一,或者简单时,我们一步一步去操作没问题,并且效率也挺高。可随着需求的更改,功能的增多,发现需要面对每一个步骤很麻......
  • 2023 年 7 月 23 日机器学习发生了什么:OpenAI 的突破性变化、更好的关注和……
    保留网络:大型语言模型转换器的继承者他们引入了一种非常有前途的注意力变体。基本上,他们:抛弃软最大值让每个令牌只关注一个状态向量,而不是所有以前的令牌在每个头上分别做层规范相对于序列维度呈指数衰减注意力,每个头部具有不同的衰减系数这使他们能够有效地在......
  • [Robot]FANUC发那科机器人零点标定
    FANUC的机械原点校准是通过零点标定来进行,具体操作步骤如下。首先,需要设定变量$MASTER_ENB的值为1,具体步骤为。1.MENU-下一页-变量。2.ITEM-输入313-变量$MASTER_ENB的值设为1。(注:不一定是313,可以通过shift+上/下键进行快速翻页查找)。接下来,通过MENU-下一页-系统-零点标定/......
  • 1.变量&&输入输出
    1.变量&&输入输出变量概念:变量,本质上是一个装东西的盒子,并且只能存放一个值。1.变量的命名规则变量的名字由:数字,字母,下划线组成,并且不能以数字开头,且区分大小写。变量的定义格式:变量名=值注意:赋值符号(从左往右读),==等于。a=1b=1.1c='hnfkujg'3.变量的类型int整型,f......
  • 1.变量&&输入输出
    1.变量&&输入输出一·变量概念:变量,本质上是一个装东西的盒子,并且只能存放一个值。1·变量的命名规则变量的名字由:数字,字母,下划线组成,并且不能以数字开头,且区分大小写。2.变量的定义格式:变量名=值注意:=赋值符号(从右往左读),==等于a=55b=6.555c='apple'3.变量的......
  • 线性代数
    线性代数在高铁上听了听线性代数的课,概念有点多,怕忘了。行列式一些基础的东西N(A):排列\(A\)的逆序数。2阶行列式:\(A=\begin{vmatrix}a&b\\c&d\end{vmatrix}=ad-bc\)3阶行列式:$A=\begin{vmatrix}a&b&c\\d&e&f\\g&j&i\end{vmatrix}=aei+djc+bf......
  • VarHandle:Java9中保证变量读写可见性、有序性、原子性利器
    文章目录一、什么是VarHandle0、JMM1、jdk9之前无锁技术的实现二、VarHandle使用1、VarHandle快速上手2、VarHandle常用方法3、实战案例1:解决可见性(比volatile轻量)4、实战案例2:解决指令重排序(比volatile轻量)(1)案例分析:partialordering(2)案例分析:totalordering一、什么是VarHand......
  • 【C语言趣味教程】(4) 变量:代码注释 | 变量的声明 | 初始化与赋值 | 变量的命名 | 关
    Ⅰ.代码注释(Comment)0x00引入:注释的作用"程序员最讨厌两种人:一种是不写注释的人,一种是让我写注释的人。"相信大家对注释早已有所耳闻,对于注释,C语言有两种注释风格,我们下面会逐个讲解。 但在这之前,我们先来了解了解注释的作用,注释就是用于解释代码的文字的。注释通常用于版本、版......
  • 交换变量a,b的值(java)
    方法1:引入中间变量inta=10;intb=20;inttemp=a;a=b;b=temp;System.out.println("a="+a+",b="+b);//a=20,b=10方法2:利用赋值符号=inta=10;intb=20;a=b+(a-(b=a));System.out.println("a="+a+&qu......
  • 埃斯顿机器人在线编程
    1,设置电脑IP与机器人控制器LAN2口为同一网段; 2,打开,点击连接;   3,下载和上载程序   4,如果想通过电脑控制埃斯顿机器人点动,需要下载单独的示教器demo,且官网下载不到; ......