Lecture 15: September 11th, 2023#
We made it to the last lecture :’) How do we all feel today?
Reminders and Updates:
Homework 7 and Homework 8 are due tonight at midnight. Use your tokens to get an extension, if you need it.
You can also use your tokens to submit a outcome revision. If you are missing an outcome and would like credit for it, you can use tokens to submit a revision assignment. Let’s take a brief trip to Canvas to see what this looks like.
Today we will cover K-Means clustering, which is the topic of outcomes P18 and P19. They will be released after today’s lecture and are due Wednesday at midnight, if you would like to attempt them (remember, an A only requires 18 outcomes).
Final project is due Wednesday at midnight! No late submissions will be accepted!
Updated student hours with Yasmeen this week: instead of Tuesday student hours, I will host Wednesday student hours from 12:00pm-1:50pm (our normal lecture time). Come with any questions you might have!
Final Project Questions#
Q: What if we can’t find a perfect linear fit? A: That’s totally fine! Maybe just point out it doesn’t look like a linear fit, and you can’t say much about the relationship. You might consider fitting to a higher degree polynomial, as well.
Q: What if our precision is really low? A: That’s also fine, just don’t try to convince us that the model works really well. You might consider trying to improve the model, or at least elaborate on a few things that you could try. Negative results are fine: I’d rather you say “we can’t make any conclusion” than try to convince of something that’s not true.
K-Means Clustering#
Today we will see our first example from unsupervised machine learning. Can anyone remind us of what the main difference is from supervised machine learning?
Main Difference: Supervised learning uses labeled data, unsupervised learning uses unlabeled data.
Clustering is one of the most famous examples of unsupervised learning, and is something we will see today.
Here is a nice flowchart from the website GeeksforGeeks which gives a nice outline of some different categories within machine learning. Don’t take it too seriously, it’s just kind of fun to look at.

