Which Python Will Run Your Experiment?
Two terminals can run the same file with different libraries. A package may be installed correctly in one Python while another reports that it is missing. An environment is therefore part of an experiment's starting state, not just an installation detail.
A virtual environment is an owned directory with a Python entry point and
an isolated set of installed packages. This course keeps one shared environment
at ~/feature-evaluation-practice/.venv and separate folders for task files.
The .venv name is a convention, not a special command. Its Python entry can
refer back to the installed base interpreter; keep that base Python installed.

Environment and task files have different jobs. Read downward: the dashed
creates arrow is the one-time environment bootstrap. Inside the practice
root, .venv/bin/python is the selected interpreter entry and site-packages
is its package area. The solid runs arrow reaches the task's run.py.
The task folder holds source and outputs; moving into it does not select a
Python. Activation changes the terminal's command lookup, or you can name the
environment interpreter explicitly.
Check the Starting Software
The command recipe is Bash on Linux x86_64 with full CPython 3.13 installed. The reference execution uses CPython 3.13.15. You need a terminal, plain-text editor, permission to write your own practice folder, internet for package installation and sufficient local disk space. Allow 5 GB free disk and 8 GB RAM as planning margins, not measured minimums. No GPU, cloud account or API key is needed. Windows/macOS/other architectures are not covered by this command recipe; matching package availability is not an executed setup.
In Bash, from any directory:
python3.13 --version
python3.13 -m ensurepip --version
The first command identifies the installed interpreter. The second checks that
its bundled pip-bootstrap module is present; --version does not install
packages. Reference output is Python 3.13.15 followed by a pip version.
A different 3.13 patch is reported by the diagnostic; passing that small health
check does not establish full-course compatibility for that patch.
If python3.13 is missing, stop before creating an environment. Obtain a full
CPython 3.13 installation alongside your system Python from your distribution's
supported tooling or a local administrator. The administrator must supply a
working python3.13 command with venv and pip bootstrap, then rerun both
checks above. Do not replace or remove the operating system's default Python.
On Ubuntu, python3-full supplies the default interpreter and its complete
library/venv support; it does not promise Python 3.13 on every Ubuntu release.
A version-specific missing-venv remedy must match the interpreter and OS package
availability. This course does not ask you to guess a sudo apt command or add
an unverified package repository.
If the second check fails with a missing ensurepip module, ask the same
supplier to install the matching venv/bootstrap support before continuing.
Installing NumPy cannot fix a missing Python bootstrap component. The
Ubuntu setup guide and
PyPA environment guide
explain those software-supplier choices. No administrator permission is needed
for the later package installs into your writable environment.
Create and Identify the Owned Environment
Bash uses pwd to print the current working directory, cd to change it,
mkdir to create a folder and ls to list entries. ~ and $HOME refer to
your home directory. The variable below names this course's root; quote it so
a home path containing spaces is kept together. The -p option creates missing
parent folders and tolerates an existing directory.
practice_root="$HOME/feature-evaluation-practice"
mkdir -p "$practice_root/set-up-cpu-environment"
cd "$practice_root"
pwd
ls -a
Check the printed path before proceeding. If .venv already exists, use the
resume section below and inspect it; do not overwrite a working environment.
For a new root without .venv, run this group and stop if any command fails:
python3.13 -m venv .venv
source .venv/bin/activate
python -c "import sys; print(sys.executable); print(sys.prefix); print(sys.base_prefix)"
python -m pip --version
-m venv runs Python's environment-creation module. source applies the
activation script to this Bash session. Now python should be the entry under
this practice root's .venv/bin. sys.prefix should name that .venv, while
sys.base_prefix names its base Python installation. Those prefixes must differ.
Do not rely only on a changed prompt: another command or editor can still select
a different interpreter. python -m pip runs pip through the selected Python,
so its printed package path should also be inside .venv.
Move into the setup task folder, keeping that environment selected:
cd "$practice_root/set-up-cpu-environment"
pwd
Supply Two Complete Files
In your text editor, save the next two complete blocks into the current task folder using the exact filenames shown. Plain text is required; do not include the Markdown fences. These files are supplied here, not fetched from a hidden author folder or a separate download.
requirements-scientific.txt names five primary package pins:
numpy==2.5.4
pandas==3.0.6
scikit-learn==1.9.1
scipy==1.18.1
matplotlib==3.11.2
NumPy handles numerical arrays, pandas handles tables, scikit-learn supplies classical models and metrics, SciPy supplies numerical routines, and Matplotlib creates figures. Dependencies installed alongside them are normal; the five pins do not freeze every transitive package forever. PyTorch is installed separately from its official CPU index.
Save this complete installation diagnostic as run.py:
"""Course-owned CPU installation diagnostic; no model training or external data."""
import importlib
import json
import math
import os
import platform
import sys
from pathlib import Path
work = Path(__file__).resolve().parent
expected_environment = work.parent / ".venv"
if sys.prefix == sys.base_prefix or Path(sys.prefix).resolve() != expected_environment.resolve():
raise SystemExit("NOT READY: use the shared practice .venv/bin/python to run this file.")
if sys.implementation.name != "cpython" or sys.version_info[:2] != (3, 13):
raise SystemExit("NOT READY: this recipe expects CPython 3.13; reference patch is 3.13.15.")
if platform.system() != "Linux" or platform.machine() != "x86_64":
raise SystemExit("NOT READY: this diagnostic recipe targets Linux x86_64.")
outputs = work / "outputs"
outputs.mkdir(exist_ok=True)
os.environ["MPLCONFIGDIR"] = str(outputs / "matplotlib-cache")
pins = {
"numpy": "2.5.4", "pandas": "3.0.6", "sklearn": "1.9.1",
"scipy": "1.18.1", "matplotlib": "3.11.2", "torch": "2.14.1+cpu",
}
packages = {}
for name, expected in pins.items():
try:
module = importlib.import_module(name)
except ImportError as error:
raise SystemExit(f"NOT READY: {name} could not import: {error}") from error
actual = module.__version__
origin = Path(module.__file__).resolve()
if actual != expected or not origin.is_relative_to(expected_environment.resolve()):
raise SystemExit(f"NOT READY: {name}={actual}, origin={origin}; expected {expected} inside .venv.")
packages[name] = {"version": actual, "origin": str(origin)}
from sklearn.metrics import mean_absolute_error
import torch
import matplotlib
classical_error = mean_absolute_error([1.0, 3.0], [2.0, 2.0])
reference = torch.tensor([[1.0], [3.0]], dtype=torch.float32, device="cpu")
predicted = torch.tensor([[2.0], [2.0]], dtype=torch.float32, device="cpu")
neural_loss = torch.nn.MSELoss()(predicted, reference).item()
if torch.version.cuda is not None or reference.device.type != "cpu":
raise SystemExit("NOT READY: expected the CPU-only torch build and CPU calculation.")
if not math.isfinite(classical_error) or not math.isfinite(neural_loss):
raise SystemExit("NOT READY: diagnostic arithmetic produced a non-finite value.")
if classical_error != 1.0 or neural_loss != 1.0:
raise SystemExit("NOT READY: the supplied fixed arithmetic check differs from 1.0.")
matplotlib.use("Agg")
import matplotlib.pyplot as plt
figure, axis = plt.subplots(figsize=(4, 3))
axis.plot([1, 2], [1, 3], marker="o")
axis.set(xlabel="Fictional observation", ylabel="Supplied reference value")
figure.tight_layout()
figure.savefig(outputs / "health.png", dpi=120)
plt.close(figure)
result = {
"status": "CPU_DIAGNOSTIC_PASSED", "python": platform.python_version(),
"reference_patch_matches": sys.version_info[:3] == (3, 13, 15),
"interpreter": sys.executable, "environment": sys.prefix,
"packages": packages, "device": str(reference.device),
"cuda_build": torch.version.cuda, "classical_absolute_error": classical_error,
"neural_squared_error": neural_loss, "plot": str(outputs / "health.png"),
}
report = json.dumps(result, indent=2)
(outputs / "health.json").write_text(report + "\n", encoding="utf-8")
print(report)
The script is a supplied health tool, not a neural-training exercise. Explain its checks before interpreting its output:
- Interpreter boundary:
workcomes from this file's location, not the terminal's current directory.work.parent / ".venv"names the shared sibling environment. The prefix checks reject the base interpreter and a different virtual environment before imports. Resolving the prefix handles path aliases; an interpreter entry itself can be a symlink. The recipe checks Linux x86_64 and CPython 3.13; the exact reference patch is reported separately. - Pins and origins: the dictionary pairs import names with versions.
scikit-learn is imported as
sklearn. The loop imports each package, compares its__version__and checks its file origin inside the expected environment. An import failure or mismatch raisesSystemExitwithNOT READY, producing a failed command rather than a misleading healthy report. - Fixed arithmetic: reference values 1 and 3 are compared with predictions 2 and 2.
Each absolute error is 1, so scikit-learn's mean absolute error is 1. Each
squared difference is also 1, so the default mean reduction in PyTorch's
MSELossalso gives 1 for these particular values. These error definitions need not agree on other inputs. The nested lists have two rows with one quantity each.float32chooses a floating number format;device="cpu"explicitly keeps the tensors on the CPU..item()retrieves the single resulting number. No model is fitted and no weights are updated. - CPU and finite checks:
torch.version.cudamust beNonefor the pinned CPU-only build. The data's device must becpu. A finite number is neither infinity nor “not a number”; the arithmetic checks require the supplied 1.0. Merely owning no GPU would not prove that a CPU-only package was installed. - Local output:
Aggselects plotting without a graphical window. The plot joins the two fictional reference points (1,1) and (2,3), and its axis labels identify them. The script puts its Matplotlib cache,health.pngand JSON report insideoutputs. JSON is a text key/value format. The same report is printed, so you can compare saved and terminal evidence. Reruns overwrite the two health files; they do not train a model or change the starter inputs.
Install and Inspect the Result
From the task folder with the course environment active, run each group to completion and inspect any error before continuing:
python -m pip install --index-url https://pypi.org/simple -r requirements-scientific.txt
-r reads the supplied pins. --index-url explicitly chooses the Python Package
Index, PyPI. Pip downloads packages and dependencies into this .venv; it may
also use its ordinary user download cache. Avoid sudo pip, which would change
the installation target and permissions.
python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.14.1+cpu
python -m pip check
python run.py
The second index supplies the +cpu build for this reference platform. Do not
replace it with the general PyPI torch install and assume the build is the same.
pip check checks installed dependency relationships; reference output is
No broken requirements found. It does not execute the course's future tasks.
The diagnostic then checks actual imports, origins, small computations and
plot output.
Illustrative excerpt of health.json; actual paths and Python patch may differ:
"status": "CPU_DIAGNOSTIC_PASSED"
"reference_patch_matches": true
"device": "cpu"
"cuda_build": null
"classical_absolute_error": 1.0
"neural_squared_error": 1.0
Confirm the full report's interpreter/environment and all six package versions
and origins. Open outputs/health.png in your image viewer: the two plotted
reference values should be 1 and 3. The status is meaningful only for the current
successful run, not an old file left by a failed rerun. reference_patch_matches
is false on a different 3.13 patch; that is a compatibility fact to retain, not a
reason to edit the expected version silently. This diagnostic does not validate
later split logic, training convergence, prediction quality or every platform.
Diagnose a Difference
| Evidence | Meaning and next check |
|---|---|
python3.13: command not found | Starting software is missing; obtain the declared full interpreter before creating .venv |
ensurepip or venv bootstrap failure | Fix the matching Python/OS component; do not reinstall scientific libraries as a remedy |
NOT READY: use the shared practice... | Wrong interpreter/environment or misplaced script; check prefixes, task path and sibling .venv |
NOT READY: ... could not import | Package import failed; inspect the full final error, selected interpreter and install log; retry the failed pinned install in the same environment |
| Version/origin mismatch | You selected other packages or a file shadows the package; inspect sys.prefix, reported origin and filenames before changing anything |
| No matching distribution | Check Python version/architecture, index and network evidence; it is different from a DNS/TLS connection failure. Do not start guessing pins or building an unsupported stack |
| GPU-enabled torch build or unexpected device | Confirm the exact +cpu version and official CPU source in this environment |
| Dependency check passes, diagnostic fails | Dependency metadata is insufficient; use the actual failing path/import/computation/plot evidence |
A source-build attempt is outside this supplied ready-built Linux/Python recipe; stop and inspect the version/platform/index rather than installing a compiler as an unexplained fix. A failed install can leave some packages in the environment. Correct the specific cause, then rerun the failed pinned command. Do not delete the whole practice root to recover a partial installation.
Resume in a Fresh Terminal
Close the terminal, open a new Bash terminal and run this complete group:
practice_root="$HOME/feature-evaluation-practice"
cd "$practice_root/set-up-cpu-environment"
../.venv/bin/python -m pip check
../.venv/bin/python run.py
The explicit relative path selects the existing shared environment without
activation. Nothing must be reinstalled. To make plain python select it again,
run source ../.venv/bin/activate from this task folder, then recheck prefixes.
If creation previously failed before pip existed, correct the matching bootstrap
component, return to the practice root and rerun the creation step for that known
partial environment; do not overwrite a working one or use --clear as a guess.
Independent Diagnosis and Questions
Open a new unactivated Bash terminal before this task; do not source the
course activation script. If you are reusing an activated terminal, deactivate
undoes its environment lookup first. Compare these two read-only path probes
from the setup task folder. Record which interpreter each actually selects,
even if both report the same Python version. Do not install anything into the
base interpreter to make the outputs look alike.
practice_root="$HOME/feature-evaluation-practice"
cd "$practice_root/set-up-cpu-environment"
python3.13 -c "import sys; print(sys.executable); print(sys.prefix); print(sys.base_prefix)"
../.venv/bin/python -c "import sys; print(sys.executable); print(sys.prefix); print(sys.base_prefix)"
Then answer:
- A new terminal's
pythonimports NumPy successfully. Does that establish that it selected this course environment? - Why do pip dependency checks and the finite CPU diagnostic answer different questions? Does either prove that a trained model will be useful?
- Why can you resume without activation, and what should survive task reset?
Answer and Reasoning
Hint 1: Compare paths and prefixes, not just version strings or the prompt.
Hint 2: An environment has a different sys.prefix from sys.base_prefix.
Hint 3: The correct prefix must name this practice root's shared .venv.
With the declared unactivated lookup, the first command normally has matching
base/prefix paths; the explicit environment command names the shared .venv as
prefix and a separate base installation. If the first command still names an
environment, its path is evidence of automatic activation or a different command
lookup; report that actual selection rather than labelling it base Python.
A system Python may already have NumPy installed, so a successful import does
not identify the environment. Inspect its path/origin before deciding whether a
package is missing, misplaced or selected through the wrong interpreter.
- No. Check
sys.executable, the prefixes and the package origin. Importing a package establishes availability in that process, not its intended origin. pip checkchecks dependency metadata. The diagnostic actually imports and computes using the declared environment and saves a plot. Neither checks future model fitting, split correctness, generalisation or deployment fitness.- The explicit
.venv/bin/pythonpath selects the interpreter directly. Activation only changes this shell's lookup. Preserve the environment, both supplied files, earlier tasks and wanted results; reset only the named outputs.
Reset Without Losing Your Setup
After preserving any report you want, return to the owned task folder and check
pwd. Only if it ends in your intended feature-evaluation-practice/set-up-cpu-environment
folder, you may remove the two generated health files:
rm -f -- outputs/health.json outputs/health.png
rm removes only these named generated files; -f tolerates their absence and
-- ends option parsing. Keep the Matplotlib cache for reuse, both starter
files and shared .venv. Rerun ../.venv/bin/python run.py to reconstruct the
health outputs. Remove the shared environment only when you deliberately finish
all course practice, not during per-task reset.
References
- Python 3.13 venv (S84) and Python 3.14 venv (S01)
- PyPA pip/environment guide (S57) and Ubuntu Python setup (S58)
- NumPy 2.5.4 (S02), pandas 3.0.6 (S03), scikit-learn 1.9.1 (S04), SciPy 1.18.1 (S05), Matplotlib 3.11.2 (S06)
- PyTorch 2.14.1 metadata (S07), official CPU index (S08), installation selector (S09), wheel tags (S60)
- Mean absolute error (S73) and MSELoss (S85)