我在使用Keras嵌入层来创建实体嵌入,这种方法在Kaggle的Rossmann Store Sales 第三名获奖作品中非常流行。然而,我不确定如何将这些嵌入映射回实际的分类值。让我们看一个非常基本的例子:
在下面的代码中,我创建了一个包含两个数值特征和一个分类特征的数据集。
分类列有5个唯一值:
print("Unique Values: ", np.unique(data[0]))Out[01]: array([0, 1, 2, 3, 4])
这些值然后被输入到带有嵌入层的Keras模型中:
inputs = []embeddings = []input_cat_col = Input(shape=(1,))embedding = Embedding(5, 3, input_length=1, name='cat_col')(input_cat_col)embedding = Reshape(target_shape=(3,))(embedding)inputs.append(input_cat_col)embeddings.append(embedding)# add the remaining two numeric columns from the 'data array' to the networkinput_numeric = Input(shape=(2,))embedding_numeric = Dense(8)(input_numeric)inputs.append(input_numeric)embeddings.append(embedding_numeric)x = Concatenate()(embeddings)output = Dense(1, activation='sigmoid')(x)model = Model(inputs, output)model.compile(loss='binary_crossentropy', optimizer='adam')history = model.fit(data, labels, epochs=10, batch_size=32, verbose=1, validation_split=0.2)
我可以通过获取嵌入层的权重来获得实际的嵌入:
embeddings = model.get_layer('cat_col').get_weights()[0]print("Unique Values: ", np.unique(data[0]))print("3 Dimensional Embedding: \n", embeddings)Unique Values: [0 1 2 3 4]3 Dimensional Embedding: [[ 0.02749949 0.04238378 0.0080842 ] [-0.00083209 0.01848664 0.0130044 ] [-0.02784528 -0.00713446 -0.01167112] [ 0.00265562 0.03886909 0.0138318 ] [-0.01526615 0.01284053 -0.0403452 ]]
然而,我不确定如何将这些值映射回去。可以安全地假设权重是有序的吗?例如,0=[ 0.02749949 0.04238378 0.0080842 ]
?
回答:
是的,嵌入层的权重对应于按整数索引的词语顺序,即嵌入层中的权重数组0对应于索引0的词语,以此类推。你可以将嵌入层视为一个查找表,其中表的第n行对应于第n个词的词向量(但嵌入层是一个可训练的层,而不仅仅是一个静态的查找表)
inputs = Input(shape=(1,))embedding = Embedding(5, 3, input_length=1, name='cat_col')(inputs)model = Model(inputs, embedding)x = np.array([0,1,2,3,4]).reshape(5,1)labels = np.zeros((5,1,3))print (model.predict(x))print (model.get_layer('cat_col').get_weights()[0])assert np.array_equal(model.predict(x).reshape(-1), model.get_layer('cat_col').get_weights()[0].reshape(-1))
model.predict(x):
[[[-0.01862894, 0.0021644 , 0.04706952]], [[-0.03891206, 0.01743075, -0.03666048]], [[-0.01799501, 0.01427511, -0.00056203]], [[ 0.03703432, -0.01952349, 0.04562894]], [[-0.02806044, -0.04623617, -0.01702447]]]
model.get_layer(‘cat_col’).get_weights()[0]
[[-0.01862894, 0.0021644 , 0.04706952], [-0.03891206, 0.01743075, -0.03666048], [-0.01799501, 0.01427511, -0.00056203], [ 0.03703432, -0.01952349, 0.04562894], [-0.02806044, -0.04623617, -0.01702447]]