重要

张量是TensorFlow在计算图上用于处理的主要数据源。我们可以把这些张量声明为变量,并将它们像占位符一样导入。首先,我们必须知道如何创建张量。

但我们创建一个张量,然后声明它为变量之后,TensorFlow在计算图中创建出了多个图结构。值得注意的是通过创建张量,TensorFlow并没有在计算图增加任何东西。我们下一节会讲到这点。

这一节主要讲解在TensorFlow中创建张量的方法。首先,我们开始加载TensorFlow并开始重设计算图。

>>> import tensorflow as tf
>>> from tensorflow.python.framework import ops
>>> ops.reset_default_graph()

注意

tensorflow.python.framework.ops.reset_default_graph模块介绍

Clears the default graph stack and resets the global default graph.

NOTE: The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a tf.compat.v1.Session or tf.compat.v1.InteractiveSession is active will result in undefined behavior. Using any previously created tf.Operation or tf.Tensor objects after calling this function will result in undefined behavior. :raises: AssertionError – If this function is called within a nested graph.

计算图

tf.Session() 开始吧!😀

# 适用于低版本Tensorflow运行
>>> sess = tf.Session()
# 适用于2.0版本TensorFlow运行, 由于版本不同,必须先运行下面的命令run才能工作
>>> tf.compat.v1.disable_eager_execution()
# compat指的是兼容v1版本的Tensorflow
>>> sess = tf.compat.v1.Session()

创建张量

TensorFlow有一些内置函数可以用创建变量张量。例如我们可以通过 tf.zeros() 来创建一个预设形状的零张量。比如:

>>> my_tensor = tf.zeros([1,20])

然后,我们可以通过 run 方法的调用来输出张量。

>>> sess.run(my_tensor)
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
0.,  0.,  0., 0.,  0.,  0.,  0.,  0.,  0.,  0.]], dtype=float32)

创建0填充张量

>>> import tensorflow as tf
>>> row_dim, col_dim = 3, 5
>>> zero_tsr = tf.zeros([row_dim, col_dim])
>>> sess.run(zero_tsr)
array([[0., 0., 0., 0., 0.],
 [0., 0., 0., 0., 0.],
 [0., 0., 0., 0., 0.]], dtype=float32)

[row_dim, col_dim] row_dim是行维度,col_dim是列维度,需要代入具体数字才可以输出。

创建1填充张量

>>> import tensorflow as tf
>>> row_dim, col_dim = 6, 7
>>> ones_tsr = tf.ones([row_dim, col_dim])
>>> sess.run(ones_tsr)
array([[1., 1., 1., 1., 1., 1., 1.],
 [1., 1., 1., 1., 1., 1., 1.],
 [1., 1., 1., 1., 1., 1., 1.],
 [1., 1., 1., 1., 1., 1., 1.],
 [1., 1., 1., 1., 1., 1., 1.],
 [1., 1., 1., 1., 1., 1., 1.]], dtype=float32)

[row_dim, col_dim] row_dim是行维度,col_dim是列维度,同样需要代入具体数字才可以输出。

创建常数填充张量

>>> import tensorflow as tf
>>> row_dim, col_dim = 6, 7
>>> filled_tsr = tf.fill([row_dim, col_dim],42)
>>> sess.run(filled_tsr)
array([[42, 42, 42, 42, 42, 42, 42],
 [42, 42, 42, 42, 42, 42, 42],
 [42, 42, 42, 42, 42, 42, 42],
 [42, 42, 42, 42, 42, 42, 42],
 [42, 42, 42, 42, 42, 42, 42],
 [42, 42, 42, 42, 42, 42, 42]], dtype=int32)

[row_dim, col_dim] row_dim是行维度,col_dim是列维度,同样需要代入具体数字才可以输出。

由给定的数创建一个张量

