Module 15 · K means clustering · Lesson 56 of 66

Project: private or public college?

Cluster 777 colleges into two groups, then see how well the groups match private and public schools.

In this lesson · about 25 minutes

  • Explore and clean a data set
  • Fit K means and compare clusters with real labels

This data describes 777 US colleges from 1995. We'll ask K means to split them into two groups using only the numbers, then check whether those groups line up with private and public schools. In real clustering you wouldn't have the answer; here we do, so we can judge the result.

Some columns: Private (Yes/No), Apps (applications received), Accept, Enroll, Top10perc (new students from the top 10% of their high school class), F.Undergrad (full-time undergraduates), Outstate (out-of-state tuition), Room.Board, PhD (faculty with PhDs, %), S.F.Ratio (students per faculty), Expend (spending per student) and Grad.Rate.

Exercise

1. Graduation rate and room and board

Use sns.scatterplot to plot Grad.Rate (y) against Room.Board (x), colored by Private with the 'coolwarm' palette.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('College_Data.csv', index_col=0)

2. Size and tuition

Exercise

3. Tuition by type

Make a FacetGrid of df with hue='Private', the 'coolwarm' palette, height=6 and aspect=2, and map plt.hist of Outstate onto it with 20 bins and alpha=0.7.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('College_Data.csv', index_col=0)

Exercise

4. A graduation rate over 100%

One school reports a graduation rate above 100. First find it: show the rows where Grad.Rate is over 100. Then set that school's rate to 100 with df.loc[...], and end by showing df.loc['Cazenovia College', 'Grad.Rate'].

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('College_Data.csv', index_col=0)

Exercise

5. Two clusters

Create KMeans(n_clusters=2, n_init=10, random_state=101) called kmeans and fit it to every column except Private. End with kmeans.cluster_centers_.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('College_Data.csv', index_col=0)
df.loc['Cazenovia College', 'Grad.Rate'] = 100
from sklearn.cluster import KMeans

Exercise

6. How close did it get?

Add a column Cluster that is 1 for private schools and 0 for public ones. Then print the confusion matrix of df['Cluster'] against kmeans.labels_.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('College_Data.csv', index_col=0)
df.loc['Cazenovia College', 'Grad.Rate'] = 100
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2, n_init=10, random_state=101)
kmeans.fit(df.drop('Private', axis=1))

The clusters match private and public schools only loosely, and which cluster number means "private" is arbitrary. K means grouped the colleges mostly by size and money, which overlaps with being private but isn't the same thing. That's the nature of clustering: it finds structure, and it's your job to interpret what that structure means.

Exercises solved: 0 of 5

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.