Python ValueError: operands could not be broadcast together with shapes

Chris C picture Chris C · Nov 11, 2012 · Viewed 12.4k times · Source

I am doing SVD and when I try to run my code I get the following error:

ValueError: operands could not be broadcast together with shapes (375, 375) (375, 500)

I am using an image with size (500, 375)

Here is my code:

from PIL import Image
from Image import new
from numpy import *
import numpy as np
from scipy.linalg import svd

im = Image.open("lake.tif")
pix = im.load()
im.show()
r, g, b = im.split()
R = np.array(r.getdata())
R.shape = (500, 375)
Ur, Sr, VrT = svd(R.T, full_matrices=False)
R1 = Ur * diag(Sr) * VrT

Answer

seberg picture seberg · Nov 12, 2012

You are doing component wise product. Either make those things matrices or use:

 R1 = np.dot(Ur, np.dot(diag(SR), VrT))

or use something like:

Ur, Sr, VrT = map(np.asmatrix, (Ur, diag(Sr), Vrt))
R1 = Ur * Sr * VrT

Which is much cleaner if you do a lot of matrix products (like in this line), otherwise arrays are typically preferable since they are the base type. If you prefer you can of course also just call np.asmatrix on each itself.