tensorflow API:tf.constant_initializer

Args:
value: A scalar, list or tuple or an n-dimensional numpy array. All elements of the initial variable will be set to the corresponding value.
dtype: data type
Official website example:

  >>> import numpy as np
  >>> import tensorflow as tf

  >>> value = [0, 1, 2, 3, 4, 5, 6, 7]
 #也可以用注释的这个作为value
     # value = np.array(value)
    # value = value.reshape([2, 4])
    init = tf.constant_initializer(value)

  >>> print('fitting shape:')
  >>> with tf.Session():
  >>>   x = tf.get_variable('x', shape=[2, 4], initializer=init)
  >>>   x.initializer.run()
  >>>   print(x.eval())

  fitting shape:
  [[ 0.  1.  2.  3.]
   [ 4.  5.  6.  7.]]

Just-sized initialization

  >>> print('larger shape:')
  >>> with tf.Session():
  >>>   x = tf.get_variable('x', shape=[3, 4], initializer=init)
  >>>   x.initializer.run()
  >>>   print(x.eval())

  larger shape:
  [[ 0.  1.  2.  3.]
   [ 4.  5.  6.  7.]
   [ 7.  7.  7.  7.]]

The initial variable is larger than init and will be filled with the last value

  >>> print('smaller shape:')
  >>> with tf.Session():
  >>>   x = tf.get_variable('x', shape=[2, 3], initializer=init)

* <b>`ValueError`</b>: Too many elements provided. Needed at most 6, but received 8

  >>> print('shape verification:')
  >>> init_verify = tf.constant_initializer(value, verify_shape=True)
  >>> with tf.Session():
  >>>   x = tf.get_variable('x', shape=[3, 4], initializer=init_verify)

* <b>`TypeError`</b>: Expected Tensor's shape: (3, 4), got (8,).

The initial variable is smaller than init, and an error will be reported.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857122&siteId=291194637