Showing posts with label Data Science. Show all posts
Showing posts with label Data Science. Show all posts

Monday, December 10, 2018

Part 1: Questions and answer about R service in SQL Server

How to verify R exists in your SQL instance
Run the code below, sometime you might need to enable external scripting and SQL Server Launchpad service to start.
EXECUTE sp_execute_external_script
@language =N'R',
@script=N'print(version)';
GO
You can see that SQL Server in this case have R version 3.3.3


How to get the list of R packages that are already installed in your SQL Server instance
EXECUTE sp_execute_external_script
@language = N'R'
, @script = N'
OutputDataSet <- data.frame(installed.packages()[,c("Package", "Version", "Depends", "License","LibPath")]);'
WITH result sets((Package NVARCHAR(255), Version NVARCHAR(100), Depends NVARCHAR(4000), License NVARCHAR(1000), LibPath NVARCHAR(2000)));


What are the parameters available can be used to execute sp_execute_external_script
sp_execute_external_script   
   @language = N'language',   
   @script = N'script'  
   [ , @input_data_1 = N'input_data_1' ]   
   [ , @input_data_1_name = N'input_data_1_name' ]  
   [ , @output_data_1_name = N'output_data_1_name' ]  
   [ , @parallel = 0 | 1 ]  
   [ , @params = N'@parameter_name data_type [ OUT | OUTPUT ] [ ,...n ]' ]
   [ , @parameter1 = 'value1' [ OUT | OUTPUT ] [ ,...n ] ]
WITH RESULT SET ()
Let’s looks a simple example:
EXECUTE sp_execute_external_script
   @language = N'R'
   , @script = N'OutputDataSet <- InputDataSet;'
   , @input_data_1 = N'SELECT ''Uma'',''Bale'',38;'
WITH RESULT SETS (([FirstName] NVARCHAR(5),[LastName] NVARCHAR(5),[Age] INT));

@language = N'language'
Indicates the script language. The valid values are R (SQL Server 2016 and later), Python (SQL Server 2017 and later), and Java (SQL Server 2019 preview)
@script = N'script'
External language script specified as a literal or variable input. Script is nvarchar(max). Default input and output variables of sp_execute_external_script: InputDataSet and OutputDataSet
@input_data_1
specifies the input data used by the external script in the form of a Transact-SQL query. The data type of input_data_1 is nvarchar(max).
@input_data_1_name
Specifies the name of the variable used to represent the query defined by @input_data_1. The data type of the variable in the external script depends on the language. In case of R, the input variable is a data frame. In the case of Python, input must be tabular. input_data_1_name is sysname. Default value is InputDataSet.
@output_data_1_name
Specifies the name of the variable in the external script that contains the data to be returned to SQL Server upon completion of the stored procedure call. The data type of the variable in the external script depends on the language. For R, the output must be a data frame. For Python, the output must be a pandas data frame. output_data_1_name is sysname. Default value is OutputDataSet.
@parallel
Enable parallel execution of R scripts by setting the @parallel parameter to 1. The default for this parameter is 0 (no parallelism).
WITH RESULT SET
By default, result sets returned by this stored procedure are output with unnamed columns. Column names used within a script are local to the scripting environment and are not reflected in the outputted result set. To name result set columns, use the WITH RESULT SET clause of EXECUTE.
EXECUTE sp_execute_external_script
 @language = N'R'
 , @script = N' SQL_out <- SQL_in * 5;'
 , @input_data_1 = N'SELECT 2 as Col;'
 , @input_data_1_name  = N'SQL_in'
 , @output_data_1_name =  N'SQL_out'
 WITH RESULT SETS (([Output] INT NOT NULL));
Cheers!
Uma

Saturday, April 8, 2017

PREDICTIVE Analytics with Microsoft SQL Server R Service

Predictive analytics involves extracting data from existing data sets with the goal of identifying trends and patterns. These trends and patterns are then used to predict future outcomes and trends. In this post, I am trying to explain how to use Predictive Analysis using Microsoft SQL Server R service.
In this example, salary will be predicted based on other know fields age, experience and gender.

Using R Studio
First, let’s see how to use R Studio for this prediction
-- Set the default path
> setwd("C:/Learn/DataScience")
-- Load data from csv file to variable called InputData
> InputData <- read.csv("data.csv")
For this prediction Linear Regression is going to used. There are mainly 2 type of linear regressions used.
  1. Simple Linear Regression
  2. Multiple Linear Regression
Simple Linear Regression
Simple linear regression is a statistical method that allows us to summarize and study relationships between two continuous (quantitative) variables:
• One variable, denoted x, is regarded as the predictor, explanatory, or independent variable.
• The other variable, denoted y, is regarded as the response, outcome, or dependent variable.
Because the other terms are used less frequently today, we'll use the "predictor" and "response" terms to refer to the variables encountered in this course. The other terms are mentioned only to make you aware of them should you encounter them in other arenas. Simple linear regression gets its adjective "simple," because it concerns the study of only one predictor variable. In contrast, multiple linear regression, which we study later in this course, gets its adjective "multiple," because it concerns the study of two or more predictor variables.
Multiple Linear Regression

