与单热编码向量一起使用时,如何解释 Keras 中嵌入层的输出形状?
How to interpret the output shape from an Embedding layer in Keras, when used with one-hot encoded vectors?
我有一大组消费品,每一种都被分配到多个类别。例如,一件夹克可以同时属于 "Sports" 和 "Outdoors" 类别。
有很多很多类别 (~1000),我想创建一个低维嵌入,我可以用它来比较产品的相似性。
我首先创建了一组代表每个产品的单热编码:
import pandas as pd
df = pd.read_csv("/tmp/one-hot.csv")
df.head()
# Sports Mens Womens Outdoor
# Product 1 1 1 0 1 ...
# Product 2 0 0 1 1 ...
# ...~30000 more products
...然后创建了一个 Keras 嵌入层。由于有 1000 个可能的类别,总词汇量为 1000(对吗?)。我投影到 10 个维度,每个乘积向量的长度为 1000。
import numpy as np
from keras.models import Sequential
from keras.layers import Embedding, Flatten
model = Sequential()
model.add(Embedding(1000, 10, input_length=1000))
model.compile('rmsprop', 'mse')
model.summary()
# Model: "sequential_17"
# _________________________________________________________________
# Layer (type) Output Shape Param #
# =================================================================
# embedding_17 (Embedding) (None, 1000, 10) 10000
# =================================================================
# Total params: 10,000
# Trainable params: 10,000
# Non-trainable params: 0
output = model.predict(df)
print(output.shape)
print(output.ndim)
# (30000, 1000, 10)
# 3
我很难理解输出形状。我曾期待一个二维向量 (30,000, 10),其中每一行都是一个产品,值是嵌入值。
是嵌入层设置不正确,还是我误解了输出向量代表什么?
您的 Embedding
实例有两个问题:
- 嵌入采用整数,而不是单热编码值。
你设置了input_length=1000
,这意味着一个整数值序列,而不是输入的维度。这会影响输入和输出中的时间步数,因此您应该省略此参数:
model.add(Embedding(1000, 10))
我有一大组消费品,每一种都被分配到多个类别。例如,一件夹克可以同时属于 "Sports" 和 "Outdoors" 类别。
有很多很多类别 (~1000),我想创建一个低维嵌入,我可以用它来比较产品的相似性。
我首先创建了一组代表每个产品的单热编码:
import pandas as pd
df = pd.read_csv("/tmp/one-hot.csv")
df.head()
# Sports Mens Womens Outdoor
# Product 1 1 1 0 1 ...
# Product 2 0 0 1 1 ...
# ...~30000 more products
...然后创建了一个 Keras 嵌入层。由于有 1000 个可能的类别,总词汇量为 1000(对吗?)。我投影到 10 个维度,每个乘积向量的长度为 1000。
import numpy as np
from keras.models import Sequential
from keras.layers import Embedding, Flatten
model = Sequential()
model.add(Embedding(1000, 10, input_length=1000))
model.compile('rmsprop', 'mse')
model.summary()
# Model: "sequential_17"
# _________________________________________________________________
# Layer (type) Output Shape Param #
# =================================================================
# embedding_17 (Embedding) (None, 1000, 10) 10000
# =================================================================
# Total params: 10,000
# Trainable params: 10,000
# Non-trainable params: 0
output = model.predict(df)
print(output.shape)
print(output.ndim)
# (30000, 1000, 10)
# 3
我很难理解输出形状。我曾期待一个二维向量 (30,000, 10),其中每一行都是一个产品,值是嵌入值。
是嵌入层设置不正确,还是我误解了输出向量代表什么?
您的 Embedding
实例有两个问题:
- 嵌入采用整数,而不是单热编码值。
你设置了
input_length=1000
,这意味着一个整数值序列,而不是输入的维度。这会影响输入和输出中的时间步数,因此您应该省略此参数:model.add(Embedding(1000, 10))