>>> import tensorflow as tf
>>> constant1_tsr = tf.constant([1,2,3])
>>> sess.run(constant1_tsr)
[1 2 3]
>>> constant2_tsr = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
>>> sess.run(constant2_tsr)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

tf.constant([...]) 可以改变输入常数的维度来输出对应的维度的常数张量。

创建相似类型的张量

>>> zeros_similar = tf.zeros_like(constant1_tsr)
>>> sess.run(zeros_similar)
array([0, 0, 0], dtype=int32)
>>> ones_similar = tf.ones_like(constant2_tsr)
>>> sess.run(ones_similar)
array([[1, 1, 1],
 [1, 1, 1],
 [1, 1, 1]], dtype=int32)

创建序列张量

# linspace必须规定start的数是bfloat16, float16, float32, float64当中的一种
>>> linear_tsr = tf.linspace(start=0.0,stop=100,num=11)
# stop=100,最后一位数包括100
>>> sess.run(linear_tsr)
array([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.],
dtype=float32)

# range的start比较宽松,可以是整数。
>>> integer_seq_tsr = tf.range(start=6,limit=15,delta=3)
# limit=15, 最后一位数不包括15
>>> sess.run(integer_seq_tsr)
array([ 6,  9, 12], dtype=int32)

创建随机张量

# 下面创建一个符合均匀分布(uniform distribution)的随机数张量
>>> row_dim, col_dim = 8, 8
# 包含minval,不包含maxval
>>> randuif_tsr = tf.compat.v1.random_uniform([row_dim, col_dim], minval=0, maxval=1)
>>> sess.run(randuif_tsr)
array([[0.67701995, 0.18257272, 0.57032907, 0.36612427, 0.9630263 ,
  0.95663846, 0.8787807 , 0.17861104],
 [0.4416871 , 0.9086859 , 0.3647703 , 0.21749687, 0.45980632,
  0.36322677, 0.45077944, 0.18235803],
 [0.23256958, 0.7551502 , 0.574257  , 0.31542778, 0.47067642,
  0.59856176, 0.7479335 , 0.9510181 ],
 [0.7199836 , 0.96217847, 0.6937009 , 0.7456448 , 0.24289751,
  0.85406077, 0.6463398 , 0.25423837],
 [0.95849264, 0.6280341 , 0.5537604 , 0.49765468, 0.07170725,
  0.19740784, 0.6923628 , 0.6402495 ],
 [0.93710315, 0.7305033 , 0.96696365, 0.46475697, 0.06905127,
  0.7408395 , 0.712886  , 0.00653875],
 [0.5427816 , 0.22150195, 0.460876  , 0.35927665, 0.32854652,
  0.13955867, 0.56905234, 0.97424316],
 [0.05879259, 0.3620267 , 0.81892705, 0.08734441, 0.361081  ,
  0.6088749 , 0.3457687 , 0.69742644]], dtype=float32)

创建一个符合正态分布的张量

正态分布(normal distribution)

>>> row_dim, col_dim = 8, 8
>>> randnorm_tsr = tf.compat.v1.random_normal([row_dim,col_dim], mean=0.0, stddev=1.0)
>>> sess.run(randnorm_tsr)
array([[-1.3551812 ,  0.44311747, -0.07009585, -0.3532377 , -0.182757, 0.13516597,  0.4071887 ,  0.27975908],
       [ 0.42585635,  0.5364396 , -0.6653683 ,  0.35444063, -1.0977732 , -0.59936076, -0.36046746, -0.07343452],
       [-0.919484  ,  0.39717674,  0.7935889 , -0.9890499 , -1.133034  , 1.0666726 , -0.968096  ,  1.2872337 ],
       [-0.66985756, -1.1499914 ,  1.7560692 , -0.10894807,  1.1841142 , 0.22291774, -0.951817  , -0.44093087],
       [-1.0684127 , -1.0498457 ,  2.9362292 , -2.013448  ,  0.4025221 , -1.1769909 , -0.05197304, -1.4978093 ],
       [-0.38958997,  0.39442828,  0.97004807,  0.13250023, -1.2196823 , 0.70165646, -1.0563769 ,  0.10399553],
       [ 0.41292164, -0.03876609, -1.2176208 ,  0.8764762 , -0.31439155, 0.06191747, -0.87645555,  0.5363252 ],
       [-1.112473  ,  2.0940979 ,  1.3212632 , -0.14039427,  1.903088  , -1.0271009 ,  0.9657831 , -0.8105811 ]], dtype=float32)

