机器学习之实验过程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, theta0 + theta1 * 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 = {theta0:.2f} + {theta1:.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()
相关推荐
水上冰石1 小时前
【MHS协议】第四章:ESP32 接入 MHS 协议实战:从零构建一个 MHS 兼容设备
人工智能·架构·机器人
知了一笑2 小时前
个体看衰AI,企业加速转型
人工智能·ai
飞哥数智坊4 小时前
一只虾到多只虾:先聊聊我为什么要“拆虾”
人工智能
飞哥数智坊4 小时前
架构图 SKILL 封装好了,顺便做了虾的适配
人工智能
冬奇Lab4 小时前
Code Agent 解剖(16):AgentTeams——为什么一个 agent 不够用?
人工智能
东风破_4 小时前
聊天记录越来越长怎么办?从消息数量截断到 Token 截断
人工智能
冬奇Lab4 小时前
开源项目第204期:LoopX — 长周期 Agent 控制平面,跑在 Codex/Claude Code 之上的状态管理层
人工智能·开源
ZGIAI4 小时前
旧模型下线前,客服 Agent 怎么迁移
人工智能·架构
东风破_5 小时前
程序重启后,AI 为什么把你忘了?从 InMemory 到持久化 Memory
人工智能
ZGIAI5 小时前
客服知识库更新后,怎么批量验收
人工智能·架构