简体   繁体   English

使3D高斯拟合数据集

[英]Fitting 3D Gaussian to data set

I have a data file with first column x, second coulmn y and third column z. 我有一个第一列x,第二列y和第三列z的数据文件。 I can call these values via 我可以通过以下方式调用这些值

x=mat0[:,0]

That is not the problem. 那不是问题。 I can also create and plot a 3D Gaussian with these data or (as you see in my script below) via definition of the function "twoD_Gauss". 我也可以使用函数“ twoD_Gauss”的定义或使用这些数据或(如您在下面的脚本中看到的)创建和绘制3D高斯。

Now I want to fit this function "twoD_Gauss" to the dataset (x,y,z) and print out the values for amplitude sigma etc. 现在,我想将此函数“ twoD_Gauss”拟合到数据集(x,y,z),并打印出振幅sigma等的值。

This is what I got: 这就是我得到的:

from matplotlib import pyplot;
from pylab import genfromtxt;  
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from numpy.random import randn
from scipy import array, newaxis

# Load file into mat0
mat0 = genfromtxt("0005.map");
fig = plt.figure(figsize=(20,10))

############ 3D  ###############
ax = fig.add_subplot(1, 2, 2, projection='3d')
#Load data
mat0 = genfromtxt("0005.map");

# define Gaussian
def twoD_Gauss((x,y),amplitude,x0,y0,sigma_x,sigma_y,offset):
    x0=float(x0)
    y0=float(y0)
    return offset + amplitude*np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2)))))

#define x and y and z (z not used, x and y shifted)
x = mat0[:,0]-150
y = mat0[:,1]-143
z = mat0[:,2]
#create data
data = twoD_Gauss((x, y), 15, 0, 0, 20, 20, 10)

# plot twoD_Gaussian data generated above
ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, data, cmap="jet", linewidth=0)

#FITTING HELP!
initial_guess = (24000,0,0,25,25,6000)
params, pcov = opt.curve_fit(twoD_Gauss, (x,y), data,initial_guess)
print(params)

plt.show()

I think I did it correct, but its actually not fitting. 我认为我做对了,但实际上不适合。

The printed params are the parameters I gave in data. 打印的参数是我在数据中给出的参数。

Ok I found the solution myself: 好的,我自己找到了解决方案:

My problem was that I fitted to the data but data was already defined. 我的问题是我适合数据,但数据已定义。 So what I did is, I changed data to the z-data given in my file. 所以我要做的是,将数据更改为文件中给定的z数据。

data=mat0[:,2]

Now the curve_fit fits the twoD_Gauss via (x,y) to the given z-values. 现在curve_fit通过(x,y)将twoD_Gauss拟合到给定的z值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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