Scikit-Learn Cheatsheet
Scikit-Learn Cheatsheet
Scikit-Learn Cheatsheet
Scikit-learnis a library in Python that provides many unsupervised andsupervised learningalgorithms. It’s built upon some of the technology you might already be familiar with, likeNumPy, pandas, and Matplotlib!
As you build robust Machine Learning programs, it’s helpful to have all thesklearncommands all in one place in case you forget.
Linear regression in Scikit-Learn
Import and create the model:
from sklearn.linear_model import LinearRegression
your_model = LinearRegression()
Copy to clipboard
from sklearn.linear_model import LinearRegression
your_model = LinearRegression()
Fit:
your_model.fit(x_training_data, y_training_data)
Copy to clipboard
your_model.fit(x_training_data, y_training_data)
- .coef_: contains the coefficients
- .intercept_: contains the intercept
Predict:
predictions = your_model.predict(your_x_data)
Copy to clipboard
predictions = your_model.predict(your_x_data)
- .score(): returns the coefficient of determination R²
Naive Bayes classification in Scikit-Learn
from sklearn.naive_bayes import MultinomialNB
your_model = MultinomialNB()
Copy to clipboard
from sklearn.naive_bayes import MultinomialNB
your_model = MultinomialNB()
your_model.fit(x_training_data, y_training_data)
Copy to clipboard
# Returns a list of predicted classes - one prediction for every data pointpredictions = your_model.predict(your_x_data)
# For every data point, returns a list of probabilities of each classprobabilities = your_model.predict_proba(your_x_data)
Copy to clipboard
# Returns a list of predicted classes - one prediction for every data pointpredictions = your_model.predict(your_x_data)
# For every data point, returns a list of probabilities of each classprobabilities = your_model.predict_proba(your_x_data)
K-nearest neighbors (KNN) in Scikit-Learn
from sklearn.neighbors import KNeighborsClassifier
your_model = KNeighborsClassifier()
Copy to clipboard
from sklearn.neighbors import KNeighborsClassifier
your_model = KNeighborsClassifier()
your_model.fit(x_training_data, y_training_data)
Copy to clipboard
# Returns a list of predicted classes - one prediction for every data pointpredictions = your_model.predict(your_x_data)
# For every data point, returns a list of probabilities of each classprobabilities = your_model.predict_proba(your_x_data)
Copy to clipboard
K-means clustering in Scikit-Learn
from sklearn.cluster import KMeans
your_model = KMeans(n_clusters=4, init='random')
Copy to clipboard
from sklearn.cluster import KMeans
your_model = KMeans(n_clusters=4, init='random')
- n_clusters: number of clusters to form and number of centroids to generate
- init: method for initializationk-means++: K-Means++ [default]random: K-Means
- random_state: the seed used by the random number generator [optional]
your_model.fit(x_training_data)
Copy to clipboard
your_model.fit(x_training_data)
predictions = your_model.predict(your_x_data)
Copy to clipboard
Validating a machine learning model
Import and print accuracy, recall, precision, and F1 score:
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score
print(accuracy_score(true_labels, guesses))print(recall_score(true_labels, guesses))print(precision_score(true_labels, guesses))print(f1_score(true_labels, guesses))
Copy to clipboard
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score
print(accuracy_score(true_labels, guesses))print(recall_score(true_labels, guesses))print(precision_score(true_labels, guesses))print(f1_score(true_labels, guesses))
Import and print the confusion matrix:
from sklearn.metrics import confusion_matrix
print(confusion_matrix(true_labels, guesses))
Copy to clipboard
from sklearn.metrics import confusion_matrix
print(confusion_matrix(true_labels, guesses))
Splitting data into training and test sets
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, test_size=0.2)
Copy to clipboard
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, test_size=0.2)
- train_size: the proportion of the dataset to include in the train split
- test_size: the proportion of the dataset to include in the test split
- random_state: the seed used by the random number generator [optional]
Conclusion
Scikit-Learnprovides a powerful and user-friendly framework for implementing machine learning models in Python. From regression and classification to clustering and model validation, it simplifies complex tasks with efficient built-in functions. Whether you’re training models, making predictions, or evaluating performance, Scikit-Learn equips you with the tools needed to build robust machine learning applications.
If you’re interested in learning more about Scikit-Learn and its applications in machine learning, please check out ourAI Catalog of articles!
Robot Emoji
Happy Coding!
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Complete Payment to Unlock Full Guide & Source Code
You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.
Ready to access the complete step-by-step tutorial?
Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.
SAM3 by Meta: Text-Prompted Image Segmentation Tutorial
Next BlueprintScikit-Learn Tutorial: Python Machine Learning Model Building
Related Blueprints & Guides
View all 166 →Decision Trees for Classification and Regression
Decision trees are a common type of machine learning model used for binary classification tasks. The natural structure of a binary tree lends itself well to predicting a “yes” or “no” target. It is traversed sequentially...
Machine learningFeature Importance
When we fit a supervised machine learning (ML) model, we often want to understand which features are most associated with our outcome of interest. Features that are highly associated with the outcome are considered more...
Machine learningHistory of Chatbots
In October of 1950, Alan Turing proposed an approach for evaluating a computer’s intelligence and famously named his method, The Imitation Game. The premise is that an interrogator talks to two people through a “typewrit...
Ready to build production-grade AI systems?
Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.