使用 SQL Server Machine Learning Services 与 Python 构建并部署滑雪租赁预测模型:rental-prediction 示例全解析
使用 SQL Server Machine Learning Services 与 Python 构建并部署滑雪租赁预测模型:rental-prediction 示例全解析
本文以
sql-server-samples仓库中 rental-prediction 示例为主线,完整讲解如何用 Python(scikit-learn + RevoScalePy)在 SQL Server 2017 Machine Learning Services 中完成「模型训练 → 模型序列化入库 → 存储过程打分 → 结果落库」的端到端预测流水线。读完本文,你将掌握sp_execute_external_script调用 Python 的完整写法、VARBINARY(MAX)模型存储方案、pickle序列化与反序列化技巧,以及独立运行 Python 脚本时连接 SQL Server 计算上下文的配置方法。
示例概览:预测建模的两个阶段
预测建模是给应用增加智能能力的经典手段——它让应用能够针对新数据预测结果。把这个能力真正落地到应用中,通常包含两个主要阶段:
- 模型训练(Model Training):基于历史数据拟合出能够刻画数据规律的模型;
- 模型运营化(Model Operationalization):把训练好的模型部署到生产环境,供业务应用对新数据实时打分。
本示例的目标业务场景是「滑雪器材租赁」:基于 dbo.rental_data 表中的历史租赁数据(年份、月份、日期、星期、是否节假日、是否下雪、租赁数量等字段),训练一个线性回归模型,用来预测某一天的滑雪器材租赁数量。
该示例的关键信息如下(摘自 README.md):
- 适用版本:SQL Server 2017 CTP2.0 或更高版本(需安装 Machine Learning Services 的 Python 组件)
- 核心功能:SQL Server Machine Learning Services
- 工作负载:SQL Server Machine Learning Services
- 编程语言:T-SQL、Python
- 作者:Nellie Gustafsson
示例目录共包含 4 个文件,职责划分非常清晰:
| 文件 | 作用 |
|---|---|
| Setup.sql | 从 .bak 备份恢复教程数据库 TutorialDB |
| rental_prediction.py | 纯 Python 脚本:连接 SQL Server 取数、训练线性回归模型并评估误差 |
| rental_prediction.sql | 把 Python 代码部署进 SQL Server,创建训练/预测存储过程与相关表 |
| README.md | 示例说明与操作步骤 |
两条路线互为补充:rental_prediction.py 展示的是「Python 客户端驱动」的工作方式,rental_prediction.sql 展示的是「数据库内(in-database)部署」的工作方式,后者正是 Machine Learning Services 最具价值的生产形态。
环境与前置条件
在动手运行示例之前,需要准备以下环境(摘自 README 的「Before you begin」章节):
数据库文件:
- 下载本教程的数据库备份文件
TutorialDB.bak,并使用 Setup.sql 完成恢复。该备份文件同时也被仓库保留在 samples/extensibility/TutorialDB.bak 中,可供离线参考。
软件前置条件:
- SQL Server 2017 CTP2.0(或更高版本),安装时需勾选 Machine Learning Services(Python) 组件;
- SQL Server Management Studio(SSMS)或 SQL Server Data Tools,用于执行 T-SQL 脚本;
- Python Tools for Visual Studio(或任意 Python IDE),用于单独调试
rental_prediction.py。
版本注意:本示例针对 SQL Server 2017 编写。
rental_prediction.py文件头部的注释明确指出,revoscalepy相关导入适用于 SQL Server 2017 RC1 及以上 版本,这与 README 标注的 CTP2.0 起点略有差异,实际使用时请以你的具体版本为准。在 SQL Server 2019 及更高版本中,对应组件为「SQL Server 机器学习服务」并已更名为 Python 运行时,sp_execute_external_script的核心用法保持一致。
恢复示例数据库
Setup.sql 的内容非常简短,核心就是一条 RESTORE DATABASE 语句:
USE master;
GO
RESTORE DATABASE TutorialDB
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Backup\TutorialDB.bak'
WITH
MOVE 'TutorialDB' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\TutorialDB.mdf'
,MOVE 'TutorialDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\TutorialDB.ldf';
GO
执行前需要做两处修改:
- 备份文件路径:把
FROM DISK = ...中的路径改为TutorialDB.bak实际存放的位置(建议放到 SQL Server 实例的MSSQL\Backup目录,确保 SQL Server 服务账户有读取权限); - 数据文件路径:把
MOVE ... TO中的.mdf/.ldf目标路径改为当前实例的MSSQL\DATA目录。
由于备份中记录了原始逻辑文件名(TutorialDB 与 TutorialDB_log),在不同实例上恢复时必须使用 MOVE 重新映射物理路径,否则可能因目录不一致导致恢复失败。
运行示例的完整步骤
README 给出了三步式运行流程,下面结合源码逐层展开。
第 1 步:恢复示例数据库
在 SSMS(或 SQL Server Data Tools)中连接目标 SQL Server 实例,打开并执行 Setup.sql,即可将 TutorialDB 数据库恢复到实例中。该数据库包含一张核心训练表 dbo.rental_data,其字段在 rental_prediction.sql 第 1 步中通过 SELECT * FROM [dbo].[rental_data] 直接展示。
第 2 步:在 SQL Server 内运行部署脚本
打开 rental_prediction.sql 并执行。整个脚本以「注释分步」的方式组织,共包含 6 个步骤:
- 创建模型存储表;
- 创建训练模型的存储过程;
- 执行训练并把模型保存到表;
- 创建使用模型进行预测的存储过程;
- 创建存放预测结果的数据库表;
- 执行预测并把结果写入表。
下面逐一拆解每个步骤的实现细节。
STEP 1 —— 模型存储表 rental_py_models
DROP TABLE IF EXISTS rental_py_models;
GO
CREATE TABLE rental_py_models (
model_name VARCHAR(30) NOT NULL DEFAULT('default model') PRIMARY KEY,
model VARBINARY(MAX) NOT NULL
);
GO
这张表是整个「模型即数据」思路的载体:model_name 是模型名称(主键,默认值为 'default model'),model 列用 VARBINARY(MAX) 存放 Python 对象经 pickle 序列化后的二进制内容。把模型放进表里,意味着模型可以像普通数据一样备份、复制、迁移,也便于后续用 WHERE model_name = ... 选取指定版本模型进行打分。
STEP 2 —— 训练存储过程 generate_rental_py_model
DROP PROCEDURE IF EXISTS generate_rental_py_model;
GO
CREATE PROCEDURE generate_rental_py_model (@trained_model varbinary(max) OUTPUT)
AS
BEGIN
EXECUTE sp_execute_external_script
@language = N'Python'
, @script = N'
from sklearn import linear_model
import pickle
df = rental_train_data
# Get all the columns from the dataframe.
columns = df.columns.tolist()
# Store the variable well be predicting on.
target = "RentalCount"
# Initialize the model class.
lin_model = linear_model.LinearRegression()
# Fit the model to the training data.
lin_model.fit(df[columns], df[target])
#Before saving the model to the DB table, we need to convert it to a binary object
trained_model = pickle.dumps(lin_model)
'
, @input_data_1 = N'select "RentalCount", "Year", "Month", "Day", "WeekDay", "Snow", "Holiday" from dbo.rental_data where Year < 2015'
, @input_data_1_name = N'rental_train_data'
, @params = N'@trained_model varbinary(max) OUTPUT'
, @trained_model = @trained_model OUTPUT;
END;
GO
这是理解整个示例的关键。它的核心是 sp_execute_external_script 系统存储过程,各参数含义如下:
@language = N'Python':指定外部脚本运行时为 Python(若为 R 则传N'R');@script:内嵌的 Python 代码字符串。脚本通过预置的输入数据变量rental_train_data直接拿到 DataFrame,用linear_model.LinearRegression()拟合模型,再用pickle.dumps()把模型对象转成二进制;@input_data_1:SQL 查询语句,作为 Python 脚本的输入数据源。这里刻意用where Year < 2015切出训练集——2015 年之前的数据用于训练;@input_data_1_name = N'rental_train_data':指定输入数据集在 Python 脚本中对应的变量名,脚本里的df = rental_train_data即来源于此;@params/@trained_model OUTPUT:声明并回传输出参数。Python 端写出的trained_model变量会被序列化回传给 T-SQL 侧的@trained_model参数。
值得注意的是,sp_execute_external_script 会自动把 @input_data_1 的查询结果转换为 pandas DataFrame 传入 Python 命名空间,因此脚本中可以直接使用 df.columns.tolist()、df[target] 等 pandas 惯用写法,无需显式导入数据。
源码注释勘误:该存储过程上方的注释写着「trains and generates an R model ... using a decision tree algorithm」,但实际代码是 Python + 线性回归(LinearRegression),并非 R 语言、也非决策树。这是原始示例注释的历史遗留问题,请以代码实现为准。
STEP 3 —— 训练并保存模型到表
TRUNCATE TABLE rental_py_models;
DECLARE @model VARBINARY(MAX);
EXEC generate_rental_py_model @model OUTPUT;
INSERT INTO rental_py_models (model_name, model) VALUES('linear_model', @model);
SELECT * FROM rental_py_models;
这一步通过 DECLARE @model VARBINARY(MAX) 承接存储过程的 OUTPUT 参数,然后把序列化后的模型以 'linear_model' 为名写入 rental_py_models 表,最后 SELECT 验证入库结果。
STEP 4 —— 预测存储过程 py_predict_rentalcount
DROP PROCEDURE IF EXISTS py_predict_rentalcount;
GO
CREATE PROCEDURE py_predict_rentalcount (@model varchar(100))
AS
BEGIN
DECLARE @py_model varbinary(max) = (select model from rental_py_models where model_name = @model);
EXEC sp_execute_external_script
@language = N'Python'
, @script = N'
import pickle
rental_model = pickle.loads(py_model)
df = rental_score_data
#print(df)
# Get all the columns from the dataframe.
columns = df.columns.tolist()
# Filter the columns to remove ones we dont want.
# columns = [c for c in columns if c not in ["Year"]]
# Store the variable well be predicting on.
target = "RentalCount"
# Generate our predictions for the test set.
lin_predictions = rental_model.predict(df[columns])
print(lin_predictions)
# Import the scikit-learn function to compute error.
from sklearn.metrics import mean_squared_error
# Compute error between our test predictions and the actual values.
lin_mse = mean_squared_error(lin_predictions, df[target])
#print(lin_mse)
import pandas as pd
predictions_df = pd.DataFrame(lin_predictions)
OutputDataSet = pd.concat([predictions_df, df["RentalCount"], df["Month"], df["Day"], df["WeekDay"], df["Snow"], df["Holiday"], df["Year"]], axis=1)
'
, @input_data_1 = N'Select "RentalCount", "Year" ,"Month", "Day", "WeekDay", "Snow", "Holiday" from rental_data where Year = 2015'
, @input_data_1_name = N'rental_score_data'
, @params = N'@py_model varbinary(max)'
, @py_model = @py_model
with result sets (("RentalCount_Predicted" float, "RentalCount" float, "Month" float,"Day" float,"WeekDay" float,"Snow" float,"Holiday" float, "Year" float));
END;
GO
预测过程与训练过程对称,重点差异有三处:
- 模型反序列化:通过
DECLARE @py_model varbinary(max) = (select model from rental_py_models where model_name = @model)把二进制模型取出来,在 Python 端用pickle.loads(py_model)还原成LinearRegression对象; - 打分数据切分:
@input_data_1使用where Year = 2015取出 2015 年的数据作为测试集,与训练集(Year < 2015)在时间上严格错开,避免数据泄漏; - 结果输出:Python 端用
pd.concat把预测值lin_predictions与RentalCount、Month、Day、WeekDay、Snow、Holiday、Year按列拼接成OutputDataSet——这是sp_execute_external_script约定的输出变量名,T-SQL 侧再用WITH RESULT SETS (...)显式声明返回列的类型(全部为float),保证结果集结构清晰可控。
此外,脚本内部用 mean_squared_error 计算了预测均方误差(默认被注释掉未打印),用于在开发阶段快速评估模型精度;脚本中还保留了一段被注释的「过滤 Year 列」代码(# columns = [c for c in columns if c not in ["Year"]]),来自 rental_prediction.py 的对应逻辑,说明在特征选择上可以按需调整。
STEP 5 —— 创建预测结果表 py_rental_predictions
DROP TABLE IF EXISTS [dbo].[py_rental_predictions];
GO
CREATE TABLE [dbo].py_rental_predictions ON [PRIMARY]
GO
这张表把「预测值」与「真实值」并列存放(RentalCount_Predicted vs RentalCount_Actual),同时保留月份、日期、星期、雪、节假日、年份等维度,方便后续在 BI 报表或仪表盘中按维度对比预测精度。
STEP 6 —— 执行预测并落库
TRUNCATE TABLE py_rental_predictions;
--Insert the results of the predictions for test set into a table
INSERT INTO py_rental_predictions
EXEC py_predict_rentalcount 'linear_model';
-- Select contents of the table
SELECT * FROM py_rental_predictions;
最后一步用 INSERT ... EXEC 把预测存储过程的返回结果集直接灌入结果表,再 SELECT 校验。至此,一条完整的「训练 → 存模型 → 取模型打分 → 结果落库」链路就闭环了:今后任何新数据到来,业务应用只需调用 py_predict_rentalcount 传入模型名即可获得预测,而无需关心 Python 运行时的内部细节。
第 3 步(可选):独立运行 Python 脚本
README 指出,你还可以抛开 T-SQL,在 Python 环境中单独运行 rental_prediction.py,它会连接 SQL Server 读取 dbo.rental_data 并直接完成训练与评估。运行前需要把 Python 解释器指向正确的环境路径:
- 数据库内(in-database)Python 服务:
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES - 独立安装的 Machine Learning Server:
C:\Program Files\Microsoft SQL Server\140\PYTHON_SERVER
该脚本整体结构如下:
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#If you are running SQL Server 2017 RC1 and above:
from revoscalepy import RxComputeContext, RxInSqlServer, RxSqlServerData
from revoscalepy import rx_import
def get_rental_predictions():
#Connection string to connect to SQL Server named instance
conn_str = 'Driver=SQL Server;Server=MYSQLSERVER;Database=TutorialDB;Trusted_Connection=True;'
#Define the columns we wish to import
column_info = {
"Year" : { "type" : "integer" },
"Month" : { "type" : "integer" },
"Day" : { "type" : "integer" },
"RentalCount" : { "type" : "integer" },
"WeekDay" : {
"type" : "factor",
"levels" : ["1", "2", "3", "4", "5", "6", "7"]
},
"Holiday" : {
"type" : "factor",
"levels" : ["1", "0"]
},
"Snow" : {
"type" : "factor",
"levels" : ["1", "0"]
}
}
#Get the data from SQL Server Table
data_source = RxSqlServerData(table="dbo.rental_data",
connection_string=conn_str, column_info=column_info)
computeContext = RxInSqlServer(
connection_string = conn_str,
num_tasks = 1,
auto_cleanup = False
)
RxInSqlServer(connection_string=conn_str, num_tasks=1, auto_cleanup=False)
# import data source and convert to pandas dataframe
df = pd.DataFrame(rx_import(input_data = data_source))
print("Data frame:", df)
# Get all the columns from the dataframe.
columns = df.columns.tolist()
# Filter the columns to remove ones we don't want to use in the training
columns = [c for c in columns if c not in ["Year"]]
# Store the variable we'll be predicting on.
target = "RentalCount"
# Generate the training set. Set random_state to be able to replicate results.
train = df.sample(frac=0.8, random_state=1)
# Select anything not in the training set and put it in the testing set.
test = df.loc[~df.index.isin(train.index)]
# Print the shapes of both sets.
print("Training set shape:", train.shape)
print("Testing set shape:", test.shape)
# Initialize the model class.
lin_model = LinearRegression()
# Fit the model to the training data.
lin_model.fit(train[columns], train[target])
# Generate our predictions for the test set.
lin_predictions = lin_model.predict(test[columns])
print("Predictions:", lin_predictions)
# Compute error between our test predictions and the actual values.
lin_mse = mean_squared_error(lin_predictions, test[target])
print("Computed error:", lin_mse)
get_rental_predictions()
脚本可以拆成四个逻辑段来理解。
(1)连接与列定义
conn_str = 'Driver=SQL Server;Server=MYSQLSERVER;Database=TutorialDB;Trusted_Connection=True;'
连接字符串使用 ODBC 驱动 SQL Server,Server=MYSQLSERVER 是占位符,需要替换为你的真实实例名(如 localhost、MYSQLSERVER\SQLEXPRESS 或 主机名\命名实例)。紧接着的 column_info 字典是 RevoScalePy 特有的列元数据描述:
| 列名 | 类型 | 说明 |
|---|---|---|
Year / Month / Day / RentalCount |
integer |
数值型特征与预测目标 |
WeekDay |
factor |
分类变量,水平为 1~7(周一至周日) |
Holiday |
factor |
分类变量,水平为 "1" / "0"(是否节假日) |
Snow |
factor |
分类变量,水平为 "1" / "0"(是否下雪) |
把 Holiday、Snow、WeekDay 声明为 factor 而非 integer,是为了让它们在进入回归模型时被当作类别特征处理,这是特征工程在数据接入层的体现。
(2)SQL Server 计算上下文
data_source = RxSqlServerData(table="dbo.rental_data",
connection_string=conn_str, column_info=column_info)
computeContext = RxInSqlServer(
connection_string = conn_str,
num_tasks = 1,
auto_cleanup = False
)
RxSqlServerData 定义一个指向 dbo.rental_data 表的数据源;RxInSqlServer 则把计算上下文指向 SQL Server,其中 num_tasks = 1 表示单任务执行(避免分布式开销),auto_cleanup = False 表示计算结束后保留临时对象以便排查。脚本第 43 行又重复调用了一次 RxInSqlServer(...)(未赋值给变量),这是原始示例中的冗余代码,功能上无影响,读者可自行忽略。
(3)取数并转 DataFrame
df = pd.DataFrame(rx_import(input_data = data_source))
rx_import 是 RevoScalePy 的核心取数函数,它按 data_source 定义的表与列元数据从 SQL Server 拉取数据并转换为 pandas DataFrame,随后即可复用整个 scikit-learn 生态。
(4)训练与评估
columns = [c for c in columns if c not in ["Year"]]
target = "RentalCount"
train = df.sample(frac=0.8, random_state=1)
test = df.loc[~df.index.isin(train.index)]
lin_model = LinearRegression()
lin_model.fit(train[columns], train[target])
lin_predictions = lin_model.predict(test[columns])
lin_mse = mean_squared_error(lin_predictions, test[target])
这里采用「随机 80/20 划分」而非数据库内的时间切分:df.sample(frac=0.8, random_state=1) 抽取 80% 数据做训练集(固定 random_state 保证结果可复现),剩余 20% 做测试集;同时把 Year 列从特征中剔除,避免年份作为强特征干扰对「季节规律」的学习。最后用 mean_squared_error 输出测试集上的均方误差,作为模型质量的量化指标。
源码级原理剖析:这条链路是如何运转的
sp_execute_external_script 的完整调用链
无论训练还是预测,核心都是 sp_execute_external_script。它相当于 SQL Server 与外部语言运行时(本示例为 Python)之间的桥:
- T-SQL 引擎把
@input_data_1的查询结果物化为 DataFrame; - 通过
@input_data_1_name注入 Python 命名空间; - Python 运行时执行
@script,可读取输入变量、调用任意已安装库(如sklearn、pandas、pickle); - 脚本写入
OutputDataSet变量或@params声明的输出参数; - 结果集按
WITH RESULT SETS的定义回流到 T-SQL。
这一机制意味着:Python 代码完全内嵌在存储过程中,模型生命周期(训练、存储、加载、打分)全部由数据库对象管理,业务层只需调用存储过程即可获得预测能力。
模型持久化的「二进制管线」
训练侧 pickle.dumps(lin_model) 与预测侧 pickle.loads(py_model) 构成对称的序列化管线,中间的载体就是 rental_py_models.model 这一 VARBINARY(MAX) 列。把模型当作二进制大对象存储,让模型可以:
- 与数据一起纳入备份/恢复、可用性组复制等数据库运维体系;
- 通过
model_name管理多个模型版本(如 A/B 对照); - 跨服务器迁移(配合模型表导出导入)。
RevoScalePy 与 scikit-learn 的协作分工
从 rental_prediction.py 的导入语句可以看到两条技术线的分工:RevoScalePy(RxSqlServerData、RxInSqlServer、rx_import)负责与 SQL Server 的数据交互与计算上下文管理,scikit-learn(LinearRegression、mean_squared_error)与 pandas 负责建模与评估。数据库内部署版(rental_prediction.sql)则完全不需要 RevoScalePy——因为数据已经在 SQL Server 内部,sp_execute_external_script 直接把查询结果交给 Python。
同仓库的其他入门示例:横向对照
sql-server-samples 的 machine-learning-services/python 目录下还提供了多个同主题入门示例,可以与本示例对照学习:
- bike-sharing prediction:基于巴黎 Vélib 共享单车数据构建二分类器,预测某个站点是否为空车。代码拆分为
datasource.py(数据源类)、pipeline.py(特征工程 + RevoScalePy 二分类逻辑回归管线)、runner.py(启动入口),展示了更工程化的 Python 项目组织方式,同样依赖 RevoScalePy 的 SQL Server 计算上下文; - customer-clustering:在
tpcxbb_1gb数据库上用KMeans(sklearn.cluster)做客户聚类,通过sp_execute_external_script计算订单/退货相关指标(orderRatio、itemsRatio、monetaryRatio、frequency)并把聚类标签写回数据,展示了无监督学习在数据库内的部署方式; - sentiment-analysis:包含预训练模型的情感分析脚本,例如 product-review-text-classification.sql,展示文本分类场景。
三者与本示例共同勾勒出 SQL Server Machine Learning Services + Python 的三类典型任务:回归预测、分类预测、聚类分析,均遵循「数据在库、脚本入库、过程化调用」的同一范式。
常见问题与注意事项
Server=MYSQLSERVER连接失败:rental_prediction.py中的连接字符串是占位示例,必须替换为真实实例名;若使用命名实例,语法为Server=主机名\实例名。- Python 环境路径选错:独立运行脚本时,务必按 README 区分「数据库内 Python 服务」与「独立 Machine Learning Server」两条路径,指向错误环境会导致
revoscalepy导入失败。 sp_execute_external_script报「找不到 Python 运行时」:说明安装 SQL Server 时未勾选 Machine Learning Services(Python)组件,需要补装功能后重启实例。WITH RESULT SETS列数不匹配:预测存储过程返回列由 Python 端pd.concat拼接顺序决定,若修改了OutputDataSet的构造,必须同步更新WITH RESULT SETS中的列定义。TRUNCATE TABLE与外部脚本的兼容性:示例在每次执行前先TRUNCATE模型表与预测表,适合教学演示;生产环境建议引入模型版本号、时间戳等维度,避免覆盖历史模型。- 版本差异:示例基于 SQL Server 2017 编写,更高版本(2019 / 2022)中机器学习服务更名为「SQL Server 机器学习服务」,Python 运行时与
sp_execute_external_script用法基本兼容,但安装路径与组件名称可能有差异。
通过本示例,你已经掌握了一条完整可复用的预测模型落地路径:用 Python 训练 → pickle 序列化 → VARBINARY(MAX) 入库 → 存储过程反序列化打分 → 结果落表。这套模式正是把机器学习能力「数据库化」的标准做法,也是后续在 Azure SQL 托管实例、大数据集群中推广预测服务的坚实基础。