import tensorflow as tf
# 2 * 2 * 2 的embedding 矩陣 , 一個batch,每個樣本有f個字段,每個字段有k維
# 那麼矩陣的大小就是batch * f * k
embedding_index = tf.constant([[[0.1,0.2],
[0.3,0.2]],
[[0.8,0.2],
[0.5,0.4]]
])
# 2 * 2 的係數矩陣
X_sparse = tf.constant([[1.0,2.0],
[3.0,4.0]])
# 爲了和embedding_index 相乘,需要增加一維度, 增加一維有下面兩種寫法
# 增加維度的方法1:sparse_value = tf.reshape(X_sparse, shape=[-1, 2, 1])
# 下面是增加維度的方法2
sparse_value = tf.expand_dims(X_sparse,2)
embedding_matmul = tf.matmul(embedding_index, sparse_value)
embedding_multiply = tf.multiply(embedding_index, sparse_value)
print(embedding_index)
print(sparse_value)
with tf.Session() as sess:
print(sess.run(X_sparse))
print("-"*10)
print(sess.run(sparse_value))
print("-"*10)
print(sess.run(embedding_index))
print("-"*10)
print(sess.run(embedding_matmul))
print("-"*10)
print(sess.run(embedding_multiply))
Tensor("Const_4:0", shape=(2, 2, 2), dtype=float32)
Tensor("ExpandDims_2:0", shape=(2, 2, 1), dtype=float32)
[[1. 2.]
[3. 4.]]
----------
[[[1.]
[2.]]
[[3.]
[4.]]]
----------
[[[0.1 0.2]
[0.3 0.2]]
[[0.8 0.2]
[0.5 0.4]]]
----------
[[[0.5 ]
[0.70000005]]
[[3.2 ]
[3.1 ]]]
----------
[[[0.1 0.2]
[0.6 0.4]]
[[2.4 0.6]
[2. 1.6]]]