machine learning自定义数据集使用框架的线性回归方法对其进行拟合

使用框架(如Scikit-learn)对自定义数据集进行线性回归拟合是一个常见的任务。以下是一个详细的步骤指南,展示如何使用Scikit-learn库在Python中完成这一任务

python 复制代码
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

# 示例数据
X = np.array([[1], [2], [3], [4], [5]])  # 特征,形状为 (n_samples, n_features)
y = np.array([1, 3, 2, 3, 5])           # 目标

# 拆分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建线性回归模型
model = LinearRegression()

# 训练模型
model.fit(X_train, y_train)

# 对测试集进行预测
y_pred = model.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"Mean Squared Error: {mse}")
print(f"R^2 Score: {r2}")

# 可视化结果
plt.scatter(X, y, color='blue', label='Data')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Regression Line')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
相关推荐
漂流瓶jz4 小时前
【AI】大模型本地部署与量化:Ollama、transformers、llama.cpp实践
人工智能·llm·ai编程
毕竟是shy哥6 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
飞哥数智坊6 小时前
AI时代,我们到底该学什么、用什么,为什么还没提效?
人工智能
飞哥数智坊6 小时前
GPT 做架构,国内模型写代码:这条 AI 开发路线能跑通吗?
人工智能·ai编程
AI_AGENT_DEV_AI6 小时前
AI 智能体的开发与上线
人工智能
VL——MOESR6 小时前
【具身智能】VLA论文阅读随笔
论文阅读·人工智能·机器学习·具身智能·vla
OCR_133716212757 小时前
从模板匹配到AI泛化识别:文本抽取如何重构护照阅读器落地生态
人工智能·重构
大唐荣华7 小时前
从OpenAI关停Sora看世界模型、AI视频与国内具身智能赛道路线分化
人工智能·openai·sora·内容生成
DevOps老兵7 小时前
AI Infra实战02:GPU监控实战,用DCGM+Prometheus+Grafana看清每一张卡
人工智能·grafana·prometheus·ai infra·gpu监控·dcgm
旧日之血_Hayter7 小时前
Antigravity 工作流的实践记录
人工智能