微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python scipy 无法传递从类属性生成的数据帧?

如何解决python scipy 无法传递从类属性生成的数据帧?

我正在学习一些关于使用类使我的代码更容易修改的知识。我正在定义一个 ml_setup 类,该类从单独的函数调用 spearman 计算。

class ml_setup:
    def __init__(self,df,dropcols,ycol,**kwargs ):
        self.ycol = ycol
        self.df = df  
        if 'stratify' in kwargs:
            self.stratify = kwargs['stratify']
        else:
            self.stratify = None
        self.train_Y = df[ycol]
        self.train_X = df.drop(columns=dropcols)
        if 'seed' in kwargs:
            self.seed = kwargs['seed']
        else:
            self.seed = self.seed_gen()
        if 'test' in kwargs:
            self.test = kwargs['test']
        else:
            self.test = 0.3
        if 'final_model' in kwargs:
            self.final_model = kwargs['final_model']
        else:
            self.final_model = None

    def seed_gen(self):
        seed = np.random.randint(0,2**32 - 1)
        return seed
    def linear_reg(self,positive=False):
        self.regr = linear_model.LinearRegression(positive=positive)    
        if self.final_model is None:
            self.X_train,self.X_test,self.y_train,self.y_test = train_test_split(self.train_X,self.train_Y,test_size=self.test,random_state=self.seed,shuffle=True,stratify=self.stratify)        
            #for test/train
            self.regr.fit(self.X_train,self.y_train)
            self.predictions = self.regr.predict(self.X_test)
            #print(y_test)
            #print(self.predictions)
            #print(self.y_test[self.ycol])
            self.p,self.s = pearson_stat(self.y_test[self.ycol],self.predictions,print_out='no')
            self.r2 = r_squared(self.y_test,self.predictions)

和 pearson_stat 函数如下所示,

def pearson_stat (x_data,y_data,print_out='no'):
    import scipy.stats as ss
    p = ss.pearsonr(x_data,y_data)
    s = ss.spearmanr(x_data,y_data)
    if print_out == 'yes':
        print('Pearson rho = {:.4f},P = {:.4g}'
                  .format(*p))
        print('Spearman r = {:.4f},P = {:.4g}'
                  .format(*s))
    return p[0],s[0]

如果我按照以下方式将 x 和 y 传递给 pearson_stat 函数,此代码将完美运行。

a,s = pearson_stat(ml_mods[seed].y_test['exp_val'],ml_mods[seed].y_test['exp_val'])

但是如果我现在从 class 属性设置“exp_val”,它就不起作用了。给我以下错误

a,s = pearson_stat(ml_mods[seed].y_test[ml_mods[seed].ycol],ml_mods[seed].y_test[ml_mods[seed].ycol])

xmean = x.mean(dtype=dtype)
  File "../anaconda3/envs/py3/lib/python3.6/site-packages/numpy/core/_methods.py",line 160,in _mean
     ret = umr_sum(arr,axis,dtype,out,keepdims)
TypeError: No loop matching the specified signature and casting was found for ufunc add

你能帮我理解一下吗?

解决方法

所以在@hpaulj 的指导下,我意识到我调用该列的方式导致了 DataFrame 而不是 Series。对于 Pearson 计算,我需要系列形式的数据(即类似数组)。

type(ml_mods[seed].y_test[ml_mods[seed].ycol]) 
<class 'pandas.core.frame.DataFrame'> 
type(ml_mods[seed].y_test['exp_val']) 
<class 'pandas.core.series.Series'>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。