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

机器学习之实验过程01

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

data_path = '/home/py/Work/labs/data/SD.csv'  # 请确保您的数据文件路径是正确的

df = pd.read_csv(data_path)

df.head()

# 创建散点图 

# 创建散点图
plt.figure(figsize=(10, 6))
plt.scatter(df['成本'], df['价格'], color='blue', label='Data Spot')
plt.title('Cost vs Price')
plt.xlabel('Cost')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()
plt.savefig('test.jpg')

实现梯度下降算法来优化线性回归模型的参数

def gradient_descent(X, y, learning_rate=0.01, iterations=100):"""实现梯度下降算法来优化线性回归模型的参数。"""m = len(y)X = np.hstack((np.ones((m, 1)), X))  # 添加一列 1 作为偏置项theta = np.zeros(X.shape[1])loss_history = []for _ in range(iterations):predictions = X.dot(theta)errors = predictions - ygradient = X.T.dot(errors) / mtheta -= learning_rate * gradientloss = np.mean(errors ** 2) / 2loss_history.append(loss)return theta, loss_history

# 准备数据

X = df[['成本']]

y = df['价格']

# 使用梯度下降优化参数

theta, _ = gradient_descent(X, y, iterations=1000)

# 绘制回归拟合图

plt.figure(figsize=(10, 6))

plt.scatter(X, y, color='blue', label='Data Spot')

plt.plot(X, theta[0] + theta[1] * X, color='red', label='Fitting line')

plt.title('Cost vs Price')

plt.xlabel('Cost')

plt.ylabel('Price')

plt.legend()

plt.grid(True)

plt.show()

# 显示回归方程

print(f"The regression equation is: Price = {theta[0]:.2f} + {theta[1]:.2f} * Cost")

# 分析迭代次数对性能的影响 

# 分析迭代次数对性能的影响
iteration_counts = [50, 100, 200, 500, 1000,2000]
losses = []for iterations in iteration_counts:_, loss_history = gradient_descent(X, y, iterations=iterations)losses.append(loss_history[-1])
# 绘制结果
plt.figure(figsize=(10, 6))
plt.plot(iteration_counts, losses, marker='o')
plt.title('Loss vs. Iteration')
plt.xlabel('Iterations')
plt.ylabel('Loss Value')
plt.grid(True)
plt.show()

http://www.lryc.cn/news/267130.html

相关文章:

  • 【【迭代16次的CORDIC算法-verilog实现】】
  • IntelliJ IDEA 2023.3 安装教程
  • Go 错误处理
  • HarmonyOS构建第一个ArkTS应用(Stage模型)
  • 故障排查利器-错误日志详解
  • 微信小程序(uniapp)api讲解
  • overtureDNS使用介绍
  • 平衡二叉树的构建(递归
  • flutter开发实战-设置bottomNavigationBar中间按钮悬浮效果
  • 不同参数规模大语言模型在不同微调方法下所需要的显存总结
  • Crow:Middlewares 庖丁解牛6 middleware_call_helper
  • MyBatis:Generator
  • rabbitmq的事务实现、消费者的事务实现
  • 龙芯杯个人赛串口——做一个 UART串口——RS-232
  • 验证码服务使用指南
  • js中Math.min(...arr)和Math.max(...arr)的注意点
  • 【zookeeper特点和集群架构】
  • MySQL集群架构搭建以及多数据源管理实战
  • C# WPF上位机开发(从demo编写到项目开发)
  • 微信小程序引入 vant组件(详细步骤)
  • Django之按钮(actions)
  • 从YOLOv1到YOLOv8的YOLO系列最新综述【2023年4月】
  • 浙江大唐乌沙山电厂选择ZStack Cloud打造新一代云基础设施
  • 电脑开机快捷启动,启动菜单没有u盘怎么办
  • 线程的同步与互斥
  • 低代码实施复杂应用的实践方法
  • 算法学习系列(十一):KMP算法
  • ****Linux下Mysql的安装和配置
  • 第十六节TypeScript 类
  • RocketMQ的Docker镜像部署(以及Dashboard的部署、ACL配置)