2016-08-05 2 views
0

저는 Microsoft의 "Data Science End to End Walkthrough"을 사용하여 R 서버로 설정하고 예제를 완벽하게 작동시킵니다.RevoScaleR : rxPredict, 매개 변수의 수가 변수의 수와 일치하지 않습니다.

예제 (뉴욕 택시 데이터)는 카테고리 변수 (팁 지불 여부에 대한 1 또는 0)를 예측하기 위해 비 카테고리 변수 (예 : 거리, 택시 요금 등)를 사용합니다.

선형 회귀 (rxLinMod 함수)를 사용하여 범주 형 변수를 입력으로 사용하여 유사한 이진 출력을 예측하려고합니다. 오류가 발생합니다.

오류는 매개 변수 수가 변수 수와 일치하지 않지만 실제로는 number of variables이 각 요소 (변수) 내의 수준 수인 것처럼 보입니다. 거기에

USE [my_database]; 
SET ANSI_NULLS ON; 
SET QUOTED_IDENTIFIER ON; 
CREATE TABLE [dbo].[example](
    [Person] [nvarchar](max) NULL, 
    [City] [nvarchar](max) NULL, 
    [Bin] [integer] NULL 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]; 

넣고 데이터 :

insert into [dbo].[example] values ('John','London',0); 
insert into [dbo].[example] values ('Paul','New York',0); 
insert into [dbo].[example] values ('George','Liverpool',1); 
insert into [dbo].[example] values ('Ringo','Paris',1); 
insert into [dbo].[example] values ('John','Sydney',1); 
insert into [dbo].[example] values ('Paul','Mexico City',1); 
insert into [dbo].[example] values ('George','London',1); 
insert into [dbo].[example] values ('Ringo','New York',1); 
insert into [dbo].[example] values ('John','Liverpool',1); 
insert into [dbo].[example] values ('Paul','Paris',0); 
insert into [dbo].[example] values ('George','Sydney',0); 
insert into [dbo].[example] values ('Ringo','Mexico City',0); 

가 나는 또한 변수를 반환하는 SQL 함수를 사용

는 SQL Server의 예를라는 테이블을 만들고 복제하려면 테이블 형식으로, Microsoft 예제 에서처럼 필요합니다. - PersonCity

USE [my_database]; 
SET ANSI_NULLS ON; 
SET QUOTED_IDENTIFIER ON; 
CREATE FUNCTION [dbo].[formatAsTable] (
@City nvarchar(max)='', 
@Person nvarchar(max)='') 
RETURNS TABLE 
AS 
    RETURN 
    (
    -- Add the SELECT statement with parameter references here 
    SELECT 
    @City AS City, 
    @Person AS Person 
); 

우리는 이제 두 개의 범주 변수 테이블이 : 함수 formatAsTable을 만듭니다.

예측을 시작해 보겠습니다. R에서 다음을 실행하십시오.

library(RevoScaleR) 
# Set up the database connection 
connStr <- "Driver=SQL Server;Server=<servername>;Database=<dbname>;Uid=<uid>;Pwd=<password>" 
sqlShareDir <- paste("C:\\AllShare\\",Sys.getenv("USERNAME"),sep="") 
sqlWait <- TRUE 
sqlConsoleOutput <- FALSE 
cc <- RxInSqlServer(connectionString = connStr, shareDir = sqlShareDir, 
        wait = sqlWait, consoleOutput = sqlConsoleOutput) 
rxSetComputeContext(cc) 
# Set the SQL which gets our data base 
sampleDataQuery <- "SELECT * from [dbo].[example] " 
# Set up the data source 
inDataSource <- RxSqlServerData(sqlQuery = sampleDataQuery, connectionString = connStr, 
           colClasses = c(City = "factor",Bin="logical",Person="factor" 
           ), 
           rowsPerRead=500)  

이제 선형 회귀 모델을 설정하십시오. 그것은 다음과 같습니다

isWonObj 

주의 사항 : 모델 객체에서

isWonObj <- rxLinMod(Bin ~ City+Person,data = inDataSource) 

봐는

... 
Total independent variables: 11 (Including number dropped: 3) 
... 

Coefficients: 
          Bin 
