So I i have a function that takes 2 arrays and returns 2 floats. But now i need to apply it for each 2xN subarray in initial one. That's what I have for now.
import numpy as np
def least_square(x, y=None):
print(x, y)
if y is None:
x, y = x
k = (np.mean(x*y)-np.mean(x)*np.mean(y))/np.var(x)
b = np.mean(y)-np.mean(x)*k
return k, b
n1, t1, r1 = np.array([5, 5, 10, 10, 20, 20]), np.array([6.53, 6.56, 13.44, 13.53, 27.38, 27.72]), 6.5
n2, t2, r2 = np.array([5, 5, 10, 10, 20, 20]), np.array([7.53, 7.62, 15.41, 15.57, 30.62, 30.87]), 4.9
n3, t3, r3 = np.array([5, 5, 10, 10, 20, 20]), np.array([8.53, 8.75, 17.50, 17.62, 36.18, 36.07]), 3.9
n4, t4, r4 = np.array([5, 5, 10, 10, 8, 8]), np.array([10.8, 11.07, 19.47, 19.38, 16.03, 15.69]), 2.5
n5, t5, r5 = np.array([5, 5, 10, 10, 8, 8]), np.array([11.91, 11.65, 21.97, 22.50, 19.25, 19.53]), 2.2
n_s = np.array([n1, n2, n3, n4, n5])
t_s = np.array([t1, t2, t3, t4, t5])
T_ls = [least_square(x, y) for x, y in np.stack((n_s, t_s), axis=-2)]
Would like to apply to this array, so function would get pairs of 6-length arrays.
print(np.stack((n_s, t_s), axis=-2))
[[[ 5. 5. 10. 10. 20. 20. ]
[ 6.53 6.56 13.44 13.53 27.38 27.72]]
[[ 5. 5. 10. 10. 20. 20. ]
[ 7.53 7.62 15.41 15.57 30.62 30.87]]
[[ 5. 5. 10. 10. 20. 20. ]
[ 8.53 8.75 17.5 17.62 36.18 36.07]]
[[ 5. 5. 10. 10. 8. 8. ]
[10.8 11.07 19.47 19.38 16.03 15.69]]
[[ 5. 5. 10. 10. 8. 8. ]
[11.91 11.65 21.97 22.5 19.25 19.53]]]
Returns
T_ls
[(1.401214285714286, -0.48750000000000426),
(1.5419285714285704, -0.05249999999998778),
(1.8357857142857141, -0.6424999999999947),
(1.693552631578944, 2.422763157894762),
(2.1261842105263162, 1.5009210526315755)]
But i'm almost sure that there's better way of doing that in numpy.
I'm not sure what you mean by a "better way", but I prefer matrix multiplication for finding the least squares.
def least_square_v2(x, y=None):
if y is None:
x, y = x
X = np.c_[np.ones(x.shape[0]), x]
k = np.dot(np.linalg.inv(np.dot(X.T, X)), X.T)
b = np.dot(k, y)
return b
The matrix multiplication method is also slightly faster.
op's function timeit
355 µs ± 30.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
v2 timeit
276 µs ± 16 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.