我有以下功能
def pad_ones(arr):
return np.convolve(arr, [1, 1, 1], "same")
# for example:
# >>> pad_ones([0, 0, 0, 1, 0, 0])
# array([0, 0, 1, 1, 1, 0])
我想用它來處理 one_hot 編碼的陣列。這當前會在 tensorflow 中引發錯誤:
NotImplementedError: Cannot convert a symbolic Tensor to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
所以我嘗試使用 keras.backend 來實作它,但找不到合適的解決方案。np.convolve 的 keras 后端等價物是什么?我發現文章指出 keras 卷積與 np.correlate 相同,但我沒有找到任何文章解釋 keras.backend 中的 np.convolve 等價物。
我嘗試像這樣使用 K.conv1d:
K.conv1d(K.constant([0, 0, 1, 0, 0, 0]), K.constant([1, 1, 1]), "same")
但我收到以下錯誤:
ValueError: "num_spatial_dims" must be 1, 2, or 3. Received: num_spatial_dims=-1.
最終解決方案(特別感謝@AloneTogether):
def keras_pad_ones(one_hot_2d_matrix):
kernel = K.constant([1, 1, 1], shape=(3, 1, 1))
x = K.expand_dims(one_hot_2d_matrix)
x = K.conv1d(x, kernel, padding='same')
x = K.squeeze(x, axis=-1)
return x
# Example:
# >>> arr_1d = K.constant([0, 0, 0, 1, 0, 0])
# >>> keras_pad_ones(K.expand_dims(arr_1d, axis=0))
# output: [[0., 0., 1., 1., 1., 0.]]
# >>> arr_2d = K.constant([[0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0]])
# >>> keras_pad_ones(arr_2d)
# output: [[0., 0., 1., 1., 1., 0.], [1., 1., 0., 0., 0., 0.]]
uj5u.com熱心網友回復:
np.convolve使用 Tensorflow進行復制的一種簡單方法是使用tf.nn.conv1d:
import tensorflow as tf
original = tf.constant([0, 0, 0, 1, 0, 0], dtype=tf.float32)
x = tf.reshape(original, (1, tf.shape(original)[0], 1))
kernel = tf.constant([1, 1, 1], dtype=tf.float32)
kernel = tf.reshape(kernel, [tf.shape(kernel)[0], 1, 1])
x = tf.nn.conv1d(x, kernel, padding='SAME', stride=1)
x = tf.reshape(x, (tf.shape(x)[1]))
print(original)
print(x)
tf.Tensor([0. 0. 0. 1. 0. 0.], shape=(6,), dtype=float32)
tf.Tensor([0. 0. 1. 1. 1. 0.], shape=(6,), dtype=float32)
或tf.keras.backend.conv1d像這樣:
x = tf.keras.backend.conv1d(x, kernel, padding='same', strides=1)
其余代碼保持不變。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/409762.html
標籤:
