Home > OS >  Operands could not be broadcast together with shapes (100,4) (4,1)
Operands could not be broadcast together with shapes (100,4) (4,1)

Time:05-06

This code should generate random data within bounds. I understand there is mismatch problem with the arrays, but I'm not sure what it is. Does this mean that the lower and upper bounds defined in the code make it impossible to work?

import pandas as pd
import numpy as np
from scipy.stats import qmc

sampler = qmc.LatinHypercube(d=4)

u_bounds = np.array([[2], [10], [10], [2]])
l_bounds = np.array([[0.1], [0.1], [0.1], [0.1]])
data = sampler.lhs_method(100)*(u_bounds-(l_bounds))   (l_bounds)
print(data)

The error code

ValueError: operands could not be broadcast together with shapes (100,4) (4,1) 

CodePudding user response:

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.

  • Related