5

現在、タイタニック データ セットを使用して Kaggle で R を練習しています。ランダム フォレスト アルゴリズムを使用しています。

以下はコードです

fit <- randomForest(as.factor(Survived) ~ Pclass + Sex + Age_Bucket + Embarked
                + Age_Bucket + Fare_Bucket + F_Name + Title + FamilySize + FamilyID, 
                data=train, importance=TRUE, ntree=5000)

次のエラーが表示されます

Error in randomForest.default(m, y, ...) : 
  NA/NaN/Inf in foreign function call (arg 1)
In addition: Warning messages:
1: In data.matrix(x) : NAs introduced by coercion
2: In data.matrix(x) : NAs introduced by coercion
3: In data.matrix(x) : NAs introduced by coercion
4: In data.matrix(x) : NAs introduced by coercion

私のデータは以下のようになります

$ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
$ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
$ Sex        : Factor w/ 2 levels "female","male": 2 1 1 1 2 2 2 2 1 1...
$ Age_Bucket : chr  "20-25" "30-40" "25-30" "30-40" ...
$ Fare_Bucket: chr  "<10" "30+" "<10" "30+" ...
$ Title      : Factor w/ 11 levels "Col","Dr","Lady",..: 7 8 5 8 7 7 7 4 8 8 ...
$ F_Name     : chr  "Braund" "Cumings" "Heikkinen" "Futrelle" ...
$ FamilySize : num  2 2 1 2 1 1 1 5 3 2 ...
$ Embarked   : Factor w/ 3 levels "C","Q","S": 3 1 3 3 3 2 3 3 3 1 ...
$ FamilyID   : chr  "Small" "Small" "Alone" "Small" ...

以下を入力するだけで、NA値を作成するために強制が発生する唯一の場所であることがわかる限り、強制の問題はありません

as.factor(Survived)

誰でも問題を見ることができますか

お時間をいただきありがとうございます

4

1 に答える 1

7

char列を因子に変換する必要があります。要素は内部的に整数として扱われますが、文字フィールドはそうではありません。次の小さなデモを参照してください。

データ:

df <- data.frame(y = sample(0:1, 26, rep=T), x1=runif(26), x2=letters, stringsAsFactors=F)

df$y <- as.factor(df$y)

> str(df)
'data.frame':   26 obs. of  3 variables:
 $ y : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 2 2 1 ...
 $ x1: num  0.457 0.296 0.517 0.478 0.764 ...
 $ x2: chr  "a" "b" "c" "d" ...

randomForest関数を実行すると、次のようになります。

> randomForest(y ~ x1 + x2, data=df)
Error in randomForest.default(m, y, ...) : 
  NA/NaN/Inf in foreign function call (arg 1)
In addition: Warning message:
In data.matrix(x) : NAs introduced by coercion

あなたと同じエラーが発生します。

char一方、列を次のように変換するとfactor:

df$x2 <- as.factor(df$x2)

> randomForest(y ~ x1 + x2, data=df)

Call:
 randomForest(formula = y ~ x1 + x2, data = df) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 1

        OOB estimate of  error rate: 61.54%
Confusion matrix:
  0  1 class.error
0 0 16           1
1 0 10           0

それはうまくいきます!

于 2015-05-10T13:47:46.667 に答える