Scikit-learn has a very clean and consistent API, making it very easy to use: a similar workflow can be applied to most techniques. Let’s go over two examples.
Load packages
from sklearn.datasets import fetch_california_housing, load_breast_cancerfrom sklearn.linear_model import LinearRegression, LogisticRegressionfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.metrics import ( mean_squared_error, mean_absolute_percentage_error, accuracy_score)import pandas as pdimport matplotlibfrom matplotlib import pyplot as pltimport numpy as npfrom collections import Counter
---------------------------------------------------------------------------ModuleNotFoundError Traceback (most recent call last)
CellIn[1], line 1----> 1fromsklearn.datasetsimportfetch_california_housing,load_breast_cancer 2fromsklearn.linear_modelimportLinearRegression,LogisticRegression 3fromsklearn.ensembleimportRandomForestRegressor 4fromsklearn.neighborsimportKNeighborsClassifierModuleNotFoundError: No module named 'sklearn'
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[2], line 1----> 1cal_housing=fetch_california_housing() 2type(cal_housing)NameError: name 'fetch_california_housing' is not defined
Let’s look at the attributes of cal_housing:
dir(cal_housing)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[3], line 1----> 1dir(cal_housing)NameError: name 'cal_housing' is not defined
cal_housing.feature_names
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[4], line 1----> 1cal_housing.feature_namesNameError: name 'cal_housing' is not defined
print(cal_housing.DESCR)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[5], line 1----> 1print(cal_housing.DESCR)NameError: name 'cal_housing' is not defined
X = cal_housing.datay = cal_housing.target
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[6], line 1----> 1X=cal_housing.data 2y=cal_housing.targetNameError: name 'cal_housing' is not defined
This can also be obtained with X, y = fetch_california_housing(return_X_y=True).
Let’s have a look at the shape of X and y:
X.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[7], line 1----> 1X.shapeNameError: name 'X' is not defined
y.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[8], line 1----> 1y.shapeNameError: name 'y' is not defined
While not at all necessary, we can turn this bunch object into a more familiar data frame to explore the data further:
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[9], line 1----> 1cal_housing_df=pd.DataFrame(cal_housing.data,columns=cal_housing.feature_names)NameError: name 'pd' is not defined
cal_housing_df.head()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[10], line 1----> 1cal_housing_df.head()NameError: name 'cal_housing_df' is not defined
cal_housing_df.tail()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[11], line 1----> 1cal_housing_df.tail()NameError: name 'cal_housing_df' is not defined
cal_housing_df.info()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[12], line 1----> 1cal_housing_df.info()NameError: name 'cal_housing_df' is not defined
cal_housing_df.describe()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[13], line 1----> 1cal_housing_df.describe()NameError: name 'cal_housing_df' is not defined
We can even plot it:
plt.hist(y)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[14], line 1----> 1plt.hist(y)NameError: name 'plt' is not defined
Create and fit a model
Let’s start with a very simple model: linear regression.
model = LinearRegression().fit(X, y)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[15], line 1----> 1model=LinearRegression().fit(X,y)NameError: name 'LinearRegression' is not defined
This is equivalent to:
model = LinearRegression()model.fit(X, y)
First, we create an instance of the class LinearRegression, then we call .fit() on it to fit the model.
model.coef_
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[16], line 1----> 1model.coef_NameError: name 'model' is not defined
Trailing underscores indicate that an attribute is estimated. .coef_ here is an estimated value.
model.coef_.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[17], line 1----> 1model.coef_.shapeNameError: name 'model' is not defined
model.intercept_
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[18], line 1----> 1model.intercept_NameError: name 'model' is not defined
We can now get our predictions:
y_hat = model.predict(X)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[19], line 1----> 1y_hat=model.predict(X)NameError: name 'model' is not defined
And calculate some measures of error:
Sum of squared errors
np.sum((y - y_hat) **2)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[20], line 1----> 1np.sum((y-y_hat)**2)NameError: name 'np' is not defined
Mean squared error
mean_squared_error(y, y_hat)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[21], line 1----> 1mean_squared_error(y,y_hat)NameError: name 'mean_squared_error' is not defined
MSE could also be calculated with np.mean((y - y_hat)**2).
mean_absolute_percentage_error(y, y_hat)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[22], line 1----> 1mean_absolute_percentage_error(y,y_hat)NameError: name 'mean_absolute_percentage_error' is not defined
Index of minimum value:
model.coef_.argmin()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[23], line 1----> 1model.coef_.argmin()NameError: name 'model' is not defined
Index of maximum value:
model.coef_.argmax()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[24], line 1----> 1model.coef_.argmax()NameError: name 'model' is not defined
XX = np.concatenate([np.ones((len(X), 1)), X], axis=1)beta = np.linalg.lstsq(XX, y, rcond=None)[0]intercept_, *coef_ = betaintercept_, model.intercept_
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[25], line 1----> 1XX=np.concatenate([np.ones((len(X),1)),X],axis=1) 2 3beta=np.linalg.lstsq(XX,y,rcond=None)[0] 4intercept_,*coef_=betaNameError: name 'np' is not defined
np.allclose(coef_, model.coef_)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[26], line 1----> 1np.allclose(coef_,model.coef_)NameError: name 'np' is not defined
This means that the two arrays are equal element-wise, within a certain tolerance.
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[27], line 1----> 1X_test=np.random.normal(size=(10,X.shape[1])) 2X_test.shapeNameError: name 'np' is not defined
y_test = X_test @ coef_ + intercept_y_test
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[28], line 1----> 1y_test=X_test@coef_+intercept_ 2y_testNameError: name 'X_test' is not defined
model.predict(X_test)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[29], line 1----> 1model.predict(X_test)NameError: name 'model' is not defined
Of course, instead of LinearRegression(), we could have used another model such as a random forest regressor (a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting) for instance:
model = RandomForestRegressor().fit(X, y).predict(X_test)model
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[30], line 1----> 1model=RandomForestRegressor().fit(X,y).predict(X_test) 2modelNameError: name 'RandomForestRegressor' is not defined
Which is equivalent to:
model = RandomForestRegressor()model.fit(X, y).predict(X_test)
Example 2: breast cancer
Load and explore the data
b_cancer = load_breast_cancer()
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[31], line 1----> 1b_cancer=load_breast_cancer()NameError: name 'load_breast_cancer' is not defined
Let’s print the description of this dataset:
print(b_cancer.DESCR)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[32], line 1----> 1print(b_cancer.DESCR)NameError: name 'b_cancer' is not defined
b_cancer.feature_names
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[33], line 1----> 1b_cancer.feature_namesNameError: name 'b_cancer' is not defined
b_cancer.target_names
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[34], line 1----> 1b_cancer.target_namesNameError: name 'b_cancer' is not defined
X = b_cancer.datay = b_cancer.target
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[35], line 1----> 1X=b_cancer.data 2y=b_cancer.targetNameError: name 'b_cancer' is not defined
Here again, we could have used instead X, y = load_breast_cancer(return_X_y=True).
X.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[36], line 1----> 1X.shapeNameError: name 'X' is not defined
y.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[37], line 1----> 1y.shapeNameError: name 'y' is not defined
set(y)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[38], line 1----> 1set(y)NameError: name 'y' is not defined
Counter(y)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[39], line 1----> 1Counter(y)NameError: name 'Counter' is not defined
Create and fit a first model
model = LogisticRegression(max_iter=10000)y_hat = model.fit(X, y).predict(X)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[40], line 1----> 1model=LogisticRegression(max_iter=10000) 2y_hat=model.fit(X,y).predict(X)NameError: name 'LogisticRegression' is not defined
Get some measure of accuracy:
accuracy_score(y, y_hat)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[41], line 1----> 1accuracy_score(y,y_hat)NameError: name 'accuracy_score' is not defined
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[42], line 4 1defsigmoid(x): 2return1/(1+np.exp(-x)) 3----> 4x=np.linspace(-10,10,100) 5plt.plot(x,sigmoid(x),lw=3) 6plt.title("The Sigmoid Function $\\sigma(x)$")NameError: name 'np' is not defined
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[43], line 1----> 1y_pred=1*(sigmoid(X@model.coef_.squeeze()+model.intercept_)>0.5) 2assertnp.all(y_pred==model.predict(X)) 3 4 np.allclose(
NameError: name 'X' is not defined
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[44], line 12 8X[:,0]=rr*np.cos(theta) 9X[:,1]=rr*np.sin(theta) 10returnX,y 11---> 12X,y=make_spirals() 13cmap=matplotlib.colormaps["viridis"] 14 15a=cmap(0)CellIn[44], line 2, in make_spirals(k, s, n) 1defmake_spirals(k=20,s=1.0,n=2000):----> 2X=np.zeros((n,2)) 3y=np.round(np.random.uniform(size=n)).astype(int) 4r=np.random.uniform(size=n)*k*np.pi 5rr=r**0.5NameError: name 'np' is not defined
Create and fit a second model
model = LogisticRegression()y_hat = model.fit(X, y).predict(X)accuracy_score(y, y_hat)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[45], line 1----> 1model=LogisticRegression() 2y_hat=model.fit(X,y).predict(X) 3accuracy_score(y,y_hat)NameError: name 'LogisticRegression' is not defined
u = np.linspace(-8, 8, 100)v = np.linspace(-8, 8, 100)U, V = np.meshgrid(u, v)UV = np.array([U.ravel(), V.ravel()]).TU.shape, V.shape, UV.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[46], line 1----> 1u=np.linspace(-8,8,100) 2v=np.linspace(-8,8,100) 3U,V=np.meshgrid(u,v) 4UV=np.array([U.ravel(),V.ravel()]).TNameError: name 'np' is not defined
np.ravel returns a contiguous flattened array.
W = model.predict(UV).reshape(U.shape)W.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[47], line 1----> 1W=model.predict(UV).reshape(U.shape) 2W.shapeNameError: name 'model' is not defined
plt.pcolormesh(U, V, W)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[48], line 1----> 1plt.pcolormesh(U,V,W)NameError: name 'plt' is not defined
Create and fit a third model
Let’s use a k-nearest neighbours classifier this time:
model = KNeighborsClassifier(n_neighbors=5)y_hat = model.fit(X, y).predict(X)accuracy_score(y, y_hat)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[49], line 1----> 1model=KNeighborsClassifier(n_neighbors=5) 2y_hat=model.fit(X,y).predict(X) 3accuracy_score(y,y_hat)NameError: name 'KNeighborsClassifier' is not defined
u = np.linspace(-8, 8, 100)v = np.linspace(-8, 8, 100)U, V = np.meshgrid(u, v)UV = np.array([U.ravel(), V.ravel()]).TU.shape, V.shape, UV.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[50], line 1----> 1u=np.linspace(-8,8,100) 2v=np.linspace(-8,8,100) 3U,V=np.meshgrid(u,v) 4UV=np.array([U.ravel(),V.ravel()]).TNameError: name 'np' is not defined
W = model.predict(UV).reshape(U.shape)W.shape
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[51], line 1----> 1W=model.predict(UV).reshape(U.shape) 2W.shapeNameError: name 'model' is not defined
plt.pcolormesh(U, V, W)
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[52], line 1----> 1plt.pcolormesh(U,V,W)NameError: name 'plt' is not defined
We can iterate over various values of k to see how the accuracy and pseudocolor plot evolve:
---------------------------------------------------------------------------NameError Traceback (most recent call last)
CellIn[53], line 1----> 1fig,axes=plt.subplots(2,4,figsize=(9.8,5)) 2fig.suptitle("Decision Regions") 3 4u=np.linspace(-8,8,100)NameError: name 'plt' is not defined