稀疏矩阵

在不定长文本识别中用到了稀疏矩阵

将列表数据转化为稀疏矩阵的代码如下:

import numpy as np
def _sparse_tuple_from(sequences, dtype=np.int32):
    """
    将矩阵转为稀疏矩阵存储方式
    :param sequences:
    :param dtype:
    :return:
    """

    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)

    return indices, values, shape

batch_label=[]
batch_label.append([56,45,2347])
batch_label.append([1,6,7,13,98])
batch_label.append([2,6,4,32,12,78])
batch_label.append([15,3])

batch_label=_sparse_tuple_from(batch_label)

print(batch_label)

返回一个三元元组,分别是indices, values, shape

结果如下:

tf.sparse_tensor_to_dense将稀疏张量转换为稠密张量

import tensorflow as tf


label = tf.sparse_placeholder(tf.int32, name='label')

dense_decoded = tf.sparse_tensor_to_dense(label, default_value=-1)

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	print(sess.run(dense_decoded,feed_dict={label:batch_label}))

结果如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值