有时默认的标准激活,如ReLU,tanh,softmax,......和LeakyReLU等高级激活是不够的.它也可能不属于keras-contrib.
你如何创建自己的激活功能?
我正在尝试使用 TF2.4 和 Keras 并使用 tf.nn.sampled_softmax_loss 来训练词嵌入分类器。但是,在调用模型的fit方法时,出现“Cannot convert asymbolic Keras input/output to a numpy array”TypeError。请帮助我修复错误或使用替代方法进行候选抽样。
import tensorflow as tf
import numpy as np
TextVectorization = tf.keras.layers.experimental.preprocessing.TextVectorization
class SampledSoftmaxLoss: #(tf.keras.losses.Loss):
def __init__(self, model, n_classes):
self.model = model
output_layer = model.layers[-1]
self.input = output_layer.input
self.weights = output_layer.weights
self.n_classes = n_classes
def loss(self, y_true, y_pred, **kwargs):
labels = tf.argmax(y_true, axis=1)
labels = tf.expand_dims(labels, -1)
loss = tf.nn.sampled_softmax_loss(
weights=self.weights[0],
biases=self.weights[1],
labels=labels,
inputs=self.input,
num_sampled = 3,
num_classes = self.n_classes
)
return loss
max_features = 50 …Run Code Online (Sandbox Code Playgroud) 我考虑过的一些方法:
从模型类继承 tensorflow keras 中的采样 softmax
从层类继承 如何在 Keras 模型中使用 TensorFlow 的采样 softmax 损失函数?
在这两种方法中,模型方法更简洁,因为层方法有点笨拙——它将目标作为输入的一部分推入,然后再见多输出模型。
我想在对 Model 类进行子类化方面得到一些帮助 - 具体来说:1) 与第一种方法不同 - 我想在指定标准 keras 模型时采用任意数量的层。例如,
class LanguageModel(tf.keras.Model):
def __init__(self, **kwargs)
Run Code Online (Sandbox Code Playgroud)
2)我希望在模型类中合并以下代码 - 但想让模型类认识到
def call(self, y_true, input):
""" reshaping of y_true and input to make them fit each other """
input = tf.reshape(input, (-1,self.hidden_size))
y_true = tf.reshape(y_true, (-1,1))
weights = tf.Variable(tf.float64))
biases = tf.Variable(tf.float64)
loss = tf.nn.sampled_softmax_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, …Run Code Online (Sandbox Code Playgroud)