机器学习之实验过程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 分钟前
宇树科技回应联合英伟达开发“H2+”人形机器人,预计今年下半年正式亮相
人工智能·科技·机器学习·ai·chatgpt·机器人·大模型
Sammyyyyy5 分钟前
2026 Mac 本地大模型部署深度解析与混合架构指南
数据库·人工智能·macos·ai·架构·servbay
阿寻寻7 分钟前
【人工智能学习-20260608】什么是生成式AI?
人工智能·学习
kTR2hD1qb17 分钟前
AI助手如何重塑开发工作流
人工智能
Hali_Botebie17 分钟前
变分推断(Variational Inference, VI)数学角度,以及结合神经网络的形式
人工智能·神经网络·机器学习
咖啡星人k18 分钟前
MonkeyCode 私有化部署实战:企业内网AI开发环境搭建全流程
人工智能·monkeycode
lqqjuly18 分钟前
一致性模型深度解析
人工智能·深度学习·算法
cxr82820 分钟前
基于人工智能的超材料逆向设计
人工智能·材料逆向设计合成
霸道流氓气质26 分钟前
Spring AI Alibaba Skills 完整实战:从零构建智能会议助手
java·人工智能·spring
眠りたいです35 分钟前
LangChainv1:agent快速上手与中间件认识
人工智能·python·中间件·langchain·langgraph