创建有界限的正态分布张量

即截断的产生正态分布的随机数,即随机数与均值的差值若大于两倍的标准差,则重新生成。

>>> row_dim, col_dim = 8, 8
>>> runcnomr_tsr = tf.compat.v1.truncated_normal([row_dim,col_dim],mean=0.0, stddev=1.0)
>>> sess.run(runcnomr_tsr)
array([[ 0.57215023, -0.02053498,  0.06714377, -1.2676795 ,  0.33678156, 0.803336  , -0.10746168, -1.073573  ],
       [-1.6188551 ,  0.26903188, -0.94024265, -1.0895174 , -0.3667447 , -1.934491  ,  0.16837268,  0.14565438],
       [ 1.3880031 ,  0.25730732, -1.2500429 ,  1.2005805 , -0.6324095 , -0.5305861 , -0.86797935,  0.58874166],
       [-0.34581357, -0.69425064, -1.8915199 , -0.7588796 , -0.4680857 , -0.6425717 , -0.35572565,  0.33899295],
       [-0.50731635, -1.191694  ,  1.2362499 , -1.6300774 , -1.7100778 , -0.5509973 ,  1.7180538 , -0.05677445],
       [-0.6379802 ,  1.0952779 , -0.57122874,  0.35372928,  0.99445486, -0.37966916, -1.5172375 , -0.2665035 ],
       [ 1.631818  ,  0.79803437,  1.6253722 , -0.02572301, -0.1393287 , -1.8196368 ,  0.03887375,  0.5125945 ],
       [ 1.0057242 , -0.93407774, -0.06123861, -0.16788454,  0.62762713, 1.2990429 ,  0.5621885 ,  0.6616505 ]], dtype=float32)

张量乱序化

runcnorm_tsr 只是一个张量例子

>>> shuffled_output = tf.compat.v1.random_shuffle(runcnomr_tsr)
>>> sess.run(shuffled_output)
array([[-1.5790983 ,  1.390395  , -1.5734539 , -1.2803887 , -0.36437657, 0.30741617,  0.9532189 ,  0.43124342],
       [-0.21545868,  0.5560213 , -1.1023369 , -1.365619  , -1.1592077 , 1.516915  , -0.386228  ,  1.6577938 ],
       [-0.56759614, -1.7026372 , -0.39424533,  0.20800175, -0.49035162, -1.4874234 ,  0.5077964 , -0.97859126],
       [-1.657173  , -1.2724566 , -0.12424537, -0.09589671, -1.3740199 , -0.19883458, -0.24118501, -0.25363442],
       [ 1.1784359 ,  1.6380433 ,  0.22968899, -0.3419656 , -0.5073284 , -0.37669885, -0.00905402,  0.10761048],
       [ 0.94037515,  0.14280881,  0.44833976, -0.3870774 ,  0.5403837 , -0.96695757,  0.54265535, -0.56348246],
       [ 0.8507602 , -1.2580659 ,  1.1683265 ,  1.4664146 ,  0.59427595, -0.49156505, -1.1784973 ,  0.14118564],
       [ 0.2539443 , -1.3915894 , -0.6779825 , -0.66317   ,  0.01306346, 0.5949122 , -1.409377  , -0.38872847]], dtype=float32)

张量裁剪

第二个参数 cropped_size 必须是 [n,m] 格式.

