在Python中绘制线图和散点图
在Python中绘制线图和散点图
我目前正在Coursera上学习机器学习课程(https://www.coursera.org/learn/ml-foundations/lecture/6wD6H/visualizing-predictions-of-simple-model-with-matplotlib)。该课程在学习和作业中使用了Graphlab Create框架。我不想使用Graphlab,而是使用pandas和numpy进行作业。\n在课程中,讲师创建了一个回归模型,并使用matplotlib展示了预测结果:\n
构建回归模型
\n
sqft_model = graphlab.linear_regression.create(train_data, target='price', features=['sqft_living'],validation_set=None)
\n然后预测的代码如下:\n
plt.plot(test_data['sqft_living'],test_data['price'],'.', test_data['sqft_living'],sqft_model.predict(test_data),'-')
\n结果如下图所示:\n\n在上面的图像中,蓝色的点是测试数据,绿色的线是简单回归的预测结果。\n我是一个完全的编程和Python初学者。我想使用免费资源如pandas和scikit。我在Ipython中使用以下代码进行同样的操作:\n
构建回归模型
\n
from pandas.stats.api import ols sqft_model = ols(y=train_data['price'], x=train_data['sqft_living'])
\n但是,在输入预测代码时,我遇到了以下错误:\n
\nValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()\n
\n因此,我无法产生与讲师相同的预期结果(即上面显示的图像)。有人能帮我吗?\n请点击以下链接下载数据:\nhttps://onedrive.live.com/redir?resid=EDAAD532F68FDF49!1091&authkey=!AKs341lbRnuCt9w&ithint=folder%2cipynb
问题的原因是Pandas的OLS模型无法理解GraphLab的SArray。解决方法是先将SFrames的train_data和test_data转换成Pandas的Dataframe,然后再进行操作。具体的代码如下:
df_train = train_data.to_dataframe() model = old(y=df_train['price'], x=df_train['sqft_living'])
但是在执行上述代码时,出现了AttributeError: 'DataFrame' object has no attribute 'to_dataframe'的错误。提问者在回答中提到了一个链接(http://stackoverflow.com/questions/20763012),但并不清楚数据的类型是什么。提问者还提供了一个Onedrive的链接来下载数据和代码文件。