'how to fix ValueError: operands could not be broadcast together with shapes (50,) (10,)

this is how the dataframe looks like and below the code with equation and curve fitting:

 all # this is the dataframe 'all' 

 [        y           x            Temp      gamma         Kc         Ko
   0     -0.501864    51.040405  26.575860  4.654191  32.342013  17.434281
   1      3.317406    82.390735  26.608765  4.658023  32.457605  17.452507
   2     10.207180   146.722313  26.645362  4.662289  32.586622  17.472796
   3     16.055772   212.771464  26.698917  4.668535  32.776289  17.502520] 

When plotting the modelled data I get the following error and I don't understand why:

def model(x, Vcmax):
  return  Vcmax*((x- gamma))/((x+Kc)*(1+(O/Ko))) - Rd

def func_fit(x):
  return model(x,  
            *popt)

from scipy.optimize import curve_fit
import math

for g in all: 
  
O = 21
Rd = 1.60  

Vcmax = 40 # initial guess
gamma=g.gamma # value from dataframe, function of temperature 
Kc=g.Kc       # value from dataframe, function of temperature
Ko=g.Ko       # value from dataframe, function of temperature

#  gamma = 34
#  Kc = 89
#  Ko = 80
    
popt, pcov = curve_fit(model, g['x'], g['y'],  p0 = np.array([Vcmax]), 
                       absolute_sigma=True, maxfev=1000000)
    

##################### new data frame
new_row = { 'Vcmax': popt[0]}

results=results.append(new_row, ignore_index=True)

x = np.linspace(0,300)
b = model(x, results.iloc[0,1],) # this is the line generating the error, 

plt.plot(x, b, 'r') # plotting modelled data
plt.scatter(df.x, df.y, color='red') # plotting observations 

ValueError: operands could not be broadcast together with shapes (50,) (10,) 

If I 'fix' the values gamma, Ko and Kc to constants instead of the current situation, then I don't get the same error but the fitting is very bad, see picture

wrong fit using constant gamma, Ko, Kc



Solution 1:[1]

I haven't tried it, but this should work:

x = np.linspace(0,300, 10)
b = model(x, results.iloc[0,1],) # this is the line generating the error, 

The problem is that the shapes of x and results.iloc[0,1] aren't the same, as they should be. Adding parameter 10 to np.linespace should change the shape of x array to the same shape as results.iloc[0,1]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mbostic