TensorFlow中如何确定张量的形状实例
我们可以使用tf.shape()获取某张量的形状张量。
importtensorflowastf 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())
---------------------------------------------------------------------------
TypeErrorTraceback(mostrecentcalllast)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyin__init__(self,fetches,contraction_fn)
299self._unique_fetches.append(ops.get_default_graph().as_graph_element(
-->300fetch,allow_tensor=True,allow_operation=True))
301exceptTypeErrorase:
~\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.pyinas_graph_element(self,obj,allow_tensor,allow_operation)
3477withself._lock:
->3478returnself._as_graph_element_locked(obj,allow_tensor,allow_operation)
3479
~\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.pyin_as_graph_element_locked(self,obj,allow_tensor,allow_operation)
3566raiseTypeError("Cannotconverta%sintoa%s."%(type(obj).__name__,
->3567types_str))
3568
TypeError:CannotconvertaTensorShapeV1intoaTensororOperation.
Duringhandlingoftheaboveexception,anotherexceptionoccurred:
TypeErrorTraceback(mostrecentcalllast)
in
---->1sess.run(x.get_shape())
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyinrun(self,fetches,feed_dict,options,run_metadata)
927try:
928result=self._run(None,fetches,feed_dict,options_ptr,
-->929run_metadata_ptr)
930ifrun_metadata:
931proto_data=tf_session.TF_GetBuffer(run_metadata_ptr)
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyin_run(self,handle,fetches,feed_dict,options,run_metadata)
1135#Createafetchhandlertotakecareofthestructureoffetches.
1136fetch_handler=_FetchHandler(
->1137self._graph,fetches,feed_dict_tensor,feed_handles=feed_handles)
1138
1139#Runrequestandgetresponse.
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyin__init__(self,graph,fetches,feeds,feed_handles)
469"""
470withgraph.as_default():
-->471self._fetch_mapper=_FetchMapper.for_fetch(fetches)
472self._fetches=[]
473self._targets=[]
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyinfor_fetch(fetch)
269ifisinstance(fetch,tensor_type):
270fetches,contraction_fn=fetch_fn(fetch)
-->271return_ElementFetchMapper(fetches,contraction_fn)
272#Didnotfindanything.
273raiseTypeError('Fetchargument%rhasinvalidtype%r'%(fetch,
~\Anaconda3\lib\site-packages\tensorflow\python\client\session.pyin__init__(self,fetches,contraction_fn)
302raiseTypeError('Fetchargument%rhasinvalidtype%r,'
303'mustbeastringorTensor.(%s)'%
-->304(fetch,type(fetch),str(e)))
305exceptValueErrorase:
306raiseValueError('Fetchargument%rcannotbeinterpretedasa'
TypeError:FetchargumentTensorShape([Dimension(10),Dimension(10),Dimension(10)])hasinvalidtype,mustbeastringorTensor.(CannotconvertaTensorShapeV1intoaTensororOperation.)
我们可以使用tf.rank()来确定张量的秩。tf.rank()会返回一个代表张量秩的张量,可直接在计算图中使用。
In[25]:tf.rank(x) Out[25]: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=[] forbinrange(int(uints[0])): encoder_output_c=[] forcinrange(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") ifc==0: encoder_output_c=encoder_output_cc else: encoder_output_c=tf.concat([encoder_output_c,encoder_output_cc],axis=3) ifb==0: encoder_output=encoder_output_c else: encoder_output=tf.concat([encoder_output,encoder_output_c],axis=0) withtf.Session()assess: 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中如何确定张量的形状实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。