簡體   English   中英

線性回歸:ValueError:除串聯軸外,所有輸入數組維必須完全匹配

[英]Linear regression:ValueError: all the input array dimensions except for the concatenation axis must match exactly

我正在尋找以下問題的解決方案,它只是無法按我想要的方式工作。

因此,我的目標是計算回歸分析並獲取多行的斜率,截距,rvalue,pvalue和stderr(這可能達到10000)。 在這個例子中,我有一個15行的文件。 這是前兩行:

array([

[   1,    2,    3,    4,    5,    6,    7,    8,    9,   10,   11,
          12,   13,   14,   15,   16,   17,   18,   19,   20,   21,   22,
          23,   24],    

[ 100,   10,   61,   55,   29,   77,   61,   42,   70,   73,   98,
          62,   25,   86,   49,   68,   68,   26,   35,   62,  100,   56,
          10,   97]]
)

完整的試用數據集:

1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24

100 10  61  55  29  77  61  42  70  73  98  62  25  86  49  68  68  26  35  62  100 56  10  97

57  89  25  89  48  56  67  17  98  10  25  90  17  52  85  56  18  20  74  97  82  63  45  87

192 371 47  173 202 144 17  147 174 483 170 422 285 13  77  116 500 136 276 392 220 121 441 268

第一行是x變量,這是自變量。 在迭代接下來的每一行時,必須保持固定不變。

對於下一行,y變量,因此是因變量,我想計算斜率,截距,rvalue,pvalue和stderr並將它們放在數據框中(如果可能,請添加到同一數據框中,但這不是必需的) 。

我嘗試了以下代碼:

import pandas as pd
import scipy.stats
import numpy as np
df = pd.read_excel("Directory\\file.xlsx")

def regr(row):
    r = scipy.stats.linregress(df.iloc[1:, :], row)
    return r

full_dataframe = None

for index,row in df.iterrows():
    x = regr(index)
   if full_dataframe is None: 
       full_dataframe = x.T
   else: 
       full_dataframe = full_dataframe.append([x.T])

full_dataframe.to_excel('Directory\\file.xlsx')

但這失敗了,並給出以下錯誤:

ValueError: all the input array dimensions except for the concatenation axis 
must match exactly

我真的在這里迷路了。

因此,我想實現從第二個開始的每行具有斜率,截距,pvalue,rvalue和stderr,因為第一行是x變量。

任何人都有一個想法如何做到這一點,並告訴我為什么我的不工作,代碼應該是什么樣子?

謝謝!!

猜問題

最有可能的問題是數字的格式,存在Unicode字符串dtype('<U21')而不是Integer或Float。

始終檢查類型:

df.dtypes

使用以下內容投射數據框:

df = df.astype(np.float64)

下面是顯示問題的一個小示例:

import numpy as np
import pandas as pd

# DataFrame without numbers (will not work for Math):
df = pd.DataFrame(['1', '2', '3'])
df.dtypes # object: placeholder for everything that is not number or timestamps (string, etc...)

# Casting DataFrame to make it suitable for Math Operations:
df = df.astype(np.float64) 
df.dtypes # float64

但是,如果沒有要使用的原始文件或數據,很難確定這一點。

仔細閱讀異常

這與您得到的異常一致:

TypeError: ufunc 'add' did not contain a loop with signature matching types 
dtype('<U21') dtype('<U21') dtype('<U21')

方法scipy.stats.linregress引發TypeError (所以它與類型有關),並告訴您不能執行add操作,因為添加String dtype('<U21')在線性回歸的上下文中沒有任何意義。

了解設計

加載數據:

import io

fh = io.StringIO("""1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
100 10  61  55  29  77  61  42  70  73  98  62  25  86  49  68  68  26  35  62  100 56  10  97
57  89  25  89  48  56  67  17  98  10  25  90  17  52  85  56  18  20  74  97  82  63  45  87
192 371 47  173 202 144 17  147 174 483 170 422 285 13  77  116 500 136 276 392 220 121 441 268""")

df = pd.read_fwf(fh).astype(np.float)

然后我們可以倒退第二行與第一行

scipy.stats.linregress(df.iloc[0,:].values, df.iloc[1,:].values)

它返回:

LinregressResult(slope=0.12419744768547877, intercept=49.60998434527584, rvalue=0.11461693561751324, pvalue=0.5938303095361301, stderr=0.22949908667668056)

組裝在一起:

result = pd.DataFrame(columns=["slope", "intercept", "rvalue"])
for i, row in df.iterrows():
    fit = scipy.stats.linregress(df.iloc[0,:], row)
    result.loc[i] = (fit.slope, fit.intercept, fit.rvalue)

返回:

      slope   intercept    rvalue
0  1.000000    0.000000  1.000000
1  0.124197   49.609984  0.114617
2 -1.095801  289.293224 -0.205150

據我了解您的問題,這是您的期望。

您收到的第二個異常是由於以下原因:

x = regr(index)

您將行的索引而不是行本身發送給了回歸方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM