Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy `ValueError: operands could not be broadcast together with shape ...`

Tags:

Im using python 2.7 and am attempting a forcasting on some random data from 1.00000000 to 3.0000000008. There are approx 196 items in my array and I get the error

ValueError: operands could not be broadcast together with shape (2) (50) 

I do not seem to be able to resolve this issue on my own. Any help or links to relevant documentation would be greatly appreciated.

Here is the code I am using that generates this error

nsample = 50 sig = 0.25 x1 = np.linspace(0,20, nsample) X = np.c_[x1, np.sin(x1), (x1-5)**2, np.ones(nsample)] beta = masterAverageList y_true = ((X, beta)) y = y_true + sig * np.random.normal(size=nsample) 
like image 789
The Spiteful Octopus Avatar asked Aug 08 '12 01:08

The Spiteful Octopus


People also ask

How do you fix ValueError operands could not be broadcast together with shapes?

To solve this error, you can use the dot() method if you want to multiply two matrices, provided that the number of columns in the first matrix equals the number of rows in the second matrix. Alternatively, if you want to do broadcasting, ensure that the dimensions of the arrays are compatible by reshaping using numpy.

Where operands could not be broadcast together with shapes?

How to Fix: ValueError: operands could not be broadcast together with shapes. This error occurs when you attempt to perform matrix multiplication using a multiplication sign (*) in Python instead of the numpy. dot() function.

Is the ability of NumPy to treat arrays of different shapes during arithmetic operations?

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.


1 Answers

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

like image 156
JoshAdel Avatar answered Oct 24 '22 04:10

JoshAdel