>>> cropped_output = tf.compat.v1.random_crop(runcnomr_tsr,[4,4])
>>> sess.run(cropped_output)
array([[-0.2630262 ,  1.2543985 ,  0.14447008, -0.00760976],
       [-1.2469869 , -0.3482599 ,  1.4325598 ,  0.03993478],
       [-1.7399155 ,  1.0116926 , -0.22996971,  1.4531476 ],
       [-0.01253414, -1.0832093 , -1.2577766 ,  1.4000101 ]],dtype=float32)

# 张量乱序化和裁剪操作都不是原处改变(in-place changes), 但是每次运行sess.run, 得到随机张量都会不一样, 必要的时候需要赋值语句
>>> sess.run(runcnomr_tsr)
array([[-0.01128286,  0.10473254,  0.7416311 ,  0.12495294, -0.621709  , 0.08294442, -0.3259678 ,  1.9100105 ],
       [-0.7485761 ,  1.871997  ,  0.3522917 , -0.27935842, -0.14542657, -0.06015118,  0.02190878, -0.07216269],
       [ 0.17552952,  0.395008  ,  0.06362368,  0.09165095,  0.41191736, 0.4416554 ,  0.5326085 ,  0.19600478],
       [ 1.1290088 ,  1.6767063 , -0.06439265,  0.68743473, -0.76912147, -0.74357826, -0.62004423, -1.5831621 ],
       [ 0.24502024, -0.04311023,  0.36677885, -0.7533206 , -0.83164   , 1.3448423 ,  0.8730749 , -0.13600092],
       [ 0.12533237,  0.49264213,  0.48348406, -0.03921305,  1.0805569 , 0.8118515 ,  0.6512441 , -0.11669531],
       [ 0.72900176,  1.8130132 ,  1.3789786 ,  0.519455  , -1.179993  , -1.0784473 ,  1.1946204 , -1.0734705 ],
       [ 0.68626446,  1.2634999 , -0.03061075, -1.3075253 , -0.4238513 , -1.4350135 ,  0.70656526,  1.2966055 ]], dtype=float32)
>>> my_tsr = sess.run(runcnomr_tsr)

# 后面我们会谈到图像处理,可能会用到下面的代码
>>> import matplotlib.pyplot as plt
>>> %matplotlib inline
>>> image_raw_data_jpg=tf.compat.v1.gfile.GFile("yourimage.jpg","rb").read()
>>> with sess as session:
...    img_data=tf.image.decode_jpeg(image_raw_data_jpg)
...    plt.figure(1)
...    print(session.run(img_data))
...    plt.imshow(img_data.eval())
[[[249 253 254]
  [249 253 254]
  [249 253 254]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

[[249 253 254]
 [249 253 254]
 [249 253 254]
 ...
 ...

# 运行了with sess as session之后, session会关闭,此时需要重新打开
>>> sess = tf.compat.v1.Session()
>>> cropped_image = tf.compat.v1.random_crop(img_data, [3, 1, 3])
>>> sess.run(cropped_image)
array([[[255, 255, 255]],

       [[255, 255, 255]],

       [[255, 255, 255]]], dtype=uint8)

下载本节 Jupyter Notebook

TensorFlow机器学习的应用

本节学习模块

注意

tensorflow.zeros模块介绍

Creates a tensor with all elements set to zero.

This operation returns a tensor of type dtype with shape shape and all elements set to zero.

>>> tf.zeros([3, 4], tf.int32)
<tf.Tensor: shape=(3, 4), dtype=int32, numpy=
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]], dtype=int32)>
param shape:A list of integers, a tuple of integers, or a 1-D Tensor of type int32.
param dtype:The DType of an element in the resulting Tensor.
param name:Optional string. A name for the operation.
returns:A Tensor with all elements set to zero.

注意

tensorflow.fill模块介绍

Creates a tensor filled with a scalar value.

This operation creates a tensor of shape dims and fills it with value.

For example:

