作业二.自定义数据集使用scikit-learn中的包实现线性回归方法对其进行拟合

from sklearn.linear_model import LinearRegression

from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error

import numpy as np

import matplotlib.pyplot as plt

np.random.seed(0)

加载自定义数据集

X = 2 * np.random.rand(100, 1)

y = 4 + 3 * X + np.random.randn(100, 1)

将数据集划分为训练集和测试集

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)

print("均方误差:", mse)

plt.scatter(X_test, y_test, color='blue')

plt.plot(X_test, y_pred, color='red')

plt.show()

相关推荐
算法与编程之美4 小时前
机器学习测试模型的性能评估与探索
人工智能·机器学习
Eiceblue4 小时前
通过 C# 将 RTF 文档转换为图片
开发语言·算法·c#
2301_764441334 小时前
使用python构建的决策逻辑的图论
开发语言·python·图论
fruge4 小时前
深入理解 JavaScript 事件循环:宏任务与微任务的执行机制
开发语言·javascript·ecmascript
IT_Octopus4 小时前
java <T> 是什么?
java·开发语言
猿饵块4 小时前
c++17--std::owner_less
开发语言·c++
大千AI助手4 小时前
Text-Embedding-Ada-002:技术原理、性能评估与应用实践综述
人工智能·机器学习·openai·embedding·ada-002·文本嵌入·大千ai助手
如竟没有火炬4 小时前
快乐数——哈希表
数据结构·python·算法·leetcode·散列表
IMPYLH4 小时前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
郝学胜-神的一滴4 小时前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程