tensorflow使用sparse_to_dense方法出現 indices is out of bounds的錯誤

tf.sparse_to_dense()方法有時會出現indices out of bounds的情況,比如:

import tensorflow as tf
# 假設數據標籤有3類
label = tf.expand_dims(tf.constant([1, 2, 2, 3, 3]), 1)
index = tf.expand_dims(tf.range(5), 1)
conact = tf.concat([index, label], 1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(tf.sparse_to_dense(conact, [5, 3], 1.0, 0.0)))
InvalidArgumentError (see above for traceback): indices[3] = [3,3] is out of bounds: need 0 <= index < [5,3]
	 [[Node: SparseToDense = SparseToDense[T=DT_FLOAT, Tindices=DT_INT32, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](concat/_1, SparseToDense/output_shape, SparseToDense/sparse_values, SparseToDense/default_value)]]

假設數據標籤爲1,2,3,按照常理輸出的矩陣大小爲[5,3],但這樣會出錯,可以把輸出矩陣大小改爲[5,4],或者將1,2,3標籤改爲0,1,2

print(sess.run(tf.sparse_to_dense(conact, [5, 4], 1.0, 0.0)))

[5,4]的輸出結果:
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 1.]]

label = tf.expand_dims(tf.constant([0, 1, 2, 2, 2]), 1)

[5,3]的輸出結果:
[[1. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章