(Intercept)  6.666667e-01 
City=London  -1.666667e-01 
City=New York  4.450074e-16 
City=Liverpool 3.333333e-01 
City=Paris  4.720871e-16 
City=Sydney  -1.666667e-01 
City=Mexico City  Dropped 
Person=John  -1.489756e-16 
Person=Paul  -3.333333e-01 
Person=George   Dropped 
Person=Ringo   Dropped 

이것이의 합으로 괜찮 11 개 변수,가 말한다 요인의 수준. 내가 CityPerson에 따라 Bin 값을 예측하려고 할 때

지금, 오류가 발생합니다 :

먼저 나는 테이블로에 대한 예측 할 CityPerson 포맷합니다. 그런 다음 이것을 입력으로 사용하는 것이 좋습니다. 당신이 pred 객체를 선택하면

sq<-"SELECT City, Person FROM [dbo].[formatAsTable]('London','George')" 
pred<-RxSqlServerData(sqlQuery = sq,connectionString = connStr 
         , colClasses = c(City = "factor",Person="factor")) 

, 그것은 예상대로 보이는 : 나는 예측하려고 할 때

> head(pred) 
    City Person 
1 London George 

지금, 나는 오류가 발생합니다.11이 어디에서 오는지

INTERNAL ERROR: In rxPredict, the number of parameters does not match the number of variables: 3 vs. 11. 

내가 볼 수 있지만 난 단지 예측 쿼리에이 개 값을 제공 한 - 3 어디에서 오는지 그래서 내가 볼 수 없습니다

scoredOutput <- RxSqlServerData(
    connectionString = connStr, 
    table = "binaryOutput" 
) 

rxPredict(modelObject = isWonObj, data = pred, outData = scoredOutput, 
      predVarNames = "Score", type = "response", writeModelVars = FALSE, overwrite = TRUE,checkFactorLevels = FALSE) 

오류는 말한다 , 또는 문제가있는 이유.

도움을 주시면 감사하겠습니다.

답변

0

답은 R이 요인 변수를 처리하는 방법과 일치하는 것으로 보이지만 오류 메시지는 요인, 수준, 변수 및 매개 변수 사이에 더 명확한 구분을 할 수 있습니다.

예측을 생성하기 위해 입력 된 매개 변수는 단순히 레벨이없는 문자 또는 요인 일 수없는 것으로 보입니다. 그들은 모델 매개 변수화에서 사용 된 동일한 변수의 인수와 동일한 수준을 가져야합니다. 그런 다음 행으로

는 :

sq<-"SELECT City, Person FROM [dbo].[formatAsTable]('London','George')" 
pred<-RxSqlServerData(sqlQuery = sq,connectionString = connStr 
         , colClasses = c(City = "factor",Person="factor")) 

...이 교체해야합니다 :이없이 제대로 작동 범주 변수와 다른 예를 보았다

sq<-"SELECT City, Person FROM [dbo].[formatAsTable]('London','George')" 

column_information<-list(
    City=list(type="factor",levels=c("London","New York","Liverpool","Paris","Sydney","Mexico City")), 
    Person=list(type="factor",levels=c("John","Paul","George","Ringo")), 
    Bin=list(type="logical") 
) 

pred<-RxSqlServerData(sqlQuery = sq,connectionString = connStr 
         ,colInfo=column_information, 
         stringsAsFactors=FALSE) 

하지만, 어쨌든 거기에 레벨이 있었을지도 모릅니다.

내가 잃어버린 시간만큼 사람을 구 해주길 바랍니다. SLSvenR의 응답

에 대한

편집 나는 훈련이 보유하고 여전히 설정과 같은 수준을 가지고에 대한 내 의견을 생각합니다.

fac <- c("one", "two", "three") 
val = c(1, 2, 3) 
trainingData <- data.frame(fac, val, stringsAsFactors = TRUE) 
lmModel <- lm(val ~ fac, data = trainingData) 
print(summary(lmModel)) 
predictionData = data.frame(fac = c("one", "three", "one", "one")) 
lmPred <- predict(lmModel, newdata = predictionData) 
lmPred 
# The result is OK: 
# 1 2 3 4 
# 1 3 1 1 

levels(predictionData$fac)<-levels(trainingData$fac) 
# rxLinMod() and rxPredict() behave different: 
rxModel <- rxLinMod(val ~ fac, data = trainingData) 
rxPred <- rxPredict(rxModel, data = predictionData, writeModelVars = TRUE,checkFactorLevels = TRUE) 
rxPred 
# This result appears correct to me. 
나는이 좋은지 나쁜지 여부에 언급 할 수

