TensorFlow中如何确定张量的形状实例


Posted in Python onJune 23, 2020

我们可以使用tf.shape()获取某张量的形状张量。

import tensorflow as tf
x = tf.reshape(tf.range(1000), [10, 10, 10])
sess = tf.Session()
sess.run(tf.shape(x))
 
Out[1]: array([10, 10, 10])

我们可以使用tf.shape()在计算图中确定改变张量的形状。

high = tf.shape(x)[0] // 2
width = tf.shape(x)[1] * 2
x_reshape = tf.reshape(x, [high, width, -1])
sess.run(tf.shape(x_reshape))
 
Out: array([ 5, 20, 10])

我们可以使用tf.shape_n()在计算图中得到若干个张量的形状。

y = tf.reshape(tf.range(504), [7,8,9])
sess.run(tf.shape_n([x, y]))
 
Out: [array([10, 10, 10]), array([7, 8, 9])]

我们可以使用tf.size()获取张量的元素个数。

sess.run([tf.size(x), tf.size(y)])

Out: [1000, 504]

tensor.get_shape()或者tensor.shape是无法在计算图中用于确定张量的形状。

In [20]: x.get_shape()
Out[20]: TensorShape([Dimension(10), Dimension(10), Dimension(10)])
 
In [21]: x.get_shape()[0]
Out[21]: Dimension(10)
 
In [22]: type(x.get_shape()[0])
Out[22]: tensorflow.python.framework.tensor_shape.Dimension
 
In [23]: x.get_shape()
Out[23]: TensorShape([Dimension(10), Dimension(10), Dimension(10)])
 
In [24]: sess.run(x.get_shape())
---------------------------------------------------------------------------
TypeError     Traceback (most recent call last)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn)
 299  self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 300  fetch, allow_tensor=True, allow_operation=True))
 301 except TypeError as e:
 
~\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
 3477 with self._lock:
-> 3478 return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
 3479
 
~\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
 3566 raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
-> 3567        types_str))
 3568
 
TypeError: Can not convert a TensorShapeV1 into a Tensor or Operation.
 
During handling of the above exception, another exception occurred:
 
