<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umar Farooque, MMA, MCS, PMP®, CSM on Medium]]></title>
        <description><![CDATA[Stories by Umar Farooque, MMA, MCS, PMP®, CSM on Medium]]></description>
        <link>https://medium.com/@muhammad.u.farooque?source=rss-2c0277167441------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ie1O-Tk9_YCYTRHJy4OpzA.jpeg</url>
            <title>Stories by Umar Farooque, MMA, MCS, PMP®, CSM on Medium</title>
            <link>https://medium.com/@muhammad.u.farooque?source=rss-2c0277167441------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:33:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammad.u.farooque/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ship ML Model to Data Using PyCaret — Part II]]></title>
            <link>https://medium.com/data-science/ship-ml-model-to-data-using-pycaret-part-ii-6a8b3f3d04d0?source=rss-2c0277167441------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a8b3f3d04d0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pycaret]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Umar Farooque, MMA, MCS, PMP®, CSM]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 01:24:44 GMT</pubDate>
            <atom:updated>2020-08-11T01:24:44.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ship Machine Learning Model to Data Using PyCaret — Part II</h3><h4>Binary Classification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3n2RWRuMocf7X67I" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My previous post <a href="https://towardsdatascience.com/machine-learning-in-sql-using-pycaret-87aff377d90c"><strong>Machine Learning in SQL using PyCaret 1.0</strong></a> provided details about integrating <a href="https://pycaret.org/"><strong>PyCaret</strong></a> with <a href="https://www.microsoft.com/en-ca/sql-server/sql-server-downloads"><strong>SQL Server</strong></a>. 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 <a href="https://pycaret.org/"><strong>PyCaret 2.0</strong></a><strong> </strong>(PyCaret is a low-code ML library in Python)<strong>.</strong></p><p><strong>Things to be covered in this article:</strong></p><p>1. How to load data into SQL Server table</p><p>2. How to create and save a model in SQL Server table</p><p>3. How to make model predictions using the saved model and store results in the table</p><h3><strong>I. Import/Load Data</strong></h3><p>You will now have to import CSV file into a database using SQL Server Management Studio.</p><p>Create a table “<strong>cancer</strong>” in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*js8AFIoUDjQZZSPa.png" /></figure><p>Right-click the database and select <strong>Tasks</strong> <strong>-&gt;</strong> <strong>Import Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*tZSAwhgQU9Oq8-uc.png" /></figure><p>For Data Source, select <strong>Flat File Source</strong>. Then use the <strong>Browse</strong> button to select the CSV file. Spend some time configuring the data import before clicking the<strong> Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*F4b5xric6n9Mc5sjWT4tHg.png" /></figure><p>For Destination, select the correct database provider (e.g. SQL Server Native Client 11.0). Enter the <strong>Server name</strong>; check <strong>Use SQL Server Authentication</strong>, enter the <strong>Username</strong>, <strong>Password</strong>, and <strong>Database </strong>before clicking the <strong>Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*c514MMvjt3DavCyI.png" /></figure><p>In the Select Source Tables and Views window, you can Edit Mappings before clicking the <strong>Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*I4VhN7PyYrQfipU5.png" /></figure><p>Check Run immediately and click the <strong>Next </strong>button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*uBqcVcjEyaUQsKNq.png" /></figure><p>Click the Finish button to run the package</p><h3><strong>II. Create ML Model &amp; Save in Database Table</strong></h3><p><strong>Classification </strong>is a type of supervised machine learning to predict the categorical class <strong>labels</strong> which are discrete and unordered. The module available in the <a href="https://pycaret.org/"><strong>PyCaret</strong></a> package can be used for <strong>binary</strong> or <strong>multiclass</strong> problems.</p><p>In this example, we will be using a ‘<strong>Breast Cancer Dataset</strong>’. Creating and saving a model in a database table is a multi-step process. Let’s go by them step by step:</p><p>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.</p><p>Below is the code used to create the procedure:</p><pre><em>-- Stored procedure that generates a PyCaret model using the cancer data using Extra Trees Classifier Algorithm</em></pre><pre>DROP PROCEDURE IF EXISTS generate_cancer_pycaret_model;</pre><pre>Go</pre><pre>CREATE PROCEDURE generate_cancer_pycaret_model (@trained_model varbinary(max) OUTPUT) AS</pre><pre>BEGIN</pre><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N&#39;Python&#39;</pre><pre>, @script = N&#39;</pre><pre>import pycaret.classification as cp</pre><pre>import pickle</pre><pre>trail1 = cp.setup(data = cancer_data, target = &quot;Class&quot;, silent = True, n_jobs=None)</pre><pre><em># Create Model</em><br>et = cp.create_model(&quot;et&quot;, verbose=False)<br></pre><pre><em>#To improve our model further, we can tune hyper-parameters using tune_model function.<br>#We can also optimize tuning based on an evaluation metric. As our choice of metric is F1-score, lets optimize our algorithm!</em></pre><pre>tuned_et = cp.tune_model(et, optimize = &quot;F1&quot;, verbose=False)<br></pre><pre><em>#The finalize_model() function fits the model onto the complete dataset.<br>#The purpose of this function is to train the model on the complete dataset before it is deployed in production</em></pre><pre>final_model = cp.finalize_model(tuned_et)</pre><pre><em># Before saving the model to the DB table, convert it to a binary object</em></pre><pre>trained_model = []<br>prep = cp.get_config(&quot;prep_pipe&quot;)<br>trained_model.append(prep)<br>trained_model.append(final_model)<br>trained_model = pickle.dumps(trained_model)&#39;</pre><pre>, @input_data_1 = N&#39;select &quot;Class&quot;, &quot;age&quot;, &quot;menopause&quot;, &quot;tumor_size&quot;, &quot;inv_nodes&quot;, &quot;node_caps&quot;, &quot;deg_malig&quot;, &quot;breast&quot;, &quot;breast_quad&quot;, &quot;irradiat&quot; from dbo.cancer&#39;</pre><pre>, @input_data_1_name = N&#39;cancer_data&#39;</pre><pre>, @params = N&#39;@trained_model varbinary(max) OUTPUT&#39;</pre><pre>, @trained_model = @trained_model OUTPUT;</pre><pre>END;</pre><pre>GO</pre><p>ii. Create a table that is required to store the trained model object</p><pre>DROP TABLE IF EXISTS dbo.pycaret_models;</pre><pre>GO</pre><pre>CREATE TABLE dbo.pycaret_models (<br>model_id  INT NOT NULL PRIMARY KEY,<br>dataset_name VARCHAR(100) NOT NULL DEFAULT(&#39;default dataset&#39;),<br>model_name  VARCHAR(100) NOT NULL DEFAULT(&#39;default model&#39;),<br>model   VARBINARY(MAX) NOT NULL<br>);</pre><pre>GO</pre><p>iii. Invoke stored procedure to create a model object and save into a database table</p><pre>DECLARE @model VARBINARY(MAX);<br>EXECUTE generate_cancer_pycaret_model @model OUTPUT;<br>INSERT INTO pycaret_models (model_id, dataset_name, model_name, model) VALUES(2, &#39;cancer&#39;, &#39;Extra Trees Classifier algorithm&#39;, @model);</pre><p>The output of this execution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*rMPx1cdPMqxZ2xAZDpqzsA.png" /><figcaption>Output from Console</figcaption></figure><p>The view of table results after saving model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*8DcdhzXZupB_fqiO6SofhQ.png" /><figcaption>SQL Server Table Results</figcaption></figure><h3><strong>III. Running Predictions</strong></h3><p>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.</p><p>i. Create a stored procedure that will use the test dataset to detect cancer for a test datapoint</p><p>Below is the code to create a database procedure:</p><pre>DROP PROCEDURE IF EXISTS pycaret_predict_cancer;<br>GO</pre><pre>CREATE PROCEDURE pycaret_predict_cancer (@id INT, @dataset varchar(100), @model varchar(100))<br>AS</pre><pre>BEGIN</pre><pre>DECLARE @py_model varbinary(max) = (select model</pre><pre>from pycaret_models</pre><pre>where model_name = @model</pre><pre>and dataset_name = @dataset</pre><pre>and model_id = @id</pre><pre>);</pre><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N&#39;Python&#39;,</pre><pre>@script = N&#39;</pre><pre># Import the scikit-learn function to compute error.</pre><pre>import pycaret.classification as cp</pre><pre>import pickle</pre><pre>cancer_model = pickle.loads(py_model)</pre><pre><em># Generate the predictions for the test set.</em></pre><pre>predictions = cp.predict_model(cancer_model, data=cancer_score_data)</pre><pre>OutputDataSet = predictions</pre><pre>print(OutputDataSet)</pre><pre>&#39;</pre><pre>, @input_data_1 = N&#39;select &quot;Class&quot;, &quot;age&quot;, &quot;menopause&quot;, &quot;tumor_size&quot;, &quot;inv_nodes&quot;, &quot;node_caps&quot;, &quot;deg_malig&quot;, &quot;breast&quot;, &quot;breast_quad&quot;, &quot;irradiat&quot; from dbo.cancer&#39;</pre><pre>, @input_data_1_name = N&#39;cancer_score_data&#39;</pre><pre>, @params = N&#39;@py_model varbinary(max)&#39;</pre><pre>, @py_model = @py_model</pre><pre>with result sets ((&quot;Class&quot; INT, &quot;age&quot; INT, &quot;menopause&quot; INT, &quot;tumor_size&quot; INT, &quot;inv_nodes&quot; INT,</pre><pre>&quot;node_caps&quot; INT, &quot;deg_malig&quot; INT, &quot;breast&quot; INT, &quot;breast_quad&quot; INT,</pre><pre>&quot;irradiat&quot; INT, &quot;Class_Predict&quot; INT, &quot;Class_Score&quot; float ));</pre><pre>END;</pre><pre>GO</pre><p>ii. Create a table to save the predictions along with the dataset</p><pre>DROP TABLE IF EXISTS [dbo].[pycaret_cancer_predictions];</pre><pre>GO</pre><pre>CREATE TABLE [dbo].[pycaret_cancer_predictions](</pre><pre>[Class_Actual] [nvarchar] (50) NULL,</pre><pre>[age] [nvarchar] (50) NULL,</pre><pre>[menopause] [nvarchar] (50) NULL,</pre><pre>[tumor_size] [nvarchar] (50) NULL,</pre><pre>[inv_nodes] [nvarchar] (50) NULL,</pre><pre>[node_caps] [nvarchar] (50) NULL,</pre><pre>[deg_malig] [nvarchar] (50) NULL,</pre><pre>[breast] [nvarchar] (50) NULL,</pre><pre>[breast_quad] [nvarchar] (50) NULL,</pre><pre>[irradiat] [nvarchar] (50) NULL,</pre><pre>[Class_Predicted] [nvarchar] (50) NULL,</pre><pre>[Class_Score] [float] NULL</pre><pre>) ON [PRIMARY]</pre><pre>GO</pre><p>iii. Call pycaret_predict_cancer procedure to save predictions result into a table</p><pre><em>--Insert the results of the predictions for test set into a table</em></pre><pre>INSERT INTO [pycaret_cancer_predictions]</pre><pre>EXEC pycaret_predict_cancer 2, &#39;cancer&#39;, &#39;Extra Trees Classifier algorithm&#39;;</pre><p>iv. Execute the SQL below to view the result of the prediction</p><pre><em>-- Select contents of the table</em></pre><pre>SELECT * FROM [pycaret_cancer_predictions];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*kboWnjA4K41DV6a__l79wA.png" /><figcaption>Predictions Result</figcaption></figure><h3>IV. Conclusion</h3><p>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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*45eSsUjDsCd_7_-J" /><figcaption>Photo by <a href="https://unsplash.com/@tofi?utm_source=medium&amp;utm_medium=referral">Tobias Fischer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You can further check out the <a href="http://pycaret.org/"><strong>PyCaret</strong></a> website for documentation on other supervised and unsupervised experiments that can be implemented in a similar manner within SQL Server.</p><p>My future posts will be tutorials on exploring other supervised &amp; unsupervised learning techniques using Python and <strong>PyCaret</strong> within a S<strong>QL Server</strong>.</p><h3>V. Important Links</h3><p><a href="https://pycaret.org/">PyCaret</a></p><p><a href="https://www.linkedin.com/in/umarfarooque/">My LinkedIn Profile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a8b3f3d04d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ship-ml-model-to-data-using-pycaret-part-ii-6a8b3f3d04d0">Ship ML Model to Data Using PyCaret — Part II</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning in SQL using PyCaret]]></title>
            <link>https://medium.com/data-science/machine-learning-in-sql-using-pycaret-87aff377d90c?source=rss-2c0277167441------2</link>
            <guid isPermaLink="false">https://medium.com/p/87aff377d90c</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Umar Farooque, MMA, MCS, PMP®, CSM]]></dc:creator>
            <pubDate>Tue, 12 May 2020 18:40:19 GMT</pubDate>
            <atom:updated>2020-07-26T22:05:30.458Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ship your ML code to data by integrating PyCaret in SQL Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxB6I95fPzYv_z9C6RRzVg.png" /></figure><p>This post is a <strong>step-by-step tutorial</strong> on how to train and deploy an Unsupervised Machine Learning Clustering model in SQL Server using <a href="https://pycaret.org/"><strong>PyCaret</strong></a>(a low-code ML library in Python)<strong>.</strong></p><p><strong>Things we will cover in this article:</strong></p><p>1. How to download and install SQL Server for free</p><p>2. How to create a new database and importing data into a database</p><p>3. How to enable and use Python scripting in database</p><p>4. How to train a clustering algorithm in order to assign cluster labels to each observation in the dataset</p><h3><strong>I. Bringing Code to Data — The case for using Database for ML</strong></h3><p>The go-to tools/ environments for performing ML experiments are Command-Line, IDEs, or Notebooks. However, such tools/environments may pose limitations when the data size gets very large, or when the ML model is required to be put in production. There has been a dire need to have the ability to programme and train models where data reside. MS SQL Server introduced this capability in their SQL Server version 2019. The distinct advantages of using SQL Server for Machine Learning are:</p><p>i. Extracting a large amount of data from the system is tedious and time-consuming. Conducting ML experiments on a server brings the code to data, rather than taking data to the code</p><p>ii. ML experiments are executed mostly in computer/cpu memory. Most of the machines hit a performance ceiling when training an ML algorithm on large data sets. ML on the SQL Server database avoids this</p><p>iii. It is easy to integrate and deploy ML Pipelines along with other ETL processes</p><h3><strong>II. SQL Server</strong></h3><p>SQL Server is a Microsoft relational database management system. As a database server, it performs the primary function of storing and retrieving data as requested by different applications. In this tutorial, we will use <a href="https://www.microsoft.com/en-ca/sql-server/sql-server-downloads"><strong>SQL Server 2019</strong> <strong>Developer</strong></a> for machine learning by importing PyCaret library into SQL Server.</p><h3><strong>III. Download Software</strong></h3><p>If you have used SQL Server before, it is likely that you have it installed and have access to the database. If not, <a href="https://www.microsoft.com/en-ca/sql-server/sql-server-downloads"><strong>click here</strong></a> to download SQL Server 2019 Developer or other edition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*lt9GPAvrhixDQAP6iatTIQ.png" /></figure><h3><strong>IV. Setting up the Environment</strong></h3><p>Before using PyCaret functionality into SQL Server, you’ll need to install SQL Server and PyCaret. This is a multi-step process:</p><h4>Step 1 — Install SQL Server</h4><p>Download the SQL Server 2019 Developer Edition file “<strong>SQL2019-SSEI-Dev.exe</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*WYIssA8f1vpYIPced1miYA.png" /></figure><p>Open the file and follow the instructions to install (recommended to use Custom install option)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*H2mr4UeI3q2DaidWtgldxQ.png" /></figure><p>Choose New SQL Server stand-alone installation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*bxqUK4NIzdW7DW1LBKObiQ.png" /></figure><p>In the Instance Features option, select the features including “<strong>Python</strong>” under <strong>Machine Learning Services and Language Extensions</strong> and <strong>Machine Learning Server (Standalone)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*OCXaVsXQmnGSBa5hPUh4GQ.png" /></figure><p>Click “<strong>Accept</strong>” to provide consent to install Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*rYm00TFsLe70EzW1503h1A.png" /></figure><p>Installation may take 15–20 minutes</p><h4>Step 2 — Install Microsoft SQL Server Management Studio (SSMS)</h4><p><a href="https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?redirectedfrom=MSDN&amp;view=sql-server-ver15"><strong>Click here</strong></a> or Open SQL Server Installation Center to download “SQL Server Management Tools” file “<strong>SSMS-Setup-ENU.exe</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*VydYoU_rbKtzFKgsJ7fPpw.png" /></figure><p>Open “<strong>SSMS-Setup-ENU.exe</strong>” file to start the installation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*Fnt_PmyaEh8AitkuQIy7og.png" /></figure><p>Installation may take 5–10 minutes</p><h4>Step 3 — Create a database for Machine Learning</h4><p>Once you have everything installed, you will need to start an instance of the server. To do so, start SSMS. At the login stage, you’ll be asked to the name of the SQL Server that you can choose from the drop-down menu. Once a connection is established, you can see all the objects from the server. If you have downloaded SQL Server for the first time and you do not have a database to work with, you will need to create a new database first.</p><p>In the Object Explorer panel, right-click on Databases, and choose New Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*4pzZ6-fk48V3ujaAIUhI2A.png" /></figure><p>Enter the database name and other information</p><p>The setup may take 2–3 minutes including creating a database, user and setting ownership</p><h4>Step 4 — Import CSV File</h4><p>You will now have to import a CSV file into a database using SQL Server Management Studio.</p><p>Create a table “<strong>jewellery</strong>” in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*-kkwdIAo4GDkzZ1013GYog.png" /></figure><p>Right-click the database and select <strong>Tasks</strong> <strong>-&gt;</strong> <strong>Import Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*d07HzD7rwEr_SHkGsR_m-Q.png" /></figure><p>For Data Source, select <strong>Flat File Source</strong>. Then use the <strong>Browse</strong> button to select the CSV file. Spend some time configuring the data import before clicking the<strong> Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*zNU8RuLdlIDNmoh93Mlu1w.png" /></figure><p>For Destination, select the correct database provider (e.g. SQL Server Native Client 11.0). Enter the <strong>Server name</strong>; check <strong>Use SQL Server Authentication</strong>, enter the <strong>Username</strong>, <strong>Password</strong>, and <strong>Database </strong>before clicking the <strong>Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*jz9FIU8o-98-H_3vinmUfA.png" /></figure><p>In the Select Source Tables and Views window, you can Edit Mappings before clicking the <strong>Next </strong>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*q1RuWU3dVZmr0zvoVWrBLg.png" /></figure><p>Check Run immediately and click the <strong>Next </strong>button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*P9yzJy0imJkl85yGgE6C7g.png" /></figure><p>Click the Finish button to run the package</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*jBBq5kfftYJNR2DKWYmRuQ.png" /><figcaption>Data Loading Result</figcaption></figure><h4>Step 5 — Enable SQL Server for Python Scripts</h4><p>We will run Python “inside” the SQL Server by using the <strong>sp_execute_external_script </strong>system stored procedure. To begin, you need to open a ‘<strong>New Query</strong>’. Execute the following query in your instance to enable the use of the procedure for remote script execution:</p><pre>EXEC sp_configure ‘external scripts enabled’, 1</pre><pre>RECONFIGURE WITH OVERRIDE</pre><p><strong>Note:</strong> Restart the instance before proceeding to the next steps.</p><p>Following SQL Statements can be executed to check the Python path and list installed packages.</p><p>Check Python Path:</p><pre>EXECUTE sp_execute_external_script</pre><pre>@language =N’Python’,</pre><pre>@script=N’import sys; print(“\n”.join(sys.path))’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WDzLc0EXLpH1Zu3TEbfsiw.png" /><figcaption>Script Execution Result</figcaption></figure><p>List Installed Packages:</p><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N’Python’,</pre><pre>@script = N’</pre><pre>import pkg_resources</pre><pre>import pandas as pd</pre><pre>installed_packages = pkg_resources.working_set</pre><pre>installed_packages_list = sorted([“%s==%s” % (i.key, i.version) for i in installed_packages])</pre><pre>df = pd.DataFrame(installed_packages_list)</pre><pre>OutputDataSet = df’</pre><pre>WITH RESULT SETS (( PackageVersion nvarchar (150) ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*1bSpU8-L-KYpzR_dDPaTPQ.png" /><figcaption>Script Execution Result</figcaption></figure><h4>Step 6 — Adding PyCaret Python Package to SQL Server</h4><p>To install PyCaret package, open a command prompt and browse to the location of Python packages where SQL Server is installed. The default location is:</p><pre>C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\PYTHON_SERVICES</pre><p>Navigate to “<strong>Scripts</strong>” directory and use pip command to install <strong>PyCaret</strong> package</p><pre>pip.exe install pycaret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EZ4cZxBOb6sJ8sTaObM5bA.png" /><figcaption>Command Prompt — PyCaret Installation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*fAL6HpAkkuweGH_q90KU-Q.png" /><figcaption>Command Prompt — PyCaret Installation End</figcaption></figure><p><strong>Note</strong>: Make sure, you have access to the SQL Server directory to install package and/or change configurations. Otherwise, the package installation will fail.</p><p>Installation may take 5–10 minutes</p><p><strong>Note:</strong> In case encounter issue about missing “<em>lightgbm</em>” module when running SQL script. Follow the instructions below:</p><p>i. Uninstall “<em>lightgbm</em>”</p><pre>pip.exe uninstall lightgbm</pre><p>ii. Reinstall “<em>lightgbm</em>”</p><pre>pip.exe install lightgbm</pre><p>Execute the following SQL to verify the PyCaret installation from SQL Server:</p><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N’Python’,</pre><pre>@script = N’</pre><pre>import pkg_resources</pre><pre>pckg_name = “pycaret”</pre><pre>pckgs = pandas.DataFrame([(i.key) for i in pkg_resources.working_set], columns = [“key”])</pre><pre>installed_pckg = pckgs.query(‘’key == @pckg_name’’)</pre><pre>print(“Package”, pckg_name, “is”, “not” if installed_pckg.empty else “”, “installed”) ’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*evwN5FoXycMQJETJcjawgA.png" /><figcaption>Script Execution Result</figcaption></figure><h3>V. ML Experiment Example — Clustering in SQL Server</h3><p>Clustering is a machine learning technique that groups data points with similar characteristics. These groupings are useful for exploring data, identifying patterns, and analyzing a subset of data. Some common business use cases for clustering are:</p><p>✔ Customer segmentation for the purpose of marketing.</p><p>✔ Customer purchasing behaviour analysis for promotions and discounts.</p><p>✔ Identifying geo-clusters in an epidemic outbreak such as COVID-19.</p><p>In this tutorial, we will use the ‘<strong>jewellery.csv’ </strong>file that is available on PyCaret’s <a href="https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/jewellery.csv">Github repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*itUa7b3dSjnzKFaaTJOkMg.png" /><figcaption>Sample Data points from jewellery dataset</figcaption></figure><h4>1. K-Means Clustering</h4><p>Run the following SQL code in SQL Server:</p><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N’Python’,</pre><pre>@script = N’dataset = InputDataSet</pre><pre>import pycaret.clustering as pc</pre><pre>dataset = pc.get_clusters(data = dataset)</pre><pre>OutputDataSet = dataset’,</pre><pre>@input_data_1 = N’SELECT [Age], [Income], [SpendingScore], [Savings] FROM [jewellery]’</pre><pre>WITH RESULT SETS(([Age] INT, [Income] INT, [SpendingScore] FLOAT, [Savings] FLOAT, [Cluster] varchar(15)));</pre><h4>2. Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*AwXT-NmfgHJ9LDU6IWrPpA.png" /><figcaption>SQL Statement Result</figcaption></figure><p>A new column ‘<strong>Cluster’</strong> containing the label is attached to the original table.</p><p>By default, PyCaret trains a <strong>K-Means</strong> clustering model with 4 clusters <em>(i.e. all the data points in the table are categorized into 4 groups</em>). Default values can be changed easily:</p><p>To change the number of clusters you can use <strong>num_clusters</strong> parameter within <strong>get_</strong>clusters( ) function.</p><p>To change model type use <strong>model</strong> parameter within <strong>get_clusters( ).</strong></p><h4><strong>3. K-Modes</strong></h4><p>See the following code for training <strong>K-Modes</strong> model with <strong>6 clusters</strong>:</p><pre>EXECUTE sp_execute_external_script</pre><pre>@language = N’Python’,</pre><pre>@script = N’dataset = InputDataSet</pre><pre>import pycaret.clustering as pc</pre><pre>dataset = pc.get_clusters(data = dataset, model=”kmodes”, num_clusters = 6)</pre><pre>OutputDataSet = dataset’,</pre><pre>@input_data_1 = N’SELECT [Age], [Income], [SpendingScore], [Savings] FROM [jewellery]’</pre><pre>WITH RESULT SETS(([Age] INT, [Income] INT, [SpendingScore] FLOAT, [Savings] FLOAT, [Cluster] varchar(15)));</pre><p>Following these steps, you can assign cluster value to every observation point in the jewellery dataset. You can use similar steps on other datasets too, to perform clustering on them.</p><h3>VI. Conclusion</h3><p>In this post, we learnt how to build a clustering model using running a Python library (PyCaret) in SQL Server. Similarly, you can build and run other types of supervised and unsupervised ML models depending on the need of the business problem.</p><p>You can further check out the <a href="http://pycaret.org/">PyCaret</a> website for documentation on other supervised and unsupervised experiments that can be implemented in a similar manner within SQL Server.</p><p>My future posts will be tutorials on exploring supervised learning techniques (regression/classification) using Python and Pycaret within a SQL Server.</p><h3>VII. Important Links</h3><p><a href="https://pycaret.org/">PyCaret</a></p><p><a href="https://pycaret.org/guide/">PyCaret: User guide and documentation</a></p><p><a href="https://pycaret.org/tutorial/">PyCaret: Tutorials</a></p><p><a href="https://www.linkedin.com/in/umarfarooque/">My LinkedIn Profile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87aff377d90c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-in-sql-using-pycaret-87aff377d90c">Machine Learning in SQL using PyCaret</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>