2010-11-15 29 views
0

矩陣我不能讓簡單的矩陣運算對數據進行工作,對我的生活我一直沒能找出我在做什麼錯誤:CSV在SciPy的

data = np.genfromtxt(dataset1, names=True, delimiter=",", dtype=float) 

X = np.matrix(data) 
print(X.T*X) 

Traceback (most recent call last): 
    File "genfromtxt.py", line 11, in <module> 
    print(X.T*X) 
    File "/usr/lib/pymodules/python2.6/numpy/matrixlib/defmatrix.py", line 319, in __mul__ 
    return N.dot(self, asmatrix(other)) 
TypeError: can't multiply sequence by non-int of type 'tuple' 

打印(數據)給出:

[ (3.0, 32.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 9.0, 0.0, 5.5606799999999996, 9.0) 
(4.0, 43.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 9.0, 0.0, 5.7203099999999996, 16.0) 
(5.0, 40.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 9.0, 0.0, 5.9964500000000003, 25.0) 
..., 
(5.0, 50.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 12.0, 0.0, 6.2146100000000004, 25.0) 
(6.0, 50.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 12.0, 0.0, 6.2915700000000001, 36.0) 
(7.0, 50.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 12.0, 0.0, 6.3716100000000004, 49.0)] 

編輯:

此外,該代碼

reader = csv.reader(open(dataset1, 'r')) 
header = reader.next() 
X = np.array([[float(col) for col in row] for row in reader]) 

print(X.shape) 
print(X.T.shape) 
print(X * X.T) 

給出了這樣的輸出:

(4165, 13) 
(13, 4165) 
Traceback (most recent call last): 
    File "genfromtxt.py", line 17, in <module> 
    print(X * X.T) 
ValueError: shape mismatch: objects cannot be broadcast to a single shape 
>>> 

回答

3

與第二例子的問題似乎是,對於NumPy的陣列操作*進行逐元素multilpication。大概你想要執行矩陣乘法。有兩種方法做到這一點:

  1. 使用numpy.matrix而不是numpy.array - 然後乘將矩陣乘法和權力,通過整數指數如預期會工作。

  2. 使用numpy.dot(A, B)而不是A*B - 這將執行陣列和矩陣的矩陣乘法。