当前位置: 首页 > news >正文

Numpy 手搓线性回归

生成模拟数据

import numpy as np

import matplotlib.pyplot as plt

# 生成模拟数据

np.random.seed(42)

X = 2 * np.random.rand(200, 1) #  200 行、1 列的二维数组,就是200个x

Y = 4 + 3 * X + np.random.randn(200, 1)

# 可视化模拟数据

plt.scatter(X, Y) # 绘制散点图

plt.xlabel('X')

plt.ylabel('Y')

plt.title('Simulated Data')

plt.show()

以梯度下降完成线性回归

# 将偏执项b作为一个特征融入矩阵运算

b_X = np.c_[np.ones((200, 1)),X]

# 定义学习率,迭代次数和样本数量

rate = 0.01

iterations = 1000

m = 200

# 参数theta

theta = np.random.randn(2, 1)

# 损失函数的梯度下降

for _ in range(iterations):

    temp = 1/m *  b_X.T.dot( b_X.dot(theta) - Y)

    theta = theta - rate * temp

X_new = np.array([[0], [2]])  # 覆盖原始X的取值范围(0到2)

X_new_b = np.c_[np.ones((2, 1)), X_new]  # 同样添加偏置项列(全为1)

y_hat = X_new_b.dot(theta)  # 计算预测值

# 绘制图像

plt.plot(X,  b_X.dot(theta), 'g-', label='Prediction')

plt.scatter(X, Y)

plt.xlabel('X')

plt.ylabel('Y')

plt.legend()

plt.title('Linear Regression')

plt.show()

绘制结果

完整代码

import numpy as np

import matplotlib.pyplot as plt

# 生成模拟数据

np.random.seed(42)

X = 2 * np.random.rand(200, 1) #  200 行、1 列的二维数组,就是200个x

Y = 4 + 3 * X + np.random.randn(200, 1)

# # 可视化模拟数据

# plt.scatter(X, Y) # 绘制散点图

# plt.xlabel('X')

# plt.ylabel('Y')

# plt.title('Simulated Data')

# plt.show()

# 将偏执项b作为一个特征融入矩阵运算

b_X = np.c_[np.ones((200, 1)),X]

# 定义学习率,迭代次数和样本数量

rate = 0.01

iterations = 1000

m = 200

# 参数theta

theta = np.random.randn(2, 1)

# 损失函数的梯度下降

for _ in range(iterations):

    temp = 1/m *  b_X.T.dot( b_X.dot(theta) - Y)

    theta = theta - rate * temp

X_new = np.array([[0], [2]])  # 覆盖原始X的取值范围(0到2)

X_new_b = np.c_[np.ones((2, 1)), X_new]  # 同样添加偏置项列(全为1)

y_hat = X_new_b.dot(theta)  # 计算预测值

# 绘制图像

plt.plot(X,  b_X.dot(theta), 'g-', label='Prediction')

plt.scatter(X, Y)

plt.xlabel('X')

plt.ylabel('Y')

plt.legend()

plt.title('Linear Regression')

plt.show()

http://www.dtcms.com/a/442177.html

相关文章:

  • 昆明网站服务器湖北seo推广
  • 医院网站建设怎么样盐城网站建设效果
  • dockerfile理解
  • SpringBoot集成Druid连接池_配置优化与监控实践指南
  • 12380网站建设打算公众号小程序开发公司
  • 高并发场景下的前后端数据同步策略:长轮询、SSE与WebSocket对比分析
  • 网站推广对接北京手机网站搭建费用
  • Raydium
  • 动态Vault
  • 量化交易策略中ATR与波动率的配合
  • 便宜的网站设计企业永久免费自动建站系统
  • 深入解析JS事件循环机制 (Event Loop)
  • 亭湖区建设局网站小红书推广计划
  • 吃透大数据算法-时间轮(TimingWheel)
  • 从输入URL到展示出页面的这个过程~
  • WebDAV 与 SMB 在钓鱼攻击中的区别
  • 8. Pandas 日期与时间序列数据处理
  • 免费网站模板做零食的网站有哪些
  • 从零开始的C++学习生活 2:类和对象(上)
  • 家纺营销型网站网站建设服务费怎么记账
  • css其他选择器(精细修饰)
  • 一般设计网站页面用什么软件做引擎网站
  • 生成式 AI 重构内容创作:从辅助工具到智能工厂
  • 华为S5720配置telnet远程
  • 面试复盘:哔哩哔哩、蔚来、字节跳动、小红书面试与总结
  • Your ViT is Secretly an Image Segmentation Model
  • 海口网站建设运营网站开发公司选择
  • 日语学习-日语知识点小记-进阶-JLPT-N1阶段应用练习(4):语法 +考え方17+2022年7月N1
  • RAG:解锁大语言模型新能力的关键钥匙
  • 广州网站建设海珠信科网站建设推广方法