Home Topics Python for ML

Python for ML

Essential libraries for data science

6 hours 25 examples Beginner
Beginner

Why Python for Machine Learning?

Python is the #1 language for Machine Learning. Over 90% of data scientists use it daily. Here's why:

Rich Ecosystem

NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch - everything you need is already built.

Easy to Learn

Readable syntax that feels like English. Focus on algorithms, not language complexity.

Huge Community

Millions of tutorials, Stack Overflow answers, and open-source contributors.

Research Standard

Most academic papers include Python code. Easy to implement latest research.

Did You Know?

Python was named after Monty Python, not the snake! The creator, Guido van Rossum, was a fan of the British comedy show.

Beginner

Setup & Installation

The easiest way to get started is with Anaconda - it includes Python and all ML libraries pre-installed.

terminal
# Option 1: Install with pip (if Python is installed)
pip install numpy pandas matplotlib scikit-learn

# Option 2: Using conda (recommended)
conda install numpy pandas matplotlib scikit-learn

# Verify installation
python -c "import numpy; print(f'NumPy version: {numpy.__version__}')"
Output
NumPy version: 1.24.3
NumPy

NumPy - Numerical Computing

NumPy (Numerical Python) is the foundation of scientific computing. It provides fast, efficient arrays that are 50x faster than Python lists!

Why NumPy is Fast

NumPy arrays are stored in contiguous memory and operations are written in C. This means vectorized operations run in compiled code, not slow Python loops.

Creating Arrays

numpy_arrays.py
import numpy as np

# Create a 1D array (vector)
arr = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr)

# Create a 2D array (matrix)
matrix = np.array([[1, 2, 3],
                   [4, 5, 6]])
print("2D Array:\n", matrix)

# Quick array creation
zeros = np.zeros((3, 3))        # 3x3 matrix of zeros
ones = np.ones((2, 4))          # 2x4 matrix of ones
randoms = np.random.rand(3, 3)  # Random values 0-1

print("Zeros:\n", zeros)
print("Shape:", zeros.shape)
Output
1D Array: [1 2 3 4 5]
2D Array:
 [[1 2 3]
 [4 5 6]]
Zeros:
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
Shape: (3, 3)

Array Operations (Vectorized)

numpy_operations.py
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Element-wise operations (NO LOOPS NEEDED!)
print("a + b =", a + b)        # Addition
print("a * b =", a * b)        # Multiplication
print("a ** 2 =", a ** 2)      # Square each element

# Statistical operations
data = np.array([23, 45, 67, 89, 12])
print("Mean:", np.mean(data))
print("Std Dev:", np.std(data))
print("Max:", np.max(data))
print("Sum:", np.sum(data))
Output
a + b = [5 7 9]
a * b = [ 4 10 18]
a ** 2 = [1 4 9]
Mean: 47.2
Std Dev: 28.14
Max: 89
Sum: 236

Key Takeaways

  • ✓ np.array() creates NumPy arrays from Python lists
  • ✓ shape tells you the dimensions (rows, cols)
  • ✓ Operations work on entire arrays at once (no loops!)
  • ✓ Built-in functions: mean(), std(), min(), max(), sum()
Pandas

Pandas - Data Manipulation

Pandas is like Excel in Python! It provides DataFrames - powerful tables with rows and columns that make data manipulation intuitive.

Creating a DataFrame

pandas_basics.py
import pandas as pd

# Create DataFrame from dictionary
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'Age': [25, 30, 35, 28],
    'Salary': [50000, 60000, 70000, 55000],
    'Department': ['Engineering', 'Marketing', 'Engineering', 'HR']
}

df = pd.DataFrame(data)
print(df)
Output
      Name  Age  Salary   Department
0    Alice   25   50000  Engineering
1      Bob   30   60000    Marketing
2  Charlie   35   70000  Engineering
3    Diana   28   55000           HR

Essential Operations

pandas_operations.py
# Quick info about data
print("First 2 rows:")
print(df.head(2))

print("\nStatistics:")
print(df.describe())

# Filtering (like SQL WHERE)
engineers = df[df['Department'] == 'Engineering']
print("\nEngineers only:")
print(engineers)

# Get average salary
avg_salary = df['Salary'].mean()
print(f"\nAverage Salary: ${avg_salary:,.0f}")
Output
First 2 rows:
    Name  Age  Salary   Department
0  Alice   25   50000  Engineering
1    Bob   30   60000    Marketing

Statistics:
             Age        Salary
count   4.000000      4.000000
mean   29.500000  58750.000000
std     4.203173   9464.847243
min    25.000000  50000.000000
max    35.000000  70000.000000

Engineers only:
      Name  Age  Salary   Department
0    Alice   25   50000  Engineering
2  Charlie   35   70000  Engineering

Average Salary: $58,750

Reading Real Data

# Read from CSV file
df = pd.read_csv('data.csv')

# Read from Excel
df = pd.read_excel('data.xlsx')

# Read from URL
df = pd.read_csv('https://example.com/data.csv')
Matplotlib

Matplotlib - Data Visualization

Matplotlib creates beautiful charts and graphs. Visualizing data helps you understand patterns before building ML models.

Line Plot

line_plot.py
import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)  # 100 points from 0 to 10
y = np.sin(x)

# Create the plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, color='cyan', linewidth=2)
plt.title('Sine Wave', fontsize=16)
plt.xlabel('X axis')
plt.ylabel('sin(x)')
plt.grid(True, alpha=0.3)
plt.show()

Output: A smooth sine wave from 0 to 10

📈 Graph displays in new window

Multiple Plot Types

multiple_plots.py
import matplotlib.pyplot as plt

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

# Create 2x2 grid of subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Bar chart
axes[0, 0].bar(categories, values, color='cyan')
axes[0, 0].set_title('Bar Chart')

# Pie chart
axes[0, 1].pie(values, labels=categories, autopct='%1.1f%%')
axes[0, 1].set_title('Pie Chart')

# Scatter plot
axes[1, 0].scatter(values, [10,20,15,25], color='magenta')
axes[1, 0].set_title('Scatter Plot')

# Histogram
axes[1, 1].hist(np.random.randn(1000), bins=30, color='purple')
axes[1, 1].set_title('Histogram')

plt.tight_layout()
plt.show()

Common Plot Types

plt.bar()

plt.plot()

plt.pie()

plt.scatter()

🎉 You've Learned the Basics!

Now you're ready to start building ML models with Scikit-learn.