>>> tf.fill([2, 3], 9)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[9, 9, 9],
       [9, 9, 9]], dtype=int32)>

tf.fill evaluates at graph runtime and supports dynamic shapes based on other runtime tf.Tensors, unlike tf.constant(value, shape=dims), which embeds the value as a Const node.

param dims:

A 1-D sequence of non-negative numbers. Represents the shape of the output tf.Tensor. Entries should be of type: int32, int64.

param value:

A value to fill the returned tf.Tensor.

param name:

Optional string. The name of the output tf.Tensor.

returns:

A tf.Tensor with shape dims and the same dtype as value.

raises:
  • InvalidArgumentErrordims contains negative entries.
  • NotFoundErrordims contains non-integer entries.

@compatibility(numpy) Similar to np.full. In numpy, more parameters are supported. Passing a number argument as the shape (np.full(5, value)) is valid in numpy for specifying a 1-D shaped result, while TensorFlow does not support this syntax. @end_compatibility

注意

tensorflow.constant模块介绍

Creates a constant tensor from a tensor-like object.

Note: All eager tf.Tensor values are immutable (in contrast to tf.Variable). There is nothing especially _constant_ about the value returned from tf.constant. This function it is not fundamentally different from tf.convert_to_tensor. The name tf.constant comes from the symbolic APIs (like tf.data or keras functional models) where the value is embeded in a Const node in the tf.Graph. tf.constant is useful for asserting that the value can be embedded that way.

If the argument dtype is not specified, then the type is inferred from the type of value.

>>> # Constant 1-D Tensor from a python list.
>>> tf.constant([1, 2, 3, 4, 5, 6])
<tf.Tensor: shape=(6,), dtype=int32,
    numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
>>> # Or a numpy array
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> tf.constant(a)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[1, 2, 3],
         [4, 5, 6]])>

If dtype is specified the resulting tensor values are cast to the requested dtype.

>>> tf.constant([1, 2, 3, 4, 5, 6], dtype=tf.float64)
<tf.Tensor: shape=(6,), dtype=float64,
    numpy=array([1., 2., 3., 4., 5., 6.])>

If shape is set, the value is reshaped to match. Scalars are expanded to fill the shape:

>>> tf.constant(0, shape=(2, 3))
  <tf.Tensor: shape=(2, 3), dtype=int32, numpy=
  array([[0, 0, 0],
         [0, 0, 0]], dtype=int32)>
>>> tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
  array([[1, 2, 3],
         [4, 5, 6]], dtype=int32)>

tf.constant has no effect if an eager Tensor is passed as the value, it even transmits gradients:

>>> v = tf.Variable([0.0])
>>> with tf.GradientTape() as g:
...     loss = tf.constant(v + v)
>>> g.gradient(loss, v).numpy()
array([2.], dtype=float32)

But, since tf.constant embeds the value in the tf.Graph this fails for symbolic tensors:

>>> i = tf.keras.layers.Input(shape=[None, None])
>>> t = tf.constant(i)
Traceback (most recent call last):
...
NotImplementedError: ...

tf.constant will _always_ create CPU (host) tensors. In order to create tensors on other devices, use tf.identity. (If the value is an eager Tensor, however, the tensor will be returned unmodified as mentioned above.)

Related Ops:

  • tf.convert_to_tensor is similar but: * It has no shape argument. * Symbolic tensors are allowed to pass through.

    >>> i = tf.keras.layers.Input(shape=[None, None])
    >>> t = tf.convert_to_tensor(i)
    
  • tf.fill: differs in a few ways: * tf.constant supports arbitrary constants, not just uniform scalar

    Tensors like tf.fill.

    • tf.fill creates an Op in the graph that is expanded at runtime, so it can efficiently represent large tensors.
    • Since tf.fill does not embed the value, it can produce dynamically sized outputs.
param value:

A constant value (or list) of output type dtype.

param dtype:

The type of the elements of the resulting tensor.

param shape:

Optional dimensions of resulting tensor.

