如何生成具有预测概率的随机数据集?

How to generate random data set with predicted probability?

我正在努力生成具有多项逻辑回归预测概率的随机数据集。

举个例子。我将使用 nnet 包进行多项逻辑回归。我还将使用 rattle.data 包中的 wine 数据集。

library("nnet")
library("rattle.data")
data(wine)
multinom.fit<-multinom(Type~Alcohol+Color,data=wine)
summary(multinom.fit)

Call:
multinom(formula = Type ~ Alcohol + Color - 1, data = wine)

Coefficients:
     Alcohol      Color
2  0.6258035 -1.9480658
3 -0.3457799  0.6944604

Std. Errors:
     Alcohol     Color
2 0.10203198 0.3204171
3 0.07042968 0.1479679

Residual Deviance: 222.5608 
AIC: 230.5608 

fit<-fitted(multinom.fit)
head(fit)

          1            2          3
1 0.6705935 0.0836177621 0.24578870
2 0.5050334 0.3847919037 0.11017466
3 0.6232029 0.0367975986 0.33999948
4 0.3895445 0.0007888818 0.60966664
5 0.4797392 0.4212542898 0.09900655
6 0.5510792 0.0077589278 0.44116190

因此,fit 数据集是 178*3 数据帧。我想使用预测概率生成 100 个随机数据集。例如,fit 数据集中的第一个样本有大约 0.67 的概率为“1”,0.08 为“2”,0.24 为“3”。每个样本都是独立招募(收集?)的。

有没有办法实现?

你可以试试:

rand.list <- lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ]))
rand.df   <- data.frame(matrix(unlist(rand.list), ncol = nrow(fit)))

它将为您提供一个 data.frame,其中包含 100 个观察值和 178 列,fit 中每一行的抽样概率不同。

对不起,我的表达有误。

比如我执行你的代码,结果是这样的

head(lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ])))
[[1]]
  [1] 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1
 [61] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3 1 1 1 1 1 1 1 1 1 1 1 1 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1 1 1 1 1 1 1 1 1 1 3 1 3 1 1 3 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

但是,在data.frame中是否有另一种表达方式?当我执行 data.frame 函数时,结果是这样的。

head(data.frame(lapply(1:nrow(fit), function(x) sample(1:3, 100, replace = TRUE, prob = fit[x, ]))))

*虽然执行了head函数,但是数据太长了。我复制了最后两行。

  c.3L..1L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..3L..
1                                                              3
2                                                              1
3                                                              3
4                                                              3
5                                                              3
  c.3L..1L..1L..1L..3L..3L..3L..1L..1L..1L..3L..1L..1L..3L..1L..
1                                                              3
2                                                              1
3                                                              1
4                                                              1
5                                                              3
 [ reached 'max' / getOption("max.print") -- omitted 1 rows ]

我想这样表达数据

   1 2 3 4 5 .... (ommited)
1 1 1 3 1 1
2 1 1 3 1 1
3 1 3 3 1 1
4 1 3 1 1 3
5 1 1 3 1 1
... (omited)

因此,data.frame 为 178*100。 178为样本数,100为随机生成试验数