- 그러나 이것이 당신이 할 수있는 가정 테스트 세트로 학습 데이터의 수준을 적용하는 것입니다 해결하기 위해 하나의 방법처럼 보인다 실시간.

0

colInfo를 지정하면 문제가 해결됩니까? 내 시나리오에서

# lm() and predict() don't have a problem with missing factor levels ("two" in this case): 
fac <- c("one", "two", "three") 
val = c(1, 2, 3) 
trainingData <- data.frame(fac, val, stringsAsFactors = TRUE) 
lmModel <- lm(val ~ fac, data = trainingData) 
print(summary(lmModel)) 
predictionData = data.frame(fac = c("one", "three", "one", "one")) 
lmPred <- predict(lmModel, newdata = predictionData) 
lmPred 
# The result is OK: 
# 1 2 3 4 
# 1 3 1 1 

# rxLinMod() and rxPredict() behave different: 
rxModel <- rxLinMod(val ~ fac, data = trainingData) 
rxPred <- rxPredict(rxModel, data = predictionData, writeModelVars = TRUE) 
# The following error is thrown: 
# "INTERNAL ERROR: In rxPredict, the number of parameters does not match 
# the number of variables: 3 vs. 4." 
# checkFactorLevels = FALSE doesn't help here, it actually seems to just 
# check the order of factor levels. 
levels(predictionData$fac) <- c("two", "three", "one") 
rxPred <- rxPredict(rxModel, data = predictionData, writeModelVars = TRUE) 
# The following error is thrown (twice): 
# ERROR:order of factor levels in the data are inconsistent with 
# the order of the model coefficients:fac = two versus fac = one. Set 
# checkFactorLevels = FALSE to ignore. 
rxPred <- rxPredict(rxModel, data = predictionData, checkFactorLevels = FALSE, writeModelVars = TRUE) 
rxPred 
# val_Pred fac 
#1 1   two 
#2 3   three 
#3 1   two 
#4 1   two 
# This looks suspicious at best. While the prediction values are still 
# correct if you look only at the order of the records in trainingData, 
# the model variables are messed up. 

내가 (단지 모델의 작성 중에라고도 함)에 대한 10.000 레벨을 가진 요소를 가지고 몇 가지 더 :은 SQL Server와 함께 rxPredict보다는 rxPredict 일반 문제가있는 것 같습니다 각 레벨은 약 5 단계입니다 (모델 작성 전에 알려짐). rxPredict()를 "올바른"순서로 호출하는 동안 모든 수준을 지정하는 것은 불가능한 것처럼 보입니다.

+0

본인의 원래 답변을 편집하여 문제를 통합했습니다. 올바르게 이해하면 도움이됩니다. –

0

레벨 (predictionData $ fac) < -levels (trainingData $ fac ...) 만 설정하면 오류가 발생하지 않으므로 모델에서 사용 된 잘못된 요소 색인으로 연결됩니다. writeModelVars가 TRUE로 설정된 경우 RxSqlServerData에서 거의 10.000 수준의 내 요인에 대해 colInfo를 설정하면 쿼리가 SQL Server에 올바르게 전달되었지만 응용 프로그램이 중지되었습니다.내가 어떤 요인없이 데이터 프레임에 데이터를로드로 내 전략을 변경 한 다음에 RxFactors을 적용

rxSetComputeContext를 ("로컬")

sqlPredictQueryDS < - RxSqlServerData (ConnectionString을 = sqlConnString,은 SQLQuery =에는 SQLQuery, stringsAsFactors = FALSE)

predictQueryDS = rxImport (sqlPredictQueryDS)

경우 %의 COLNAMES (predictQueryDS에서 ("Artikelnummer"%)) {predictQueryDS < - rxFactors (predictQueryDS, factorInfo = 목록 (Artikelnummer = 목록 (레벨 =의 allItems))) }

필요한 요인 수준을 설정하는 것 외에도 RxFactors는 요소 지수를 재정렬합니다. colInfo가있는 솔루션이 잘못되었다고 말하는 것이 아닙니다. 아마도 "너무 많은"수준의 요소에 대해서는 작동하지 않을 수도 있습니다.

+0

좋은 지적. 이와 같은 문제는 이후 내가 할 수있을 때마다 RevoScaleR 사용을 피하려고 노력한 이유입니다! –

관련 문제