Operands could not be broadcast together with shapes (100,4) (4,1)
You get this error because you do a * b
, and the *
operator is for pointwise multiplication, which is accomplished using broadcasting if required, but the shapes (100, 4)
and (4, 1)
can't be broadcast.
You want matrix multiplication, for which you need to use the @
operator, or the np.matmul()
function*
data = sampler.lhs_method(100) @ (u_bounds - l_bounds) + l_bounds
# or
data = np.matmul(sampler.lhs_method(100), u_bounds - l_bounds) + l_bounds
As Daniel pointed out below, you'll get a similar error because the matrix multiplication sampler.lhs_method(100) @ (u_bounds - l_bounds)
is a matrix of shape (100, 1)
and l_bounds
is a matrix of shape (4, 1)
, which can't be added together, so you'll need to check your math.
*I removed the unnecessary parentheses.
How to solve: ValueError: operands could not be broadcast together with shapes (4,) (4,6)
Arrays need to have compatible shapes and same number of dimensions when performing a mathematical operation. That is, you can't add two arrays of shape (4,) and (4, 6), but you can add arrays of shape (4, 1) and (4, 6).
You can add that extra dimension as follows:
a = np.array(a)
a = np.expand_dims(a, axis=-1) # Add an extra dimension in the last axis.
A = np.array(A)
G = a + A
Upon doing this and broadcasting, a
will practically become
[[0 0 0 0 0 0]
[1 1 1 1 1 1]
[2 2 2 2 2 2]
[3 3 3 3 3 3]]
for the purpose of addition (the actual value of a
won't change, a
will still be [[0] [1] [2] [3]]
; the above is the array A
will be added to).
Numpy Error: Operands could not be broadcast together with shapes (2,) (0,)
The issue was that the pend_func function was returning an array of a different shape than the rest of the arrays. This was fixed by changing
return [[d1], [d2]]
to
return [d1, d2]
Python - ValueError: operands could not be broadcast together with shapes (17,90) (17,)
I found a solution. Apparently, optimize.minimize
didn't like that y and theta had shapes (90,1) and (17,1), respectively. I converted their shape to (90,) and (17,) and the error message went away.
In terms of code, I changed
initial_theta = np.zeros([n + 1, 1])
to just this:
initial_theta = np.zeros([n + 1])
and I added the following line:
y = np.reshape(y, [m])
Thanks to those who tried to help me.
Related Topics
How to Sort Unicode Strings Alphabetically in Python
Importing an Ipynb File from Another Ipynb File
Python/Numpy First Occurrence of Subarray
Read File from Line 2 or Skip Header Row
Pandas Select from Dataframe Using Startswith
What's the Best Way to Parse Command Line Arguments
How to Display Custom Values on a Bar Plot
Python Numpy Valueerror: Operands Could Not Be Broadcast Together with Shapes
Zip Variable Empty After First Use
How to Make an Exe File from a Python Program
Pylint "Unable to Import" Error - How to Set Pythonpath
Is the Time-Complexity of Iterative String Append Actually O(N^2), or O(N)