bootstrap重抽样代码
时间: 2024-12-21 12:01:20 浏览: 9
Bootstrap重抽样是一种统计学方法,用于估计样本统计量的不确定性。在Python中,我们可以利用`bootstrap`库来实现。以下是简单的Bootstrap重抽样代码示例:
```python
from sklearn.datasets import load_iris
import numpy as np
from scipy.stats import ttest_ind
from bootstrapped.bootstrap import Bootstrap
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 假设我们要比较两组数据的均值
group1, group2 = X[y == 0], X[y == 1]
# 定义Bootstrap函数
def sample_t_test(data1, data2):
mean_diff = np.mean(data1) - np.mean(data2)
return mean_diff
# 使用Bootstrap进行重抽样
bootstrap = Bootstrap(np.concatenate((group1, group2)), n_samples=1000)
bootstraped_results = bootstrap.sample(sample_t_test)
# 输出平均差分以及置信区间
mean_difference, ci = bootstraped_results.quantile([.5, .025, .975])
print(f"Mean difference: {mean_difference}")
print(f"95% Confidence Interval: ({ci[0]}, {ci[2]})")
阅读全文