Python - 使用Numpy.mgrid和Numpy.reshape

时间:2014-05-17 15:48:53

标签: python arrays numpy grid reshape

我刚问了一个非常相似的问题,但是,我认为还不够清楚...... 所以我想使用Numpy.mgrid来拟合函数,并且为了适应这个函数,我使用最小二乘最小化。 为此,我必须使用Numpy.reshape将我的2D数据阵列转换为1D数组。

我确信我的剧本质量! :)但是,结果非常糟糕,所以也许它可以用np.reshape作为转换起源...? 我可以在不改变形状的情况下进行最小化吗? 非常感谢你的帮助!

了解更多信息: https://stackoverflow.com/questions/23712377/python-use-of-numpy-mgrid-for-minimization

我的一小段代码,看看我做了什么:

例如(实际上:Lx = 600且Ly = 450)

import numpy as np
import scipy.optimize as sco

#Inputs

U2 = np.array([[  0.53,   -0.3,   -1.03, -1.79, -2.96, -2.87, -1.99],
[  0.3, -1.46, -1.54, -1.75, -1.95, -2.13, -0.17],
[0.11,  -1.74, -1.68, -1.68, -1.65, -1.77, 0.19],
[-0.53, -2.04, -1.90, -1.70, -1.6, -1.36, 0.31],
[-1.45, -2.41, -2., -1.83, -1.04, -1.04, 1.13]])


V2 = np.array([[ -12.97, -12.14, -13.3, -15.76, -10.95, -10.12, -10.6],
[-21.34, -22.39, -22.47, -22.62, -22.56, -22.4, -21.5],
[-21.27, -21.5, -21.7, -21.7,-21.7,-21.28, -21.11],
[-21.15, -22.05, -22.13, -22.2, -22.27, -21.95, -21.12],
[-21.43,-20.98, -21.62, -21.79,-21.33,-20.74,-19.48]])


V = -21.5*np.ones((5, 7))


#Definition of the grid

Lx=7.
Ly=5.

YA, XA = np.mgrid[-Ly/2:Ly/2, -Lx/2:Lx/2]


#I transform the 2D arrays in 1D arrays to do minimization

Vvect=np.reshape(V,Lx*Ly)

U2vect=np.reshape(U2,Lx*Ly)
V2vect=np.reshape(V2,Lx*Ly)

XAvect=np.reshape(XA,Lx*Ly)
YAvect=np.reshape(YA,Lx*Ly)


#Minimization

x0 = 0
y0 = 0
k1 = 2.49*10**(-7)

def residual_x(vars, XA, YA, x0, y0, V, donnees):
    k1 = vars[0]
    x0 = vars[1]
    y0 = vars[2]
    modele = (XA - x0) + k1*(XA - x0)*((XA - x0)**2 + (YA - (y0 + V.mean()))**2) - (XA - x0) + k1*(XA - x0)*((XA - x0)**2 + (YA - y0)**2) 
    return (donnees-modele)

from scipy.optimize import leastsq
vars = [k1, x0, y0]
out_x = sco.leastsq(residual_x, vars, args=(XAvect, YAvect, x0, y0, Vvect, U2vect),epsfcn=0.01)

print out_x


def residual_y(vars, XA, YA, x0, y0, V, donnees):
    k1 = vars[0]
    x0 = vars[1]
    y0 = vars[2]
    modele = (YA - (y0 + V.mean())) + k1*(YA - (y0 + V.mean()))*((XA - x0)**2 + (YA - (y0 + V.mean()))**2) - (YA - y0) + k1*(YA - y0)*((XA - x0)**2 + (YA - y0)**2) + V.mean() - V
    return (donnees-modele)

vars = [k1, x0, y0]
out_y = sco.leastsq(residual_y, vars, args=(XAvect, YAvect, x0, y0, Vvect, V2vect),epsfcn=0.01)

print out_y

当我说结果不好时,x0和y0代表了扭曲的中心,但正如你在下面看到的那样,它是一个非常重要的值。它必须靠近我的网格中心。

print out_x
(array([  1.78359982e-14,   3.79619402e+03,  -1.06863804e+05]), 1)

print out_y
(array([  1.46118433e-14,   1.67809050e+05,   4.76986504e+04]), 5)

0 个答案:

没有答案