scipy.optimize.leastsq错误不是浮点数组

时间:2016-02-16 11:50:48

标签: python numpy error-handling scipy mathematical-optimization

这是我的代码

import os
import sys
import numpy as np
import scipy
from scipy.optimize import leastsq


def peval (inp_mat,p):
    m0,m1,m2,m3,m4,m5,m6,m7 = p
    out_mat = np.array(np.zeros(inp_mat.shape,dtype=np.float32))
    mid = inp_mat.shape[0]/2
    for xy in range(0,inp_mat.shape[0]):
        if (xy<(inp_mat.shape[0]/2)):
            out_mat[xy] = ( (  (inp_mat[xy+mid]*m0)+(inp_mat[xy]*m1)+ m2 ) /( (inp_mat[xy+mid]*m6)+(inp_mat[xy]*m7)+1 ) )
        else:
            out_mat[xy] = ( (  (inp_mat[xy]*m3)+(inp_mat[xy-mid]*m4)+ m5 ) /( (inp_mat[xy]*m6)+(inp_mat[xy-mid]*m7)+1 ) )
    return np.array(out_mat)

def residuals(p, out_mat, inp_mat):
    m0,m1,m2,m3,m4,m5,m6,m7 = p
    err=np.array(np.zeros(inp_mat.shape,dtype=np.float32))
    if (out_mat.shape == inp_mat.shape):
        for xy in range(0,inp_mat.shape[0]):
            err[xy] =  err[xy]+ (out_mat[xy] -inp_mat[xy])
        return np.array(err)




f = open('/media/anilil/Data/Datasets/repo/txt_op/vid.txt','r')
x = np.loadtxt(f,dtype=np.int16,comments='#',delimiter='\t')
nof = x.shape[0]/72 # Find the number of frames
x1 = x.reshape(-1,60,40)
x1_1= x1[0,:,:].flatten()
x1_2= x1[1,:,:].flatten()

x= []
y= []

for xy in range(1,50,1):
    y.append(x1[xy,:,:].flatten())
    x.append(x1[xy-1,:,:].flatten())

x=np.array(x,dtype=np.float32)
y=np.array(y,dtype=np.float32)
length =  x1_1.shape#initail guess
p0 = np.array([1,1,1,1,1,1,1,1],dtype=np.float32)

abc=leastsq(residuals, p0,args=(y,x))
print ('Size of first matrix is '+str(x1_1.shape))
print ('Size of first matrix is '+str(x1_2.shape))

print ("Done with program")

我尝试在大多数地方添加np.array没有用。 有人可以帮助我吗?

这里的另一个问题是我是否通过添加所有errorsnp.sum(err,axis=1)将残差()的输出作为单个值。或者保持原样?

我在return np.sum(err,axis=1)函数中residuals()。初始猜测没有变化。它只是保持不变。

I.E错误是输入输出映射中的每个项目。或总体上的组合错误?

Example data.

输出

ValueError: object too deep for desired array
Traceback (most recent call last):
  File "/media/anilil/Data/charm/mv_clean/.idea/nose_reduction_mpeg.py", line 49, in <module>
    abc=leastsq(residuals, p0,args=(y,x))
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 378, in leastsq
    gtol, maxfev, epsfcn, factor, diag)
minpack.error: Result from function call is not a proper array of floats.

1 个答案:

答案 0 :(得分:1)

leastsq需要从residuals函数返回一维数组。

目前,您计算整个图像的残差并将其作为2D数组返回。

简单的解决方法是压平残差数组(将2D数组转换为1D数据)。

所以不要回来

return np.array(err)

改为

return err.flatten()

请注意,err已经是一个numpy数组,所以不需要在返回之前进行转换(我想在你尝试调试它时会滑入!)