PyCaret Official
Searchโ€ฆ
LEARN PYCARET
๐Ÿ“–
Official Blog
Ship ML Models to SQL Server using PyCaret

Ship Machine Learning Model to Data Using PyCaret โ€” Part II

Binary Classification

by Umar Farooque

Photo by Joshua Sortino on Unsplash
My previous post **Machine Learning in SQL using PyCaret 1.0** provided details about integrating **PyCaret** with **SQL Server. In this article, I will provide step-by-step details on how to train and deploy a Supervised Machine Learning Classification model in SQL Server using **PyCaret 2.0 (PyCaret is a low-code ML library in Python).
Things to be covered in this article:
  1. 1.
    How to load data into SQL Server table
  2. 2.
    How to create and save a model in SQL Server table
  3. 3.
    How to make model predictions using the saved model and store results in the table

I. Import/Load Data

You will now have to import CSV file into a database using SQL Server Management Studio.
Create a table โ€œcancerโ€ in the database
Right-click the database and select Tasks -> Import Data
For Data Source, select Flat File Source. Then use the Browse button to select the CSV file. Spend some time configuring the data import before clicking the **Next **button.
For Destination, select the correct database provider (e.g. SQL Server Native Client 11.0). Enter the Server name; check Use SQL Server Authentication, enter the Username, Password, and **Database **before clicking the **Next **button.
In the Select Source Tables and Views window, you can Edit Mappings before clicking the **Next **button.
Check Run immediately and click the **Next **button
Click the Finish button to run the package

II. Create ML Model & Save in Database Table

**Classification is a type of supervised machine learning to predict the categorical class labels which are discrete and unordered. The module available in the **PyCaret package can be used for binary or multiclass problems.
In this example, we will be using a โ€˜Breast Cancer Datasetโ€™. Creating and saving a model in a database table is a multi-step process. Letโ€™s go by them step by step:
i. Create a stored procedure to create a trained model in this case an Extra Trees Classifier algorithm. The procedure will read data from the cancer table created in the previous step.
Below is the code used to create the procedure:
1
*-- Stored procedure that generates a PyCaret model using the cancer data using Extra Trees Classifier Algorithm*
2
โ€‹
3
DROP PROCEDURE IF EXISTS generate_cancer_pycaret_model;
4
โ€‹
5
Go
6
โ€‹
7
CREATE PROCEDURE generate_cancer_pycaret_model (@trained_model varbinary(max) OUTPUT) AS
8
โ€‹
9
BEGIN
10
โ€‹
11
EXECUTE sp_execute_external_script
12
โ€‹
13
@language = N'Python'
14
โ€‹
15
, @script = N'
16
โ€‹
17
import pycaret.classification as cp
18
โ€‹
19
import pickle
20
โ€‹
21
trail1 = cp.setup(data = cancer_data, target = "Class", silent = True, n_jobs=None)
22
โ€‹
23
*# Create Model*
24
et = cp.create_model("et", verbose=False)
25
โ€‹
26
โ€‹
27
*#To improve our model further, we can tune hyper-parameters using tune_model function.
28
#We can also optimize tuning based on an evaluation metric. As our choice of metric is F1-score, lets optimize our algorithm!*
29
โ€‹
30
tuned_et = cp.tune_model(et, optimize = "F1", verbose=False)
31
โ€‹
32
โ€‹
33
*#The finalize_model() function fits the model onto the complete dataset.
34
#The purpose of this function is to train the model on the complete dataset before it is deployed in production*
35
โ€‹
36
final_model = cp.finalize_model(tuned_et)
37
โ€‹
38
*# Before saving the model to the DB table, convert it to a binary object*
39
โ€‹
40
trained_model = []
41
prep = cp.get_config("prep_pipe")
42
trained_model.append(prep)
43
trained_model.append(final_model)
44
trained_model = pickle.dumps(trained_model)'
45
โ€‹
46
, @input_data_1 = N'select "Class", "age", "menopause", "tumor_size", "inv_nodes", "node_caps", "deg_malig", "breast", "breast_quad", "irradiat" from dbo.cancer'
47
โ€‹
48
, @input_data_1_name = N'cancer_data'
49
โ€‹
50
, @params = N'@trained_model varbinary(max) OUTPUT'
51
โ€‹
52
, @trained_model = @trained_model OUTPUT;
53
โ€‹
54
END;
55
โ€‹
56
GO
Copied!
ii. Create a table that is required to store the trained model object
1
DROP TABLE IF EXISTS dbo.pycaret_models;
2
โ€‹
3
GO
4
โ€‹
5
CREATE TABLE dbo.pycaret_models (
6
model_id INT NOT NULL PRIMARY KEY,
7
dataset_name VARCHAR(100) NOT NULL DEFAULT('default dataset'),
8
model_name VARCHAR(100) NOT NULL DEFAULT('default model'),
9
model VARBINARY(MAX) NOT NULL
10
);
11
โ€‹
12
GO
Copied!
iii. Invoke stored procedure to create a model object and save into a database table
1
DECLARE @model VARBINARY(MAX);
2
EXECUTE generate_cancer_pycaret_model @model OUTPUT;
3
INSERT INTO pycaret_models (model_id, dataset_name, model_name, model) VALUES(2, 'cancer', 'Extra Trees Classifier algorithm', @model);
Copied!
The output of this execution is:
Output from Console
The view of table results after saving model
SQL Server Table Results

