您的位置:首页 > 其它

机器学习入门-线性回归

2017-08-13 13:05 393 查看

工具

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查看表格
sf
sf.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 graphlab
sales = 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) 多特征模型预测(偏差过大,当然不一定,取决于数据)




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: