Мне нужно сделать одномерную линейную интерполяцию для построения моей модели в TensorFlow. Я попытался следовать определению и написать функцию линейной интерполяции. Но это вычислительно интенсивно и почти непригодно для моей модели. Есть ли эффективный метод для выполнения одномерной интерполяции в TensorFlow?
Вот мой код для линейной интерполяции. похож на NumPy.interp ().
t contains interpolated values and it has shape [64,64].
x contains x-coordinates data points and it has shape [91,1].
y contains y-coordinates data points and it has shape [91,1].
t and x are numpy arraies and y is a tensor.
def tf_interpolation_v2(t, x, y, left, right):
# perform one dimensional linear interpolation
# returns tensor same shape as t
# t is the interpolated values
# x is the The x-coordinates of the data points, must be increasing
# y is the The y-coordinates of the data points, same length as x.
# left is the Value to return for x < x[0]
# right is the Value to return for x > x[-1]
t = np.asarray(t)
t = t.astype(np.float32)
x = x.astype(np.float32)
y = tf.cast(y, tf.float32)
t_return = []
t_return_row = []
for row in t:
for v in row:
if v < x[0]: # value smaller than x[0]
a = left
t_return_row.append(a)
elif v > x[-1]: # value larger than x[-1]
a = right
t_return_row.append(a)
else: # finding interval where t is in
nearest_index = 0 # initialize interval index
for i in range(1, len(x) - 1):
if (v >= x[i]) & (v <= x[i+1]): # if t larger than x[i] but smaller than x[i+1]. i is the index
nearest_index = i # we need
break
k = tf.subtract(tf.gather(y, nearest_index + 1), tf.gather(y, nearest_index)) # calculate slope
de_x = x[nearest_index + 1] - x[nearest_index]
k = tf.divide(k, de_x)
b_sub = tf.multiply(k, x[nearest_index]) # calculate bias
b = tf.subtract(tf.gather(y, nearest_index), b_sub)
a = tf.multiply(k, v)
a = tf.add(a, b)
t_return_row.append(a)
t_return.append(t_return_row)
t_return_row = []
t_return = tf.convert_to_tensor(t_return)
t_return = tf.cast(t_return, tf.float32)
return t_return
EDIT:
Я говорю, что это непригодно, потому что: TensorFlow нужно будет вычислять градиенты для всех этих переменных в функции линейной интерполяции, что делает сеть очень трудной для обучения. Это может быть ответом на вопрос, который я задал вчера.
В TensorFlow есть функция, выполняющая билинейную интерполяцию.
tf.contrib.resampler.resampler ()
Интересно, можно ли использовать эту функцию для линейной интерполяции в моих обстоятельствах?