🐍 Python Tutorial: Machine Learning
Machine learning in Python can be approached using several powerful libraries. This tutorial introduces you to three of the most commonly used: scikit-learn for traditional ML, TensorFlow and Keras for deep learning. We will walk through their roles, use cases, and example usage.
1. scikit-learn
scikit-learn is a simple and efficient tool for data mining and data analysis. It supports classification, regression, clustering, dimensionality reduction, and more:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))2. TensorFlow
TensorFlow is an end-to-end open-source platform for machine learning developed by Google. It provides tools for building and training neural networks at scale:
import tensorflow as tf
# Build a simple model
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])3. Keras
Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow. It is user-friendly and fast to prototype with:
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(64, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# model.fit(X_train, y_train, epochs=10)