首页 > 解决方案 > 通过使用python消除异常值达到目标斜率值

问题描述

我有一个数据集,我可以从中消除最多两个数据点以达到目标斜率 10。我拒绝异常值的标准是,如果斜率在 +/-5% 范围内,如果目标值 (10),则为 ALL好的。但是,高于此的任何内容都应删除。

一个试验数据集如下:

数据集

从图像左侧可以看出,得到了三个斜率=11.6、10.5和9.4。然而,目标斜率是 10。

在数据的右侧,我删除了倾斜斜率的数据点,即不允许它达到目标斜率 10。

这只是一个构建的数据集,但概念类似于我对最终数据集的需要。

我该如何在python中做呢?非常感谢您对此事的任何帮助。

标签: pythonpython-3.xpandasscipystatsmodels

解决方案


首先,如果你已经知道你想要的斜率,这可以在 python 中完成,但如果你有很多数据,你需要小心。其次,以 5% 为标准,斜率 10.5 将不会被纠正。

您要求的解决方案

#some imports
import pandas as pd
import numpy as np
from scipy.stats import norm
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
df = read_csv('your_file.csv')
state = 'USA'
desire_slope = 10
x = df[df['Country']==state][x]
y = df[df['Country']==state][y]

'''to use for test
x = [ 4+(i/10) for i in range(100)]
y = [c*11+norm.rvs()*4 for c in x ]
'''
z = [abs(v-desire_slope*c) for v,c in zip(y,x)]

slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
print(slope)
if(abs(slope-desire_slope)/slope<0.05):
    print("slope is fine")
else:
    sorted_index_pos = [index for index, num in sorted(enumerate(z), key=lambda x: x[-1])][-2:]
    print(sorted_index_pos)
    del x[sorted_index_pos[-1]]
    del y[sorted_index_pos[-1]]
    del x[sorted_index_pos[0]]
    del y[sorted_index_pos[0]]

new_slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
print(new_slope)

输出

11.08066739990693
[78, 85]
11.026005655263733

为什么你需要小心

首先我们不考虑拦截,这可能是一个问题。另外,如果我运行以下命令:

x = [ 4+(i/100) for i in range(1000)]
y = [c*10+norm.rvs()*4 for c in x ]

slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
print("the slope here is: "+str(slope))
z = [c*slope for c in x]
print("average of values: "+str(sum(x)/len(x)))
plt.plot(x,y,'b',x,z,'r-')

我得到以下输出:

the slope here is: 10.04367376783041
average of values: 8.995

在此处输入图像描述

Wich 表明,这些点不一定平均分布在斜坡的两侧。将点骑得更远可能会使数据集更加不平衡,因此不会改善斜率。所以这样做时要小心


推荐阅读