鹿酸梅 发表于 2022-3-22 21:34:58

关于获取数据异常值的代码几处疑问。问题可能有点多。已经加了注释。请大神帮忙指点

    # predict y value using model
    try:
      y_pred=pd.Series(model.predict(X),index=y.index)       #这里try里面和except里面的代码不懂是什么意思,,index=y.index是什么意思,为什么在except里面加上model.fit(X,y)
    except:
      model.fit(X,y)
      y_pred=pd.Series(model.predict(X),index=y.index)

    reside=y-y_pred
    mean_reside=reside.mean()
    std_reside=reside.std()   

    z=(reside-mean_reside)/std_reside
    outliers=z.index      #设置异常数据的条件


    print('R2=',model.score(X,y))
    print('mse=',mean_squared_error(y,y_pred))
    print('----------------------------------')

    print(len(outliers),'outliers')
    print(outliers.tolist)      

    plt.figure(figsize=(15,5))
    ax_131=plt.subplot(1,3,1)
    plt.plot(y,y_pred,'.')
    plt.plot(y.loc,y_pred.loc,'ro')
   
    plt.legend(['Accepted','Outlier'])   
    plt.xlabel('y')
    plt.ylabel('y_pred');
    plt.show()###################代码运行结果(如图),是因为这里的区别,不加这一句就是正常结果,但是想不明白加了为什么会是图片所示的那样紫



    ax_132=plt.subplot(1,3,2)
    plt.plot(y,y-y_pred,'.')
    plt.plot(y.loc,y.loc-y_pred.loc,'ro')
    plt.legend(['Accepled','Outlier'])
    plt.xlabel('y')
    plt.ylabel('y-y_pred')
   

    ax_133=plt.subplot(1,3,3)
    z.plot.hist(bins=50,ax=ax_133)
    z.loc.plot.hist(color='r',bins=50,ax=ax_133)   #ax=ax_133是什么意思,并没有在hist函数中找到ax参数
    plt.legend(['Accepted','Outlier'])
    plt.xlabel('z')
   


    plt.savefig('outliers.png')

    return outliers
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
X_train=train_data.iloc[:,0:-1]                                         #不明白这句代码的意思
y_train=train_data.iloc[:,-1]
outliers=find_outliers(Ridge(),X_train,y_train)

Python初学者8号 发表于 2022-3-23 11:05:02

我是用箱线图方法做的

Python初学者8号 发表于 2022-3-23 11:05:47

import pandas as pd
import numpy as np
# 读取文件
file = 'S3地下水位高程-step2.CSV'
f = pd.read_csv(file, encoding='gbk')
f.head()
# 定义 异常点 正常点 的集合
anomalies,normal= [],[]

# 统计高程的信息
f1 = f.describe()
sdata = dict(pd.Series(f1.level, index = list(f1.index)))
print(sdata)

# 求 分位数和上下胡须
Q1, Q3 = sdata['25%'],sdata['75%']
IQR = Q3 - Q1
lower_limit = Q1 - 1.5 * IQR
upper_limit = Q3 + 1.5 * IQR
print("下限:{0:3f} \n上限:{1:3f}".format(lower_limit,upper_limit))
# 下限:203.020000
# 上限:205.960000

# 给出两种异常点,并且获取新的无异常点的数据集合
low_point = f.loc < lower_limit, :]
up_point = f.loc > upper_limit, :]

# 留下正常值啊
norm_data = f.loc[(lower_limit < f['level'] ) & (f['level'] < upper_limit) , :]
# (lower_limit > f['level'] ) + (f['level'] > upper_limit) 这个可以做加和,是我理解的&负号的那种or作用

norm_data.to_csv('S3地下水位高程-step2-去异常值版本.csv')
页: [1]
查看完整版本: 关于获取数据异常值的代码几处疑问。问题可能有点多。已经加了注释。请大神帮忙指点