代码案例分析
以下是一个使用线性回归进行简单房价预测的机器学习代码案例分析:
代码示例
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# 生成一些示例数据(房屋面积和价格)
area = np.array([100, 120, 150, 80, 90, 110, 130, 140, 70, 160]).reshape(-1, 1)
price = np.array([200, 240, 300, 160, 180, 220, 260, 280, 140, 320])
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(area, price, test_size=0.2, random_state=42)
# 创建线性回归模型并拟合数据
model = LinearRegression()
model.fit(X_train, y_train)
# 进行预测
y_pred = model.predict(X_test)
# 评估模型性能
score = model.score(X_test, y_test)
print(f"模型得分:{score}")
# 绘制结果
plt.scatter(X_train, y_train, color='blue', label='训练数据')
plt.scatter(X_test, y_test, color='red', label='测试数据')
plt.plot(X_test, y_pred, color='green', label='预测结果')
plt.xlabel('房屋面积')
plt.ylabel('房屋价格')
plt.title('房价预测')
plt.legend()
plt.show()
代码分析
- 数据准备:创建了两个数组 area 和 price 分别表示房屋面积和价格,并通过 train_test_split 函数将数据划分为训练集和测试集,其中测试集占比20%。
- 模型创建与训练:使用 LinearRegression 类创建线性回归模型,然后使用训练数据 X_train 和 y_train 对模型进行拟合。
- 模型预测与评估:使用训练好的模型对测试集 X_test 进行预测,得到预测结果 y_pred ,并通过 score 方法评估模型在测试集上的性能,这里的得分是决定系数 R^2,越接近1表示模型拟合效果越好。
- 结果可视化:使用 matplotlib 库绘制散点图和直线,展示训练数据、测试数据以及预测结果之间的关系,直观地呈现了模型的预测效果。
通过这个简单的案例,可以看到机器学习中线性回归模型的基本应用流程,包括数据处理、模型训练、预测和评估等步骤。在实际应用中,可以根据具体问题收集更丰富的数据,选择更合适的模型和算法,以提高预测的准确性和可靠性。