#!/usr/bin/env python # coding: utf-8 # # 启动graphlab create # In[1]: import graphlab # # 读取房屋销售数据 # In[2]: sales = graphlab.SFrame('home_data.gl/') # In[3]: sales # In[5]: graphlab.canvas.set_target('ipynb') # 将生成的图片展示在jupyter中 # In[9]: sales.show(view="Scatter Plot",x="sqft_living", y="price") # 画散点图 # # 分离出训练集和测试集 # In[18]: train_data, test_data = sales.random_split(0.8, seed=0) # 将数据集随机划分,0.8表示随机百分之八十划分为训练集。剩下百分之二十位测试集,seed=0表示将划分确定 # ## 构建回归模型 # In[16]: sqft_model = graphlab.linear_regression.create(train_data, target="price", features=["sqft_living"]) # # 评估这个简单的线性回归模型 # In[19]: print test_data['price'].mean() # 均值 # In[20]: print sqft_model.evaluate(test_data) # # 查看预测效果 # In[24]: import matplotlib.pyplot as plt # ### 使绘制的图片在当前notebook显示 # In[28]: get_ipython().run_line_magic('matplotlib', 'inline') # In[31]: plt.plot(test_data["sqft_living"], test_data["price"], '.', test_data["sqft_living"], sqft_model.predict(test_data), '-') # In[34]: sqft_model.get('coefficients') # 显示截距与斜率 # # 探索数据集的其他特征 # In[35]: my_features = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'zipcode'] # 卧室,浴室,房屋大小,客厅大小,楼层,地区码 # In[36]: sales[my_features].show() # In[41]: sales.show(view="BoxWhisker Plot", x=u'地区码', y=u'价格') # 根据地区码来分组 # # 构建更多特征的回归模型 # In[42]: my_features_model = graphlab.linear_regression.create(train_data, target='price', features=my_features) # In[61]: print sqft_model.evaluate(test_data) # In[46]: print my_features_model.evaluate(test_data) # # 应用学到的模型来预测房屋的售价 # In[47]: house1 = sales[sales['id']=='5309101200'] # 取出这一行数据 # In[49]: print house1['price'] # In[50]: print sqft_model.predict(house1) # 单变量特征模型 # In[51]: print my_features_model.predict(house1) # 多特征模型 # # 预测另一个房屋的售价 # In[52]: house2 = sales[sales['id']=='1925069082'] # In[53]: house2 # In[54]: house2['price'] # In[57]: print sqft_model.predict(house2) # In[58]: print my_features_model.predict(house2) # In[ ]: