You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中生成满足联合比例约束的二元合成数据集

生成满足联合约束的二元合成数据集问题

给定的约束条件存在数学矛盾,无法同时满足:

  • 已知P(A=1)=0.6,因此P(A=0)=0.4;同时要求P(A=0,B=0)=0,意味着所有A=0的样本中B必须为1,即P(A=0,B=1)=P(A=0)=0.4。
  • 要求P(B=1)=0.8,而P(B=1)=P(A=1,B=1)+P(A=0,B=1),代入得0.8=P(A=1,B=1)+0.4 → P(A=1,B=1)必须为0.4,但你要求该比例为0.25,两者冲突。
  • 反之,如果坚持P(A=1,B=1)=0.25,结合P(A=0,B=1)=0.4,P(B=1)最多只能是0.65,无法达到0.8。

方案1:调整约束为可行组合

如果保留「A=1占60%、B=1占80%、同时为0占0%」,则同时为1的比例必须为40%(由P(A∪B)=1推导:0.6+0.8-P(A∩B)=1 → P(A∩B)=0.4)。以下是生成该数据集的R代码:

n <- 1000  # 样本量

# 计算各单元格的样本数
count_A1B1 <- round(n * 0.4)
count_A1B0 <- round(n * 0.6) - count_A1B1
count_A0B1 <- round(n * 0.4)  # A=0时B必为1,样本数等于A=0的总样本量
count_A0B0 <- 0

# 生成各组合的样本
dat <- data.frame(
  A = c(rep(1, count_A1B1), rep(1, count_A1B0), rep(0, count_A0B1)),
  B = c(rep(1, count_A1B1), rep(0, count_A1B0), rep(1, count_A0B1))
)

# 打乱样本顺序
dat <- dat[sample(nrow(dat)), ]
rownames(dat) <- NULL

# 验证比例
cat("A=1比例:", mean(dat$A), "\n")
cat("B=1比例:", mean(dat$B), "\n")
cat("同时为1比例:", mean(dat$A & dat$B), "\n")
cat("同时为0比例:", mean(!dat$A & !dat$B), "\n")

方案2:近似满足原约束(允许比例误差)

如果必须接近原约束的比例,只能优先满足部分约束,让其余比例尽可能接近目标。以下代码优先保证「同时为1占25%、同时为0占0%、A=1占60%」,调整B的比例:

n <- 1000

# 优先固定同时为1和同时为0的样本数
count_A1B1 <- round(n * 0.25)
count_A0B0 <- 0

# 分配A=1剩余样本到B=0
count_A1B0 <- round(n * 0.6) - count_A1B1

# A=0的样本只能全部分配给B=1(受A=0总样本量限制)
count_A0B1 <- n - count_A1B1 - count_A1B0 - count_A0B0

# 生成数据集
dat <- data.frame(
  A = c(rep(1, count_A1B1), rep(1, count_A1B0), rep(0, count_A0B1)),
  B = c(rep(1, count_A1B1), rep(0, count_A1B0), rep(1, count_A0B1))
)

# 打乱顺序
dat <- dat[sample(nrow(dat)), ]
rownames(dat) <- NULL

# 验证比例
cat("A=1比例:", mean(dat$A), "\n")
cat("B=1比例:", mean(dat$B), "\n")
cat("同时为1比例:", mean(dat$A & dat$B), "\n")
cat("同时为0比例:", mean(!dat$A & !dat$B), "\n")

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 09:20:15