2017-04-12 87 views
0

我試圖通過嘗試實現$$(X^{T} X)^ { - 1} X^{T} y $ $Numpy.linalg.inv或Numpy.linalg.solve類型錯誤

但是,這樣做的時候,我得到以下錯誤:TypeError: No loop matching the specified signature and casting was found for ufunc inv

我的代碼如下:

import pandas as pd 
import numpy as np 
from numpy.linalg import inv 


data = pd.read_csv("Tbill10yr.csv") 
X = data.as_matrix()[:,1] 
X1 = X[:730] 
y_1 = X[1:,].reshape((730,1)) 
Nobs = y_1.shape[0] 
X1 = np.c_[ np.ones((Nobs,1)) , X1] 
XX = np.dot(X1.T , X1) 
Xy = np.dot(X1.T , y_1) 

beta_hat = np.dot(inv(XX),Xy) 

後來我想通了,我不得不使用beta_hat = np.dot(inv(XX.dtype(float)),Xy)

爲什麼是否有必要這樣做?有沒有適當的方法去解決這個問題?

任何解釋都很有意思。

感謝

回答

0

一個可能的原因可能是您的數據沒有被認定爲float。從data.as_matrixdocumentation

The dtype will be a lower-common-denominator dtype (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. Use this with care if you are not dealing with the blocks.

您可以通過執行XX.dtype檢查陣列的類型。