机器学习之实验过程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()
相关推荐
却道天凉_好个秋27 分钟前
深度学习(二):神经元与神经网络
人工智能·神经网络·计算机视觉·神经元
UQI-LIUWJ28 分钟前
unsloth笔记:运行&微调 gemma
人工智能·笔记·深度学习
THMAIL31 分钟前
深度学习从入门到精通 - 生成对抗网络(GAN)实战:创造逼真图像的魔法艺术
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·cnn
却道天凉_好个秋33 分钟前
计算机视觉(八):开运算和闭运算
人工智能·计算机视觉·开运算与闭运算
无风听海34 分钟前
神经网络之深入理解偏置
人工智能·神经网络·机器学习·偏置
JoinApper35 分钟前
目标检测系列-Yolov5下载及运行
人工智能·yolo·目标检测
飞哥数智坊1 小时前
即梦4.0实测:我真想对PS说“拜拜”了!
人工智能
fantasy_arch1 小时前
9.3深度循环神经网络
人工智能·rnn·深度学习
Ai工具分享1 小时前
视频画质差怎么办?AI优化视频清晰度技术原理与实战应用
人工智能·音视频
新智元2 小时前
不到 10 天,国产「香蕉」突袭!一次 7 图逼真还原,合成大法惊呆歪果仁
人工智能·openai