Agentic AI DevOps: ML Training – Regression Models
Recap of the previous session
- The use case: predict an employee’s salary from experience, using a small CSV with a feature (experience) and a target (salary). This is supervised learning.
- Scikit-learn provides ready-made algorithms, so you do not code gradient descent yourself. Data scientists short-list the algorithms for your problem.
- Setup: Python 3.11 or 3.12, an IDE, and Jupyter notebook for experimenting one cell at a time.
- Pandas reads the data and NumPy handles the numbers.
In this session
- Virtual environments: one set of libraries per project
requirements.txtand pinned versions- Working in a notebook
- Reading and analysing the data with Pandas
- Splitting the data into features (
X) and target (y) - Training the model with
fitand predicting withpredict - Reading the learned
mandb - Exporting the model as an artifact (
.pkl)
In one sentence: training a model is three lines of code: create the algorithm object, call
fit(X, y), then callpredict.
1. Virtual environments
If you install a library directly, it goes to the system level, shared by every project. That causes trouble: one project may need one version of a library and another project a different version.
A virtual environment gives each project its own copy of Python and its own libraries.
python3 -m venv .venv # create it (makes a .venv folder in this project)
source .venv/bin/activate # activate it (the prompt now shows .venv)
- It is per folder. Anything you install now goes into this project’s
.venvonly. - Activate it every time you open a new terminal for the project.
2. requirements.txt and pinned versions
List the libraries your project needs in a file called requirements.txt, one per line:
pandas
scikit-learn
joblib
notebook
python3 -m pip install -r requirements.txt
- One command installs everything, and anyone who receives your code knows what it needs.
- Dependencies come along automatically. Installing Pandas also installs NumPy, because Pandas needs it.
- Pin versions in real projects (for example
pandas==3.0.6). Without a version, every install picks the latest, and a new release can change behaviour. The release history on PyPI lists the versions.
3. Working in a notebook
python3 -m notebook
Create a notebook (for example salary_v1). Things to know:
- A cell shows
[*]while it runs, and a number when it has finished. - If you close the notebook server and reopen the file, the variables are lost (they live in temporary memory). Re-run the cells from the top.
- A cell can be a markdown cell, used for notes and documentation.
- Put
!at the start of a line to run a terminal command inside a cell, for example!python3 -m pip install joblib. - The last value in a cell prints on its own, so
printis optional.
For any library, the official documentation shows the import and the methods. Copy the syntax from there. AI assistants help with code too, but you should understand the basics.
4. Reading and analysing the data
import pandas as pd # pd is the usual short name
data = pd.read_csv("employee_salary_data.csv")
print(data)
type(data) # pandas DataFrame
Pandas returns the data as a DataFrame, an object with many built-in methods. Before training you always analyse the data first:
| Method | What it tells you |
|---|---|
data.shape |
Number of records and columns, here 10 by 2 |
data.head() |
First 5 rows (use head(3) for 3). Useful when there are thousands of rows |
data.info() |
Column names, data types and how many values are not null |
data.columns |
The column names |
info() matters because missing values mean poor-quality data. Here every column has 10 non-null values.
5. Features and target
The dataset is supervised: the target is in the data. Which column is the target depends on the problem. To predict salary from experience, salary is the target. To predict experience from salary, it would be the other way round.
Split the data in two:
X = data[["experience"]] # features (input)
Y = data[["salary"]] # target (the answer)
The double brackets keep X as a table, which is the shape scikit-learn expects for features. With several features, you put all of them into the one variable X.
6. Training the model
from sklearn.linear_model import LinearRegression
lg_model = LinearRegression() # create an object of the class: this is the model
lg_model.fit(X, Y) # training
LinearRegressionis a Python class. Calling it creates an object, and that object already has all the logic: random starting values, the loss, the adjustments, the epochs.fit(X, Y)is the training. It does everything from the theory sessions automatically.
After training, read the learned parameters:
lg_model.coef_ # [[5000.]] the slope m
lg_model.intercept_ # [25000.] the bias b
These are the m and b of y = m·x + b. Slope and coefficient mean the same thing, and so do bias and intercept. Check by hand: 5 years of experience gives 5000 × 5 + 25000 = 50,000.
7. Predicting
predictions = lg_model.predict(X) # one prediction for each row
predictions
- The model returns one prediction per input row, here 10 of them.
- For 5 years, the prediction is 50,000, which matches the real salary in the data. On this tiny, perfectly linear dataset, the accuracy is 100%.
fitis for training andpredictis for predictions.- New inputs work the same way. For 20 years of experience, the model applies 5000 × 20 + 25000 = 125,000.
Whether the predictions are good depends on the quality of the training and the data. If they are not, you go back, change something and train again. That is why we use a notebook.
8. Choosing the algorithm, and preparing the data
- There are hundreds of algorithms in scikit-learn, and you do not pick one at random. The data science team analyses the business problem and recommends two or three. You use those.
- Your own part is the data preparation you just did: analysing the data, then splitting it into features and target. Changing the data this way is called feature engineering. Then you train with the recommended algorithms.
9. Exporting the model as an artifact
The trained model lives only in the notebook’s memory. To use it in production you save it as a file, which you can ship to any server.
Analogy: run a Java build and you get a
.jarfile that you copy to the server. Training gives you a model artifact.
!python3 -m pip install joblib
import joblib
joblib.dump(lg_model, "model.pkl") # .pkl is the "pickle" file extension
model.pkl contains the trained model with the learned m and b. You can copy it to a server and use it for inference. Running a model as a service comes in a later session.
Summary
Key takeaways
- Use a virtual environment per project, and list the dependencies in
requirements.txt. - Pandas reads the CSV into a DataFrame, and
shape,head,infoandcolumnshelp you analyse it. - Split the data into X (features) and Y (target). The target is decided by the problem.
- Create the algorithm object, call
fit(X, Y)to train, andpredictto get predictions. coef_andintercept_are the learnedmandb.- Save the trained model with joblib as a
.pklartifact.
Quick revision
| Term | Meaning |
|---|---|
| Virtual environment | A project’s own Python and libraries (python3 -m venv .venv) |
requirements.txt |
The list of libraries a project needs |
| DataFrame | The Pandas object that holds a table of data |
X, Y |
Features and target |
fit / predict |
Train the model / generate predictions |
coef_ / intercept_ |
The learned m and b |
.pkl |
The saved, trained model file |
Remember: analyse, split, fit, predict, save.
