05.16 「入门」TensorFlow中的基本操作,与Numpy类型的无缝衔接

「入门」TensorFlow中的基本操作,与Numpy类型的无缝衔接

这篇文章总结,深度学习的框架:TensorFlow 的基本接口和操作类型。

01

Operations分类预览

「入门」TensorFlow中的基本操作,与Numpy类型的无缝衔接

02

Tensor

1 0-d tensor, or "scalar"

t_0 = 19

tf.zeros_like(t_0) # ==> 0

tf.ones_like(t_0) # ==> 1

2 1-d tensor, or "vector"

t_1 = ['apple', 'peach', 'banana'] #==>['' '' '']

3 2x2 tensor, or "matrix"

t_2 = [[True, False, False], [False, False, True], [False, True, False]]

tf.zeros_like(t_2) # ==> 2x2 tensor, all elements are False

tf.ones_like(t_2) # ==> 2x2 tensor, all elements are True

03

TensorFlow和Numpy

TensorFlow 和 Numpy能做到无缝衔接,例如:

tf.int32 == np.int32 # True

但是,将来tensorflow和numpy可能兼容性没有现在这么好。

可以传递Numpy对象给TensorFlow ops

tf.ones([2, 2], np.float32) # ⇒ [[1.0 1.0], [1.0 1.0]]

不要传递python的原生对象给Tensorflow,因为Tensorflow必须推断python的类型。

04

Constant

tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)

b = tf.constant([[0, 1], [2, 3]], name="b")

tf.ones(shape, dtype=tf.float32, name=None)

tf.linspace(10.0, 13.0, 4) #==> [10.0 11.0 12.0 13.0]

tf.random_normal(shape, mean=0.0, stddev=1.0, dtype= tf.float32, seed=None, name=None)

tf.set_random_seed(seed)

a = tf.constant([3, 6])

b = tf.constant([2, 2])

tf.add(a, b) # >> [5 8]

05

What's wrong with constant?

Constants 存储在 graph definition 中,当 constants很大时,加载图就会变得非常昂贵。

什么场合下用constant? 仅仅用primitive types为constant,用variables or readers 来缓存占用内存更大的数据。


分享到:


相關文章: