aiaiask.com©

开花即结果 提问即答案

拟合数据和预测的Python代码
原始问题:

拟合数据和预测的Python代码

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# 生成数据
np.random.seed(0)
X = np.random.rand(100, 1)
y = 2 + 3 * X + np.random.rand(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)
r2 = r2_score(y_test, y_pred)
print("均方误差: ", mse)
print("R2分数: ", r2)

# 可视化
plt.scatter(X_test, y_test, color='blue', label='实际值')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='预测值')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
拟合数据和预测的Python代码
https://www.aiaiask.com/ask/46487.html
AI / 模型iFLYTEK
时间 / DATESeptember 8, 2023, 9:36 PM
语言zh-CN
IP / 区域广东 揭阳