跳至主要内容

在 SQL 中远程运行 Python 和 R

了解如何从 Jupyter Notebooks 将 R 和 Python 的执行远程发送到 SQL Server。
· 7分钟 阅读

使用 AI 探索

run r and python in sql server from any ide

简介

您是否知道,您可以在 Jupyter Notebooks 或任意 IDE 中,将 R 和 Python 代码远程提交到 SQL Server 执行?SQL Server 的 Machine Learning Services 省去了移动数据的需求。无需通过网络传输海量且敏感的数据,或用示例 csv 文件训练导致精度损失,您可以让 R/Python 代码直接在数据库内执行。您可以在 Jupyter Notebooks、RStudio、PyCharm、VSCode、Visual Studio 等任意环境中工作,然后将函数执行发送到 SQL Server,把智能带到数据所在之处。

本教程将演示如何从 Juptyter notebooks 将您的 Python 代码发送到 SQL Server 内执行。同样的原则也适用于 R 以及其他任何 IDE。若您更喜欢通过视频学习,本教程也已发布在 YouTube:

https://youtu.be/D5erljpJDjE

How To Run R & Python in SQL Server from Jupyter Notebooks or any IDE

环境准备先决条件

1. 在 SQL Server 上安装 ML Services

要在 SQL 中执行 R 或 Python,首先需要安装并配置 Machine Learning Services 功能。请参阅此操作指南。

2. 通过 Microsoft 的 Python 客户端安装 RevoscalePy

要从 Jupyter Notebooks 将 Python 执行发送到 SQL,您需要使用 Microsoft 的 RevoscalePy 包。要获取 RevoscalePy,请下载并安装 Microsoft 的 ML Services Python 客户端。文档页或直接下载链接(适用于 Windows)。

下载完成后,以管理员身份打开 PowerShell 并导航到下载文件夹。使用以下命令开始安装(可按需自定义安装目录):.\Install-PyForMLS.ps1 -InstallFolder "C:\Program Files\MicrosoftPythonClient"

安装可能需要一些时间,请耐心等待。安装完成后,导航到您设定的新路径。我们先创建一个空文件夹并打开 Jupyter Notebooks:mkdir JupyterNotebooks; cd JupyterNotebooks; ..\Scripts\jupyter-notebook

使用 Python 3 解释器创建一个新笔记本:

create new notebook with python 3 interpreter

为测试是否一切就绪,请在第一个单元中导入 revoscalepy 并执行。若无错误消息,即可继续。

import revoscalepy

数据库设置(仅本教程需要)

在后续步骤中,如果您不想复制粘贴所有代码,可以从 Github 克隆此 Jupyter Notebook。此数据库设置仅需执行一次,以确保您拥有与本教程相同的数据。若使用您自己的数据,无需进行这些设置。

1. 创建数据库

根据您的服务器修改连接字符串,并使用 pyodbc 创建一个新数据库。

 import pyodbc

# creating a new db to load Iris sample in
new_db_name = "MLRemoteExec"
connection_string = "Driver=SQL Server;Server=localhost\MSSQLSERVER2017;Database={0};Trusted_Connection=Yes;"
cnxn = pyodbc.connect(connection_string.format("master"), autocommit=True)
cnxn.cursor().execute("IF EXISTS(SELECT * FROM sys.databases WHERE [name] = '{0}') DROP DATABASE {0}".format(new_db_name))
cnxn.cursor().execute("CREATE DATABASE " + new_db_name)
cnxn.close()

print("Database created")

2. 从 SkLearn 导入 Iris 示例

Iris 是入门数据科学教程中常用的数据集,sklearn 包默认已包含。

from sklearn import datasets
import pandas as pd

# SkLearn has the Iris sample dataset built into the package
iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)

3. 使用 RecoscalePy API 创建表并加载 Iris 数据

(您也可以使用 pyodbc、sqlalchemy 或其他包实现)

 from revoscalepy import RxSqlServerData, rx_data_step

# Example of using RX APIs to load data into SQL table. You can also do this with pyodbc
table_ref = RxSqlServerData(connection_string=connection_string.format(new_db_name), table="Iris")
rx_data_step(input_data = df, output_file = table_ref, overwrite = True)

print("New Table Created: Iris")
print("Sklearn Iris sample loaded into Iris table")

定义要发送到 SQL Server 的函数

编写您希望在 SQL 中执行的任意 Python 代码。本示例在 iris 数据集上创建散点矩阵,并仅将 .png 的字节流返回到 Jupyter Notebooks,在客户端进行渲染。

def send_this_func_to_sql():from revoscalepy import RxSqlServerData, rx_import
    from pandas.tools.plotting import scatter_matrix
    import matplotlib.pyplot as plt
    import io

    # remember the scope of the variables in this func are within our SQL Server Python Runtime
    connection_string = "Driver=SQL Server;Server=localhost\MSSQLSERVER2017;Database=MLRemoteExec;Trusted_Connection=Yes;"# specify a query and load into pandas dataframe df
    sql_query = RxSqlServerData(connection_string=connection_string, sql_query = "select * from Iris")
    df = rx_import(sql_query)

    scatter_matrix(df)

    # return bytestream of image created by scatter_matrix
    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)

    return buf.getvalue()

发送执行到 SQL

至此环境已准备就绪,来看看远程执行有多简单!首先,import revoscalepy。创建一个 sql_compute_context,然后使用 RxExec 将任意函数的执行无缝发送到 SQL Server。无需将原始数据从 SQL 传回 Jupyter Notebook。所有计算均在数据库内完成,只有图像文件被返回用于显示。

from IPython import display
import matplotlib.pyplot as plt
from revoscalepy import RxInSqlServer, rx_exec

# create a remote compute context with connection to SQL Server
sql_compute_context = RxInSqlServer(connection_string=connection_string.format(new_db_name))

# use rx_exec to send the function execution to SQL Server
image = rx_exec(send_this_func_to_sql, compute_context=sql_compute_context)[0]

# only an image was returned to my jupyter client. All data remained secure and was manipulated in my db.
display.Image(data=image)

尽管对 Iris 数据集而言此示例较为简单,但想象一下您已经解锁的额外规模、性能与安全能力。您可以使用任意最新的开源 R/Python 包,在 SQL Server 中对海量数据构建深度学习与 AI 应用。我们还在 Microsoft 的 前沿高性能算法中提供了 RevoScaleR 和 RevoScalePy API。将这些与开源领域的最新创新结合使用,可为您的应用带来无与伦比的选择、性能与可扩展性。

进一步了解

查看 DataCamp 的教程:如何在 SQL 中执行 Python/R。

查看 SQL Machine Learning Services 文档,了解如何通过 SQL 存储过程轻松部署您的 R/Python 代码,使其可用于 ETL 流程或任何应用。在数据库中训练并存储机器学习模型,把智能带到数据所在之处。

在 SQL Server 中运行基础 R 和 Python:https://aka.ms/BasicMLServicesExecution

在 SQL Server 中设置 Machine Learning Services:https://aka.ms/SetupMLServices

Github 上的端到端教程方案:https://microsoft.github.io/sql-ml-tutorials/

其他 YouTube 教程:

如果您有兴趣进一步学习,请查看 DataCamp 的入门课程。

主题