把张量变成int_如何获取Tensorflow张量尺寸(形状)作为int值?

假设我有一个Tensorflow张量。如何获取张量的尺寸(形状)作为整数值?我知道有两种方法,tensor.get_shape()和tf.shape(tensor),但是我不能将形状值作为整int32数值。

例如,下面我创建了一个二维张量,我需要获取行数和列数,int32以便可以调用reshape()以创建shape张量(num_rows *

num_cols, 1)。但是,该方法tensor.get_shape()返回值作为Dimension类型,而不是类型int32。

import tensorflow as tf

import numpy as np

sess = tf.Session()

tensor = tf.convert_to_tensor(np.array([[1001,1002,1003],[3,4,5]]), dtype=tf.float32)

sess.run(tensor)

# array([[ 1001., 1002., 1003.],

# [ 3., 4., 5.]], dtype=float32)

tensor_shape = tensor.get_shape()

tensor_shape

# TensorShape([Dimension(2), Dimension(3)])

print tensor_shape

# (2, 3)

num_rows = tensor_shape[0] # ???

num_cols = tensor_shape[1] # ???

tensor2 = tf.reshape(tensor, (num_rows*num_cols, 1))

# Traceback (most recent call last):

# File "", line 1, in

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1750, in reshape

# name=name)

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 454, in apply_op

# as_ref=input_arg.is_ref)

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 621, in convert_to_tensor

# ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function

# return constant(v, dtype=dtype, name=name)

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/constant_op.py", line 163, in constant

# tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 353, in make_tensor_proto

# _AssertCompatible(values, dtype)

# File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.py", line 290, in _AssertCompatible

# (dtype.name, repr(mismatch), type(mismatch).__name__))

# TypeError: Expected int32, got Dimension(6) of type 'Dimension' instead.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值