- Posted on
- • Artificial Intelligence
Getting Started with Artificial Intelligence and Python on Linux
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Getting Started with Artificial Intelligence and Python on Linux
You’re a few terminal commands away from training your first AI model. If you’re comfortable with Bash, Linux gives you unmatched control, performance, and reproducibility for machine learning and deep learning. In this guide, you’ll go from a clean Linux install to training your first model with Python—fast.
Why this matters:
Python is the lingua franca of AI, with extensive libraries (NumPy, pandas, scikit-learn, PyTorch, TensorFlow).
Linux provides first-class CLI tooling, automation, and server/GPU support.
Knowing how to set up a clean, isolated environment lets you iterate quickly and avoid “it works on my machine” bugs.
Below you’ll find a minimal, practical path: install the right tools, create a virtual environment, install AI libraries, run a small model, and adopt a Bash-friendly workflow.
What you’ll do (overview)
Prepare your system with Python, compilers, and Git.
Create and activate a project-specific virtual environment.
Install core AI libraries (NumPy, pandas, scikit-learn, Jupyter) and optionally a deep learning framework (PyTorch or TensorFlow).
Train a quick model to validate the setup.
Adopt CLI workflows that scale (requirements, Makefile, remote notebooks).
1) Prepare your Linux system
Install Python 3, pip, development tools (for building wheels), and Git. Use your distro’s package manager.
Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y python3 python3-pip python3-venv python3-dev build-essential git curl pkg-config
Fedora/RHEL/CentOS Stream (dnf):
sudo dnf -y groupinstall "Development Tools"
sudo dnf -y install python3 python3-pip python3-devel git curl pkgconf-pkg-config
openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y python3 python3-pip python3-devel git curl gcc gcc-c++ make pkg-config
Verify:
python3 --version
pip3 --version
git --version
Optional: Check if you have an NVIDIA GPU (for deep learning acceleration):
nvidia-smi
If that returns a table with driver info, your NVIDIA stack is visible. GPU-accelerated frameworks require compatible drivers and CUDA/cuDNN. For your exact GPU + distro, follow the official framework/distro docs.
2) Create a Python virtual environment
Use a per-project venv to isolate dependencies.
mkdir -p ~/projects/ai-hello && cd ~/projects/ai-hello
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip setuptools wheel
Tip: When a venv is active, your prompt usually shows (.venv). To deactivate later:
deactivate
3) Install essential AI packages
Start with the basics: arrays, data handling, classical ML, plotting, and notebooks.
pip install numpy pandas scikit-learn matplotlib jupyterlab
Choose one deep learning framework (optional, pick one to start):
- PyTorch (CPU-only):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
- PyTorch (NVIDIA GPU): Use the correct cuXXX (CUDA) index for your system (example for CUDA 12.1):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
- TensorFlow (CPU):
pip install tensorflow
Note: GPU use with TensorFlow requires matching NVIDIA drivers and CUDA/cuDNN. Check TensorFlow’s official install guidance if you want GPU acceleration.
Sanity check:
python -c "import numpy, pandas, sklearn; print('Core libs OK')"
4) Train your first model (scikit-learn)
This minimal example uses the Iris dataset to train a logistic regression classifier, prints accuracy, and saves the model.
Create train_iris.py:
#!/usr/bin/env python3
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import joblib
def main():
data = load_iris(as_frame=True)
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Simple, strong baseline for small structured datasets
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
preds = model.predict(X_test)
acc = accuracy_score(y_test, preds)
print(f"Test accuracy: {acc:.3f}")
joblib.dump(model, "model.joblib")
print("Saved model to model.joblib")
if __name__ == "__main__":
main()
Run it:
python train_iris.py
You should see a test accuracy (typically > 0.9) and a model.joblib file saved in your project directory.
5) Optional: Quick deep learning check (PyTorch)
Install PyTorch if you didn’t earlier (CPU-only example shown):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
Create torch_check.py:
#!/usr/bin/env python3
import torch
print("PyTorch:", torch.__version__)
print("CUDA available:", torch.cuda.is_available())
if torch.cuda.is_available():
print("GPU:", torch.cuda.get_device_name())
# Tiny synthetic training loop (2-layer MLP on random data)
device = "cuda" if torch.cuda.is_available() else "cpu"
X = torch.randn(512, 32, device=device)
y = torch.randint(0, 2, (512,), device=device)
model = torch.nn.Sequential(
torch.nn.Linear(32, 64),
torch.nn.ReLU(),
torch.nn.Linear(64, 2)
).to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = torch.nn.CrossEntropyLoss()
for step in range(200):
opt.zero_grad()
logits = model(X)
loss = loss_fn(logits, y)
loss.backward()
opt.step()
if step % 50 == 0:
print(f"Step {step:03d} Loss {loss.item():.4f}")
Run it:
python torch_check.py
You’ll see version info, whether CUDA is available, and a decreasing loss value.
6) Bash-friendly workflow tips
- Freeze and share dependencies:
pip freeze > requirements.txt
# Later, or on another machine:
pip install -r requirements.txt
- Use a Makefile to standardize commands:
Create
Makefile:
PY := python
VENV := .venv
.PHONY: venv install train jupyter clean
venv:
python3 -m venv $(VENV)
install: venv
. $(VENV)/bin/activate && \
$(PY) -m pip install --upgrade pip setuptools wheel && \
$(PY) -m pip install -r requirements.txt
train:
. $(VENV)/bin/activate && $(PY) train_iris.py
jupyter:
. $(VENV)/bin/activate && jupyter lab --no-browser --port 8888
clean:
rm -rf __pycache__ *.pyc .pytest_cache model.joblib
Then:
make train
- Run notebooks without a desktop environment:
jupyter lab --no-browser --port 8888
If running on a remote server, tunnel the port:
ssh -N -L 8888:localhost:8888 user@your.server
Open http://localhost:8888 in your browser and paste the token from the terminal.
- Keep data and models organized:
mkdir -p data/ raw/ models/ notebooks/ src/
- Automate venv activation in your shell (optional): Add to your shell rc file (e.g., ~/.bashrc) to auto-activate when entering the project directory:
cd() { builtin cd "$@"; if [ -f .venv/bin/activate ]; then . .venv/bin/activate; fi; }
Why Linux + Python is a winning combo for AI
Performance and drivers: Best-in-class support for server hardware and GPUs.
Automation: Bash, cron/systemd timers, and Makefiles let you schedule training and batch jobs easily.
Reproducibility: Versioned requirements and container-friendly tooling simplify collaboration and deployment.
Ecosystem depth: Python’s scientific stack has decades of optimization and a huge community.
Real-world next steps (pick one today)
- Classic ML: Load a CSV of your own (sales, logs, sensor data) and train with scikit-learn. Start with
RandomForestClassifierorXGBClassifier(xgboost) for strong baselines.
pip install xgboost
- Computer vision: Try PyTorch +
torchvisionfor image classification on a small dataset you curate (e.g., two categories of images in separate folders).
pip install torchvision
- NLP: Use
transformersfor zero-shot or fine-tuned text tasks.
pip install transformers accelerate
- Reproducible experiments: Add
mlflowto log metrics and artifacts locally.
pip install mlflow
Conclusion and Call to Action
You now have a clean, Linux-native AI workflow:
System packages installed with apt/dnf/zypper.
A project-scoped virtual environment.
Core AI libraries ready.
A model trained and saved from the terminal.
A workflow you can automate and share.
Your next step:
Pick a small, real dataset you care about.
Create a new project folder, spin up a venv, and adapt the Iris script to your data.
Commit everything (including requirements.txt and Makefile) to Git for reproducibility.
When you’re ready, add a deep learning framework and try a GPU-backed experiment. Keep it simple, iterate quickly, and let Linux + Python do the heavy lifting.