Python linear regression model (Pandas, statsmodels) - Value error: endog exog matrices size mismatch

Python linear regression model (Pandas, statsmodels) - Value error: endog exog matrices size mismatch

我的一个朋友问我这个线性回归代码,我也解不出来,所以现在也是我的问题。

我们得到的错误: ValueError: endog 和 exog 矩阵大小不同

当我从 ind_names 中删除 "Tech" 时,它工作正常。这可能毫无意义,但为了消除语法错误的可能性,我尝试这样做了。

科技和金融行业标签在 DataFrame 中的分布不均,所以这可能会导致大小不匹配?但是我无法进一步调试所以决定问你们。

如果能够确认错误和解决思路,那就太好了。请在下面找到代码。

    #We have a portfolio constructed of 3 randomly generated factors (fac1, fac2, fac3). 
#Python code provides the following message 
#ValueError: The indices for endog and exog are not aligned

import pandas as pd
from numpy.random import rand
import numpy as np
import statsmodels.api as sm

fac1, fac2, fac3 = np.random.rand(3, 1000) #Generate  random factors

#Consider a collection of hypothetical stock portfolios
#Generate randomly 1000 tickers
import random; random.seed(0)
import string
N = 1000
def rands(n):
  choices = string.ascii_uppercase
  return ''.join([random.choice(choices) for _ in range(n)])


tickers = np.array([rands(5) for _ in range(N)])
ticker_subset = tickers.take(np.random.permutation(N)[:1000])

#Weighted sum of factors plus noise

port = pd.Series(0.7 * fac1 - 1.2 * fac2 + 0.3 * fac3 + rand(1000), index=ticker_subset)
factors = pd.DataFrame({'f1': fac1, 'f2': fac2, 'f3': fac3}, index=ticker_subset)

#Correlations between each factor and the portfolio 
#print(factors.corrwith(port))
factors1=sm.add_constant(factors)


#Calculate factor exposures using a regression estimated by OLS
#print(sm.OLS(np.asarray(port), np.asarray(factors1)).fit().params)

#Calculate the exposure on each industry
def beta_exposure(chunk, factors=None):
    return sm.OLS(np.asarray(chunk), np.asarray(factors)).fit().params


#Assume that we have only two industries – financial and tech

ind_names = np.array(['Financial', 'Tech'])
#Create a random industry classification 

sampler = np.random.randint(0, len(ind_names), N)
industries = pd.Series(ind_names[sampler], index=tickers, name='industry')
by_ind = port.groupby(industries)



exposures=by_ind.apply(beta_exposure, factors=factors1)
print(exposures)
#exposures.unstack()

#Determinate the exposures on each industry 

了解错误信息:

ValueError: endog and exog matrices are different sizes

好吧,还不错。内生矩阵和外生矩阵的大小不同。该模块提供了这个 page,它告诉我们 内生因素是系统内部的因素 外生因素是系统外部的因素 .

一些调试

检查我们为阵列获得的形状。要做到这一点,我们需要拆开 oneliner 并打印参数的 .shape 或者打印每个参数的前几个。另外,注释掉引发错误的行。所以在那里,我们发现我们得到:

chunk [490]
factor [1000    4]
chunk [510]
factor [1000    4]

哦!就在那里。我们期待 factor 也被分块。第一次应该是[490 4],第二次应该是[510 4]。注意:由于类别是随机分配的,因此每次都会有所不同。

基本上我们在该函数中的信息太多了。我们可以使用块来查看要选择的因素,将因素过滤为那些因素,然后一切都会起作用。

查看文档中的函数定义:

class statsmodels.regression.linear_model.OLS(endog, exog=None, missing='none', hasconst=None, **kwargs)

我们只传递两个参数,其余的是可选的。再看看我们路过的两个

endog (array-like) – 1-d endogenous response variable. The dependent variable.

exog (array-like) – A nobs x k array where nobs is the number of observations and k is the number of regressors...

啊,又是endogexogendog 类似于一维数组。到目前为止一切顺利,形状 490 有效。 exog nobs?哦,它的观察数。所以它是一个二维数组,在这种情况下,我们需要形状 490 by 4.

这个具体问题:

beta_exposure 应该是:

def beta_exposure(chunk, factors=None):
    factors = factors.loc[factors.index.isin(chunk.index)]
    return sm.OLS(np.asarray(chunk), np.asarray(factors)).fit().params

问题是您将 beta_exposures 应用于列表的每个部分(它是随机的,所以假设 Financial 有 490 个元素,Tech 有 510 个元素)但是 factors=factors1 总是给你 1000 个值(groupby 代码不涉及那个)。

请参阅 http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLS.html and http://www.statsmodels.org/dev/endog_exog.html 以了解我用于研究此内容的参考资料。