NumPy is a Python library used for numerical computations, including machine learning tasks. Here, we will discuss examples of some commonly used NumPy machine learning methods with accompanying Python code.
Linear Regression: Linear regression is a popular technique for modeling the relationship between a dependent variable and one or more independent variables. NumPy provides a convenient method for performing linear regression.
import numpy as np
from sklearn.linear_model import LinearRegression
# Create a simple dataset
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
y = np.dot(X, np.array([1, 2])) + 3
# Train the linear regression model
reg = LinearRegression().fit(X, y)
# Print the coefficients
print(reg.coef_)
print(reg.intercept_)
Principal Component Analysis (PCA): PCA is a dimensionality reduction technique that finds the principal components of a dataset. NumPy provides a method for performing PCA.
import numpy as np
from sklearn.decomposition import PCA
# Create a dataset with three features
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Fit PCA on the dataset
pca = PCA(n_components=2)
pca.fit(X)
# Get the transformed data
X_transformed = pca.transform(X)
# Print the transformed data
print(X_transformed)
K-Means Clustering: K-Means is a popular clustering algorithm that partitions data into K clusters. NumPy provides a method for performing K-Means clustering.
import numpy as np
from sklearn.cluster import KMeans
# Create a dataset with two features
X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
# Fit K-Means on the dataset
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
# Get the cluster labels
labels = kmeans.labels_
# Print the cluster labels
print(labels)
Support Vector Machines (SVM): SVM is a popular classification algorithm that finds the hyperplane that separates two classes. NumPy provides a method for performing SVM classification.
import numpy as np
from sklearn import svm
# Create a dataset with two features and two classes
X = np.array([[0, 0], [1, 1]])
y = np.array([0, 1])
# Fit SVM on the dataset
clf = svm.SVC()
clf.fit(X, y)
# Predict the class of a new datapoint
print(clf.predict([[2, 2]]))
Advertisement
Advertisement