机器学习之实验过程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()
相关推荐
金井PRATHAMA4 小时前
描述逻辑(Description Logic)对自然语言处理深层语义分析的影响与启示
人工智能·自然语言处理·知识图谱
Rock_yzh4 小时前
AI学习日记——参数的初始化
人工智能·python·深度学习·学习·机器学习
CiLerLinux5 小时前
第四十九章 ESP32S3 WiFi 路由实验
网络·人工智能·单片机·嵌入式硬件
七芒星20237 小时前
多目标识别YOLO :YOLOV3 原理
图像处理·人工智能·yolo·计算机视觉·目标跟踪·分类·聚类
Learn Beyond Limits7 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
ACERT3338 小时前
5.吴恩达机器学习—神经网络的基本使用
人工智能·python·神经网络·机器学习
C嘎嘎嵌入式开发8 小时前
(一) 机器学习之深度神经网络
人工智能·神经网络·dnn
Aaplloo8 小时前
【无标题】
人工智能·算法·机器学习
大模型任我行8 小时前
复旦:LLM隐式推理SIM-CoT
人工智能·语言模型·自然语言处理·论文笔记
tomlone8 小时前
AI大模型核心概念
人工智能