首页 > 解决方案 > 制作稀疏矩阵时缺少列 (R)

问题描述

我有两个数据集train(这个包含变量date, store, item)和test(其中有id, date,store, item)我已经组合成一个df_all然后再次分区,因为我想最终使用train数据集来创建一个预测模型sales

的结构df_all

    'data.frame':   958000 obs. of  5 variables:
 $ date : Factor w/ 1916 levels "2013-01-01","2013-01-02",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ store: int  1 1 1 1 1 1 1 1 1 1 ...
 $ item : int  1 1 1 1 1 1 1 1 1 1 ...
 $ sales: num  13 11 14 13 10 12 10 9 12 9 ...
 $ id   : Factor w/ 45001 levels "0","1","10","100",..: 45001 45001 45001 45001 45001 45001 45001 45001 45001 45001 ...`

对数据进行分区,如:

set.seed(1234)
n = nrow(df_all)
index = sample(1:n, size = round(0.7*n), replace=T)
train = df_all[index, ]
test = df_all[-index, ]

然后使用 one-hot 编码,因为id它是一个分类变量:

trainm <- sparse.model.matrix(sales ~ ., data= train)[,-1]

除了这是我遇到问题的地方,因为我的矩阵最终看起来像

6 x 46917 sparse Matrix of class "dgCMatrix"
   [[ suppressing 20 column names ‘date2013-01-02’, ‘date2013-01-03’, ‘date2013-01-04’ ... ]]

108928 . . . . . . . . . . . . . . . . . . . .
596163 . . . . . . . . . . . . . . . . . . . .
583686 . . . . . . . . . . . . . . . . . . . .
597198 . . . . . . . . . . . . . . . . . . . .
824757 . . . . . . . . . . . . . . . . . . . .
613418 . . . . . . . . . . . . . . . . . . . .

108928 ......
596163 ......
583686 ......
597198 ......
824757 ......
613418 ......

 .....suppressing columns in show(); maybe adjust 'options(max.print= *, width = *)'
 ..............................

这看起来不像我需要的稀疏矩阵,并且出现了奇怪的情况,列不是它们应有的样子(即日期、ID、商店、商品、销售)。因此,如果有人对如何解决此问题有任何建议,或者如果有其他方法可以做到这一点,我们将不胜感激!

标签: rmachine-learningone-hot-encoding

解决方案


在拆分主数据集之前,我们应该始终进行 one-hot 编码。原因是,有时您可能会在测试中发现不在训练中的值,在这种情况下,您无法训练/预测模型,因为总列数会不匹配。

因此你应该这样做:

# ohe columns
df_ohe <- model.matrix(~.-1, data = df_all[,-c('id','date')])

# join id column with ohe columns
df_all_new <- cbind(df_all[,1], df_ohe)

而且,现在您可以将数据拆分为训练和测试。


推荐阅读