[英]manipulate Tensor by indices and values in TensorFlow
需求
給定張量像:
SparseTensorValue(indices=array([[0, 0], [1, 0], [1, 1], [1, 2]]),
values=array([2, 0, 2, 5]),
dense_shape=array([2, 3]))
形狀是2x3
| 2 na na |
| 0 2 5 |
需要一個索引中具有值的新張量,如下所示:
請注意,值的總數為6([0、1、2、3、4、5]的集合),形狀為2x6
| 0 0 1 0 0 0 |
| 1 0 1 0 0 1 |
張量可以通過以下代碼創建:
SparseTensorValue(indices=array([[0, 2], [1, 0], [1, 2], [1, 5]]),
values=array([1, 1, 1, 1]),
dense_shape=array([2, 6]))
如何以TensorFlow方式進行? 以下兩種方法均無效
import tensorflow as tf
tags = tf.SparseTensor(indices=[[0, 0], [1, 0], [1, 1], [1, 2]],
values=[2, 0, 2, 5],
dense_shape=[2, 3])
print(type(tags.indices))
# approach 1: the TensorFlow way to implement the python logic
new_indices = [[tags.indices[i], tags.values[i]]
for i in range(tags.values.shape[0])] # syntax incorrect
# approach 2:
indice_idx = tf.map_fn(lambda x : x[0], tags.indices)
value_idx = tf.map_fn(lambda x : x[1], tags.indices)
value_arr = tf.gather(tags.values, value_idx)
with tf.Session() as s1:
print(indice_idx.eval())
print(tags.values.eval())
print('value_arr', value_arr.eval())
"""
[0 0 1 2] <-- value_idx, which is the index of tags.values
want to combine
[0 1 1 1] <-- indice_idx
[2 2 0 2] <-- value_arr, which is the value of tags.values
==>
[[0,2], [1,2], [1,0], [1,2]]
"""
new_indices = tf.concat(indice_idx, value_arr) # syntax incorrect
with tf.Session() as s:
s.run([tf.global_variables_initializer(), tf.tables_initializer()])
print(s.run(value_arr))
print(s.run(tags.values))
print(s.run(new_indices))
print(s.run(tags.indices[3, 1]))
回答
在方法2中: new_indices = tf.stack([indice_idx, value_arr], axis=1)
完整版本的代碼是
import tensorflow as tf
tags = tf.SparseTensor(indices=[[0, 0], [1, 0], [1, 1], [1, 2]],
values=[2, 0, 2, 5],
dense_shape=[2, 3])
print(type(tags.indices))
# # approach 1: any TensorFlow way to implement the Python logic below?
# new_indices = [[tags.indices[i], tags.values[i]]
# for i in range(tags.values.shape[0])] # syntax incorrect
# approach 2:
indice_idx = tf.map_fn(lambda x : x[0], tags.indices)
value_idx = tf.map_fn(lambda x : x[1], tags.indices)
value_arr = tf.cast(tf.gather(tags.values, value_idx), tf.int64)
with tf.Session() as s1:
print(indice_idx.eval())
print(tags.values.eval())
print('value_arr', value_arr.eval())
"""
[0 0 1 2] <-- value_idx, which is the index of tags.values
tf.stack does:
[0 1 1 1] <-- indice_idx
[2 2 0 2] <-- value_arr, which is the value of tags.values
==>
[[0,2], [1,2], [1,0], [1,2]]
"""
new_indices = tf.stack([indice_idx, value_arr], axis=1)
with tf.Session() as s:
s.run([tf.global_variables_initializer(), tf.tables_initializer()])
print(s.run(value_arr))
print(s.run(tags.values))
print(s.run(new_indices))
print(s.run(tags.indices[3, 1]))
這個問題本身就解決了。
一個單獨的相關問題
附注:如果讀取文件,它將無法正常工作,請參閱:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.