Я опирался на другие ответы и оригинальную формулу регрессии, чтобы построить функцию, которая работает для любого тензора.
Он рассчитает наклоны данных вдоль заданной оси. Итак, если у вас есть произвольные тензоры X[i,j,k,l], Y[i,j,k,l]
и вы хотите знать наклоны для всех других осей вдоль данных на третьей оси, вы можете вызвать его с помощью calcSlopes( X, Y, axis = 2 )
.
import numpy as np
def calcSlopes( x = None, y = None, axis = -1 ):
assert x is not None or y is not None
# assume that the given single data argument are equally
# spaced y-values (like in numpy plot command)
if y is None:
y = x
x = None
# move axis we wanna calc the slopes of to first
# as is necessary for subtraction of the means
# note that the axis 'vanishes' anyways, so we don't need to swap it back
y = np.swapaxes( y, axis, 0 )
if x is not None:
x = np.swapaxes( x, axis, 0 )
# https://en.wikipedia.org/wiki/Simple_linear_regression
# beta = sum_i ( X_i - <X> ) ( Y_i - <Y> ) / ( sum_i ( X_i - <X> )^2 )
if x is None:
# axis with values to reduce must be trailing for broadcast_to,
# therefore transpose
x = np.broadcast_to( np.arange( y.shape[0] ), y.T.shape ).T
x = x - ( x.shape[0] - 1 ) / 2. # mean of (0,1,...,n-1) is n*(n-1)/2/n
else:
x = x - np.mean( x, axis = 0 )
y = y - np.mean( y, axis = 0 )
# beta = sum_i x_i y_i / sum_i x_i*^2
slopes = np.sum( np.multiply( x, y ), axis = 0 ) / np.sum( x**2, axis = 0 )
return slopes
У него также есть уловка для работы с данными с одинаково разнесенными y данными. Так, например:
y = np.array( [
[ 1, 2, 3, 4 ],
[ 2, 4, 6, 8 ]
] )
print( calcSlopes( y, axis = 0 ) )
print( calcSlopes( y, axis = 1 ) )
x = np.array( [
[ 0, 2, 4, 6 ],
[ 0, 4, 8, 12 ]
] )
print( calcSlopes( x, y, axis = 1 ) )
Выход:
[1. 2. 3. 4.]
[1. 2.]
[0.5 0.5]