机器学习之实验过程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 - y
        gradient = X.T.dot(errors) / m
        theta -= learning_rate * gradient
        loss = np.mean(errors ** 2) / 2
        loss_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()
相关推荐
白熊1882 分钟前
【计算机视觉】论文精读《基于改进YOLOv3的火灾检测与识别》
人工智能·yolo·计算机视觉
鸢想睡觉11 分钟前
【OpenCV基础 1】几何变换、形态学处理、阈值分割、区域提取和脱敏处理
图像处理·人工智能
有Li19 分钟前
联合建模组织学和分子标记用于癌症分类|文献速递-深度学习医疗AI最新文献
人工智能·深度学习·分类
乌旭30 分钟前
开源GPU架构RISC-V VCIX的深度学习潜力测试:从RTL仿真到MNIST实战
人工智能·深度学习·stable diffusion·架构·aigc·midjourney·risc-v
qq_4162764235 分钟前
SuperYOLO:多模态遥感图像中的超分辨率辅助目标检测之论文阅读
论文阅读·人工智能·目标检测
RuizhiHe37 分钟前
从零开始实现大语言模型(十六):加载开源大语言模型参数
人工智能·chatgpt·llm·大语言模型·deepseek·从零开始实现大语言模型
asdfg125896341 分钟前
深度估计中为什么需要已知相机基线(known camera baseline)?
人工智能·计算机视觉
LeeZhao@44 分钟前
【AGI】大模型微调数据集准备
人工智能·数据挖掘·aigc·agi
atbigapp.com1 小时前
PromptIDE提示词开发工具支持定向优化啦
人工智能
jndingxin1 小时前
OpenCV CUDA模块中逐元素操作------算术运算
人工智能·opencv·计算机视觉