在SQL Server中使用r模型

时间:2018-06-03 14:19:06

标签: r sql-server

我试图遵循这个:

https://docs.microsoft.com/en-us/sql/advanced-analytics/tutorials/rtsql-create-a-predictive-model-r?view=sql-server-2017

提供的代码:

DROP PROCEDURE IF EXISTS generate_linear_model;
GO
CREATE PROCEDURE generate_linear_model
AS
BEGIN
    EXEC sp_execute_external_script
    @language = N'R'
    , @script = N'lrmodel <- rxLinMod(formula = distance ~ speed, data = CarsData);
        trained_model <- data.frame(payload = as.raw(serialize(lrmodel, connection=NULL)));'
    , @input_data_1 = N'SELECT [speed], [distance] FROM CarSpeed'
    , @input_data_1_name = N'CarsData'
    , @output_data_1_name = N'trained_model'
    WITH RESULT SETS ((model varbinary(max)));
END;
GO

只是不起作用。

不应将数据称为汽车。汽车数据也没有列距离,而是相距dist。我改编了这样的代码:

DROP PROCEDURE IF EXISTS generate_linear_model;
GO
CREATE PROCEDURE generate_linear_model
AS
BEGIN
EXEC sp_execute_external_script
@language = N'R'
, @script = N'lrmodel <- rxLinMod(formula = distance ~ speed, data = cars);
trained_model <- data.frame(payload = as.raw(serialize(lrmodel, connection=NULL)));'
, @input_data_1 = N'SELECT [speed], [dist] FROM cars'
, @input_data_1_name = N'cars'
, @output_data_1_name = N'trained_model'
WITH RESULT SETS ((model varbinary(max)));
END;
GO

但仍然会出错。顺便说一下,我有点困惑:

@input_data_1 = N'SELECT [speed], [dist] FROM cars'

一样。这是对R中数据车的查询吗?任何指针都将非常感激。感谢。

PS:

以下评论帮助我修复了代码:

--CREATE TABLE stopping_distance_models (
--    model_name varchar(30) not null default('default model') primary key,
--    model varbinary(max) not null);

DROP PROCEDURE IF EXISTS generate_linear_model;
GO
CREATE PROCEDURE generate_linear_model
AS
BEGIN
EXEC sp_execute_external_script
@language = N'R'
,@script = N'data(cars); 
lrmodel <- rxLinMod(formula = dist ~ speed, data = cars);
trained_model <- data.frame(payload = as.raw(serialize(lrmodel, connection=NULL)));'
, @input_data_1 = N''
, @input_data_1_name = N'cars'
, @output_data_1_name = N'trained_model'
WITH RESULT SETS ((model varbinary(max)));
END;
GO

INSERT INTO stopping_distance_models (model)
EXEC generate_linear_model;

1 个答案:

答案 0 :(得分:1)

你应该这样做的是下一个,只留下空EXEC sp_execute_external_script @language = N'R' ,@script = N'data(cars); lrmodel <- rxLinMod(formula = dist ~ speed, data = cars); trained_model <- data.frame(payload = as.raw(serialize(lrmodel, connection=NULL)));' , @input_data_1 = N'' , @input_data_1_name = N'cars' , @output_data_1_name = N'trained_model' WITH RESULT SETS ((model varbinary(max))); END; GO ,因为你没有对你的moedel使用任何查询:

R

SQLRecyclerView结合起来非常有用。如有任何问题,请与我联系。