更新于
2026年7月11日
线性回归#
线性回归(Linear Regression) 是机器学习中最基础且经典的算法之一,主要用于解决回归类问题(即对连续值的预测),例如根据房屋面积预测房价。
示例代码#
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
def make_data():
np.random.seed(20)
x = np.random.rand(100) * 30 + 50 # square
noise = np.random.rand(100) * 50
y = x * 8 - 127 # price
y = y - noise
return x, y
def main(x, y):
model = LinearRegression()
x = np.reshape(x, (-1, 1))
model.fit(x, y)
y_pre = model.predict(x)
print("参数w={},b={}".format(model.coef_, model.intercept_))
print("面积50的房价为:", model.predict([[50]]))
# 以下部分可视化代码
plt.rcParams['ytick.direction'] = 'in' # 刻度向内
plt.rcParams['xtick.direction'] = 'in' # 刻度向内
plt.scatter(x, y)
plt.plot(x, y_pre, c='r')
plt.xlabel('面积', fontsize=16)
plt.ylabel('房价', fontsize=16)
plt.tick_params(axis='x', labelsize=15) # x轴刻度数字大小
plt.tick_params(axis='y', labelsize=15) # y轴刻度数字大小
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.tight_layout() # 调整子图间距
plt.show()
if __name__ == '__main__':
x, y = make_data()
main(x, y)运行结果#
参数w = [7.97699647], b = -154.31885006061555
面积50的房价为: [244.53097351]
阅读
--