Python - Machine Learning Part 3: Building and Training Machine Learning Models

Python offers pre-built algorithms for regression, classification, and clustering through libraries like scikit-learn. This step involves selecting the right algorithm, training the model, and optimizing parameters.

Examples:

Regression Model

from sklearn.linear_model import LinearRegression

import numpy as np

# Data

X = np.array([[1], [2], [3], [4]])

y = np.array([3, 7, 11, 15])

# Model

model = LinearRegression()

model.fit(X, y)

print(model.predict([[5]]))  # Predict output

Explanation: A linear regression model is trained to predict a continuous output.

Classification Model

from sklearn.neighbors import KNeighborsClassifier

import numpy as np

# Data

X = np.array([[1, 1], [2, 2], [3, 3]])

y = [0, 0, 1]

# Model

model = KNeighborsClassifier(n_neighbors=1)

model.fit(X, y)

print(model.predict([[2.5, 2.5]]))

Explanation: The k-nearest neighbors algorithm classifies data points based on their proximity to existing labeled points.

Clustering Model

from sklearn.cluster import KMeans

import numpy as np

# Data

X = np.array([[1, 1], [2, 2], [3, 3], [10, 10]])

model = KMeans(n_clusters=2)

model.fit(X)

print(model.labels_)

Explanation: K-means groups data into clusters based on similarity, such as segmenting customers into groups.