param name:

Optional name for the tensor.

returns:

A Constant Tensor.

raises:
  • TypeError – if shape is incorrectly specified or unsupported.
  • ValueError – if called on a symbolic tensor.

注意

tensorflow.zeros_like模块介绍

Creates a tensor with all elements set to zero.

See also tf.zeros.

Given a single tensor or array-like object (input), this operation returns a tensor of the same type and shape as input with all elements set to zero. Optionally, you can use dtype to specify a new type for the returned tensor.

实际案例

>>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
>>> tf.zeros_like(tensor)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 0, 0]], dtype=int32)>
>>> tf.zeros_like(tensor, dtype=tf.float32)
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0., 0., 0.],
       [0., 0., 0.]], dtype=float32)>
>>> tf.zeros_like([[1, 2, 3], [4, 5, 6]])
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 0, 0]], dtype=int32)>
param input:A Tensor or array-like object.
param dtype:A type for the returned Tensor. Must be float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128, bool or string (optional).
param name:A name for the operation (optional).
returns:A Tensor with all elements set to zero.

注意

tensorflow.ones_like模块介绍

Creates a tensor of all ones that has the same shape as the input.

See also tf.ones.

Given a single tensor (tensor), this operation returns a tensor of the same type and shape as tensor with all elements set to 1. Optionally, you can use dtype to specify a new type for the returned tensor.

For example:

>>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
>>> tf.ones_like(tensor)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
  array([[1, 1, 1],
         [1, 1, 1]], dtype=int32)>
param input:A Tensor.
param dtype:A type for the returned Tensor. Must be float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128, bool or string.
param name:A name for the operation (optional).
returns:A Tensor with all elements set to one.

注意

tensorflow.linspace模块介绍

Generates values in an interval.

A sequence of num evenly-spaced values are generated beginning at start. If num > 1, the values in the sequence increase by stop - start / num - 1, so that the last one is exactly stop.

For example:

` tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0  11.0  12.0] `

param start:A Tensor. Must be one of the following types: bfloat16, half, float32, float64. 0-D tensor. First entry in the range.
param stop:A Tensor. Must have the same type as start. 0-D tensor. Last entry in the range.
param num:A Tensor. Must be one of the following types: int32, int64. 0-D tensor. Number of values to generate.
param name:A name for the operation (optional).
returns:A Tensor. Has the same type as start.

注意

tensorflow.range模块介绍

Creates a sequence of numbers.

Creates a sequence of numbers that begins at start and extends by increments of delta up to but not including limit.

The dtype of the resulting tensor is inferred from the inputs unless it is provided explicitly.

Like the Python builtin range, start defaults to 0, so that range(n) = range(0, n).

For example:

>>> start = 3
>>> limit = 18
>>> delta = 3
>>> tf.range(start, limit, delta)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 3,  6,  9, 12, 15], dtype=int32)>
>>> start = 3
>>> limit = 1
>>> delta = -0.5
>>> tf.range(start, limit, delta)
<tf.Tensor: shape=(4,), dtype=float32,
numpy=array([3. , 2.5, 2. , 1.5], dtype=float32)>
>>> limit = 5
>>> tf.range(limit)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([0, 1, 2, 3, 4], dtype=int32)>
param start:A 0-D Tensor (scalar). Acts as first entry in the range if limit is not None; otherwise, acts as range limit and first entry defaults to 0.
param limit:A 0-D Tensor (scalar). Upper limit of sequence, exclusive. If None, defaults to the value of start while the first entry of the range defaults to 0.
param delta:A 0-D Tensor (scalar). Number that increments start. Defaults to 1.
param dtype:The type of the elements of the resulting tensor.
param name:A name for the operation. Defaults to “range”.
returns:An 1-D Tensor of type dtype.

@compatibility(numpy) Equivalent to np.arange @end_compatibility

注意

tensorflow.compat.v1.random_uniform模块介绍