III. Running Predictions

The next step is to run the prediction for the test dataset based on the saved model. This is again a multi-step process. Letโ€™s go through all the steps again.
i. Create a stored procedure that will use the test dataset to detect cancer for a test datapoint
Below is the code to create a database procedure:
1
DROP PROCEDURE IF EXISTS pycaret_predict_cancer;
2
GO
3
โ€‹
4
CREATE PROCEDURE pycaret_predict_cancer (@id INT, @dataset varchar(100), @model varchar(100))
5
AS
6
โ€‹
7
BEGIN
8
โ€‹
9
DECLARE @py_model varbinary(max) = (select model
10
โ€‹
11
from pycaret_models
12
โ€‹
13
where model_name = @model
14
โ€‹
15
and dataset_name = @dataset
16
โ€‹
17
and model_id = @id
18
โ€‹
19
);
20
โ€‹
21
EXECUTE sp_execute_external_script
22
โ€‹
23
@language = N'Python',
24
โ€‹
25
@script = N'
26
โ€‹
27
# Import the scikit-learn function to compute error.
28
โ€‹
29
import pycaret.classification as cp
30
โ€‹
31
import pickle
32
โ€‹
33
cancer_model = pickle.loads(py_model)
34
โ€‹
35
*# Generate the predictions for the test set.*
36
โ€‹
37
predictions = cp.predict_model(cancer_model, data=cancer_score_data)
38
โ€‹
39
OutputDataSet = predictions
40
โ€‹
41
print(OutputDataSet)
42
โ€‹
43
'
44
โ€‹
45
, @input_data_1 = N'select "Class", "age", "menopause", "tumor_size", "inv_nodes", "node_caps", "deg_malig", "breast", "breast_quad", "irradiat" from dbo.cancer'
46
โ€‹
47
, @input_data_1_name = N'cancer_score_data'
48
โ€‹
49
, @params = N'@py_model varbinary(max)'
50
โ€‹
51
, @py_model = @py_model
52
โ€‹
53
with result sets (("Class" INT, "age" INT, "menopause" INT, "tumor_size" INT, "inv_nodes" INT,
54
โ€‹
55
"node_caps" INT, "deg_malig" INT, "breast" INT, "breast_quad" INT,
56
โ€‹
57
"irradiat" INT, "Class_Predict" INT, "Class_Score" float ));
58
โ€‹
59
END;
60
โ€‹
61
GO
Copied!
ii. Create a table to save the predictions along with the dataset
1
DROP TABLE IF EXISTS [dbo].[pycaret_cancer_predictions];
2
โ€‹
3
GO
4
โ€‹
5
CREATE TABLE [dbo].[pycaret_cancer_predictions](
6
โ€‹
7
[Class_Actual] [nvarchar] (50) NULL,
8
โ€‹
9
[age] [nvarchar] (50) NULL,
10
โ€‹
11
[menopause] [nvarchar] (50) NULL,
12
โ€‹
13
[tumor_size] [nvarchar] (50) NULL,
14
โ€‹
15
[inv_nodes] [nvarchar] (50) NULL,
16
โ€‹
17
[node_caps] [nvarchar] (50) NULL,
18
โ€‹
19
[deg_malig] [nvarchar] (50) NULL,
20
โ€‹
21
[breast] [nvarchar] (50) NULL,
22
โ€‹
23
[breast_quad] [nvarchar] (50) NULL,
24
โ€‹
25
[irradiat] [nvarchar] (50) NULL,
26
โ€‹
27
[Class_Predicted] [nvarchar] (50) NULL,
28
โ€‹
29
[Class_Score] [float] NULL
30
โ€‹
31
) ON [PRIMARY]
32
โ€‹
33
GO
Copied!
iii. Call pycaret_predict_cancer procedure to save predictions result into a table
1
*--Insert the results of the predictions for test set into a table*
2
โ€‹
3
INSERT INTO [pycaret_cancer_predictions]
4
โ€‹
5
EXEC pycaret_predict_cancer 2, 'cancer', 'Extra Trees Classifier algorithm';
Copied!
iv. Execute the SQL below to view the result of the prediction
1
*-- Select contents of the table*
2
โ€‹
3
SELECT * FROM [pycaret_cancer_predictions];
Copied!
Predictions Result

IV. Conclusion

In this post, we learnt how to build a classification model using a PyCaret in SQL Server. Similarly, you can build and run other types of supervised and unsupervised ML models depending on the need of your business problem.
Photo by Tobias Fischer on Unsplash
You can further check out the **PyCaret** website for documentation on other supervised and unsupervised experiments that can be implemented in a similar manner within SQL Server.
My future posts will be tutorials on exploring other supervised & unsupervised learning techniques using Python and PyCaret within a SQL Server.
โ€‹PyCaretโ€‹
โ€‹My LinkedIn Profileโ€‹