Machine Learning Model on Docker Container

Rahulbhatia1998
3 min readMay 30, 2021

In this blog, we’re going to set up a machine learning environment and code on the Docker container using Dockerfile.

Linear Regression:

Linear Regression is the machine learning algorithm that learns using the formula y=mx+c, where y needs to be predicted and x is the predictor. It works on the continuous data where the correlation forms a linear line. Slope(m) and intercept(c) is learnt over a time.

We’re using Salary dataset for linear regression without any hyperparameters tunning.

We need to import the modules given in the below screenshot.

Then, we’ll import the dataset using pandas.read_csv().

We need to convert the X and y into NumPy arrays as they pandas data frame and scikit-learn only take the NumPy array as the input.

We need to reshape the X to 2-dimensional data as NumPy only takes 2 dimensions array as the input and split the data using train-test split.

Then, we’ll create a LinearRegression object and train the model using the X_train and y_train as the input. Using the model created to predict the output on X_test and then store it in result variable and measure the error using MSE and y_test and result as an input to the MSE.

Then, print the intercept, coefficient and MSE of the model.

Steps to create a docker image and container using it:

  • We’re going to use the CentOS image as the base image. Here, the image is referenced using FROM centos:latest.
  • Then, we need to install the python using yum and packages used for machine learning like scikit-learn, pandas and NumPy using pip3.
  • Then, we need to copy the dataset and ML model files to the image.
  • Lastly, we need to define the ENTRYPOINT to tell which command to run at the launch of the container. We’ll specify linear regression program to run using python.
docker build . -t salary_pred:v1

Use the above command to create an image.

Python is successfully installed in the above screenshot.

All the specified files and entry point command is added to the image successfully. Now, we can run the below command to get the output of machine learning model.

docker run salary_pred:v1

Docker container started, trained Linear Regression model, gave output and exited giving the output to the screen.

We have successfully created a docker image and container using it for executing Linear Regression code.

--

--