A real-estate team in Austin asked me which Python libraries for machine learning their analysts should learn for home prices. My answer: NumPy, pandas and scikit-learn first, then XGBoost or LightGBM for tables, and PyTorch or Keras only when deep learning is really needed.
The trouble with most “top 10” lists is that they rank libraries without running them. So I trained every library below on the same 600-home dataset and compared real errors in dollars.
Quick answer: install the core stack with one command, then add a deep learning framework later:
pip install numpy pandas scikit-learn xgboost lightgbm
pip install torch # or: pip install tensorflow
In this tutorial, I’ll walk through the Python libraries for machine learning I actually use, what each one is for, and the test error each scored. Everything ran on Python 3.12.5 in Command Prompt.
Which Versions of the Python ML Libraries Did I Test?
These are the versions installed in my test environment in November 2026. If you’re starting fresh, install the Python packages into a virtual environment first:
import sys
from importlib.metadata import version
libs = ["numpy", "pandas", "scikit-learn", "scipy", "xgboost",
"lightgbm", "torch", "tensorflow", "keras", "matplotlib"]
print(f"Python {sys.version.split()[0]}")
for name in libs:
print(f" {name:<13}{version(name)}")
Output:
Python 3.12.5
numpy 2.5.3
pandas 3.0.6
scikit-learn 1.9.1
scipy 1.18.1
xgboost 3.4.1
lightgbm 4.7.0
torch 2.14.0+cpu
tensorflow 2.21.0
keras 3.15.1
matplotlib 3.11.2

Sample US Housing Data Used in Every Example
All examples load one file, homes.py. It builds 600 made-up home sales across Texas, Florida, North Carolina, Arizona and California, with prices in USD driven by size, bedrooms, age and state:
import numpy as np
import pandas as pd
STATES = ["TX", "FL", "NC", "AZ", "CA"]
PREMIUM = {"TX": 0, "FL": 25_000, "NC": 10_000,
"AZ": 30_000, "CA": 260_000}
def load_homes(n=600, seed=2026):
rng = np.random.default_rng(seed)
state = rng.choice(STATES, size=n)
sqft = rng.integers(900, 3800, size=n)
beds = rng.integers(2, 6, size=n)
age = rng.integers(0, 61, size=n)
noise = rng.normal(0, 18_000, size=n)
prem = np.array([PREMIUM[s] for s in state])
price = (60_000 + 145 * sqft + 9_500 * beds
- 1_100 * age + prem + noise)
return pd.DataFrame({"state": state, "sqft": sqft, "beds": beds,
"age": age, "price": price.round(2)})
if __name__ == "__main__":
print(load_homes().shape)
Output:
(600, 5)
NumPy: Fast Arrays Under Every ML Library
NumPy stores numbers in typed arrays and does math on whole arrays at once, without Python loops. pandas, scikit-learn and the boosting libraries all hand data to NumPy internally. The sample data itself comes from NumPy random generators:
import numpy as np
from homes import load_homes
df = load_homes()
prices = df["price"].to_numpy()
print(prices.dtype, prices.shape)
print(f"Mean ${prices.mean():,.2f} Median ${np.median(prices):,.2f}")
per_sqft = prices / df["sqft"].to_numpy() # vectorized, no loop
print(f"Average price per sq ft: ${per_sqft.mean():,.2f}")
Output:
float64 (600,)
Mean $459,695.73 Median $454,454.43
Average price per sq ft: $202.66
Same 600 homes: the mean is $459,695.73 and the average price per square foot is $202.66. That division ran on all 600 rows in one line.
pandas: Load, Clean and Explore Tables
pandas gives you the DataFrame, a table with named columns. I use it to read CSVs, fix missing values and check the data before any model sees it. Grouping by state is a one-liner, as in pandas groupby with aggregation:
from homes import load_homes
df = load_homes()
print(df.head(3))
print(df.groupby("state")["price"].agg(["count", "mean"]).round(2))
Output:
state sqft beds age price
0 CA 3605 5 3 878906.07
1 TX 3053 4 38 489442.75
2 TX 2273 2 35 341196.62
count mean
state
AZ 120 419799.87
CA 107 682412.72
FL 121 415617.86
NC 133 422114.80
TX 119 386489.60
California homes average far more than the other four states, which tells me the state column matters before I train anything. pandas 3.0 also uses copy-on-write by default, so chained assignments no longer change the original table.
scikit-learn: The Default Library for Classical Machine Learning
scikit-learn covers regression, classification, clustering, preprocessing and model evaluation behind one API: fit(), predict(), score(). Same homes, with the state column one-hot encoded (the step data preprocessing covers in depth):
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from homes import load_homes
df = pd.get_dummies(load_homes(), columns=["state"], dtype=int)
X, y = df.drop(columns="price"), df["price"]
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, random_state=42)
for model in (LinearRegression(),
RandomForestRegressor(n_estimators=200, random_state=42)):
model.fit(X_tr, y_tr)
mae = mean_absolute_error(y_te, model.predict(X_te))
print(f"{type(model).__name__:<22} MAE ${mae:,.2f}")
Output:
LinearRegression MAE $14,127.50
RandomForestRegressor MAE $19,860.60

