# 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)
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()
不用看了,模型很一般
模型的衡量指标
均方误差
# 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