Introduction to Machine Learning with Python

Get started with ML using Python and build your first model.

Illustration of machine learning with Python

Introduction to Machine Learning with Python

Learn the basics of machine learning and build a simple model using Python.

1. What is Machine Learning?

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.

2. Setting Up Python for ML

Install necessary libraries:

pip install scikit-learn numpy pandas matplotlib

3. Loading and Exploring Data

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())

4. Preprocessing Data

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)

5. Building and Training a Model

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))

6. Visualizing Results

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()

7. Conclusion

Machine learning with Python is accessible and powerful. Experiment with different algorithms and datasets to deepen your understanding.