2 min read

Python Scikit-Learn Module

Scikit-learn is a simple and efficient tool for predictive data analysis. It is built on NumPy, SciPy, and matplotlib.

Installation

pip install scikit-learn

Importing the Module

import sklearn

Basic Workflow

The typical workflow in scikit-learn involves:

  1. Loading data
  2. Splitting data into training and testing sets
  3. Initializing a model
  4. Fitting the model to the training data
  5. Predicting on new data
  6. Evaluating the model

Loading Data

Scikit-learn comes with a few standard datasets, for example the iris and digits datasets for classification and the diabetes dataset for regression.

from sklearn import datasets

iris = datasets.load_iris()
X = iris.data  # Features
y = iris.target # Labels

Splitting Data

To evaluate the performance of a model, it is important to split the data into a training set and a testing set.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Training a Model

Here is an example using the K-Nearest Neighbors (KNN) classifier.

from sklearn.neighbors import KNeighborsClassifier

# Initialize the model
knn = KNeighborsClassifier(n_neighbors=3)

# Train the model
knn.fit(X_train, y_train)

Making Predictions

predictions = knn.predict(X_test)
print(predictions)

Evaluating the Model

from sklearn.metrics import accuracy_score

accuracy = accuracy_score(y_test, predictions)
print(f"Accuracy: {accuracy}")

Regression Example

Here is a quick example using Linear Regression.

from sklearn.linear_model import LinearRegression
import numpy as np

# Dummy data
X = np.array(<a href='/1%5D%2C%20%5B2%5D%2C%20%5B3%5D%2C%20%5B4%5D%2C%20%5B5'>1], [2], [3], [4], [5</a>)
y = np.array([2, 4, 6, 8, 10])

model = LinearRegression()
model.fit(X, y)

print(f"Prediction for 6: {model.predict(<a href='/6'>6</a>)}")
# Output: Prediction for 6: [12.]

programming/python/python