Introduction to Machine Learning with Scikit-Learn
Learn the basics of machine learning using Scikit-Learn and Python with a simple classification example.
Introduction to Machine Learning with Scikit-Learn
Step 1: Install Required Libraries
To start with machine learning, you need to have Python and the necessary libraries installed. You can install the required libraries using pip:
pip install numpy scipy scikit-learn
Step 2: Import Libraries and Load Dataset
Next, import the necessary libraries and load the dataset you want to work with. For this example, we'll use the famous Iris dataset:
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
Step 3: Split Dataset into Training and Test Sets
Split your dataset into training and test sets. The training set will be used to train the model, and the test set will be used to evaluate its performance:
# Split dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 4: Standardize Features
Standardize features by removing the mean and scaling to unit variance. This step is crucial for many machine learning algorithms:
# Standardize features
sc = StandardScaler()
X_train_std = sc.fit_transform(X_train)
X_test_std = sc.transform(X_test)
Step 5: Train a Model
Train a simple K-Nearest Neighbors classifier on your data:
# Train a KNN classifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train_std, y_train)
Step 6: Make Predictions and Evaluate the Model
Use your trained model to make predictions on the test set and evaluate its performance using accuracy score:
# Make predictions and evaluate the model
y_pred = knn.predict(X_test_std)
print('Accuracy:', accuracy_score(y_test, y_pred))
By following these steps, you've successfully introduced yourself to machine learning with Scikit-Learn and Python.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based machine learning video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked machine learning books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.