简体   繁体   中英

fit along one dimension of numpy array

I have a numpy array (sums_norm) of dimension (44,36) and I would like to fit all its rows with a known function. (This question is an extension of the already asked curve fitting with a known function numpy ). I am using this code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x,beta,p):
   return p/(4.0*np.pi)*(1+beta*(3.0/2*(np.cos(x)*np.cos(x))-1.0/2))

popt = np.zeros(((sums_norm.shape[0]),2))
pcov = np.zeros(((sums_norm.shape[0]),2))
y_fit =  np.zeros(((sums_norm.shape[0]),(sums_norm.shape[1]))) 
for i in range(0,sums_norm.shape[0],1):
   guesses = [0.2,5]
   popt[i,:],pcov[i,:] = curve_fit(func,angle_plot,sums_norm[i,:],p0=guesses)
   y_fit[i,:] =  func(angle_plot,*popt)

print popt

But when I run it I get the error : "could not broadcast input array from shape (2,2) into shape (2)". What do I do wrong? Thank you

ValueError                                Traceback (most recent call last)
<ipython-input-315-cc50a1dcf07b> in <module>()
 29 for i in range(0,sums_norm.shape[0],1):
 30    guesses = [0.2,5]
 ---> 31    popt[i,:],pcov[i,:] = curve_fit(func,angle_plot,sums_norm[i,:],p0=guesses)
 32    y_fit[i,:] =  func(angle_plot,*popt)

ValueError: could not broadcast input array from shape (2,2) into shape (2)

I modified you code with some random data, you need create pcov with shape (44, 2, 2) :

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

sums_norm = np.random.rand(44, 36)
angle_plot = np.random.rand(36)

def func(x,beta,p):
    return p/(4.0*np.pi)*(1+beta*(3.0/2*(np.cos(x)*np.cos(x))-1.0/2))

popt = np.zeros(((sums_norm.shape[0]),2))
pcov = np.zeros(((sums_norm.shape[0]),2, 2))
y_fit =  np.zeros(((sums_norm.shape[0]),(sums_norm.shape[1]))) 
for i in range(0,sums_norm.shape[0],1):
   guesses = [0.2,5]
   popt[i,:],pcov[i,:] = curve_fit(func,angle_plot,sums_norm[i,:],p0=guesses)
   y_fit[i,:] =  func(angle_plot,*popt[i,:])

print popt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM