如何用文本和数字变量训练套索?
how to train a lasso with both text and numeric variables?
考虑这个修改后的经典示例:
library(dplyr)
library(tibble)
dtrain <- data_frame(text = c("Chinese Beijing Chinese",
"Chinese Chinese Shanghai",
"France",
"Tokyo Japan Chinese"),
add_numeric = c(1, 1, 0, 1),
doc_id = 1:4,
class = c(1, 1, 1, 0))
> dtrain
# A tibble: 4 x 4
text add_numeric doc_id class
<chr> <dbl> <int> <dbl>
1 Chinese Beijing Chinese 1 1 1
2 Chinese Chinese Shanghai 1 2 1
3 France 0 3 1
4 Tokyo Japan Chinese 1 4 0
在这里,我想用套索来预测class
。感兴趣的变量是 text
和 add_numeric
.
我知道如何使用 text2vec
或 tm
仅使用 text
来预测 class
:包会将 text
转换为稀疏文档术语矩阵并提供给模型。
但是,在这里,我想同时使用文本变量 text
和 add_numeric
。我不知道如何混合这两种方法。有任何想法吗?
谢谢!
我还没有检查如何使用 text2vec 执行此操作,但是使用 quanteda 这很容易做到,只需使用 cbind
并且优点是保持稀疏矩阵。我没有更改 dimnames,所以添加的列将显示为 feat1。
library(quanteda)
dtm <- dfm(dtrain$text) # create documenttermmatrix
dtm_num <- cbind(dtm, dtrain$add_numeric) # add column to sparse matrix.
dtm_num
Document-feature matrix of: 4 documents, 7 features (60.7% sparse).
4 x 7 sparse Matrix of class "dfm"
features
docs chinese beijing shanghai france tokyo japan feat1
text1 2 1 0 0 0 0 1
text2 2 0 1 0 0 0 1
text3 0 0 0 1 0 0 0
text4 1 0 0 0 1 1 1
考虑这个修改后的经典示例:
library(dplyr)
library(tibble)
dtrain <- data_frame(text = c("Chinese Beijing Chinese",
"Chinese Chinese Shanghai",
"France",
"Tokyo Japan Chinese"),
add_numeric = c(1, 1, 0, 1),
doc_id = 1:4,
class = c(1, 1, 1, 0))
> dtrain
# A tibble: 4 x 4
text add_numeric doc_id class
<chr> <dbl> <int> <dbl>
1 Chinese Beijing Chinese 1 1 1
2 Chinese Chinese Shanghai 1 2 1
3 France 0 3 1
4 Tokyo Japan Chinese 1 4 0
在这里,我想用套索来预测class
。感兴趣的变量是 text
和 add_numeric
.
我知道如何使用 text2vec
或 tm
仅使用 text
来预测 class
:包会将 text
转换为稀疏文档术语矩阵并提供给模型。
但是,在这里,我想同时使用文本变量 text
和 add_numeric
。我不知道如何混合这两种方法。有任何想法吗?
谢谢!
我还没有检查如何使用 text2vec 执行此操作,但是使用 quanteda 这很容易做到,只需使用 cbind
并且优点是保持稀疏矩阵。我没有更改 dimnames,所以添加的列将显示为 feat1。
library(quanteda)
dtm <- dfm(dtrain$text) # create documenttermmatrix
dtm_num <- cbind(dtm, dtrain$add_numeric) # add column to sparse matrix.
dtm_num
Document-feature matrix of: 4 documents, 7 features (60.7% sparse).
4 x 7 sparse Matrix of class "dfm"
features
docs chinese beijing shanghai france tokyo japan feat1
text1 2 1 0 0 0 0 1
text2 2 0 1 0 0 0 1
text3 0 0 0 1 0 0 0
text4 1 0 0 0 1 1 1