预测

数据科学的一个重要方面是发现数据能告诉我们关于未来的什么信息。关于气候和污染的数据对几十年后的温度有何启示?基于一个人的网络资料,哪些网站可能引起他们的兴趣?如何利用患者的病史来判断他们对治疗的反应程度?

为了回答这些问题,数据科学家开发了进行“预测”的方法。在本章中,我们将研究一种最常用的方法:基于一个变量的值来预测另一个变量的值。

[In ]:
from datascience import *
import matplotlib
path_data = '../../assets/data/'
matplotlib.use('Agg')
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
import numpy as np

这是一个用于基于父母身高预测成年子女身高的历史数据集。我们在前面的章节中已经研究过这个数据集。表 heights 包含 934 名成年“子女”的父母中位身高和子女身高(均以英寸为单位)的数据。回顾一下,父母中位身高是父母双方身高的平均值。

[In ]:
# Data on heights of parents and their adult children
original = Table.read_table(path_data + 'family_heights.csv')
heights = Table().with_columns(
    'MidParent', original.column('midparentHeight'),
    'Child', original.column('childHeight')
    )
[In ]:
heights
MidParent | Child
75.43     | 73.2
75.43     | 69.2
75.43     | 69
75.43     | 69
73.66     | 73.5
73.66     | 72.5
73.66     | 65.5
73.66     | 65.5
72.06     | 71
72.06     | 68
... (924 rows omitted)
[In ]:
heights.scatter('MidParent')
Scatterplot with 'MidParent' on the x-axis and 'Child' on the y-axis. The data points tend to have a positive correlation, where as the x value increases, so does the y-value. The data points do not fall along a specific line, but generally all follow this trend.

研究这些数据的一个主要原因是为了能够预测与数据集中类似的父母所生子女的成年身高。我们在 8.1 节中注意到两个变量之间的正关联后,进行了这些预测。

我们的方法是基于所有与新人父母中位身高相近的点来进行预测。为此,我们编写了一个名为 predict_child 的函数,它接受一个父母中位身高作为参数,并返回所有父母中位身高在该参数半英寸范围内的子女的平均身高。

[In ]:
def predict_child(mpht):
    """Return a prediction of the height of a child 
    whose parents have a midparent height of mpht.
    
    The prediction is the average height of the children 
    whose midparent height is in the range mpht plus or minus 0.5 inches.
    """
    
    close_points = heights.where('MidParent', are.between(mpht-0.5, mpht + 0.5))
    return close_points.column('Child').mean()                       

我们将该函数应用于 Midparent 身高列,并将结果可视化。

[In ]:
# Apply predict_child to all the midparent heights

heights_with_predictions = heights.with_column(
    'Prediction', heights.apply(predict_child, 'MidParent')
    )
[In ]:
# Draw the original scatter plot along with the predicted values

heights_with_predictions.scatter('MidParent')
Scatterplot with 'MidParent' on the x-axis. The previous data points are shown again in dark blue and labeled 'Child.' These dark blue data points tend to have a positive correlation; as the x value increases so does the y value. There are additionally gold data points labeled 'Prediction.' The gold data points are in the center of the blue data points and also show a positive association.

给定父母中位身高处的预测值大致位于该身高处垂直条带的中心。这种预测方法称为“回归”。在本章后面,我们将看看是否可以避免将“接近”任意定义为“0.5 英寸以内”。但首先,我们将开发一种度量,该度量可以在多种场景中用于判断一个变量作为另一个变量的预测变量有多好。