TensorFlow-无法使用get_shape命令获取矩阵的形状 [英] TensorFlow - Cannot get the shape of matrix with the get_shape command

查看:1810
本文介绍了TensorFlow-无法使用get_shape命令获取矩阵的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时,我似乎无法获得张量的形状

I can't seem to get the shape of the tensor when I do

get_shape().as_list()

这是我编写的代码:

matrix1 = tf.placeholder(tf.int32) 
matrix2 = tf.placeholder(tf.int32)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    a = sess.run(matrix1, {matrix1: [[1,2,3],[4,5,6],[7,8,9]]})
    b = sess.run(matrix2, {matrix2: [[10,11,12],[13,14,15], [16,17,18]]})
    print(a.get_shape().as_list()) #ERROR

我收到以下错误:

AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

我想知道矩阵的形状,以便可以采用任意矩阵并遍历其行和列.

I want to know the shape of the matrix so that I can take in an arbitrary matrix and loop through its rows and columns.

推荐答案

只需在注释中总结讨论内容,而无需多加注释

matrix1a都是多维数组,但是有一个区别:

Both matrix1 and a are multidimensional arrays, but there is a difference:

  • matrix1 tf.Tensor 的实例,它支持两种访问形状的方法:matrix1.shape属性和matrix1.get_shape()方法.

tf.Tensor评估结果a是一个numpy

The result of tf.Tensor evaluation, a, is a numpy ndarray, which has just a.shape attribute.

从历史上看,tf.Tensor仅具有get_shape()方法,后来又添加了shape以使其类似于numpy.还有一点需要注意:在tensorflow中,张量形状可以是动态的(例如您的示例),在这种情况下,get_shape()shape都不会返回数字.在这种情况下,可以使用 tf.shape 函数在运行时进行访问(下面的示例可能有用).

Historically, tf.Tensor had only get_shape() method, shape was added later to make it similar to numpy. And one more note: in tensorflow, tensor shape can be dynamic (like in your example), in which case neither get_shape() nor shape will return a number. In this case, one can use tf.shape function to access it in runtime (here's an example when it might be useful).

这篇关于TensorFlow-无法使用get_shape命令获取矩阵的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