[英]using tensorflow functions with tf.keras
I have a question regarding tf.keras and tf functions in tf 2.0.我有一个关于 tf.keras 和 tf 2.0 中的 tf 函数的问题。 If i have a model like this:
如果我有这样的模型:
inputdata = keras.Input(shape=(2048, 1))
x = layers.Conv1D(16, 3, activation='relu')(inputdata)
x = layers.Conv1D(32, 3, activation='relu')(x)
x = layers.Conv1D(64, 3, activation='relu')(x)
and I want to add a custom function like this which is a 1D SubPixel Layer:我想添加一个像这样的自定义函数,它是一个 1D 子像素层:
def SubPixel1D(I, r):
with tf.name_scope('subpixel'):
X = tf.transpose(I, [2,1,0]) # (r, w, b)
X = tf.batch_to_space_nd(X, [r], [[0,0]]) # (1, r*w, b)
X = tf.transpose(X, [2,1,0])
return X
can I include this layer in keras without problems?我可以在 keras 中包含这一层而没有问题吗? Since tensorflow 2.0 is so much easier then the previous tensorflow versions iam not sure about it if this is not mixing up the backends and the sessions?
由于 tensorflow 2.0 容易得多,那么之前的 tensorflow 版本我不确定这是否不会混淆后端和会话?
inputdata = keras.Input(shape=(2048, 1))
x = layers.Conv1D(16, 3, activation='relu')(inputdata)
x = layers.Conv1D(32, 3, activation='relu')(x)
x = SubPixel1D(x,2)
x = layers.Conv1D(64, 3, activation='relu')(x)
after that compile and fit model will work?在那之后编译和拟合模型会起作用吗? If tensorflow and keras is imported
如果导入 tensorflow 和 keras
import tensorflow as tf
from tensorflow import keras
similar to the a custom loss function in keras.类似于 keras 中的自定义损失函数。 If I define a custom loss function like this:
如果我定义一个这样的自定义损失函数:
def my_loss(y_true, y_pred):
# compute l2 loss/ equal to Keras squared mean
sqrt_l2_loss = tf.reduce_mean((y_pred-y_true)**2, axis=[1, 2])
avg_sqrt_l2_loss = tf.reduce_mean(sqrt_l2_loss, axis=0)
return avg_sqrt_l2_loss
and use tf.并使用 tf. operations or functions, can i just pass this function to keras as usual?
操作或函数,我可以像往常一样将此函数传递给 keras 吗? Can i just use it in Keras loss?
我可以在 Keras 损失中使用它吗?
Just subclass tf.keras.Layer
and you will be good to go.只需将
tf.keras.Layer
子类tf.keras.Layer
,您就可以开始使用了。 Great reference here:https://www.tensorflow.org/guide/keras/custom_layers_and_models .这里有很好的参考:https ://www.tensorflow.org/guide/keras/custom_layers_and_models 。 Your layer should look something like this:
您的图层应如下所示:
class SubPixel1D(tf.keras.layers.Layer):
def __init__(self, r)
super(SubPixel1D, self).__init__()
self.r = r
def call(self, inputs):
with tf.name_scope('subpixel'):
X = tf.transpose(inputs, [2,1,0]) # (r, w, b)
X = tf.batch_to_space_nd(X, [self.r], [[0,0]]) # (1, r*w, b)
X = tf.transpose(X, [2,1,0])
return X
and then call it when defining your model然后在定义模型时调用它
inputdata = keras.Input(shape=(2048, 1))
x = layers.Conv1D(16, 3, activation='relu')(inputdata)
x = layers.Conv1D(32, 3, activation='relu')(x)
x = SubPixel1D(2)(x)
x = layers.Conv1D(64, 3, activation='relu')(x)
I don't know how tf.name_scope
will behave, but I don't see any immediate issues.我不知道
tf.name_scope
会如何表现,但我没有看到任何直接的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.