机器学习之实验过程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()
相关推荐
深图智能4 分钟前
yoloV5训练visDrone2019-Det无人机视觉下目标检测
人工智能·yolo·目标检测·计算机视觉
手插口袋谁也不爱♡24 分钟前
本地化语音识别CapsWriter结合内网穿透远程会议录音秒变文字稿
人工智能·语音识别
deephub34 分钟前
FANformer:融合傅里叶分析网络的大语言模型基础架构
人工智能·语言模型·傅立叶分析
飞哥数智坊41 分钟前
Cursor实战:1小时集成天地图
人工智能·cursor
ianozo1 小时前
[GHCTF 2025]UPUPUP【.htaccess绕过 XBM/WBMP】
图像处理·人工智能
大囚长1 小时前
deepseek+ansible实现AI自动化集群部署
人工智能·自动化·ansible
程序边界1 小时前
AI+游戏开发:如何用 DeepSeek 打造高性能贪吃蛇游戏
人工智能·游戏
CodeJourney.1 小时前
光储直流微电网:能源转型的关键力量
数据库·人工智能·算法·能源
艾思科蓝 AiScholar1 小时前
【 IEEE出版 | 快速稳定EI检索 | 往届已EI检索】2025年储能及能源转换国际学术会议(ESEC 2025)
人工智能·计算机网络·自然语言处理·数据挖掘·自动化·云计算·能源
Fulima_cloud1 小时前
智慧锂电:开启能源新时代的钥匙
大数据·人工智能·物联网