Linear regression missed by $14,127.50 on average, and the random forest by $19,860.60. Prices here grow in a straight line with size, so the simple model fits better. I always start with it as a baseline.
XGBoost and LightGBM: Gradient Boosting for Tabular Data
Both libraries build hundreds of small decision trees, each fixing the previous one’s mistakes. They win most competitions on spreadsheet-style data and handle categorical columns natively, so state needs no one-hot step. For background on the task itself, see regression in machine learning:
import xgboost as xgb
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from homes import load_homes
df = load_homes()
df["state"] = df["state"].astype("category") # no one-hot needed
X, y = df.drop(columns="price"), df["price"]
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, random_state=42)
models = {
f"XGBoost {xgb.__version__}": xgb.XGBRegressor(
n_estimators=300, learning_rate=0.05,
enable_categorical=True, tree_method="hist"),
f"LightGBM {lgb.__version__}": lgb.LGBMRegressor(
n_estimators=300, learning_rate=0.05, verbose=-1),
}
for name, model in models.items():
model.fit(X_tr, y_tr)
mae = mean_absolute_error(y_te, model.predict(X_te))
print(f"{name:<16} MAE ${mae:,.2f}")
Output:
XGBoost 3.4.1 MAE $19,296.42
LightGBM 4.7.0 MAE $22,784.40

XGBoost scored $19,296.42 and LightGBM $22,784.40, both behind the linear baseline on this straight-line data. On real listings with messy interactions, boosting usually pulls ahead. That’s exactly why I test a baseline first.
PyTorch: Flexible Deep Learning in Python
PyTorch is the framework most research code and Hugging Face models use. You write the training loop yourself, which feels like plain Python. This small network uses nn.Linear layers and L1 loss, which is the mean absolute error:
import pandas as pd
import torch
from torch import nn
from homes import load_homes
torch.manual_seed(42)
df = pd.get_dummies(load_homes(), columns=["state"], dtype=float)
X = torch.tensor(df.drop(columns="price").to_numpy(),
dtype=torch.float32)
y = torch.tensor(df[["price"]].to_numpy() / 1000,
dtype=torch.float32)
X = (X - X.mean(0)) / X.std(0) # scale features
X_tr, X_te, y_tr, y_te = X[:480], X[480:], y[:480], y[480:]
model = nn.Sequential(nn.Linear(X.shape[1], 32), nn.ReLU(),
nn.Linear(32, 1))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.L1Loss() # MAE in $1,000s
for epoch in range(1, 1501):
opt.zero_grad()
loss = loss_fn(model(X_tr), y_tr)
loss.backward()
opt.step()
if epoch % 500 == 0:
print(f"epoch {epoch:>4} train MAE ${loss.item() * 1000:,.2f}")
with torch.no_grad():
mae = loss_fn(model(X_te), y_te).item() * 1000
print(f"PyTorch {torch.__version__} test MAE ${mae:,.2f}")
Output:
epoch 500 train MAE $15,451.28
epoch 1000 train MAE $13,391.66
epoch 1500 train MAE $13,122.00
PyTorch 2.14.0+cpu test MAE $16,407.77

The test error came to $16,407.77. A neural network needs scaled inputs and many epochs to match a linear model on 480 rows, so deep learning pays off on images, text and audio, not small tables.
TensorFlow and Keras: Deep Learning with a High-Level API
Keras 3 is a high-level API that runs on TensorFlow, JAX or PyTorch. Here it ran on TensorFlow 2.21.0, with the TensorFlow install done through pip. The same network is about ten lines:
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # hide C++ logs
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
import keras
import pandas as pd
from homes import load_homes
keras.utils.set_random_seed(42)
df = pd.get_dummies(load_homes(), columns=["state"], dtype=float)
X = df.drop(columns="price").to_numpy()
y = df["price"].to_numpy() / 1000
norm = keras.layers.Normalization()
norm.adapt(X[:480])
model = keras.Sequential([keras.Input((X.shape[1],)), norm,
keras.layers.Dense(32, activation="relu"),
keras.layers.Dense(1)])
model.compile(optimizer=keras.optimizers.Adam(0.01), loss="mae")
model.fit(X[:480], y[:480], epochs=300, verbose=0)
mae = model.evaluate(X[480:], y[480:], verbose=0) * 1000
print(f"Keras {keras.__version__} on {keras.backend.backend()}")
print(f"Test MAE ${mae:,.2f}")
Output:
Keras 3.15.1 on tensorflow
Test MAE $16,164.85
Keras reported a test error of $16,164.85, close to PyTorch. Note: TensorFlow 2.11 and later doesn’t use the GPU on native Windows; it prints a warning unless you silence its logger, as I did here. Use WSL2 for GPU training.
Still deciding between the two frameworks? My TensorFlow vs PyTorch comparison goes deeper.