Tensorflow 稀疏向量, 密集向量

稀疏向量转密集向量

代码:

import tensorflow as tf

def getSparseTensor():

    indices = [[0, 0], [1, 2]]
    values = [1, 2]
    shape = [3, 4]
    return indices, values, shape

if __name__ == "__main__":
    sparse_tensor = getSparseTensor()
    targets = tf.sparse_placeholder(tf.int32, name='targets')

    dense_tensor1 = tf.sparse_tensor_to_dense(targets, default_value=0)

    with tf.Session() as sess:
        print(sess.run(dense_tensor1, feed_dict={targets: sparse_tensor}))

输出:

[[1 0 0 0]
 [0 0 2 0]
 [0 0 0 0]]

密集向量转稀疏向量

代码

import numpy as np

def sparse_tuple_from(sequences, dtype=np.int32):
    """
        Inspired (copied) from https://github.com/igormq/ctc_tensorflow_example/blob/master/utils.py
    """

    indices = []
    values = []

    for n, seq in enumerate(sequences):
        indices.extend(zip([n] * len(seq), [i for i in range(len(seq))]))
        values.extend(seq)

    indices = np.asarray(indices, dtype=np.int64)
    values = np.asarray(values, dtype=dtype)
    shape = np.asarray(
        [len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64
    )

    print("*************")
    print(indices)
    print("-------------")
    print(values)
    print("-------------")
    print(shape)
    print("*************")

    return indices, values, shape

if __name__ == "__main__":
    codes = [[1, 2], [3]]
    targets = [np.asarray(i) for i in codes]
    print(targets)
    sparse_tuple_from(targets)

输出

[array([1, 2]), array([3])]
*************
[[0 0]
 [0 1]
 [1 0]]
-------------
[1 2 3]
-------------
[2 2]
*************

你可能感兴趣的:(Tensorflow)