机器学习入门-线性回归

来源:互联网 发布:java的反射机制详解 编辑:程序博客网 时间:2024/05/21 15:45

工具

  • graphlab create
  • 下载地址:https://turi.com/download/install-graphlab-create.html
  • Ipython NoteBook
    • enter + shift
    • cell 切换makedown (esc + m)

graphlab create

import graphlab 导入包读取数据集sf = graphlab.SFrame('数据集.csv')SFrame查看表格sfsf.head sf.tail

GraphLab Canvas 画布

sf.show()当前页面打开画布graphlab.canvas.set_target('ipynb')sf['数据name'].show[view='Categorical']

SFrame中的列操作

sf['列名称']mean()函数,求平均值max()sf['增加列'] = sf['其他列'] + '' + sf['其他列']

SFrame中的apply函数

def transform_country(country):    if country == 'falseData':        return 'trueData'    else:        return country赋值数据集       sf['country'] = sf['country'].apply(transform_country)

线性回归(预测房价)

线性回归(Linear regression)是利用称为线性回归方程的最小二乘函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析。这种函数是一个或多个称为回归系数的模型参数的线性组合。只有一个自变量的情况称为简单回归,大于一个自变量情况的叫做多元回归。
通俗说,假设你在纸上画了一堆点,然后打算画一条线,这些点到这条线的距离尽量得短。

我的房价如何预估?
邻居房价近期(两年)销售情况(面积,售价)
x为权重,或者说是回归系数;w0:截距(在y轴位置);w1:斜率
最小化残差平方和

这里写图片描述

这里写图片描述

这里写图片描述

如何选择模型阶数/复杂度

这里写图片描述

误差和模型复杂度的关系

这里写图片描述

加入特征(澡堂….)

这里写图片描述

回归预测其他案例

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

总结

这里写图片描述

实战

import graphlabsales = graphlab.SFrame('home_data.gl/')根据房屋大小和价格生成散点图sales.show(view="Scatter Plot",x="sqft_living",y="price")随机划分训练集,测试集(seed种子确保随机划分可以重用)train_data,test_data = sales.random_split(.8,seed=0)
构建回归模型(数据,目标,特征)sqft_model = graphlab.linear_regression.create(train_data,target='price',features=['sqft_living'])
评估模型print test_data['price'].mean() 均值print sqft_model.evaluate(test_data)评估(最大误差,rmse均衡误差)可视化预测(误差)import matplotlib.pyplot as plt%matplotlib inline(重定向该页面),x轴,y轴,.表示点真实数据房屋大小,价格关系的散点图plt.plot(test_data['sqft_living'],test_data['price'],'.',预测回归模型线test_data['sqft_living'],sqft_model.predict[test_data],'-')获取参数:截距(intercept)标准差,斜率(sqft_living)标准差sqft_model.get('coefficients')

多特征模型

my_features = ['bedrooms','bathrooms','sqft_living','sqft_lot','floors','zipcode']检查数据sales[my_features].show()根据地区码把房价范围分组sales.show(view='BoxWhisker Plot',x = 'zipcode',y='price')构建回归模型(数据,目标,特征)my_features_model = qraphlab.linear_regression.create(train_data,target='price',my_features= my_features)评估(比单特征模型好)print my_features_model.evaluate(test_data)评估(最大误差,rmse均衡误差)

预测房屋售价

取到该房屋数据house1=sales[sales['id'] == '5309101200']print house1['price'] 真实价格print sqft_model.predict(house1) 单特征模型预测价格print my_features_model.predict(house1) 多特征模型预测(偏差过大,当然不一定,取决于数据)

这里写图片描述
这里写图片描述

原创粉丝点击