StandardScaler#
I’m a little surprised we haven’t talked about this topic yet, but today we’ll be rescaling numeric data so that it has a mean of zero and a standard deviation of one. Why would we want to do something like this?
From the chat: we want to make things not dependent on units! Example: Suppose I have a DataFrame with one column in kilograms and one column in grams. We might expect that the grams column has numbers that are much larger than the kilograms column. Even though these are both weights, we might be biased towards grams since they are larger numbers.
Load the iris dataset from Seaborn and drop any rows with missing values.
import seaborn as sns
import pandas as pd
import numpy as np
import altair as alt
df = sns.load_dataset("iris").dropna()
df.sample(5)
| sepal_length | sepal_width | petal_length | petal_width | species | |
|---|---|---|---|---|---|
| 72 | 6.3 | 2.5 | 4.9 | 1.5 | versicolor |
| 139 | 6.9 | 3.1 | 5.4 | 2.1 | virginica |
| 25 | 5.0 | 3.0 | 1.6 | 0.2 | setosa |
| 7 | 5.0 | 3.4 | 1.5 | 0.2 | setosa |
| 68 | 6.2 | 2.2 | 4.5 | 1.5 | versicolor |
We still have the standard workflow for scikit-learn:
import
instantiate
fitpredictortransform
Import
StandardScalerfromsklearn.preprocessing
from sklearn.preprocessing import StandardScaler
Instantiate a
StandardScalerobject and name itscaler.
scaler = StandardScaler()
type(scaler)
sklearn.preprocessing._data.StandardScaler
Try fitting StandardScaler to the iris dataset.
scaler.fit(df)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [6], line 1
----> 1 scaler.fit(df)
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/preprocessing/_data.py:809, in StandardScaler.fit(self, X, y, sample_weight)
807 # Reset internal state before fitting
808 self._reset()
--> 809 return self.partial_fit(X, y, sample_weight)
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/preprocessing/_data.py:844, in StandardScaler.partial_fit(self, X, y, sample_weight)
812 """Online computation of mean and std on X for later scaling.
813
814 All of X is processed as a single batch. This is intended for cases
(...)
841 Fitted scaler.
842 """
843 first_call = not hasattr(self, "n_samples_seen_")
--> 844 X = self._validate_data(
845 X,
846 accept_sparse=("csr", "csc"),
847 dtype=FLOAT_DTYPES,
848 force_all_finite="allow-nan",
849 reset=first_call,
850 )
851 n_features = X.shape[1]
853 if sample_weight is not None:
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/base.py:577, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, **check_params)
575 raise ValueError("Validation should be done on X, y or both.")
576 elif not no_val_X and no_val_y:
--> 577 X = check_array(X, input_name="X", **check_params)
578 out = X
579 elif no_val_X and not no_val_y:
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/utils/validation.py:856, in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)
854 array = array.astype(dtype, casting="unsafe", copy=False)
855 else:
--> 856 array = np.asarray(array, order=order, dtype=dtype)
857 except ComplexWarning as complex_warning:
858 raise ValueError(
859 "Complex data not supported\n{}\n".format(array)
860 ) from complex_warning
File /shared-libs/python3.9/py/lib/python3.9/site-packages/pandas/core/generic.py:1899, in NDFrame.__array__(self, dtype)
1898 def __array__(self, dtype=None) -> np.ndarray:
-> 1899 return np.asarray(self._values, dtype=dtype)
ValueError: could not convert string to float: 'setosa'
What’s going on here? Notice the species column has strings, and it doesn’t make sense to scale these. When we use StandardScaler, we only want to apply it to numeric columns.
Let’s get just the numeric columns of our DataFrame. Notice, the only non-numeric column is “species”.
df.columns
Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width',
'species'],
dtype='object')
numcols = [c for c in df.columns if c != "species"]
numcols
['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
Here != means not equal. Here’s another way we could do it.
[c for c in df.columns if not (c == "species")]
['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
I also just want to show you the following function.
from pandas.api.types import is_numeric_dtype
is_numeric_dtype(df["species"])
False
is_numeric_dtype(df["sepal_length"])
True
df.apply(is_numeric_dtype, axis=0)
sepal_length True
sepal_width True
petal_length True
petal_width True
species False
dtype: bool
[c for c in df.columns if is_numeric_dtype(df[c])]
['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
Now let’s try fitting again.
scaler.fit(df[numcols])
StandardScaler()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
StandardScaler()
Call
transformon the numeric columns ofdf.
df[numcols] = scaler.transform(df[numcols])
df
| sepal_length | sepal_width | petal_length | petal_width | species | |
|---|---|---|---|---|---|
| 0 | -0.900681 | 1.019004 | -1.340227 | -1.315444 | setosa |
| 1 | -1.143017 | -0.131979 | -1.340227 | -1.315444 | setosa |
| 2 | -1.385353 | 0.328414 | -1.397064 | -1.315444 | setosa |
| 3 | -1.506521 | 0.098217 | -1.283389 | -1.315444 | setosa |
| 4 | -1.021849 | 1.249201 | -1.340227 | -1.315444 | setosa |
| ... | ... | ... | ... | ... | ... |
| 145 | 1.038005 | -0.131979 | 0.819596 | 1.448832 | virginica |
| 146 | 0.553333 | -1.282963 | 0.705921 | 0.922303 | virginica |
| 147 | 0.795669 | -0.131979 | 0.819596 | 1.053935 | virginica |
| 148 | 0.432165 | 0.788808 | 0.933271 | 1.448832 | virginica |
| 149 | 0.068662 | -0.131979 | 0.762758 | 0.790671 | virginica |
150 rows Ă— 5 columns
Check that the mean and standard deviation of the resulting columns are 0 and 1, respectively.
df.mean(axis=0)
sepal_length -4.736952e-16
sepal_width -7.815970e-16
petal_length -4.263256e-16
petal_width -4.736952e-16
dtype: float64
These values are not exactly zero, but very close. This is all we can expect (remember, we never expect floats to be exactly equal to something else).
df.std(axis=0)
sepal_length 1.00335
sepal_width 1.00335
petal_length 1.00335
petal_width 1.00335
dtype: float64
Similarly, these are not exactly equal to 1, but they are very close, and this is good enough.
First, let me show you how to implement K-Means clustering in scikit-learn. Then we’ll go through the details of how it works.
Import
KMeansfromsklearn.clusterand instantiate aKMeansobject.
from sklearn.cluster import KMeans
kmeans = KMeans()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [36], line 1
----> 1 kmeans = KMeans()
TypeError: 'KMeans' object is not callable
Fit our
KMeansobject to the numeric columns ofdf.
Notice that when we fit here there’s no target (unlike in Linear Regression, for instance). This is because KMeans is unsupervised. Recall that the target is some correct value we’re trying to predict. Here, we don’t have that.
kmeans.fit(df[numcols])
KMeans()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans()
Put the predicted clusters into a new column called “cluster”.
df["cluster"] = kmeans.predict(df[numcols])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [23], line 1
----> 1 df["cluster"] = KMeans.predict(df[numcols])
TypeError: predict() missing 1 required positional argument: 'X'
df
| sepal_length | sepal_width | petal_length | petal_width | species | cluster | |
|---|---|---|---|---|---|---|
| 0 | -0.900681 | 1.019004 | -1.340227 | -1.315444 | setosa | 1 |
| 1 | -1.143017 | -0.131979 | -1.340227 | -1.315444 | setosa | 7 |
| 2 | -1.385353 | 0.328414 | -1.397064 | -1.315444 | setosa | 7 |
| 3 | -1.506521 | 0.098217 | -1.283389 | -1.315444 | setosa | 7 |
| 4 | -1.021849 | 1.249201 | -1.340227 | -1.315444 | setosa | 1 |
| ... | ... | ... | ... | ... | ... | ... |
| 145 | 1.038005 | -0.131979 | 0.819596 | 1.448832 | virginica | 6 |
| 146 | 0.553333 | -1.282963 | 0.705921 | 0.922303 | virginica | 2 |
| 147 | 0.795669 | -0.131979 | 0.819596 | 1.053935 | virginica | 2 |
| 148 | 0.432165 | 0.788808 | 0.933271 | 1.448832 | virginica | 6 |
| 149 | 0.068662 | -0.131979 | 0.762758 | 0.790671 | virginica | 2 |
150 rows Ă— 6 columns
Make an altair chart with sepal_length along the x-axis, petal_length along the y-axis, and with colors/shapes determined by the cluster predicted by
kmeans.
numcols
['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
alt.Chart(df).mark_point(filled=True,size=100).encode(
x="sepal_length",
y="petal_length",
color="cluster:N",
shape="cluster:N"
)
Usually, we will specify the number of clusters that we want. If not, the default number of clusters is 8. In the code above, it’s not that 8 was determined to be a good number of clusters, this is just the default.
help(kmeans)
Help on KMeans in module sklearn.cluster._kmeans object:
class KMeans(_BaseKMeans)
| KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')
|
| K-Means clustering.
|
| Read more in the :ref:`User Guide <k_means>`.
|
| Parameters
| ----------
|
| n_clusters : int, default=8
| The number of clusters to form as well as the number of
| centroids to generate.
|
| init : {'k-means++', 'random'}, callable or array-like of shape (n_clusters, n_features), default='k-means++'
| Method for initialization:
|
| 'k-means++' : selects initial cluster centroids using sampling based on
| an empirical probability distribution of the points' contribution to the
| overall inertia. This technique speeds up convergence, and is
| theoretically proven to be :math:`\mathcal{O}(\log k)`-optimal.
| See the description of `n_init` for more details.
|
| 'random': choose `n_clusters` observations (rows) at random from data
| for the initial centroids.
|
| If an array is passed, it should be of shape (n_clusters, n_features)
| and gives the initial centers.
|
| If a callable is passed, it should take arguments X, n_clusters and a
| random state and return an initialization.
|
| n_init : int, default=10
| Number of time the k-means algorithm will be run with different
| centroid seeds. The final results will be the best output of
| n_init consecutive runs in terms of inertia.
|
| max_iter : int, default=300
| Maximum number of iterations of the k-means algorithm for a
| single run.
|
| tol : float, default=1e-4
| Relative tolerance with regards to Frobenius norm of the difference
| in the cluster centers of two consecutive iterations to declare
| convergence.
|
| verbose : int, default=0
| Verbosity mode.
|
| random_state : int, RandomState instance or None, default=None
| Determines random number generation for centroid initialization. Use
| an int to make the randomness deterministic.
| See :term:`Glossary <random_state>`.
|
| copy_x : bool, default=True
| When pre-computing distances it is more numerically accurate to center
| the data first. If copy_x is True (default), then the original data is
| not modified. If False, the original data is modified, and put back
| before the function returns, but small numerical differences may be
| introduced by subtracting and then adding the data mean. Note that if
| the original data is not C-contiguous, a copy will be made even if
| copy_x is False. If the original data is sparse, but not in CSR format,
| a copy will be made even if copy_x is False.
|
| algorithm : {"lloyd", "elkan", "auto", "full"}, default="lloyd"
| K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`.
| The `"elkan"` variation can be more efficient on some datasets with
| well-defined clusters, by using the triangle inequality. However it's
| more memory intensive due to the allocation of an extra array of shape
| `(n_samples, n_clusters)`.
|
| `"auto"` and `"full"` are deprecated and they will be removed in
| Scikit-Learn 1.3. They are both aliases for `"lloyd"`.
|
| .. versionchanged:: 0.18
| Added Elkan algorithm
|
| .. versionchanged:: 1.1
| Renamed "full" to "lloyd", and deprecated "auto" and "full".
| Changed "auto" to use "lloyd" instead of "elkan".
|
| Attributes
| ----------
| cluster_centers_ : ndarray of shape (n_clusters, n_features)
| Coordinates of cluster centers. If the algorithm stops before fully
| converging (see ``tol`` and ``max_iter``), these will not be
| consistent with ``labels_``.
|
| labels_ : ndarray of shape (n_samples,)
| Labels of each point
|
| inertia_ : float
| Sum of squared distances of samples to their closest cluster center,
| weighted by the sample weights if provided.
|
| n_iter_ : int
| Number of iterations run.
|
| n_features_in_ : int
| Number of features seen during :term:`fit`.
|
| .. versionadded:: 0.24
|
| feature_names_in_ : ndarray of shape (`n_features_in_`,)
| Names of features seen during :term:`fit`. Defined only when `X`
| has feature names that are all strings.
|
| .. versionadded:: 1.0
|
| See Also
| --------
| MiniBatchKMeans : Alternative online implementation that does incremental
| updates of the centers positions using mini-batches.
| For large scale learning (say n_samples > 10k) MiniBatchKMeans is
| probably much faster than the default batch implementation.
|
| Notes
| -----
| The k-means problem is solved using either Lloyd's or Elkan's algorithm.
|
| The average complexity is given by O(k n T), where n is the number of
| samples and T is the number of iteration.
|
| The worst case complexity is given by O(n^(k+2/p)) with
| n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii,
| 'How slow is the k-means method?' SoCG2006)
|
| In practice, the k-means algorithm is very fast (one of the fastest
| clustering algorithms available), but it falls in local minima. That's why
| it can be useful to restart it several times.
|
| If the algorithm stops before fully converging (because of ``tol`` or
| ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,
| i.e. the ``cluster_centers_`` will not be the means of the points in each
| cluster. Also, the estimator will reassign ``labels_`` after the last
| iteration to make ``labels_`` consistent with ``predict`` on the training
| set.
|
| Examples
| --------
|
| >>> from sklearn.cluster import KMeans
| >>> import numpy as np
| >>> X = np.array([[1, 2], [1, 4], [1, 0],
| ... [10, 2], [10, 4], [10, 0]])
| >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
| >>> kmeans.labels_
| array([1, 1, 1, 0, 0, 0], dtype=int32)
| >>> kmeans.predict([[0, 0], [12, 3]])
| array([1, 0], dtype=int32)
| >>> kmeans.cluster_centers_
| array([[10., 2.],
| [ 1., 2.]])
|
| Method resolution order:
| KMeans
| _BaseKMeans
| sklearn.base._ClassNamePrefixFeaturesOutMixin
| sklearn.base.TransformerMixin
| sklearn.base.ClusterMixin
| sklearn.base.BaseEstimator
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')
| Initialize self. See help(type(self)) for accurate signature.
|
| fit(self, X, y=None, sample_weight=None)
| Compute k-means clustering.
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| Training instances to cluster. It must be noted that the data
| will be converted to C ordering, which will cause a memory
| copy if the given data is not C-contiguous.
| If a sparse matrix is passed, a copy will be made if it's not in
| CSR format.
|
| y : Ignored
| Not used, present here for API consistency by convention.
|
| sample_weight : array-like of shape (n_samples,), default=None
| The weights for each observation in X. If None, all observations
| are assigned equal weight.
|
| .. versionadded:: 0.20
|
| Returns
| -------
| self : object
| Fitted estimator.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from _BaseKMeans:
|
| fit_predict(self, X, y=None, sample_weight=None)
| Compute cluster centers and predict cluster index for each sample.
|
| Convenience method; equivalent to calling fit(X) followed by
| predict(X).
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| New data to transform.
|
| y : Ignored
| Not used, present here for API consistency by convention.
|
| sample_weight : array-like of shape (n_samples,), default=None
| The weights for each observation in X. If None, all observations
| are assigned equal weight.
|
| Returns
| -------
| labels : ndarray of shape (n_samples,)
| Index of the cluster each sample belongs to.
|
| fit_transform(self, X, y=None, sample_weight=None)
| Compute clustering and transform X to cluster-distance space.
|
| Equivalent to fit(X).transform(X), but more efficiently implemented.
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| New data to transform.
|
| y : Ignored
| Not used, present here for API consistency by convention.
|
| sample_weight : array-like of shape (n_samples,), default=None
| The weights for each observation in X. If None, all observations
| are assigned equal weight.
|
| Returns
| -------
| X_new : ndarray of shape (n_samples, n_clusters)
| X transformed in the new space.
|
| predict(self, X, sample_weight=None)
| Predict the closest cluster each sample in X belongs to.
|
| In the vector quantization literature, `cluster_centers_` is called
| the code book and each value returned by `predict` is the index of
| the closest code in the code book.
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| New data to predict.
|
| sample_weight : array-like of shape (n_samples,), default=None
| The weights for each observation in X. If None, all observations
| are assigned equal weight.
|
| Returns
| -------
| labels : ndarray of shape (n_samples,)
| Index of the cluster each sample belongs to.
|
| score(self, X, y=None, sample_weight=None)
| Opposite of the value of X on the K-means objective.
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| New data.
|
| y : Ignored
| Not used, present here for API consistency by convention.
|
| sample_weight : array-like of shape (n_samples,), default=None
| The weights for each observation in X. If None, all observations
| are assigned equal weight.
|
| Returns
| -------
| score : float
| Opposite of the value of X on the K-means objective.
|
| transform(self, X)
| Transform X to a cluster-distance space.
|
| In the new space, each dimension is the distance to the cluster
| centers. Note that even if X is sparse, the array returned by
| `transform` will typically be dense.
|
| Parameters
| ----------
| X : {array-like, sparse matrix} of shape (n_samples, n_features)
| New data to transform.
|
| Returns
| -------
| X_new : ndarray of shape (n_samples, n_clusters)
| X transformed in the new space.
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.base._ClassNamePrefixFeaturesOutMixin:
|
| get_feature_names_out(self, input_features=None)
| Get output feature names for transformation.
|
| Parameters
| ----------
| input_features : array-like of str or None, default=None
| Only used to validate feature names with the names seen in :meth:`fit`.
|
| Returns
| -------
| feature_names_out : ndarray of str objects
| Transformed feature names.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from sklearn.base._ClassNamePrefixFeaturesOutMixin:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from sklearn.base.BaseEstimator:
|
| __getstate__(self)
|
| __repr__(self, N_CHAR_MAX=700)
| Return repr(self).
|
| __setstate__(self, state)
|
| get_params(self, deep=True)
| Get parameters for this estimator.
|
| Parameters
| ----------
| deep : bool, default=True
| If True, will return the parameters for this estimator and
| contained subobjects that are estimators.
|
| Returns
| -------
| params : dict
| Parameter names mapped to their values.
|
| set_params(self, **params)
| Set the parameters of this estimator.
|
| The method works on simple estimators as well as on nested objects
| (such as :class:`~sklearn.pipeline.Pipeline`). The latter have
| parameters of the form ``<component>__<parameter>`` so that it's
| possible to update each component of a nested object.
|
| Parameters
| ----------
| **params : dict
| Estimator parameters.
|
| Returns
| -------
| self : estimator instance
| Estimator instance.
Create a new
KMeansobject namedkmeans2and specify that it should include 2 clusters.
kmeans2 = KMeans(n_clusters=2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [35], line 1
----> 1 KMeans2 = KMeans(n_clusters=2)
TypeError: 'KMeans' object is not callable
Fit
kmeans2and then store the predictions in a new column called cluster2.
kmeans2.fit(df[numcols])
KMeans(n_clusters=2)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=2)
df["cluster2"] = kmeans2.predict(df[numcols])
Make the same altair chart as above, but now with the colors and shapes determined by cluster2.
alt.Chart(df).mark_point(size=100,filled=True).encode(
x="sepal_length",
y="petal_length",
color="cluster2:N",
shape="cluster2:N"
)
Notice how much more clear the clusters are here! This is looking a little more promising to me than the previous example.
Using predictions from cluster2, make a list of altair charts that have the same encodings as before, but with the y-axis going through all columns of
numcols.
numcols
['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
chart_list = []
for c in numcols:
chart = alt.Chart(df).mark_point(size=100,filled=True).encode(
x="sepal_length",
y=c,
color="cluster2:N",
shape="cluster2:N"
)
chart_list.append(chart)
#list of altair charts
chart_list
[alt.Chart(...), alt.Chart(...), alt.Chart(...), alt.Chart(...)]
#unpack the charts and stack them vertically
alt.vconcat(*chart_list)
Importance of Scaling#
Exercise#
Make a DataFrame
dfwith two columns, “miles” and “cars”, containing the following five data points in (miles, cars): (0,1), (0,5), (1,0), (1,1), (1,5).For later use, make a copy of df called
df2. Be sure to use .copy().Using K-Means clustering, divide this
dfdata into two clusters. Store the data in a new column called “cluster”.Does the result match what you expect?
df = pd.DataFrame([[0,1],[0,5],[1,0],[1,1],[1,5]], columns=["miles","cars"])
df
| miles | cars | |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 0 | 5 |
| 2 | 1 | 0 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
# here's another way
df = pd.DataFrame({"miles":[0,0,1,1,1],"cars":[1,5,0,1,5]})
df
| miles | cars | |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 0 | 5 |
| 2 | 1 | 0 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
df2 = df.copy()
Think about how you expect the points to be clustered together. Then compare with what we get below.
kmeans = KMeans(n_clusters=2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [59], line 1
----> 1 kmeans = KMeans(n_cluster=2)
TypeError: __init__() got an unexpected keyword argument 'n_cluster'
kmeans.fit(df)
KMeans(n_clusters=2)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=2)
df["clusters"] = kmeans.predict(df)
df
| miles | cars | clusters | |
|---|---|---|---|
| 0 | 0 | 1 | 0 |
| 1 | 0 | 5 | 1 |
| 2 | 1 | 0 | 0 |
| 3 | 1 | 1 | 0 |
| 4 | 1 | 5 | 1 |
Some observations: Two data points with 5 cars are in one cluster, while the remaining data points with 0 or 1 cars are in another cluster. Note: The names of the clusters are not important.
Rename the miles column of
df2to “feet”, and convert the values from miles to feet.
df2 = df2.rename({"miles":"feet"},axis=1).copy()
df2
| feet | cars | |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 0 | 5 |
| 2 | 1 | 0 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
#There are 5280 feet in a mile
df2.feet = df.miles
| feet | cars | |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 0 | 5 |
| 2 | 147197952000 | 0 |
| 3 | 147197952000 | 1 |
| 4 | 147197952000 | 5 |
df2.feet = 5280*df2.feet
df2
| feet | cars | |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 0 | 5 |
| 2 | 1 | 0 |
| 3 | 1 | 1 |
| 4 | 1 | 5 |
Notice, df2 contains the exact same information as df, but now the “feet” column is overpowering the “cars” column. This is bad because we only changed the unit of measurement used.
Using K-Means clustering, divide the
df2data into two clusters. Store the data in a new column called “cluster”.
kmeans2 = KMeans(n_clusters=2)
kmeans2.fit(df2)
KMeans(n_clusters=2)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=2)
df2["clusters"] = kmeans2.predict(df2)
/shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/base.py:493: FutureWarning: The feature names should match those that were passed during fit. Starting version 1.2, an error will be raised.
Feature names unseen at fit time:
- clusters
warnings.warn(message, FutureWarning)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [76], line 1
----> 1 df2["clusters"] = kmeans2.predict(df2)
2 df2
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/cluster/_kmeans.py:1021, in _BaseKMeans.predict(self, X, sample_weight)
999 """Predict the closest cluster each sample in X belongs to.
1000
1001 In the vector quantization literature, `cluster_centers_` is called
(...)
1017 Index of the cluster each sample belongs to.
1018 """
1019 check_is_fitted(self)
-> 1021 X = self._check_test_data(X)
1022 x_squared_norms = row_norms(X, squared=True)
1023 sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/cluster/_kmeans.py:897, in _BaseKMeans._check_test_data(self, X)
896 def _check_test_data(self, X):
--> 897 X = self._validate_data(
898 X,
899 accept_sparse="csr",
900 reset=False,
901 dtype=[np.float64, np.float32],
902 order="C",
903 accept_large_sparse=False,
904 )
905 return X
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/base.py:600, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, **check_params)
597 out = X, y
599 if not no_val_X and check_params.get("ensure_2d", True):
--> 600 self._check_n_features(X, reset=reset)
602 return out
File /shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/base.py:400, in BaseEstimator._check_n_features(self, X, reset)
397 return
399 if n_features != self.n_features_in_:
--> 400 raise ValueError(
401 f"X has {n_features} features, but {self.__class__.__name__} "
402 f"is expecting {self.n_features_in_} features as input."
403 )
ValueError: X has 3 features, but KMeans is expecting 2 features as input.
df2
| feet | cars | clusters | |
|---|---|---|---|
| 0 | 0 | 1 | 1 |
| 1 | 0 | 5 | 0 |
| 2 | 1 | 0 | 1 |
| 3 | 1 | 1 | 1 |
| 4 | 1 | 5 | 0 |
Notice now that the clusters are different compared to when we first tried with just df. Here, because feet is so much larger than cars, it is influencing the model.
Exercise: Apply StandardScaler to df2 and then try clustering again. See what happens!
Upshot: Unless the same unit of measurement is used over the columns, we should normalize (e.g. with StandardScaler).
The K-Means Algorithm#
Reference: Wikipedia page on K-Means clustering. (See the standard algorithm section.)
This portion of the lecture I plan to sketch out on the iPad.





Iterating by hand#
Question 1: Using the following dataset, run the KMeans algorithm by hand, starting with the initial points (3,0) and (1,0). (How many clusters do you expect with this setup?)
Two initial points means we expect 2 clusters.
Warning: Notice the scaling on the x- and y-axes.
import pandas as pd
import altair as alt
from sklearn.cluster import KMeans
df = pd.DataFrame({"x":[0,0,1,1,3,4],"y":[0,10,0,10,0,0]})
datapoints = alt.Chart(df).mark_point(size=100, color="black", filled=True).encode(
x = "x",
y = "y"
)
datapoints
First Iteration: Cluster 1: Points closest to (3,0) (3,0),(4,0) Cluster 2: Points closest to (1,0) (1,0),(0,0), (1,10), (0,10)
It’s not too hard to see that (4,0) is closer to (3,0). Similarly, (0,0) is closer to (1,0)
Distance between (1,0) and (1,10): 10 Distance between (3,0) and (1,10): \(\sqrt{2^2 + (-10)^2} = \sqrt{4 + 100} = \sqrt{104} > 10\)
Let’s now compute the centroids of each cluster. Cluster 1: \(\frac{1}{2}(3+4,0) = (3.5,0)\) Cluster 2: \(\frac{1}{4}(1+0+1+0,0+0+10+10) = (0.5,5)\)
round1 = pd.DataFrame({"x":[3.5,0.5],"y":[0,5]})
average1 = alt.Chart(round1).mark_point(size=100,filled=True,color="green").encode(
x="x",
y="y"
)
datapoints + average1
Second Iteration: Cluster 1: Points closest to (3.5,0): (3,0),(4,0),(1,0),(0,0) Cluster 2: Points closest to (0.5,5): (0,10) and (1,10)
Compute centroids again: (2,0) and (0.5,10)
round2 = pd.DataFrame({"x":[2,0.5],"y":[0,10]})
average2 = alt.Chart(round2).mark_point(color="orange",size=100,filled=True).encode(
x="x",
y="y"
)
datapoints + average1 + average2
Notice that this is where we terminate the algorithm because if we try to reassign points to the nearest centroid, they all stay in the same cluster.
Let’s check how we did.
kmeans = KMeans(n_clusters=2)
kmeans.fit(df)
df["clusters"] = kmeans.predict(df)
datapoints.encode(
color="clusters:N"
)