假设您有 N 个不直接具有数学表示的对象。例如单词。
由于神经网络只能处理张量,因此您应该寻找某种方法将这些对象转换为张量。
解决方案是在一个巨大的矩阵(embedding matrix)中,它将对象的每个索引与其与张量的平移相关联。
object_index_1: vector_1
object_index_1: vector_2
...
object_index_n: vector_n
选择特定对象的向量可以通过以下方式转换为矩阵乘积:
其中 v 是确定需要翻译哪个单词的 one-hot 向量。 M 是嵌入矩阵。
如果我们提出通常的管道,它将如下:
- 我们有一个对象列表。
objects = ['cat', 'dog', 'snake', 'dog', 'mouse', 'cat', 'dog', 'snake', 'dog']
- 我们将这些对象转换为索引(我们计算唯一对象)。
unique = ['cat', 'dog', 'snake', 'mouse'] # list(set(objects))
objects_index = [0, 1, 2, 1, 3, 0, 1, 2, 1] #map(unique.index, objects)
- 我们将这些索引转换为一个热向量(请记住,索引所在的位置只有一个)
objects_one_hot = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0],
[0, 0 , 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0]] # map(lambda x: [int(i==x) for i in range(len(unique))], objects_index)
#objects_one_hot is matrix is 4x9
- 我们创建或使用嵌入矩阵:
#M = matrix of dim x 4 (where dim is the number of dimensions you want the vectors to have).
#In this case dim=2
M = np.array([[1, 1], [1, 2], [2, 2], [3,3]]).T # or... np.random.rand(2, 4)
#objects_vectors = M * objects_one_hot
objects_vectors = [[1, 1], [1, 2], [2, 2], [1, 2],
[3, 3], [1, 1], [1, 2], [2,2], [1, 2]] # M.dot(np.array(objects_one_hot).T)
通常嵌入矩阵是在同一个模型学习过程中学习的,为每个对象适配最佳向量。我们已经有了对象的数学表示!
如您所见,我们使用了一种热产品,后来又使用了矩阵产品。您真正要做的是获取代表该单词的 M 列。
在学习过程中,这个 M 将被调整以改善对象的表示,因此损失会下降。