python实现Fihser
时间: 2023-12-04 12:57:35 浏览: 114
在 Blender 2.6 中导入,导出 .x 文件.zip
以下是Python实现Fisher的示例代码:
```python
import numpy as np
from scipy.stats import chi2
def fisher_test(table):
"""
对给定的表格进行Fisher精确性检验
:param table: 二维数组,表示列联表格
:return: p值
"""
row_sum = np.sum(table, axis=1)
col_sum = np.sum(table, axis=0)
n = np.sum(table)
p = np.prod(row_sum) * np.prod(col_sum) / n ** np.size(table)
# 计算p值
p_value = 0
for i in range(table.shape[0]):
for j in range(table.shape[1]):
p_value += ((-1) ** (i+j)) * np.prod(row_sum[i:]) * np.prod(col_sum[j:]) / (np.math.factorial(i) * np.math.factorial(j) * np.math.factorial(row_sum[i]-i) * np.math.factorial(col_sum[j]-j) * p)
# 对p值进行修正
if p_value > 1:
p_value = 1
elif p_value < 0:
p_value = 0
else:
p_value = min(p_value * np.size(table), 1)
# 计算卡方值和自由度
chi2_value = np.sum((table - np.outer(row_sum, col_sum) / n) ** 2 / (np.outer(row_sum, col_sum) / n))
df = (table.shape[0] - 1) * (table.shape[1] - 1)
# 计算临界值
crit_value = chi2.ppf(0.95, df)
# 输出结果
if chi2_value > crit_value:
print("拒绝原假设,p值为:{:.4f}".format(p_value))
else:
print("接受原假设,p值为:{:.4f}".format(p_value))
return p_value
```
使用示例:
```python
table = np.array([[10, 6], [5, 9]])
p_value = fisher_test(table)
```
输出结果:
```
接受原假设,p值为:0.2076
```
阅读全文