Outputs random values from a uniform distribution.

The generated values follow a uniform distribution in the range [minval, maxval). The lower bound minval is included in the range, while the upper bound maxval is excluded.

For floats, the default range is [0, 1). For ints, at least maxval must be specified explicitly.

In the integer case, the random integers are slightly biased unless maxval - minval is an exact power of two. The bias is small for values of maxval - minval significantly smaller than the range of the output (either 2**32 or 2**64).

Examples:

>>> tf.random.uniform(shape=[2])
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([..., ...], dtype=float32)>
>>> tf.random.uniform(shape=[], minval=-1., maxval=0.)
<tf.Tensor: shape=(), dtype=float32, numpy=-...>
>>> tf.random.uniform(shape=[], minval=5, maxval=10, dtype=tf.int64)
<tf.Tensor: shape=(), dtype=int64, numpy=...>

The seed argument produces a deterministic sequence of tensors across multiple calls. To repeat that sequence, use tf.random.set_seed:

>>> tf.random.set_seed(5)
>>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=2>
>>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=0>
>>> tf.random.set_seed(5)
>>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=2>
>>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=0>

Without tf.random.set_seed but with a seed argument is specified, small changes to function graphs or previously executed operations will change the returned value. See tf.random.set_seed for details.

param shape:A 1-D integer Tensor or Python array. The shape of the output tensor.
param minval:A Tensor or Python value of type dtype, broadcastable with maxval. The lower bound on the range of random values to generate (inclusive). Defaults to 0.
param maxval:A Tensor or Python value of type dtype, broadcastable with minval. The upper bound on the range of random values to generate (exclusive). Defaults to 1 if dtype is floating point.
param dtype:The type of the output: float16, float32, float64, int32, or int64.
param seed:A Python integer. Used in combination with tf.random.set_seed to create a reproducible sequence of tensors across multiple calls.
param name:A name for the operation (optional).
returns:A tensor of the specified shape filled with random uniform values.
raises:ValueError – If dtype is integral and maxval is not specified.

注意

tensorflow.compat.v1.random_normal模块介绍

Outputs random values from a normal distribution.

Example that generates a new set of random values every time:

>>> tf.random.set_seed(5);
>>> tf.random.normal([4], 0, 1, tf.float32)
<tf.Tensor: shape=(4,), dtype=float32, numpy=..., dtype=float32)>

Example that outputs a reproducible result:

>>> tf.random.set_seed(5);
>>> tf.random.normal([2,2], 0, 1, tf.float32, seed=1)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-1.3768897 , -0.01258316],
      [-0.169515   ,  1.0824056 ]], dtype=float32)>

In this case, we are setting both the global and operation-level seed to ensure this result is reproducible. See tf.random.set_seed for more information.

param shape:A 1-D integer Tensor or Python array. The shape of the output tensor.
param mean:A Tensor or Python value of type dtype, broadcastable with stddev. The mean of the normal distribution.
param stddev:A Tensor or Python value of type dtype, broadcastable with mean. The standard deviation of the normal distribution.
param dtype:The type of the output.
param seed:A Python integer. Used to create a random seed for the distribution. See tf.random.set_seed for behavior.
param name:A name for the operation (optional).
returns:A tensor of the specified shape filled with random normal values.

注意

tensorflow.compat.v1.truncated_normal模块介绍

Outputs random values from a truncated normal distribution.

The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked.

param shape:A 1-D integer Tensor or Python array. The shape of the output tensor.
param mean:A 0-D Tensor or Python value of type dtype. The mean of the truncated normal distribution.
param stddev:A 0-D Tensor or Python value of type dtype. The standard deviation of the normal distribution, before truncation.
param dtype:The type of the output.
param seed:A Python integer. Used to create a random seed for the distribution. See tf.random.set_seed for behavior.
param name:A name for the operation (optional).
returns:A tensor of the specified shape filled with random truncated normal values.

注意

