2020年7月6日 星期一

[Py DS] Ch5 - Machine Learning (Part13)

In-Depth: Kernel Density Estimation
In the previous section we covered Gaussian mixture models (GMM), which are a kind of hybrid between a clustering estimator and a density estimator. Recall that a density estimator is an algorithm that takes a D-dimensional dataset and produces an estimate of the D-dimensional probability distribution which that data is drawn from. The GMM algorithm accomplishes this by representing the density as a weighted sum of Gaussian distributions. Kernel density estimation (KDEis in some senses an algorithm that takes the mixture-of-Gaussians idea to its logical extreme: it uses a mixture consisting of one Gaussian component per point, resulting in an essentially nonparametric estimator of density. In this section, we will explore the motivation and uses of KDE. We begin with the standard imports:
  1. %matplotlib inline  
  2. import matplotlib.pyplot as plt  
  3. import seaborn as sns; sns.set()  
  4. import numpy as np  
Motivating KDE: Histograms
As already discussed, a density estimator is an algorithm that seeks to model the probability distribution that generated a dataset. For one-dimensional data, you are probably already familiar with one simple density estimator: the histogram. A histogram divides the data into discrete bins, counts the number of points that fall in each bin, and then visualizes the results in an intuitive manner.

For example, let’s create some data that is drawn from two normal distributions:
  1. def make_data(N, f=0.3, rseed=1):  
  2.     rand = np.random.RandomState(rseed)  
  3.     x = rand.randn(N)  
  4.     x[int(f * N):] += 5  
  5.     return x  
  6.   
  7. x = make_data(1000)  
We have previously seen that the standard count-based histogram can be created with the plt.hist() function. By specifying the density parameter of the histogram, we end up with a normalized histogram where the height of the bins does not reflect counts, but instead reflects probability density (Figure 5-140):
  1. hist = plt.hist(x, bins=30, density=True)  

Figure 5-140. Data drawn from a combination of normal distributions

Notice that for equal binning, this normalization simply changes the scale on the y-axis, leaving the relative heights essentially the same as in a histogram built from counts. This normalization is chosen so that the total area under the histogram is equal to 1, as we can confirm by looking at the output of the histogram function:
  1. density, bins, patches = hist  
  2. widths = bins[1:] - bins[:-1]  
  3. (density * widths).sum()  
Output:
1.0

One of the issues with using a histogram as a density estimator is that the choice of bin size and location can lead to representations that have qualitatively different features. For example, if we look at a version of this data with only 20 points, the choice of how to draw the bins can lead to an entirely different interpretation of the data! Consider this example (visualized in Figure 5-141):
  1. x = make_data(20)  
  2. bins = np.linspace(-51010)  
  3. fig, ax = plt.subplots(12, figsize=(124), sharex=True, sharey=True, subplot_kw={'xlim':(-49), 'ylim':(-0.020.3)})  
  4. fig.subplots_adjust(wspace=0.05)  
  5. for i, offset in enumerate([0.00.6]):  
  6.     ax[i].hist(x, bins=bins + offset, density=True)  
  7.     ax[i].plot(x, np.full_like(x, -0.01), '|k', markeredgewidth=1)  
Figure 5-141. The problem with histograms: the location of bins can affect interpretation

On the left, the histogram makes clear that this is a bimodal distribution. On the right, we see a unimodal distribution with a long tail. Without seeing the preceding code, you would probably not guess that these two histograms were built from the same data. With that in mind, how can you trust the intuition that histograms confer? And how might we improve on this?

Stepping back, we can think of a histogram as a stack of blocks, where we stack one block within each bin on top of each point in the dataset. Let’s view this directly (Figure 5-142):
  1. fig, ax = plt.subplots()  
  2. bins = np.arange(-38)  
  3. ax.plot(x, np.full_like(x, -0.1), '|k', markeredgewidth=1)  
  4. for count, edge in zip(*np.histogram(x, bins)):  
  5.     for i in range(count):  
  6.         ax.add_patch(plt.Rectangle((edge, i), 11, alpha=0.5))  
  7.           
  8. ax.set_xlim(-48)  
  9. ax.set_ylim(-0.28)  
Figure 5-142. Histogram as stack of blocks

The problem with our two binnings stems from the fact that the height of the block stack often reflects not on the actual density of points nearby, but on coincidences of how the bins align with the data points. This misalignment between points and their blocks is a potential cause of the poor histogram results seen here. But what if, instead of stacking the blocks aligned with the bins, we were to stack the blocks aligned with the points they represent? If we do this, the blocks won’t be aligned, but we can add their contributions at each location along the x-axis to find the result. Let’s try this (Figure 5-143):
  1. x_d = np.linspace(-482000)  
  2. density = sum((abs(xi - x_d) < 0.5for xi in x)  
  3. plt.fill_between(x_d, density, alpha=0.5)  
  4. plt.plot(x, np.full_like(x, -0.1), '|k', markeredgewidth=1)  
  5. plt.axis([-48, -0.28]);  
Figure 5-143. A “histogram” where blocks center on each individual point; this is an example of a kernel density estimate

The result looks a bit messy, but is a much more robust reflection of the actual data characteristics than is the standard histogram. Still, the rough edges are not aesthetically pleasing, nor are they reflective of any true properties of the data. In order to smooth them out, we might decide to replace the blocks at each location with a smooth function, like a Gaussian. Let’s use a standard normal curve at each point instead of a block (Figure 5-144):
  1. from scipy.stats import norm  
  2. x_d = np.linspace(-481000)  
  3. density = sum(norm(xi).pdf(x_d) for xi in x)  
  4. plt.fill_between(x_d, density, alpha=0.5)  
  5. plt.plot(x, np.full_like(x, -0.1), '|k', markeredgewidth=1)  
  6. plt.axis([-48, -0.25]);  
Figure 5-144. A kernel density estimate with a Gaussian kernel

This smoothed-out plot, with a Gaussian distribution contributed at the location of each input point, gives a much more accurate idea of the shape of the data distribution, and one that has much less variance (i.e., changes much less in response to differences in sampling). These last two plots are examples of kernel density estimation in one dimension: the first uses a so-called “tophat” kernel and the second uses a Gaussian kernel. We’ll now look at kernel density estimation in more detail.

Kernel Density Estimation in Practice
The free parameters of kernel density estimation are the kernel, which specifies the shape of the distribution placed at each point, and the kernel bandwidth, which controls the size of the kernel at each point. In practice, there are many kernels you might use for a kernel density estimation: in particular, the Scikit-Learn KDE implementation supports one of six kernels, which you can read about in Scikit-Learn’s Density Estimation documentation.

While there are several versions of kernel density estimation implemented in Python (notably in the SciPy and StatsModels packages), I prefer to use Scikit-Learn’s version because of its efficiency and flexibility. It is implemented in the sklearn.neigh bors.KernelDensity estimator, which handles KDE in multiple dimensions with one of six kernels and one of a couple dozen distance metrics. Because KDE can be fairly computationally intensive, the Scikit-Learn estimator uses a tree-based algorithm under the hood and can trade off computation time for accuracy using the atol (absolute tolerance) and rtol (relative tolerance) parameters. We can determine the kernel bandwidth, which is a free parameter, using Scikit-Learn’s standard cross validation tools, as we will soon see.

Let’s first see a simple example of replicating the preceding plot using the Scikit-Learn KernelDensity estimator (Figure 5-145):
  1. from sklearn.neighbors import KernelDensity  
  2. # instantiate and fit the KDE model  
  3. kde = KernelDensity(bandwidth=1.0, kernel='gaussian')  
  4. kde.fit(x[:, None])  
  5. # score_samples returns the log of the probability density  
  6. logprob = kde.score_samples(x_d[:, None])  
  7. plt.fill_between(x_d, np.exp(logprob), alpha=0.5)  
  8. plt.plot(x, np.full_like(x, -0.01), '|k', markeredgewidth=1)  
  9. plt.ylim(-0.020.22)  
Figure 5-145. A kernel density estimate computed with Scikit-Learn

The result here is normalized such that the area under the curve is equal to 1.

Selecting the bandwidth via cross-validation
The choice of bandwidth within KDE is extremely important to finding a suitable density estimate, and is the knob that controls the bias–variance trade-off in the estimate of density: too narrow a bandwidth leads to a high-variance estimate (i.e., overfitting), where the presence or absence of a single point makes a large difference. Too wide a bandwidth leads to a high-bias estimate (i.e., underfitting) where the structure in the data is washed out by the wide kernel.

There is a long history in statistics of methods to quickly estimate the best bandwidth based on rather stringent assumptions about the data: if you look up the KDE implementations in the SciPy and StatsModels packages, for example, you will see implementations based on some of these rules.

In machine learning contexts, we’ve seen that such hyperparameter tuning often is done empirically via a cross-validation approach. With this in mind, the KernelDensity estimator in Scikit-Learn is designed such that it can be used directly within Scikit-Learn’s standard grid search tools. Here we will use GridSearchCV to optimize the bandwidth for the preceding dataset. Because we are looking at such a small dataset, we will use leave-one-out cross-validation, which minimizes the reduction in training set size for each cross-validation trial:
  1. from sklearn.model_selection import GridSearchCV  
  2. from sklearn.model_selection import LeaveOneOut  
  3. bandwidths = 10 ** np.linspace(-11100)  
  4. grid = GridSearchCV(KernelDensity(kernel='gaussian'), {'bandwidth': bandwidths}, cv=len(x))  
  5. grid.fit(x[:, None]);  
Now we can find the choice of bandwidth that maximizes the score (which in this case defaults to the log-likelihood):
Output:
{'bandwidth': 1.1233240329780276}

The optimal bandwidth happens to be very close to what we used in the example plot earlier, where the bandwidth was 1.0 (i.e., the default width of scipy.stats.norm).

Example: KDE on a Sphere
Perhaps the most common use of KDE is in graphically representing distributions of points. For example, in the Seaborn visualization library (discussed earlier in “Visualization with Seaborn” on page 311), KDE is built in and automatically used to help visualize points in one and two dimensions.

Here we will look at a slightly more sophisticated use of KDE for visualization of distributions. We will make use of some geographic data that can be loaded with Scikit-Learn: the geographic distributions of recorded observations of two South American mammals, Bradypus variegatus (the brown-throated sloth) and Microryzomys minutus (the forest small rice rat).

With Scikit-Learn, we can fetch this data as follows:
  1. from sklearn.datasets import fetch_species_distributions  
  2. data = fetch_species_distributions()  
  3. # Get matrices/arrays of species IDs and locations  
  4. latlon = np.vstack([data.train['dd lat'], data.train['dd long']]).T  
  5. species = np.array([d.decode('ascii').startswith('micro'for d in data.train['species']], dtype='int')  
With this data loaded, we can use the Basemap toolkit (mentioned previously in “Geographic Data with Basemap”) to plot the observed locations of these two species on the map of South America (Figure 5-146):
  1. from mpl_toolkits.basemap import Basemap  
  2. from sklearn.datasets.species_distributions import construct_grids  
  3.   
  4. xgrid, ygrid = construct_grids(data)  
  5. # plot coastlines with Basemap  
  6. m = Basemap(projection='cyl', resolution='c', llcrnrlat=ygrid.min(), urcrnrlat=ygrid.max(),  
  7.             llcrnrlon=xgrid.min(), urcrnrlon=xgrid.max())  
  8. m.drawmapboundary(fill_color='#DDEEFF')  
  9. m.fillcontinents(color='#FFEEDD')  
  10. m.drawcoastlines(color='gray', zorder=2)  
  11. m.drawcountries(color='gray', zorder=2)  
  12.   
  13. # plot locations  
  14. m.scatter(latlon[:, 1], latlon[:, 0], zorder=3, c=species, cmap='rainbow', latlon=True);  

Figure 5-146. Location of species in training data

Unfortunately, this doesn’t give a very good idea of the density of the species, because points in the species range may overlap one another. You may not realize it by looking at this plot, but there are over 1,600 points shown here! Let’s use kernel density estimation to show this distribution in a more interpretable way: as a smooth indication of density on the map. Because the coordinate system here lies on a spherical surface rather than a flat plane, we will use the haversine distance metric, which will correctly represent distances on a curved surface.

There is a bit of boilerplate code here (one of the disadvantages of the Basemap toolkit), but the meaning of each code block should be clear (Figure 5-147):

Figure 5-147. A kernel density representation of the species distributions

Compared to the simple scatter plot we initially used, this visualization paints a much clearer picture of the geographical distribution of observations of these two species.

Example: Not-So-Naive Bayes
This example looks at Bayesian generative classification with KDE, and demonstrates how to use the Scikit-Learn architecture to create a custom estimator.

In “In Depth: Naive Bayes Classification”, we took a look at naive Bayesian classification, in which we created a simple generative model for each class, and used these models to build a fast classifier. For naive Bayes, the generative model is a simple axis-aligned Gaussian. With a density estimation algorithm like KDE, we can remove the “naive” element and perform the same classification with a more sophisticated generative model for each class. It’s still Bayesian classification, but it’s no longer naive.

The general approach for generative classification is this:
1. Split the training data by label.
2. For each set, fit a KDE to obtain a generative model of the data. This allows you for any observation x and label y to compute a likelihood P(x | y) .
3. From the number of examples of each class in the training set, compute the class prior, P(y) .
4. For an unknown point x, the posterior probability for each class is P(y | x) ∝ P(x | y) P(y) . The class that maximizes this posterior is the label assigned to the point.

The algorithm is straightforward and intuitive to understand; the more difficult piece is couching it within the Scikit-Learn framework in order to make use of the grid search and cross-validation architecture. This is the code that implements the algorithm within the Scikit-Learn framework; we will step through it following the code block:
  1. from sklearn.base import BaseEstimator, ClassifierMixin  
  2.   
  3. class KDEClassifier(BaseEstimator, ClassifierMixin):  
  4.     """Bayesian generative classification based on KDE  
  5.     Parameters  
  6.     ----------  
  7.     bandwidth : float  
  8.         the kernel bandwidth within each class  
  9.     kernel : str  
  10.         the kernel name, passed to KernelDensity  
  11.     """  
  12.     def __init__(self, bandwidth=1.0, kernel='gaussian'):  
  13.         self.bandwidth = bandwidth  
  14.         self.kernel = kernel  
  15.           
  16.     def fit(self, X, y):  
  17.         self.classes_ = np.sort(np.unique(y))  
  18.         training_sets = [X[y == yi] for yi in self.classes_]  
  19.         self.models_ = [KernelDensity(bandwidth=self.bandwidth, kernel=self.kernel).fit(Xi) for Xi in training_sets]  
  20.         self.logpriors_ = [np.log(Xi.shape[0] / X.shape[0]) for Xi in training_sets]  
  21.         return self  
  22.       
  23.     def predict_proba(self, X):  
  24.         logprobs = np.array([model.score_samples(X) for model in self.models_]).T  
  25.         result = np.exp(logprobs + self.logpriors_)  
  26.         return result / result.sum(1, keepdims=True)  
  27.           
  28.     def predict(self, X):  
  29.         return self.classes_[np.argmax(self.predict_proba(X), 1)]  
The anatomy of a custom estimator
Let’s step through this code and discuss the essential features:
  1. from sklearn.base import BaseEstimator, ClassifierMixin  
  2.   
  3. class KDEClassifier(BaseEstimator, ClassifierMixin):  
  4.     """Bayesian generative classification based on KDE  
  5.     Parameters  
  6.     ----------  
  7.     bandwidth : float  
  8.         the kernel bandwidth within each class  
  9.     kernel : str  
  10.         the kernel name, passed to KernelDensity  
  11.     """  
Each estimator in Scikit-Learn is a class, and it is most convenient for this class to inherit from the BaseEstimator class as well as the appropriate mixin, which provides standard functionality. For example, among other things, here the BaseEstimator contains the logic necessary to clone/copy an estimator for use in a crossvalidation procedure, and ClassifierMixin defines a default score() method used by such routines. We also provide a docstring, which will be captured by IPython’s help functionality (see “Help and Documentation in IPython” on page 3).

Next comes the class initialization method:
  1. def __init__(self, bandwidth=1.0, kernel='gaussian'):  
  2.     self.bandwidth = bandwidth  
  3.     self.kernel = kernel  
This is the actual code executed when the object is instantiated with KDEClassifier(). In Scikit-Learn, it is important that initialization contains no operations other than assigning the passed values by name to self. This is due to the logic contained in BaseEstimator required for cloning and modifying estimators for crossvalidation, grid search, and other functions. Similarly, all arguments to __init__ should be explicit; that is, *args or **kwargs should be avoided, as they will not be correctly handled within cross-validation routines.

Next comes the fit() method, where we handle training data:
  1. def fit(self, X, y):  
  2.     self.classes_ = np.sort(np.unique(y))  
  3.     training_sets = [X[y == yi] for yi in self.classes_]  
  4.     self.models_ = [KernelDensity(bandwidth=self.bandwidth, kernel=self.kernel).fit(Xi) for Xi in training_sets]  
  5.     self.logpriors_ = [np.log(Xi.shape[0] / X.shape[0]) for Xi in training_sets]  
  6.     return self  
Here we find the unique classes in the training data, train a KernelDensity model for each class, and compute the class priors based on the number of input samples. Finally, fit() should always return self so that we can chain commands. For example:
  1. label = model.fit(X, y).predict(X)  
Notice that each persistent result of the fit is stored with a trailing underscore (e.g., self.logpriors_). This is a convention used in Scikit-Learn so that you can quickly scan the members of an estimator (using IPython’s tab completion) and see exactly which members are fit to training data.

Finally, we have the logic for predicting labels on new data:
  1. def predict_proba(self, X):  
  2.     logprobs = np.array([model.score_samples(X) for model in self.models_]).T  
  3.     result = np.exp(logprobs + self.logpriors_)  
  4.     return result / result.sum(1, keepdims=True)  
  5.       
  6. def predict(self, X):  
  7.     return self.classes_[np.argmax(self.predict_proba(X), 1)]  
Because this is a probabilistic classifier, we first implement predict_proba(), which returns an array of class probabilities of shape [n_samples, n_classes]. Entry [i, j] of this array is the posterior probability that sample i is a member of class j, computed by multiplying the likelihood by the class prior and normalizing.

Finally, the predict() method uses these probabilities and simply returns the class with the largest probability.

Using our custom estimator
Let’s try this custom estimator on a problem we have seen before: the classification of handwritten digits. Here we will load the digits, and compute the cross-validation score for a range of candidate bandwidths using the GridSearchCV meta-estimator (refer back to “Hyperparameters and Model Validation”for more information on this):
  1. from sklearn.datasets import load_digits  
  2. from sklearn.model_selection import GridSearchCV  
  3.   
  4. digits = load_digits()  
  5. bandwidths = 10 ** np.linspace(02100)  
  6. grid = GridSearchCV(KDEClassifier(), {'bandwidth': bandwidths})  
  7. grid.fit(digits.data, digits.target)  
  8. scores = [val for val in grid.cv_results_['mean_test_score']]  
Next we can plot the cross-validation score as a function of bandwidth (Figure 5-148):
  1. plt.semilogx(bandwidths, scores)  
  2. plt.xlabel('bandwidth')  
  3. plt.ylabel('accuracy')  
  4. plt.title('KDE Model Performance')  
  5. print(grid.best_params_)  
  6. print('accuracy =', grid.best_score_)  
Output:
{'bandwidth': 6.135907273413174}
accuracy = 0.9677298050139276

Figure 5-148. Validation curve for the KDE-based Bayesian classifier

We see that this not-so-naive Bayesian classifier reaches a cross-validation accuracy of just over 96%; this is compared to around 80% for the naive Bayesian classification:
  1. from sklearn.naive_bayes import GaussianNB  
  2. from sklearn.model_selection import cross_val_score  
  3. cross_val_score(GaussianNB(), digits.data, digits.target).mean()  
Output:
0.8069281956050759

One benefit of such a generative classifier is interpretability of results: for each unknown sample, we not only get a probabilistic classification, but a full model of the distribution of points we are comparing it to! If desired, this offers an intuitive window into the reasons for a particular classification that algorithms like SVMs and randomforests tend to obscure.

If you would like to take this further, there are some improvements that could be made to our KDE classifier model:
 We could allow the bandwidth in each class to vary independently.
 We could optimize these bandwidths not based on their prediction score, but on the likelihood of the training data under the generative model within each class (i.e., use the scores from KernelDensity itself rather than the global prediction accuracy).

Finally, if you want some practice building your own estimator, you might tackle building a similar Bayesian classifier using Gaussian mixture models instead of KDE.

Supplement
Windows Python Basemap Install 安裝教學
Wiki - Bayes theorem
FAQ - AttributeError : 'GridSearchCV' object has no attribute 'grid_scores_'

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...