首页 文章

在Tensorflow和Python中应用tensorflow.convert_to_tensor时获取ValueError

提问于
浏览
0

我试图通过以下方式将两个具有不同形状的矩阵放在张量中:

import tensorflow as tf
    matrix =  [[1, 2,  3,  4,  5],
              [6,  7,  8,  9, 10],
              [11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25]]
    matrix2 = [[1, 2, 3],
              [6, 7, 8],
              [11, 12, 13],
              [16, 17, 18],
              [21, 22, 23]]
    test = []
    test.append(matrix)
    test.append(matrix2)
    with tf.Session().as_default():
         c = tf.convert_to_tensor(test)
         print(c.eval())

执行此代码会生成以下错误:

ValueError: Argument must be a dense tensor: got shape [2, 5], but wanted [2, 5, 5]

如果我将这些矩阵转换为numpy数组,那么numpy数组会将每个矩阵的行视为列表 . 有没有其他方法可以在Tensorflow中执行我的目标操作?

1 回答

  • 0

    该错误是由于 matrix (5x5)和 matrix2 (5x3)的尺寸不匹配造成的 .

    import numpy as np
    
    mat2=[[1,2,3],[6,7,8]]
    mat1=[[1,2,3,4,5],[3,4,5,6,7]]
    test = []
    test.append(mat1)
    test.append(mat2)
    res=np.array(test)
    print res
    

    array([[list([1,2,3,4,5]),list([3,4,5,6,7])],[list([1,2,3]),list( [6,7,8])]],dtype = object)

    这里 resJagged array . 为了创建一个张量,你需要一个Matrix,即基本的区别是 Shape of matrix a.k.a Rank of the tensor(Different from Rank in Mathematics) should be rectangular(number of elements at every row are equal) See here .

    在你的情况下,你试图从维度[(5x5),(5x3)]的三维列表创建一个张量,即 . 三维阵列内的两个二维阵列的尺寸不匹配 .

    Solution

    要么 matrix [5x3]要么 matrix2 [5x5]

相关问题