我想創建一個自定義 ReLU 函式,該函式采用一個V包含 2D 像素位置的向量,即[[1, 3], [1,1] ..]
并在所有通道上對這些像素執行 ReLU 操作。
input_tensor 是通過Conv2D 層后的張量 - 所以它的形狀是:(None, 30, 30, 16)
(原圖是32x32x3)
我的代碼(我知道它實際上不會回傳更改后的 input_tensor,它只是對我遇到的一些第一個問題進行排序):
def relu(x):
if x > 0:
return x
else:
return 0
class Custom_ReLU(Layer):
def __init__(self):
super(Custom_ReLU, self).__init__()
def call(self, input_tensor, V=None):
for i in range(len(V)):
relu(input_tensor[ V[i] ])
return input_tensor
運行此程式時,我收到一個錯誤,我將張量傳遞給 relu - 所以我的索引不正確,但我嘗試以不同的方式索引它,但我一無所獲:
ValueError: Exception encountered when calling layer "custom__re_lu" (type Custom_ReLU).
in user code:
File "/home/adav/prog/tf/main.py", line 63, in call *
relu(input_tensor[ V[i][0], V[i][1] ])
File "/home/adav/prog/tf/main.py", line 51, in relu *
if x > 0:
ValueError: condition of if statement expected to be `tf.bool` scalar, got Tensor("my_model/custom__re_lu/Greater:0", shape=(30, 16), dtype=bool); to check for None, use `is not None`
Call arguments received:
? input_tensor=tf.Tensor(shape=(None, 30, 30, 16), dtype=float32)
? V=array([[ 1, 1],
[ 1, 4],
[ 1, 7],
.
.
.
任何幫助,將不勝感激 !
uj5u.com熱心網友回復:
您可以嘗試使用tf.gather_ndand tf.tensor_scatter_nd_update:
import tensorflow as tf
class Custom_ReLU(tf.keras.layers.Layer):
def __init__(self):
super(Custom_ReLU, self).__init__()
def call(self, inputs):
shape = tf.shape(inputs)
V = tf.stack([(i, j) for i in tf.range(1,29,3) for j in tf.range(1,29,3)])
indices = tf.concat([tf.expand_dims(tf.repeat(tf.range(0, shape[0]), repeats=tf.shape(V)[0]), axis=-1), tf.tile(V, [shape[0],1])], axis=-1)
y = tf.gather_nd(inputs, indices)
y = tf.where(tf.greater(y, 0.0), y, tf.constant(0.0))
return tf.tensor_scatter_nd_update(x, indices, y)
custom_relu = Custom_ReLU()
x = tf.random.normal((2, 30, 30, 16))
print(custom_relu(x))
使用較小的張量運行幾次迭代以查看值如何變化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426827.html
