如何在3D中使用固定点进行多项式拟合

Alw*_*ver 9 python curve-fitting data-fitting

我在3D空间中有一组x,y,z点,另一个变量叫做charge表示在特定的x,y,z坐标中沉积的电荷量.我想对这个数据进行加权(通过检测器中沉积的电荷量加权,这对应于更高的重量以获得更多电荷),使得它通过给定点即顶点.

现在,当我为2D做这个时,我尝试了各种方法(将顶点带到原点并对所有其他点进行相同的变换,并强制拟合穿过原点,给出顶点非常高的权重)但是没有一个像Jaime在这里给出的答案一样好:如何用固定点进行多项式拟合

它使用拉格朗日乘数的方法,我从本科高级多变量课程中模糊地熟悉,但其他并不多,看起来这个代码的转换就像添加az坐标一样简单.(请注意,即使代码没有考虑到沉积的电荷量,它仍然给我最好的结果).我想知道是否有相同算法的版本,但是在3D中.我还在Gmail中联系了答案的作者,但没有收到他的回复.

以下是有关我的数据的更多信息以及我在2D中尝试做的事情:如何权衡散点图中的点以获得拟合?

这是我执行此操作的代码,其中我强制顶点位于原点,然后适合数据设置fit_intercept=False.我目前正在研究2D数据的这种方法,因为我不确定拉格朗日乘数是否有3D版本,但是在3D中有线性回归方法,例如,这里:在3D中拟合一条线:

import numpy as np
import sklearn.linear_model

def plot_best_fit(image_array, vertexX, vertexY):
    weights = np.array(image_array)
    x = np.where(weights>0)[1]
    y = np.where(weights>0)[0]
    size = len(image_array) * len(image_array[0])
    y = np.zeros((len(image_array), len(image_array[0])))
    for i in range(len(np.where(weights>0)[0])):
        y[np.where(weights>0)[0][i]][np.where(weights>0)[1][i]] = np.where(weights>0)[0][i]
    y = y.reshape(size)
    x = np.array(range(len(image_array)) * len(image_array[0]))
    weights = weights.reshape((size))
    for i in range(len(x)):
        x[i] -= vertexX
        y[i] -= vertexY
    model = sklearn.linear_model.LinearRegression(fit_intercept=False)
    model.fit(x.reshape((-1, 1)),y,sample_weight=weights)
    line_x = np.linspace(0, 512, 100).reshape((-1,1))
    pred = model.predict(line_x)
    m, b = np.polyfit(np.linspace(0, 512, 100), np.array(pred), 1)
    angle = math.atan(m) * 180/math.pi
    return line_x, pred, angle, b, m
Run Code Online (Sandbox Code Playgroud)

image_array是一个numpy数组,vertexX并且vertexY分别是顶点的x和y坐标.这是我的数据:https://uploadfiles.io/bbhxo.我不能创建玩具数据,因为没有简单的方法来复制这些数据,它是由Geant4模拟中微子与氩核相互作用产生的.我不想摆脱数据的复杂性.而这个特定的事件碰巧是我的代码不能正常工作的事件,我不确定我是否可以专门生成数据,因此我的代码无法正常工作.

mik*_*ski 5

这更像是使用基本优化的手工解决方案。这是直接的。只需测量点到要拟合的线的距离,并使用 basic 最小化加权距离optimize.leastsq。代码如下:

# -*- coding: utf-8 -*
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from scipy import optimize
import numpy as np

def rnd( a ):
    return  a * ( 1 - 2 * np.random.random() ) 

def affine_line( s, theta, phi, x0, y0, z0 ):
    a = np.sin( theta) * np.cos( phi )
    b = np.sin( theta) * np.sin( phi )
    c = np.cos( theta )
    return np.array( [ s * a + x0, s * b + y0, s * c + z0 ] )

def point_to_line_distance( x , y, z , theta, phi, x0, y0, z0 ):
    xx = x - x0
    yy = y - y0
    zz = z - z0
    a = np.sin( theta) * np.cos( phi )
    b = np.sin( theta) * np.sin( phi )
    c = np.cos( theta )
    r = np.array( [ xx, yy, zz ] )
    t = np.array( [ a, b, c ] )
    return np.linalg.norm( r - np.dot( r, t) * t )

def residuals( parameters, fixpoint, data, weights=None ):
    theta, phi = parameters
    x0, y0, z0 = fixpoint
    if weights is None:
        w = np.ones( len( data ) )
    else:
        w = np.array( weights )
    diff = np.array( [ point_to_line_distance( x , y, z , theta, phi , *fixpoint ) for x, y, z in data ] )
    diff = diff * w
    return diff

### some test data
fixpoint = [ 1, 2 , -.3 ]
trueline = np.array( [ affine_line( s, .7, 1.7, *fixpoint ) for s in np.linspace( -1, 2, 50 ) ] )
rndData = np.array( [ np.array( [ a + rnd( .6), b + rnd( .35 ), c + rnd( .45 ) ] ) for a, b, c in trueline ] )
zData = [ 20 * point_to_line_distance( x , y, z , .7, 1.7, *fixpoint ) for x, y, z in rndData ]

### unweighted
bestFitValuesUW, ier= optimize.leastsq(residuals, [ 0, 0],args=( fixpoint, rndData ) )
print bestFitValuesUW
uwLine = np.array( [ affine_line( s, bestFitValuesUW[0], bestFitValuesUW[1], *fixpoint ) for s in np.linspace( -2, 2, 50 ) ] )

### weighted ( chose inverse distance as weight....would be charge in OP's case )
bestFitValuesW, ier= optimize.leastsq(residuals, [ 0, 0],args=( fixpoint, rndData, [ 1./s for s in zData ] ) )
print bestFitValuesW
wLine = np.array( [ affine_line( s, bestFitValuesW[0], bestFitValuesW[1], *fixpoint ) for s in np.linspace( -2, 2, 50 ) ] )

### plotting
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1, projection='3d' )
ax.plot( *np.transpose(trueline ) ) 
ax.scatter( *fixpoint, color='k' )
ax.scatter( rndData[::,0], rndData[::,1], rndData[::,2] , c=zData, cmap=cm.jet )

ax.plot( *np.transpose( uwLine ) ) 
ax.plot( *np.transpose( wLine ) ) 

ax.set_xlim( [ 0, 2.5 ] )
ax.set_ylim( [ 1, 3.5 ] )
ax.set_zlim( [ -1.25, 1.25 ] )

plt.show()
Run Code Online (Sandbox Code Playgroud)

返回

>> [-0.68236386 -1.3057938 ]
>> [-0.70928735 -1.4617517 ]
Run Code Online (Sandbox Code Playgroud)

结果

固定点以黑色显示。原线为蓝色。未加权和加权拟合分别为橙色和绿色。数据根据到线的距离着色。