這個問題是關于派生一個數學函式,該函式根據資料陣列回傳成對的值 - 二維值來自二維值。
我創建
從筆的 x/y 位置,我獲得所需的電機角度,并從中獲得需要饋送到它們的脈沖寬度。
這些廉價的電機當然是相當非線性的,并且整個機械系統表現出滯后和失真行為。
該庫可以以不同的方式計算所需的脈沖寬度值。一種方法是確定每個伺服系統的一些實際脈沖寬度/角度測量值,如下所示:
servo_angle_pws = [
# angle, pulse-width
[ 45, 1000],
[ 60, 1200],
[ 90, 1500],
[120, 1800],
[135, 2000],
]
然后
現在我想再邁出一步,以類似的方式找到一個函式,讓我知道 x/y 位置和脈沖寬度之間的關系,而不是角度(這將提供更高的準確性,因為它會考慮更多系統中的實際缺陷)。不過,在這種情況下,我將有兩對值,如下所示:
# x/y positions, servo pulse-widths
((-8.0, 8.0), (1900, 1413)),
((-8.0, 4.0), (2208, 1605)),
(( 8.0, 4.0), ( 977, 1622)),
((-0.0, 4.0), (1759, 1999)),
(( 6.0, 13.0), (1065, 1121)),
我的問題是:我需要做什么才能獲得一個函式(我當然需要其中兩個),它回傳所需的一對 x/y 位置的脈沖寬度值?例如:
pw1 = xy_to_pulsewidths1(x=-4, y=6.3)
pw2 = xy_to_pulsewidths2(x=-4, y=6.3)
我相信我需要做一個“多元回歸”——但我不是數學家,所以我不知道這是否正確,即使是這樣,我在 numpy 和 scipy 的研究中還沒有發現任何表明什么我實際上需要在我的代碼中做。
uj5u.com熱心網友回復:
如果我理解正確,您想要執行多元回歸,這相當于解決多元最小二乘問題。假設您的函式是一個二維多項式,您可以使用polyval2d和的組合scipy.optimize.least_squares:
import numpy as np
from numpy.polynomial.polynomial import polyval2d
from scipy.optimize import least_squares
x = np.array((-8.0,-8.0, 8.0, -0.0, 6.0))
y = np.array((8.0, 4.0, 4.0, 4.0, 13.0))
pulse_widths = np.array(((1900, 1413),(2208, 1605),(977, 1622),(1759, 1999),(1065, 1121)))
# we want to minimize the sum of the squares of the residuals
def residuals(coeffs, x, y, widths, poly_degree):
return polyval2d(x, y, coeffs.reshape(-1, poly_degree 1)) - widths
# polynomial degree
degree = 3
# initial guess for the polynomial coefficients
x0 = np.ones((degree 1)**2)
# res1.x and res2.x contain your coefficients
res1 = least_squares(lambda coeffs: residuals(coeffs, x, y, pulse_widths[:, 0], degree), x0=x0)
res2 = least_squares(lambda coeffs: residuals(coeffs, x, y, pulse_widths[:, 1], degree), x0=x0)
# Evaluate the 2d Polynomial at (x,y)
def xy_to_pulswidth(x, y, coeffs):
num_coeffs = int(np.sqrt(coeffs.size))
return polyval2d(x, y, coeffs.reshape(-1, num_coeffs))
# Evaluate the function
pw1 = xy_to_pulswidth(-4, 6.3, res1.x)
pw2 = xy_to_pulswidth(-4, 6.3, res2.x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463190.html
