glmnet
andonehot
パッケージを使用してridge / lassoを実行しようとすると、エラーが発生します。
library(glmnet)
library(onehot)
set.seed(123)
Sample <- HouseData[1:1460, ]
smp_size <- floor(0.5 * nrow(Sample))
train_ind <- sample(seq_len(nrow(Sample)), size = smp_size)
train <- Sample[train_ind, ]
test <- Sample[-train_ind, ]
############Ridge & Lasso Regressions ################
# Define the response for the training + test set
y_train <- train$SalePrice
y_test <- test$SalePrice
# Define the x training and test
x_train <- train[,!names(train)=="SalePrice"]
x_test <- test[,!names(train)=="SalePrice"]
str(y_train)
## encoding information for training set
x_train_encoded_data_info <- onehot(x_train,stringsAsFactors = TRUE, max_levels = 50)
x_train_matrix <- (predict(x_train_encoded_data_info,x_train))
x_train_matrix <- as.matrix(x_train_matrix)
# create encoding information for x test
x_test_encoded_data_info <- onehot(x_test,stringsAsFactors = TRUE, max_levels = 50)
x_test_matrix <- (predict(x_test_encoded_data_info,x_test))
str(x_train_matrix)
###Calculate best lambda
cv.out <- cv.glmnet(x_train_matrix, y_train,
alpha = 0, nlambda = 100,
lambda.min.ratio = 0.0001)
best.lambda <- cv.out$lambda.min
best.lambda
model <- glmnet(x_train_matrix, y_train, alpha = 0, lambda = best.lambda)
results_ridge <- predict(model,newx=x_test_matrix)
データがクリーンで、行列が同じサイズであることはわかっていますが、予測を実行しようとすると、このエラーが発生し続けます。
h(simpleError(msg、call))のエラー:関数 'as.matrix'のメソッドを選択する際の引数 'x'の評価エラー:Cholmodエラー 'Xおよび/またはYの次元が間違っています'ファイル../MatrixOps /cholmod_sdmult.c、90行目
教授から、データを分割する前にワンホットエンコードするように言われましたが、それは私には意味がありません。
onehot
コード内の関数がどこから来ているのかが完全に明確ではないため、その特定のエラーをデバッグするのは困難です。ベースR
またはglmnet
パッケージには存在しません。
とは言うものの、への引数を作成するには、古い組み込みのスタンバイ関数model.matrix
(または、sparse.model.matrix
より大きなデータセットがある場合はそのスパースないとこ)を使用することをお勧めします。自動的にワンホットエンコード係数またはカテゴリ変数を使用します。入力としてモデル式が必要です。これは、以下に示すようにデータセットから作成できます。x
glmnet
model.matrix
# create the model formula
y_variable <- "SalePrice"
model_formula <- as.formula(paste(y_variable, "~",
paste(names(train)[names(train) != y_variable], collapse = "+")))
# test & train matrices
x_train_matrix <- model.matrix(model_formula, data = train)[, -1]
x_test_matrix <- model.matrix(model_formula, data = test)[, -1]
###Calculate best lambda
cv.out <- cv.glmnet(x_train_matrix, y_train,
alpha = 0, nlambda = 100,
lambda.min.ratio = 0.0001)
2番目の新しいオプションは、組み込みglmnet
関数を使用することですmakeX()
。この関数は、テスト/トレーニングデータフレームから行列を作成します。これはちょうどに供給することができるcv.glmnet
ようx
、以下のように引数。
## option 2: use glmnet built in function to create x matrices
x_matrices <- glmnet::makeX(train = train[, !names(train) == "SalePrice"],
test = test[, !names(test) == "SalePrice"])
###Calculate best lambda
cv.out <- cv.glmnet(x_matrices$x, y_train,
alpha = 0, nlambda = 100,
lambda.min.ratio = 0.0001)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加