【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))
相关推荐
凯_kyle2 小时前
Python 算法竞赛 —— 基础篇(更新ing)
笔记·python·算法
Elastic 中国社区官方博客3 小时前
Elasticsearch:构建一个 AI 驱动的电子邮件钓鱼检测
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
lizz313 小时前
C++操作符重载深度解析
java·c++·算法
IT_陈寒3 小时前
Vite 5大优化技巧:让你的构建速度飙升50%,开发者都在偷偷用!
前端·人工智能·后端
l1t3 小时前
利用DeepSeek计算abcde五人排成一队,要使c在ab 之间,有几种排法
人工智能·组合数学·deepseek
阿拉斯攀登3 小时前
电子签名:笔迹特征比对核心算法详解
人工智能·算法·机器学习·电子签名·汉王
说私域3 小时前
基于开源链动2+1模式、AI智能名片与S2B2C商城小程序的运营创新研究
人工智能·小程序
ytttr8733 小时前
matlab进行利用遗传算法对天线阵列进行优化
开发语言·算法·matlab
一招定胜负3 小时前
机器学习算法三:决策树
算法·决策树·机器学习
无限进步_3 小时前
【C语言】队列(Queue)数据结构的实现与分析
c语言·开发语言·数据结构·c++·算法·链表·visual studio