作业二.自定义数据集使用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()

相关推荐
qq_416018722 分钟前
实时数据可视化库
开发语言·c++·算法
阿钱真强道2 分钟前
27 Python 分类-从概率角度做分类,一文认识朴素贝叶斯
python·分类·朴素贝叶斯·分类算法·贝叶斯分类·gaussiannb
2401_8732046516 分钟前
C++中的策略模式进阶
开发语言·c++·算法
xushichao198921 分钟前
C++中的职责链模式实战
开发语言·c++·算法
2301_7765087221 分钟前
Python日志记录(Logging)最佳实践
jvm·数据库·python
清风徐来QCQ27 分钟前
js中的模板字符串
开发语言·前端·javascript
2301_8184190134 分钟前
C++中的协程编程
开发语言·c++·算法
2401_8796938734 分钟前
用Python批量处理Excel和CSV文件
jvm·数据库·python
add45a36 分钟前
C++中的工厂方法模式
开发语言·c++·算法
java1234_小锋36 分钟前
Java高频面试题:Spring-AOP通知和执行顺序?
java·开发语言·spring