张量,python,tensorflow,scikit-learn,cosine-similarity"/>

首页 > 解决方案 > TypeError:无法转换类型的对象张量

问题描述

我正在尝试使用 tensorflow 计算 350k 句子之间的余弦相似度。

我的句子首先使用 sklearn 进行矢量化:

doc =  df['text']
vec = TfidfVectorizer(binary=False,norm='l2',use_idf=False,smooth_idf=False,lowercase=True,stop_words='english',min_df=1,max_df=1.0,max_features=None,ngram_range=(1, 1))
X = vec.fit_transform(doc)
print(X.shape)
print(type(X))

这很好用,我得到了稀疏矩阵,然后我尝试了两种方法将我的稀疏矩阵转换为密集矩阵。

(1)我试过这个:

dense = X.toarray()

这仅适用于少量数据(大约 10k 个句子),但在实际计算中会失败。

(2) 我一直在尝试以X 这种方式转换输出,但在执行第一步时得到相同的错误消息K

K = tf.convert_to_tensor(X, dtype=None, dtype_hint=None, name=None)
Y = tf.sparse.to_dense(K, default_value=None, validate_indices=True, name=None)

任何解决这个谜团的提示/技巧将不胜感激。如果在大小方面应该更有效,也很高兴考虑批量计算我的计算?

标签: pythontensorflowscikit-learncosine-similarity

解决方案


你需要从你的 SciPy 中创建一个 TensorFlow 稀疏矩阵。由于您的矩阵似乎是 CSR 格式,您可以按如下方式进行:

import numpy as np
import scipy.sparse
import tensorflow as tf

def sparse_csr_to_tf(csr_mat):
    indptr = tf.constant(csr_mat.indptr, dtype=tf.int64)
    elems_per_row = indptr[1:] - indptr[:-1]
    i = tf.repeat(tf.range(csr_mat.shape[0], dtype=tf.int64), elems_per_row)
    j = tf.constant(csr_mat.indices, dtype=tf.int64)
    indices = np.stack([i, j], axis=-1)
    data = tf.constant(csr_mat.data)
    return tf.sparse.SparseTensor(indices, data, csr_mat.shape)

# Test
m = scipy.sparse.csr_matrix([
    [0, 0, 1, 0],
    [0, 0, 0, 0],
    [2, 0, 3, 4],
], dtype=np.float32)
tf_mat = sparse_csr_to_tf(m)
tf.print(tf.sparse.to_dense(tf_mat))
# [[0 0 1 0]
#  [0 0 0 0]
#  [2 0 3 4]]

推荐阅读