Python:使用 scipy.optimize.minimize 旋转角度不正确

问题描述 投票:0回答:1

我有两组 x 和 y 坐标,其中一组绕原点 (0,0) 旋转成为另一组。我想知道旋转角度是多少。

无论如何,我看到的角度不正确,无法找到脚本的错误。

此脚本产生的角度约为 -45°,但本示例的正确角度是 5°。

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

# function to calculate the error between both datasets
def error(rotation_angle, data1, data2):

    theta = np.radians(rotation_angle)
    rotation_matrix = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])
    
    # rotate data1
    rotated_data1 = np.matmul(data1, rotation_matrix)
    error = np.sum((rotated_data1 - data2) ** 2)

    return error

# calculated sample data for a rotation of 5°
data1 = np.array([[0, 0], [0, 1], [0, 2], [0, 3]])
data2 = np.array([[0, 0], [0.08715574, 0.9961947],[0.17431149, 1.9923894],[0.26146723, 2.98858409]])

# this value is low as expected (6.741376595818406e-17)
print(error(5, data1, data2))

initial_guess = 3

# minimize error to obtain the angle
result = minimize(error, initial_guess, args=(data1, data2), method='L-BFGS-B')

print(result)

fitted_rotation_angle = result.x[0]
print("rotation angle:", fitted_rotation_angle)

结果如下:

       message: Optimization terminated successfully.
       success: True
        status: 0
           fun: 13.101511152940214
             x: [-4.500e+01]
           nit: 27
          nfev: 54
 final_simplex: (array([[-4.500e+01],
                       [-4.500e+01]]), array([ 1.310e+01,  1.310e+01]))
rotation angle: -45.0000000000001

另一方面,误差函数图似乎状况良好:

angle = np.arange(4, 6., 0.01)
plt.plot(angle,[error(a, data1, data2) for a in angle])
plt.xlabel("rotation angle [°]")
plt.ylabel("error")
plt.show()

Error-Function over rotation angle.

我做错了什么?

python optimization data-fitting scipy-optimize-minimize rotational-matrices
1个回答
1
投票

问题是

minimize
没有发送
rotation_angle
的单个号码。它发送一个单元素 numpy 数组,这会搞砸你的计算。添加:

def error(rotation_angle, data1, data2):
    if isinstance(rotation_angle,np.ndarray):
        rotation_angle = rotation_angle[0]

一切都运转良好。

© www.soinside.com 2019 - 2024. All rights reserved.