1

私はRtmパッケージを使用して、コーパスをトレーニングセットとテストセットに分割し、これを選択のためにメタデータにエンコードしようとしています。これを行う最も簡単な方法は何ですか(サンプルを半分に分割しようとしていると仮定します)?

これが私が試したいくつかのことです:

  1. 私がタイプするとき、私はそれを知っています...
> meta(d)
    MetaID Y
1        0 1
2        0 1

IDは表示されますが、アクセスできないようです(前半はあるセットに属し、後半は別のセットに属していると言うため)。 rownames(attributes(d)$DMetaData)インデックスを教えてくれますが、これは見苦しく、要因です。

  1. ここで、データフレームに変換した後、dが私のデータセットであると言うと、次のようになります。
half <- floor(dim(d)[1]/2)
d$train <- d[1:half,]
d$test <- d[(half+1):(half*2),]

しかし、どうすれば簡単に次のようなことができますか...

meta(d, tag="split") = ifelse((meta(d,"ID")<=floor(length(d)/2)),"train","test")

...次のような結果を得るには:

> meta(d)
    MetaID Y split
1        0 1 train
2        0 1 train
...      . . ...
100      0 1 test

残念ながら、meta(d,"ID")機能しませんが、meta(d[[1]],"ID") == 1機能しますが、冗長です。メタIDにアクセスするベクトル全体の方法、または「分割」メタ変数にサブセット化して割り当てる一般的にスマートな方法を探しています。

4

2 に答える 2

4

コーパスは単なるリストです。したがって、通常のリストのように分割できます。ここに例があります:

いくつかのデータを作成します。tmパッケージ内のデータを使用します

txt <- system.file("texts", "txt", package = "tm")
(ovid <- Corpus(DirSource(txt)))
A corpus with 5 text documents

次に、データをトレーニングとテストに分割します

nn <- length(ovid)
ff <- as.factor(c(rep('Train',ceiling(nn/2)),   ## you create the split factor as you want
                rep('Test',nn-ceiling(nn/2))))  ## you can add validation set for example...
ll <- split(as.matrix(ovid),ff)
ll
$Test
A corpus with 2 text documents

$Train
A corpus with 3 text documents

次に、新しいタグを割り当てます

ll <- sapply( names(ll),
              function(x) {
                meta(ll[[x]],tag = 'split') <- ff[ff==x]
                ll[x]
              })

結果を確認できます。

lapply(ll,meta)
$Test.Test
  MetaID split
4      0  Test
5      0  Test

$Train.Train
  MetaID split
1      0 Train
2      0 Train
3      0 Train
于 2013-02-12T01:59:12.150 に答える
2
## use test corpus crude in tm
library(tm)
data(crude)

#random training sample
half<-floor(length(crude)/2)
train<-sample(1:length(crude), half)

# meta doesnt handle lists or vector very well, so loop:
for (i in 1:length(crude)) meta(crude[[i]], tag="Tset") <- "test"
for (i in 1:half) meta(crude[[train[i]]], tag="Tset") <- "train"

# check result
for (i in 1:10) print(meta(crude[[i]], tag="Tset"))

これはうまくいくようです。

于 2013-02-12T20:35:59.147 に答える