# 1.1读取数据
cars = pd.read_table("D:\\user\\data\\auto-mpg.data", delim_whitespace=True, names=columns, index_col=False)

1.不加index_col参数,在pycharm中列不会对齐,原因是: 如果文件不规则,行尾有分隔符,则可以设定index_col=False 来是的pandas不适用第一列作为行索引。

2.数据以空格分隔,不属于csv文件,所以用pd.read_table()配合参数读取

 

# 1.2数据不直观,故可视化(只是概述流程)
fig = plt.figure()  # figure上加2个子图
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 1)
cars.plot('weight', 'mpg',  kind='scatter', ax=ax1) # x轴:weight y轴:mpg(每加仑行驶里程)
cars.plot('acceleration', 'mpg',  kind='scatter', ax=ax2)
plt.show()

 

# 2.1模型拟合
# 先只指定一个属性
lr = LinearRegression()
lr.fit(cars[["weight"]], cars['mpg'])
print(lr)

LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

Viedo: scikit-learn_oil-wear分析案例-线性回归

fit中的input数据需要是n×m的矩阵(需转化)形式,output指定为列向量(单标签)/矩阵(多标签)形式的label值(毕竟有监督)

 

# 2.1+2.2 模型拟合+预测
lr = LinearRegression(fit_intercept=True)
lr.fit(cars[["weight"]], cars['mpg'])
predictions = lr.predict(cars[["weight"]])  # 此处应该是新来的样本数据
print(predictions[0:5])  # 预测值
print(cars["mpg"][0:5])  # 真实label值

[19.41852276 17.96764345 19.94053224 19.96356207 19.84073631]
0    18.0
1    15.0
2    18.0
3    16.0
4    17.0
Name: mpg, dtype: float64

 

# 画图才能直观比较
plt.scatter(cars["weight"], cars["mpg"], c='red')  # 横轴都是车的重量
plt.scatter(cars["weight"], predictions, c='blue')
plt.show()

Viedo: scikit-learn_oil-wear分析案例-线性回归

不用看了,模型很一般

 

模型的衡量指标

均方误差

Viedo: scikit-learn_oil-wear分析案例-线性回归

# skl库实现好的均方误差
lr = LinearRegression()
lr.fit(cars[["weight"]], cars[["mpg"]])
predictions = lr.predict(cars[["weight"]])
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(cars["mpg"], predictions) # 参数:真实的标签值和预测值
print(mse ** 0.5) # 更多使用根号下的均方误差

 

 

转载于:https://my.oschina.net/u/4013710/blog/2877724

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-27
  • 2022-12-23
  • 2022-01-20
  • 2021-12-06
  • 2021-07-23
  • 2021-07-08
猜你喜欢
  • 2021-12-13
  • 2021-06-15
  • 2021-09-30
  • 2022-12-23
  • 2021-12-30
  • 2021-04-26
  • 2021-07-21
相关资源
相似解决方案