【Deep-ML系列】Linear Regression Using Gradient Descent(手写梯度下降)

题目链接:Deep-ML

这道题主要是要考虑矩阵乘法的维度,保证维度正确,就可以获得最终的theata

python 复制代码
import numpy as np
def linear_regression_gradient_descent(X: np.ndarray, y: np.ndarray, alpha: float, iterations: int) -> np.ndarray:
    """
    Linear regression
    :param X: m * n
    :param y:
    :param alpha:
    :param iterations:
    :return:
    """
    m, n = X.shape
    theta = np.zeros((n, 1))
    y = y.reshape(m, 1)     # 保证y是列向量
    for i in range(iterations):
        prediction = np.dot(X, theta)   # m * 1
        error = prediction - y          # m * 1
        gradient = np.dot(X.T, error)   # n * 1
        theta = theta - alpha * (1 / m) * gradient
    theta = np.round(theta, decimals=4)
    return theta

if __name__ == '__main__':
    X = np.array([[1, 1], [1, 2], [1, 3]])
    y = np.array([1, 2, 3])
    alpha = 0.01
    iterations = 1000
    print(linear_regression_gradient_descent(X, y, alpha, iterations))
相关推荐
能来帮帮蒟蒻吗4 分钟前
深度学习(2)—— 神经网络与训练
人工智能·深度学习·神经网络
新加坡内哥谈技术18 分钟前
从文字到世界:空间智能是人工智能的下一个前沿
人工智能
wefg134 分钟前
【数据结构】unordered 系列容器底层结构和封装
数据结构·算法·哈希算法
oil欧哟35 分钟前
文心 5.0 来了,百度大模型的破局之战
前端·人工智能·百度·prompt
玩转AGI35 分钟前
一文看懂 Agentic AI:搭建单体 vs 多智能体系统,结果出乎意料!
人工智能
ai大模型分享员36 分钟前
项目实战:基于RAPTOR RAG检索技术的工业设备故障诊断系统
人工智能
从零点41 分钟前
插补算法(逐点比较法)+PWM配置操作
算法
DARLING Zero two♡1 小时前
【优选算法】LinkedList-Concatenate:链表的算法之契
数据结构·c++·算法·链表
MUTA️1 小时前
什么是RKNN?
人工智能