tensorflow.compat.v1.random_shuffle模块介绍

Randomly shuffles a tensor along its first dimension.

The tensor is shuffled along dimension 0, such that each value[j] is mapped to one and only one output[i]. For example, a mapping that might occur for a 3x2 tensor is:

```python [[1, 2], [[5, 6],

[3, 4], ==> [1, 2], [5, 6]] [3, 4]]

```

param value:A Tensor to be shuffled.
param seed:A Python integer. Used to create a random seed for the distribution. See tf.random.set_seed for behavior.
param name:A name for the operation (optional).
returns:A tensor of same shape and type as value, shuffled along its first dimension.

注意

tensorflow.compat.v1.random_crop模块介绍

Randomly crops a tensor to a given size.

Slices a shape size portion out of value at a uniformly chosen offset. Requires value.shape >= size.

If a dimension should not be cropped, pass the full size of that dimension. For example, RGB images can be cropped with size = [crop_height, crop_width, 3].

param value:Input tensor to crop.
param size:1-D tensor with size the rank of value.
param seed:Python integer. Used to create a random seed. See tf.random.set_seed for behavior.
param name:A name for this operation (optional).
returns:A cropped tensor of the same rank as value and shape size.

注意

tensorflow.compat.v1.gfile.GFile模块介绍(选修)

File I/O wrappers without thread locking.

The main roles of the tf.io.gfile module are:

  1. To provide an API that is close to Python’s file I/O objects, and
  2. To provide an implementation based on TensorFlow’s C++ FileSystem API.

The C++ FileSystem API supports multiple file system implementations, including local files, Google Cloud Storage (using a gs:// prefix, and HDFS (using an hdfs:// prefix). TensorFlow exports these as tf.io.gfile, so that you can use these implementations for saving and loading checkpoints, writing to TensorBoard logs, and accessing training data (among other uses). However, if all your files are local, you can use the regular Python file API without any problem.

Note: though similar to Python’s I/O implementation, there are semantic differences to make tf.io.gfile more efficient for backing filesystems. For example, a write mode file will not be opened until the first write call, to minimize RPC invocations in network filesystems.

tensorflow.compat.v1.gfile.GFile.mode

Returns the mode in which the file was opened.

tensorflow.compat.v1.gfile.GFile.name

Returns the file name.

注意

tensorflow.image.decode_jpeg模块介绍(选修)

Decode a JPEG-encoded image to a uint8 tensor.

The attr channels indicates the desired number of color channels for the decoded image.

Accepted values are:

  • 0: Use the number of channels in the JPEG-encoded image.
  • 1: output a grayscale image.
  • 3: output an RGB image.

If needed, the JPEG-encoded image is transformed to match the requested number of color channels.

The attr ratio allows downscaling the image by an integer factor during decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than downscaling the image later.

This op also supports decoding PNGs and non-animated GIFs since the interface is the same, though it is cleaner to use tf.image.decode_image.

param contents:A Tensor of type string. 0-D. The JPEG-encoded image.
param channels:An optional int. Defaults to 0. Number of color channels for the decoded image.
param ratio:An optional int. Defaults to 1. Downscaling ratio.
param fancy_upscaling:
 An optional bool. Defaults to True. If true use a slower but nicer upscaling of the chroma planes (yuv420/422 only).
param try_recover_truncated:
 An optional bool. Defaults to False. If true try to recover an image from truncated input.
param acceptable_fraction:
 An optional float. Defaults to 1. The minimum required fraction of lines before a truncated input is accepted.
param dct_method:
 An optional string. Defaults to “”. string specifying a hint about the algorithm used for decompression. Defaults to “” which maps to a system-specific default. Currently valid values are [“INTEGER_FAST”, “INTEGER_ACCURATE”]. The hint may be ignored (e.g., the internal jpeg library changes to a version that does not have that specific option.)
param name:A name for the operation (optional).
returns:A Tensor of type uint8.