【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))
相关推荐
康康的AI博客5 小时前
多模态大一统:从GPT-4突破到AI领域质的飞跃之路
人工智能·ai
gjxDaniel5 小时前
A+B问题天堂版
c++·算法·字符串·字符数组
咚咚王者5 小时前
人工智能之核心基础 机器学习 第十九章 强化学习入门
人工智能·机器学习
M__335 小时前
动态规划进阶:简单多状态模型
c++·算法·动态规划
flying_13145 小时前
图神经网络分享系列-GGNN(GATED GRAPH SEQUENCE NEURAL NETWORKS)(一)
人工智能·深度学习·神经网络·图神经网络·ggnn·门控机制·图特征学习
未来之窗软件服务5 小时前
计算机等级考试—Dijkstra(戴克斯特拉)& Kruskal(克鲁斯卡尔)—东方仙盟
算法·计算机软考·仙盟创梦ide·东方仙盟
Hcoco_me5 小时前
大模型面试题89:GPU的内存结构是什么样的?
人工智能·算法·机器学习·chatgpt·机器人
N.D.A.K5 小时前
CF2138C-Maple and Tree Beauty
c++·算法
sanggou5 小时前
Spring Boot 中基于 WebClient 的 SSE 流式接口实战
java·人工智能
DREAM依旧5 小时前
本地微调的Ollama模型部署到Dify平台上
人工智能·python