使用可视化:distplot
了解因变量的分布非常重要,它会影响我们选择的模型类型或预处理方式。最好的方法之一就是把它画出来。不过,绘图不是 PySpark 的内置功能,我们需要做一些中间步骤来确保它能正确运行。在本练习中,您将可视化 'LISTPRICE' 变量,并通过计算偏度来进一步了解它的分布。
matplotlib.pyplot 和 seaborn 包已经分别以别名 plt 和 sns 为您导入。
本练习是课程的一部分
使用 PySpark 进行特征工程
练习说明
- 使用
sample()从数据框df中抽样 50%,确保不放回采样,并将随机种子设为 42。 - 使用
toPandas()将 Spark DataFrame 转换为pandas.DataFrame()。 - 使用
seaborn的distplot()方法绘制分布图。 - 从
pyspark.sql.functions导入skewness()函数,并在'LISTPRICE'列上使用agg()进行聚合后计算偏度。记得使用collect()收集结果以触发计算。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Select a single column and sample and convert to pandas
sample_df = df.select(['LISTPRICE']).____(____, ____, 42)
pandas_df = sample_df.____()
# Plot distribution of pandas_df and display plot
sns.____(____)
plt.show()
# Import skewness function
from pyspark.sql.functions import skewness
# Compute and print skewness of LISTPRICE
print(df.____({____: ____}).collect())