TypeError     Traceback (most recent call last)
<ipython-input-24-de007c69e003> in <module>
----> 1 sess.run(x.get_shape())
 
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
 927 try:
 928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929    run_metadata_ptr)
 930 if run_metadata:
 931  proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
 
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
 1135 # Create a fetch handler to take care of the structure of fetches.
 1136 fetch_handler = _FetchHandler(
-> 1137  self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
 1138
 1139 # Run request and get response.
 
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, graph, fetches, feeds, feed_handles)
 469 """
 470 with graph.as_default():
--> 471 self._fetch_mapper = _FetchMapper.for_fetch(fetches)
 472 self._fetches = []
 473 self._targets = []
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in for_fetch(fetch)
 269  if isinstance(fetch, tensor_type):
 270  fetches, contraction_fn = fetch_fn(fetch)
--> 271  return _ElementFetchMapper(fetches, contraction_fn)
 272 # Did not find anything.
 273 raise TypeError('Fetch argument %r has invalid type %r' % (fetch,
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn)
 302  raise TypeError('Fetch argument %r has invalid type %r, '
 303    'must be a string or Tensor. (%s)' %
--> 304    (fetch, type(fetch), str(e)))
 305 except ValueError as e:
 306  raise ValueError('Fetch argument %r cannot be interpreted as a '
TypeError: Fetch argument TensorShape([Dimension(10), Dimension(10), Dimension(10)]) has invalid type <class 'tensorflow.python.framework.tensor_shape.TensorShapeV1'>, must be a string or Tensor. (Can not convert a TensorShapeV1 into a Tensor or Operation.)

我们可以使用tf.rank()来确定张量的秩。tf.rank()会返回一个代表张量秩的张量,可直接在计算图中使用。

In [25]: tf.rank(x)
Out[25]: <tf.Tensor 'Rank:0' shape=() dtype=int32>
 
In [26]: sess.run(tf.rank(x))
Out[26]: 3

补充知识:tensorflow循环改变tensor的值

使用tf.concat()实现4维tensor的循环赋值

alist=[[[[1,1,1],[2,2,2],[3,3,3]],[[4,4,4],[5,5,5],[6,6,6]]],[[[7,7,7],[8,8,8],[9,9,9]],[[10,10,10],[11,11,11],[12,12,12]]]] #2,2,3,3-n,c,h,w
kenel=(np.asarray(alist)*2).tolist()
print(kenel)
inputs=tf.constant(alist,dtype=tf.float32)
kenel=tf.constant(kenel,dtype=tf.float32)
inputs=tf.transpose(inputs,[0,2,3,1]) #n,h,w,c
kenel=tf.transpose(kenel,[0,2,3,1]) #n,h,w,c
uints=inputs.get_shape()
h=int(uints[1])
w=int(uints[2])
encoder_output=[]
for b in range(int(uints[0])):
 encoder_output_c=[]
 for c in range(int(uints[-1])):
  one_channel_in = inputs[b, :, :, c]
  one_channel_in = tf.reshape(one_channel_in, [1, h, w, 1])
  one_channel_kernel = kenel[b, :, :, c]
  one_channel_kernel = tf.reshape(one_channel_kernel, [h, w, 1, 1])
  encoder_output_cc = tf.nn.conv2d(input=one_channel_in, filter=one_channel_kernel, strides=[1, 1, 1, 1], padding="SAME")
  if c==0:
   encoder_output_c=encoder_output_cc
  else:
   encoder_output_c=tf.concat([encoder_output_c,encoder_output_cc],axis=3)

 if b==0:
  encoder_output=encoder_output_c
 else:
  encoder_output = tf.concat([encoder_output, encoder_output_c], axis=0)

with tf.Session() as sess:
 print(sess.run(tf.transpose(encoder_output,[0,3,1,2])))
 print(encoder_output.get_shape())

输出:

[[[[ 32. 48. 32.]
 [ 56. 84. 56.]
 [ 32. 48. 32.]]

 [[ 200. 300. 200.]
 [ 308. 462. 308.]
 [ 200. 300. 200.]]]


 [[[ 512. 768. 512.]
 [ 776. 1164. 776.]
 [ 512. 768. 512.]]

 [[ 968. 1452. 968.]
 [1460. 2190. 1460.]
 [ 968. 1452. 968.]]]]
(2, 3, 3, 2)

以上这篇TensorFlow中如何确定张量的形状实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
纯Python开发的nosql数据库CodernityDB介绍和使用实例
Oct 23 Python
使用基于Python的Tornado框架的HTTP客户端的教程
Apr 24 Python
批处理与python代码混合编程的方法
May 19 Python
一步步教你用python的scrapy编写一个爬虫
Apr 17 Python
关于Python 的简单栅格图像边界提取方法
Jul 05 Python
python 模拟创建seafile 目录操作示例
Sep 26 Python
python爬虫 线程池创建并获取文件代码实例
Sep 28 Python
基于Python获取城市近7天天气预报
Nov 26 Python
Python批量将图片灰度化的实现代码
Apr 11 Python
实现Python3数组旋转的3种算法实例
Sep 16 Python
利用pipenv和pyenv管理多个相互独立的Python虚拟开发环境
Nov 01 Python
Restful_framework视图组件代码实例解析
Nov 17 Python
Python docutils文档编译过程方法解析
Jun 23 #Python
python3的pip路径在哪
Jun 23 #Python
Python错误的处理方法
Jun 23 #Python
python文件读取失败怎么处理
Jun 23 #Python
使用tensorflow根据输入更改tensor shape
Jun 23 #Python
pytorch 计算ConvTranspose1d输出特征大小方式
Jun 23 #Python
Android Q之气泡弹窗的实现示例
Jun 23 #Python
You might like
PHP与javascript的两种交互方式
2006/10/09 PHP
PHP+jQuery实现自动补全功能源码
2013/05/15 PHP
PHP实现事件机制实例分析
2015/06/26 PHP
CI操作cookie的方法分析(基于helper类库)
2016/03/28 PHP
Javascript的各种节点操作实例演示代码
2012/06/27 Javascript
js触发asp.net的Button的Onclick事件应用
2013/02/02 Javascript
JS验证日期的格式YYYY-mm-dd 具体实现
2013/06/29 Javascript
Jquery搜索父元素操作方法
2015/02/10 Javascript
javascript实现链接单选效果的方法
2015/05/13 Javascript
实例详解angularjs和ajax的结合使用
2015/10/22 Javascript
javascript针对cookie的基本操作实例详解
2015/11/30 Javascript
JS实现鼠标框选效果完整实例
2016/06/20 Javascript
使用nodejs中httpProxy代理时候出现404异常的解决方法
2016/08/15 NodeJs
基于cookie实现zTree树刷新后展开状态不变
2017/02/28 Javascript
深入浅析JSONAPI在PHP中的应用
2017/12/24 Javascript
vue全局组件与局部组件使用方法详解
2018/03/29 Javascript
layer弹出层父子页面事件相互调用方法
2018/08/17 Javascript
Vue之mixin全局的用法详解
2018/08/22 Javascript
NodeJS实现同步的方法
2019/03/02 NodeJs
微信小程序保存图片到相册权限设置
2020/04/09 Javascript
解决vue项目input输入框双向绑定数据不实时生效问题
2020/08/05 Javascript
讲解Python中运算符使用时的优先级
2015/05/14 Python
详解Python nose单元测试框架的安装与使用
2017/12/20 Python
python实现用户管理系统
2018/01/10 Python
python opencv 读取图片 返回图片某像素点的b,g,r值的实现方法
2019/07/03 Python
python scrapy爬虫代码及填坑
2019/08/12 Python
python3 Scrapy爬虫框架ip代理配置的方法
2020/01/17 Python
在keras中获取某一层上的feature map实例
2020/01/24 Python
Python ATM功能实现代码实例
2020/03/19 Python
CSS3中的常用选择器使用示例整理
2016/06/13 HTML / CSS
美体小铺英国官网:The Body Shop英国
2017/01/24 全球购物
小学新学期寄语
2014/04/02 职场文书
购房协议书
2014/04/11 职场文书
会计专业自荐书
2014/07/08 职场文书
2015暑假打工实践报告
2015/07/13 职场文书
Win10本地连接不见了怎么恢复? win10系统电脑本地连接不见了解决方法
2023/01/09 数码科技