欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[机器学习] - 线性回归(自我监督学习) - 10.示例代码(Python 实现)

最编程 2024-10-02 21:25:54
...

以下是一个使用 Python 和 scikit-learn 实现简单线性回归的示例:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# 生成示例数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([1.2, 1.9, 3.2, 3.9, 5.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)

# 打印结果
print(f"预测值: {y_pred}")
print(f"模型系数: {model.coef_}")
print(f"截距: {model.intercept_}")

# 可视化回归直线
plt.scatter(X, y, color='blue')
plt.plot(X, model.predict(X), color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('线性回归示例')
plt.show()

总结
线性回归是监督学习中最基础的算法之一,适用于线性关系的回归任务。虽然简单易用,但在面对复杂非线性问题时,通常需要使用更加复杂的模型或对数据进行预处理。