We move from the simple linear regression model with one predictor to the multiple linear regression model with two or more predictors. That is, we use the adjective "simple" to denote that our model has only predictor, and we use the adjective "multiple" to indicate that our model has at least two predictors.
Please read more information here.
R provides comprehensive support for linear regression.
lm() is a linear model function, such like linear regression analysis.

lm(formula, data, subset, weights, ...)
formula: model description, such as x ~ y
data: optional, variables in the model
subset: optional, a subset vector of observations to be used in the fitting process
weights: optional, a vector of weights to be used in the fitting process
> Model <- lm(InputData$Salary~InputData$Age+InputData$Experience+factor(InputData$Gender))
> summary (Model)
The important part of model out is highlighted below.
InputData$Salary~InputData$Age+InputData$Experience+factor(InputData$Gender)
You can have noticed that Gender field is used as factor, so the interpretation of the above outcome.
If Gender = Male, Then
Salary = (-13061124) + (-473000 * PredictSal$Experience) + (592065 * PredictSal$Age) + 683640
If Gender = Female, Then
Salary = (-13061124) + (-473000 * PredictSal$Experience) + (592065 * PredictSal$Age)

Visual Studio
Now let’s see how to use Visual Studio instead of R Studio with SQL Server. The below image shows that how the data is stored in a table in SQL Server database.
To following screenshots shows the prediction in Visual studio
<Code>
install.packages("RODBC")
library("RODBC")
cn <- odbcDriverConnect(connection = "Driver={SQL Server Native Client 11.0};Server=THETA362L\\MSSQLSERVER2016;Database=R_Sample;Trusted_Connection=yes;")
SalData <- sqlQuery(cn, "SELECT [Salary],[Age],[Experience],[Gender],[Type] FROM [R_Sample].[dbo].[Salary] WHERE [Salary] IS NOT NULL AND [Type]='HISTORICAL'")
View(SalData)
SalData
Model <- lm(SalData$Salary ~ SalData$Experience + SalData$Age + factor(SalData$Gender))
summary(Model)
PredictSal <- sqlQuery(cn, "SELECT [Salary],[Age],[Experience],[Gender],[Type] FROM [R_Sample].[dbo].[Salary] WHERE [Salary] IS NULL AND [Type]='PREDICTED'")
PredictSal
PredictSal$Age <- as.numeric(as.character(PredictSal$Age))
PredictSal$Experience <- as.numeric(as.character(PredictSal$Experience))

PredictSal$Salary <- ifelse(PredictSal$Gender == "Male"
   , ((-13061124) + (-473000) * PredictSal$Experience + 592065 * PredictSal$Age + 683640)
   , ((-13061124) + (-473000) * PredictSal$Experience + 592065 * PredictSal$Age))
PredictSal

Using SQL Server Management Studio
You can run the R code in SQL Server Management studio via external script. You need to follow the below steps to run the R script.
First configure the SQL Server and restart to enable to run the external scripts
sp_configure
GO
sp_configure 'external scripts enabled',1;
GO
RECONFIGURE
GO

If you get the following error message while you run the R script please make sure you enable the Lunch Pad.
SQL Server was unable to communicate with the LaunchPad service. Please verify the configuration of the service.
Administrative Tools -> Services 
and find "SQL Server LaunchPad (MSSQLSERVER)"
right-click it and select "Start" and my scripts run again.
Create the stored procedure as shown below
CREATE PROCEDURE dbo.PredictSalary
AS
BEGIN
EXEC sp_execute_external_script
@language = N'R'
,@script = N'
PredictSal <- InputDataSet
PredictSal <- setNames(PredictSal, c("Age","Experience","Gender"))
PredictSal$Age <- as.numeric(as.character(PredictSal$Age))
PredictSal$Experience <- as.numeric(as.character(PredictSal$Experience))
PredictSal$Salary <-0
PredictSal$Salary <- ifelse(PredictSal$Gender == "Male"
   , ((-13061124) + ((-473000) * PredictSal$Experience) + (592065 * PredictSal$Age) + 683640)
   , ((-13061124) + ((-473000) * PredictSal$Experience) + (592065 * PredictSal$Age)))
OutputDataSet <- PredictSal'
,@input_data_1 = N'SELECT [Age],[Experience],[Gender] FROM [R_Sample].[dbo].[Salary] WHERE [Salary] IS NULL AND [Type]=''PREDICTED'''
,@output_data_1_name = N'OutputDataSet'
WITH RESULT SETS ((
"Age" INT NOT NULL,
"Experience" FLOAT NOT NULL,
"Gender" VARCHAR(10) NOT NULL,
"Salary" INT NOT NULL));
END

If you run the stored procedure, you will find the outcome as shown below.
EXEC dbo.PredictSalary
You can add the following logic to update prediction outcome automatically into the table.

CREATE TABLE #TEMP (Age INT, Experience INT, Gender VARCHAR(10), Salary INT)
GO
INSERT INTO #TEMP
EXEC dbo.PredictSalary
GO
SELECT * FROM #TEMP
GO
UPDATE E
SET E.Salary=T.Salary
FROM dbo.Salary E INNER JOIN #TEMP T ON E.Age=T.Age AND E.Experience=T.Experience AND E.Gender=T.Gender
WHERE E.Salary IS NULL AND E.Type ='PREDICTED'
The table will get update once you run the script.

Cheers! Uma