我运行了以下的编码,但是不论在data输入什么数据,最后print输出的都是空白。我是想用格拉布斯检验法检测数据异常值。我不会自己写代码,今天自己摸索着装上了Python和Pycharm以及一系列的第三方数据库,一开始使用from import这个命令完全不能运行,一直显示unresloved reference,然后我根据教材改了PATH还有虚拟环境啥的,也不知道弄对了没有,反正可以用了。但是后续就是只有在第一次输入数据串的时候运行出了结果,后面不论我怎么换数据,结果都是空的。
import numpy as np
from scipy.stats import t
def grubbs_test(data, alpha):
n = len(data)
mean = np.mean(data)
std_dev = np.std(data)
t_critical = t.ppf(1 - alpha / (2 * n), n - 2)
# Find the maximum absolute deviation from the mean
max_deviation = np.max(np.abs(data - mean))
# Calculate the test statistic
G = max_deviation / std_dev
# Calculate the critical value
critical_value = (n - 1) / np.sqrt(n) * np.sqrt(t_critical ** 2 / (n - 2 + t_critical ** 2))
# Determine if the maximum deviation is an outlier
is_outlier = G > critical_value
# Return the data without outliers
return data[~is_outlier]
# Example usage
data = np.array([73.15, 60.80, 85.39, 103.81, 110.92, 100.92, 109.63, 108.21])
alpha = 0.05
data_without_outliers = grubbs_test(data, alpha)
print("Data without outliers:", data_without_outliers)
运行结果如下:
D:\PYCharm\Scripts\python.exe "C:\Users\Administrator\PycharmProjects\pythonProject\Grubbs Test final.py"
Data without outliers: []
Process finished with exit code 0