我正在尝试构建一个自定义的Keras层,该层从前一个softmax层中选择一个类别,并返回其对应的独热编码向量。例如,如果Softmax层返回[0.4 0.1 0.5],我希望根据这个softmax概率在类别0到2中随机选择一个类别。
这是我目前所做的工作:
import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersfrom tensorflow.keras import utilsdef sampling(x): # 在这里:我需要将'x'输入到'tf.math.log'函数中,但我尝试后产生了一个错误 samples = tf.random.categorical(tf.math.log([[0.4 0.1 0.5]]), 1) # samples应该像[[z]],其中z是0到2之间的一个数字 return utils.to_categorical(samples[0][0], num_classes=3)x = keras.Input(shape=(1,1,))x, _, _ = layers.LSTM(100, return_sequences=True, return_state=True)(x)x = layers.Dense(3, activation="softmax")(x)x = layers.Lambda(sampling)(x)
这段代码返回的结果是:
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/np_utils.pyin to_categorical(y, num_classes, dtype)6768 “””—> 69 y = np.array(y, dtype=’int’)70 input_shape = y.shape71 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
TypeError: array() 需要1个位置参数,但提供了2个
这里是Google Colab链接
回答:
你可以使用tf.one_hot
来实现这一点。
如果采样函数的输入是二维的:
X = np.random.uniform(0,1, (100,1,1))y = tf.keras.utils.to_categorical(np.random.randint(0,3, (100,)))def sampling(x): zeros = x*0 ### 无用但重要,用于产生梯度 samples = tf.random.categorical(tf.math.log(x), 1) samples = tf.squeeze(tf.one_hot(samples, depth=3), axis=1) return zeros+samplesinp = Input(shape=(1,1,))x, _, _ = LSTM(100, return_sequences=False, return_state=True)(inp)x = Dense(3, activation="softmax")(x)out = Lambda(sampling)(x)model = Model(inp, out)model.compile('adam', 'categorical_crossentropy')model.fit(X,y, epochs=3)
如果采样函数的输入是三维的:
tf.random.categorical
只接受二维的logits。你可以使用tf.map_fn
来适应三维的logits操作
X = np.random.uniform(0,1, (100,1,1))y = tf.keras.utils.to_categorical(np.random.randint(0,3, (100,)))y = y.reshape(-1,1,3)def sampling(x): zeros = x*0 ### 无用但重要,用于产生梯度 samples = tf.map_fn(lambda t: tf.random.categorical(tf.math.log(t), 1), x, fn_output_signature=tf.int64) samples = tf.squeeze(tf.one_hot(samples, depth=3), axis=1) return zeros+samplesinp = Input(shape=(1,1,))x, _, _ = LSTM(100, return_sequences=True, return_state=True)(inp)x = Dense(3, activation="softmax")(x)out = Lambda(sampling)(x)model = Model(inp, out)model.compile('adam', 'categorical_crossentropy')model.fit(X,y, epochs=3)
这里是运行的笔记本