首页 文章

将稀疏矩阵转换为张量

提问于
浏览
2

我有一个pandas数据帧对象,其中包含一个包含一个单词表示文本的列,存储为29881x23947类型为''的稀疏矩阵 . 使用sklearn和fit_transform()函数处理该列 .

我现在想要使用convert_to_tensor()函数将此Colum转换为2D Tensor .

x_train_tensor = tf.convert_to_tensor(x_train)

收到错误消息:

TypeError:预期的二进制或unicode字符串

将矩阵转换为张量需要哪种格式?

Edit :打印出它所说的列的类型:

<class 'scipy.sparse.csr.csr_matrix'>

作为输出的数据帧示例:

0          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
1          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
2          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...
3          (0, 6276)\t1\n  (0, 8209)\t1\n  (0, 14299)\t...

1 回答

  • 0

    以下是将稀疏 scipy 矩阵转换为密集格式的示例 .

    Input sparse scipy matrix

    A = np.array([[1,2,0],[0,0,3],[4,0,0]])
    sA = sparse.csr_matrix(A)
    
    print (sA)
    # (0, 0)    1
    # (0, 1)    2
    # (1, 2)    3
    # (2, 0)    4
    
    idx, idy, val = sparse.find(sA)
    
    print(idx, idy, val)
    #[0 2 0 1] [0 0 1 2] [1 4 2 3]
    

    To tensorflow

    #merge idx and idy array to convert to [idx, idy] matrix    
    full_indices = tf.stack([idx, idy], axis=1)
    
    #Output matrix size
    depth_x = 3
    depth_y = 3
    
    # sparse to dense matrix 
    dense = tf.sparse_to_dense(full_indices,tf.constant([depth_x,depth_y]), val, validate_indices=False)
    
    with tf.Session() as sess:
       print(sess.run(dense))
    #[[1 2 0]
    # [0 0 3]
    # [4 0 0]]
    

相关问题