Machine Learning Lab Using Python Dr Benabderrezak
Comprehensive Python Lab : From Basics to Mastering Machine Learning
Objective
- This lab aims to take you from the fundamentals of Python programming to mastering machine learning
and statistics.
- It provides hands-on exercises for data manipulation, visualization, statistical analysis, and advanced
machine learning techniques.
Part 1 : Python Basics
1.1 Variables and Data Types
# Integer, Float, String, Boolean
x = 10 # Integer
y = 3.14 # Float
name = "Machine Learning" # String
is_python_fun = True # Boolean
1.2 Lists, Tuples, and Dictionaries
# List
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers)
# Tuple (Immutable)
coordinates = (10.0, 20.0)
print(coordinates)
# Dictionary
student = {"name": "Alice", "age": 25, "grade": "A"}
print(student["name"])
1
Machine Learning Lab Using Python Dr Benabderrezak
1.3 Loops and Conditionals
for i in range(5):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
1.4 Functions
def square(num):
return num ** 2
print(square(4))
Part 2 : Data Manipulation with NumPy and Pandas
2.1 NumPy Basics
import numpy as np
# Creating an array
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2) # Element-wise operations
2.2 Pandas Basics
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df.head())
2
Machine Learning Lab Using Python Dr Benabderrezak
Part 3 : Data Visualization with Matplotlib & Seaborn
import matplotlib.pyplot as plt
import seaborn as sns
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.show()
Part 4 : Statistics & Probability
4.1 Descriptive Statistics
print(df.describe()) # Summary statistics
4.2 Probability Distributions
from scipy.stats import norm
# Normal distribution
x = np.linspace(-3, 3, 100)
plt.plot(x, norm.pdf(x))
plt.title("Normal Distribution")
plt.show()
Part 5 : Machine Learning Basics
5.1 Train-Test Split
from sklearn.model_selection import train_test_split
X = df[['Age']]
y = df['Age'] > 28 # Creating a binary target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
3
Machine Learning Lab Using Python Dr Benabderrezak
5.2 Training a Model
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
Part 6 : Advanced Machine Learning
6.1 Decision Trees and Random Forests
from sklearn.ensemble import RandomForestClassifier
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
6.2 Hyperparameter Tuning
from sklearn.model_selection import GridSearchCV
param_grid = {'n_estimators': [50, 100, 200]}
gs = GridSearchCV(RandomForestClassifier(), param_grid, cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
Part 7 : Deep Learning Introduction
7.1 Neural Networks with TensorFlow
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
4
Machine Learning Lab Using Python Dr Benabderrezak
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=32)
Conclusion
This lab covered Python basics, data manipulation, visualization, statistics, and machine learning techniques. Next
steps include deep learning, reinforcement learning, and model deployment.
Reference :
https://www.w3schools.com/python/python_ml_getting_started.asp