【python問題系列--4】ValueError: operands could not be broadcast together with shapes (100,3) (3,1)


背景:dataMatrix是(100,3)的列表,labelMat是(1,100)的列表,weights是(3,1)的數組,屬性如下代碼所示:

>>> import types
>>> type(dataMatrix)
<type 'list'>
>>> type(labelMat)
<type 'list'>
>>> type(weights)
<type 'numpy.ndarray'>

我的代碼:

>>> dataMatrix=dataArr
>>> labelMat=labelMat.transpose()
>>> m,n=shape(dataMatrix)
>>> alpha=0.001
>>> maxCycles=500
>>> weights=ones((n,1))
>>> for k in range(maxCycles):
...     h=logRegres.sigmoid(dataMatrix*weights)
...     error=(labelMat-h)
...     weights=weights+alpha*dataMatrix.transpose()*error
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: operands could not be broadcast together with shapes (100,3) (3,1)

解釋:

本人出現的問題是,dataMatrix,weights的大小分別為(100,3) (3,1), 是<type 'list'>、<numpy.ndarray>類型,而不是<matrix>類型,直接進行乘積C = A*B, 之后,提示上述錯誤,原因是數組大小“不一致”, 解決方案,不用"*"符號,使用numpy中的dot()函數,可以實現兩個二維數組的乘積,或者將數組類型轉化為矩陣類型,使用"*"相乘,具體如下:

第一種方法:

>>> dataMatrix=dataArr
>>> labelMat=labelMat.transpose()
>>> m,n=shape(dataMatrix)
>>> alpha=0.001
>>> maxCycles=500
>>> weights=ones((n,1))

>>> for k in range(maxCycles):
...     h=logRegres.sigmoid(dot(dataMatrix,weights))
...     error=(labelMat-h)
...     weights=weights+alpha*dataMatrix.transpose()*error
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: 'list' object has no attribute 'transpose'

分析:這次沒有出現上次的錯誤,但是這次出現的錯誤是指'list'沒有'transpose'轉置功能,我們知道只有矩陣才有轉置。所以用第二種方法,直接將dataMatrix,weights都轉換為矩陣,代碼如下:

第二種方法:

>>> dataMatrix=mat(dataArr)
>>> labelMat=mat(labelMat)
>>> m,n=shape(dataMatrix)
>>> alpha=0.001
>>> maxCycles=500
>>> weights=ones((n,1))
>>> for k in range(maxCycles):
...     h=logRegres.sigmoid(dataMatrix*weights)
...     error=(labelMat-h)
...     weights=weights+alpha*dataMatrix.transpose()*error
...
>>>
這次沒有出現錯誤,解決了剛才的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM