Get started with ML using Python and build your first model.
Learn the basics of machine learning and build a simple model using Python.
Machine learning is a subset of AI that enables systems to learn from data. This post covers supervised learning, where models predict outcomes based on labeled data, using Python and scikit-learn.
Install necessary libraries:
pip install scikit-learn numpy pandas matplotlib
Use the Iris dataset:
from sklearn.datasets import load_iris
import pandas as pd
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
print(df.head())
Split into training and testing sets:
from sklearn.model_selection import train_test_split
X = df
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
Use a K-Nearest Neighbors classifier:
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
Plot a confusion matrix:
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True)
plt.show()
Machine learning with Python is accessible and powerful. Experiment with different algorithms and datasets to deepen your understanding.