python深度学习tensorflow1.0参数初始化initializer

目录
  • 正文
  • 所有初始化方法定义
    • 1、tf.constant_initializer()
    • 2、tf.truncated_normal_initializer()
    • 3、tf.random_normal_initializer()
    • 4、random_uniform_initializer = RandomUniform()
    • 5、tf.uniform_unit_scaling_initializer()
    • 6、tf.variance_scaling_initializer()
    • 7、tf.orthogonal_initializer()
    • 8、tf.glorot_uniform_initializer()
    • 9、glorot_normal_initializer()

正文

CNN中最重要的就是参数了,包括W,b。 我们训练CNN的最终目的就是得到最好的参数,使得目标函数取得最小值。参数的初始化也同样重要,因此微调受到很多人的重视,那么tf提供了哪些初始化参数的方法呢,我们能不能自己进行初始化呢?

所有初始化方法定义

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Operations often used for initializing tensors.
All variable initializers returned by functions in this file should have the
following signature:
def _initializer(shape, dtype=dtypes.float32, partition_info=None):
  Args:
    shape: List of `int` representing the shape of the output `Tensor`. Some
      initializers may also be able to accept a `Tensor`.
    dtype: (Optional) Type of the output `Tensor`.
    partition_info: (Optional) variable_scope._PartitionInfo object holding
      additional information about how the variable is partitioned. May be
      `None` if the variable is not partitioned.
  Returns:
    A `Tensor` of type `dtype` and `shape`.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import random_ops
class Initializer(object):
  """Initializer base class: all initializers inherit from this class.
  """
  def __call__(self, shape, dtype=None, partition_info=None):
    raise NotImplementedError
class Zeros(Initializer):
  """Initializer that generates tensors initialized to 0."""
  def __init__(self, dtype=dtypes.float32):
    self.dtype = dtype
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return constant_op.constant(False if dtype is dtypes.bool else 0,
                                dtype=dtype, shape=shape)
class Ones(Initializer):
  """Initializer that generates tensors initialized to 1."""
  def __init__(self, dtype=dtypes.float32):
    self.dtype = dtype
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return constant_op.constant(1, dtype=dtype, shape=shape)
class Constant(Initializer):
  """Initializer that generates tensors with constant values.
  The resulting tensor is populated with values of type `dtype`, as
  specified by arguments `value` following the desired `shape` of the
  new tensor (see examples below).
  The argument `value` can be a constant value, or a list of values of type
  `dtype`. If `value` is a list, then the length of the list must be less
  than or equal to the number of elements implied by the desired shape of the
  tensor. In the case where the total number of elements in `value` is less
  than the number of elements required by the tensor shape, the last element
  in `value` will be used to fill the remaining entries. If the total number of
  elements in `value` is greater than the number of elements required by the
  tensor shape, the initializer will raise a `ValueError`.
  Args:
    value: A Python scalar, list of values, or a N-dimensional numpy array. All
      elements of the initialized variable will be set to the corresponding
      value in the `value` argument.
    dtype: The data type.
    verify_shape: Boolean that enables verification of the shape of `value`. If
      `True`, the initializer will throw an error if the shape of `value` is not
      compatible with the shape of the initialized tensor.
  Examples:
    The following example can be rewritten using a numpy.ndarray instead
    of the `value` list, even reshaped, as shown in the two commented lines
    below the `value` list initialization.
  ```python
    >>> import numpy as np
    >>> import tensorflow as tf
    >>> value = [0, 1, 2, 3, 4, 5, 6, 7]
    >>> # 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.]]
    >>> 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.]]
    >>> print('smaller shape:')
    >>> with tf.Session():
    >>>   x = tf.get_variable('x', shape=[2, 3], initializer=init)
    ValueError: 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)
    TypeError: Expected Tensor's shape: (3, 4), got (8,).
  ```
  """
  def __init__(self, value=0, dtype=dtypes.float32, verify_shape=False):
    self.value = value
    self.dtype = dtype
    self.verify_shape = verify_shape
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return constant_op.constant(self.value, dtype=dtype, shape=shape,
                                verify_shape=self.verify_shape)
class RandomUniform(Initializer):
  """Initializer that generates tensors with a uniform distribution.
  Args:
    minval: A python scalar or a scalar tensor. Lower bound of the range
      of random values to generate.
    maxval: A python scalar or a scalar tensor. Upper bound of the range
      of random values to generate.  Defaults to 1 for float types.
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type.
  """
  def __init__(self, minval=0, maxval=None, seed=None, dtype=dtypes.float32):
    self.minval = minval
    self.maxval = maxval
    self.seed = seed
    self.dtype = dtype
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return random_ops.random_uniform(shape, self.minval, self.maxval,
                                     dtype, seed=self.seed)
class RandomNormal(Initializer):
  """Initializer that generates tensors with a normal distribution.
  Args:
    mean: a python scalar or a scalar tensor. Mean of the random values
      to generate.
    stddev: a python scalar or a scalar tensor. Standard deviation of the
      random values to generate.
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  """
  def __init__(self, mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32):
    self.mean = mean
    self.stddev = stddev
    self.seed = seed
    self.dtype = _assert_float_dtype(dtype)
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return random_ops.random_normal(shape, self.mean, self.stddev,
                                    dtype, seed=self.seed)
class TruncatedNormal(Initializer):
  """Initializer that generates a truncated normal distribution.
  These values are similar to values from a `random_normal_initializer`
  except that values more than two standard deviations from the mean
  are discarded and re-drawn. This is the recommended initializer for
  neural network weights and filters.
  Args:
    mean: a python scalar or a scalar tensor. Mean of the random values
      to generate.
    stddev: a python scalar or a scalar tensor. Standard deviation of the
      random values to generate.
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  """
  def __init__(self, mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32):
    self.mean = mean
    self.stddev = stddev
    self.seed = seed
    self.dtype = _assert_float_dtype(dtype)
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    return random_ops.truncated_normal(shape, self.mean, self.stddev,
                                       dtype, seed=self.seed)
class UniformUnitScaling(Initializer):
  """Initializer that generates tensors without scaling variance.
  When initializing a deep network, it is in principle advantageous to keep
  the scale of the input variance constant, so it does not explode or diminish
  by reaching the final layer. If the input is `x` and the operation `x * W`,
  and we want to initialize `W` uniformly at random, we need to pick `W` from
      [-sqrt(3) / sqrt(dim), sqrt(3) / sqrt(dim)]
  to keep the scale intact, where `dim = W.shape[0]` (the size of the input).
  A similar calculation for convolutional networks gives an analogous result
  with `dim` equal to the product of the first 3 dimensions.  When
  nonlinearities are present, we need to multiply this by a constant `factor`.
  See [Sussillo et al., 2014](https://arxiv.org/abs/1412.6558)
  ([pdf](http://arxiv.org/pdf/1412.6558.pdf)) for deeper motivation, experiments
  and the calculation of constants. In section 2.3 there, the constants were
  numerically computed: for a linear layer it's 1.0, relu: ~1.43, tanh: ~1.15.
  Args:
    factor: Float.  A multiplicative factor by which the values will be scaled.
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  """
  def __init__(self, factor=1.0, seed=None, dtype=dtypes.float32):
    self.factor = factor
    self.seed = seed
    self.dtype = _assert_float_dtype(dtype)
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    scale_shape = shape
    if partition_info is not None:
      scale_shape = partition_info.full_shape
    input_size = 1.0
    # Estimating input size is not possible to do perfectly, but we try.
    # The estimate, obtained by multiplying all dimensions but the last one,
    # is the right thing for matrix multiply and convolutions (see above).
    for dim in scale_shape[:-1]:
      input_size *= float(dim)
    # Avoid errors when initializing zero-size tensors.
    input_size = max(input_size, 1.0)
    max_val = math.sqrt(3 / input_size) * self.factor
    return random_ops.random_uniform(shape, -max_val, max_val,
                                     dtype, seed=self.seed)
class VarianceScaling(Initializer):
  """Initializer capable of adapting its scale to the shape of weights tensors.
  With `distribution="normal"`, samples are drawn from a truncated normal
  distribution centered on zero, with `stddev = sqrt(scale / n)`
  where n is:
    - number of input units in the weight tensor, if mode = "fan_in"
    - number of output units, if mode = "fan_out"
    - average of the numbers of input and output units, if mode = "fan_avg"
  With `distribution="uniform"`, samples are drawn from a uniform distribution
  within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
  Arguments:
    scale: Scaling factor (positive float).
    mode: One of "fan_in", "fan_out", "fan_avg".
    distribution: Random distribution to use. One of "normal", "uniform".
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  Raises:
    ValueError: In case of an invalid value for the "scale", mode" or
      "distribution" arguments.
  """
  def __init__(self, scale=1.0,
               mode="fan_in",
               distribution="normal",
               seed=None,
               dtype=dtypes.float32):
    if scale <= 0.:
      raise ValueError("`scale` must be positive float.")
    if mode not in {"fan_in", "fan_out", "fan_avg"}:
      raise ValueError("Invalid `mode` argument:", mode)
    distribution = distribution.lower()
    if distribution not in {"normal", "uniform"}:
      raise ValueError("Invalid `distribution` argument:", distribution)
    self.scale = scale
    self.mode = mode
    self.distribution = distribution
    self.seed = seed
    self.dtype = _assert_float_dtype(dtype)
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    scale = self.scale
    scale_shape = shape
    if partition_info is not None:
      scale_shape = partition_info.full_shape
    fan_in, fan_out = _compute_fans(scale_shape)
    if self.mode == "fan_in":
      scale /= max(1., fan_in)
    elif self.mode == "fan_out":
      scale /= max(1., fan_out)
    else:
      scale /= max(1., (fan_in + fan_out) / 2.)
    if self.distribution == "normal":
      stddev = math.sqrt(scale)
      return random_ops.truncated_normal(shape, 0.0, stddev,
                                         dtype, seed=self.seed)
    else:
      limit = math.sqrt(3.0 * scale)
      return random_ops.random_uniform(shape, -limit, limit,
                                       dtype, seed=self.seed)
class Orthogonal(Initializer):
  """Initializer that generates an orthogonal matrix.
  If the shape of the tensor to initialize is two-dimensional, i is initialized
  with an orthogonal matrix obtained from the singular value decomposition of a
  matrix of uniform random numbers.
  If the shape of the tensor to initialize is more than two-dimensional,
  a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`
  is initialized, where `n` is the length of the shape vector.
  The matrix is subsequently reshaped to give a tensor of the desired shape.
  Args:
    gain: multiplicative factor to apply to the orthogonal matrix
    dtype: The type of the output.
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
  """
  def __init__(self, gain=1.0, dtype=dtypes.float32, seed=None):
    self.gain = gain
    self.dtype = _assert_float_dtype(dtype)
    self.seed = seed
  def __call__(self, shape, dtype=None, partition_info=None):
    if dtype is None:
      dtype = self.dtype
    # Check the shape
    if len(shape) < 2:
      raise ValueError("The tensor to initialize must be "
                       "at least two-dimensional")
    # Flatten the input shape with the last dimension remaining
    # its original shape so it works for conv2d
    num_rows = 1
    for dim in shape[:-1]:
      num_rows *= dim
    num_cols = shape[-1]
    flat_shape = (num_rows, num_cols)
    # Generate a random matrix
    a = random_ops.random_uniform(flat_shape, dtype=dtype, seed=self.seed)
    # Compute the svd
    _, u, v = linalg_ops.svd(a, full_matrices=False)
    # Pick the appropriate singular value decomposition
    if num_rows > num_cols:
      q = u
    else:
      # Tensorflow departs from numpy conventions
      # such that we need to transpose axes here
      q = array_ops.transpose(v)
    return self.gain * array_ops.reshape(q, shape)
# Aliases.
# pylint: disable=invalid-name
zeros_initializer = Zeros
ones_initializer = Ones
constant_initializer = Constant
random_uniform_initializer = RandomUniform
random_normal_initializer = RandomNormal
truncated_normal_initializer = TruncatedNormal
uniform_unit_scaling_initializer = UniformUnitScaling
variance_scaling_initializer = VarianceScaling
orthogonal_initializer = Orthogonal
# pylint: enable=invalid-name
def glorot_uniform_initializer(seed=None, dtype=dtypes.float32):
  """The Glorot uniform initializer, also called Xavier uniform initializer.
  It draws samples from a uniform distribution within [-limit, limit]
  where `limit` is `sqrt(6 / (fan_in + fan_out))`
  where `fan_in` is the number of input units in the weight tensor
  and `fan_out` is the number of output units in the weight tensor.
  Reference: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
  Arguments:
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  Returns:
    An initializer.
  """
  return variance_scaling_initializer(scale=1.0,
                                      mode="fan_avg",
                                      distribution="uniform",
                                      seed=seed,
                                      dtype=dtype)
def glorot_normal_initializer(seed=None, dtype=dtypes.float32):
  """The Glorot normal initializer, also called Xavier normal initializer.
  It draws samples from a truncated normal distribution centered on 0
  with `stddev = sqrt(2 / (fan_in + fan_out))`
  where `fan_in` is the number of input units in the weight tensor
  and `fan_out` is the number of output units in the weight tensor.
  Reference: http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf
  Arguments:
    seed: A Python integer. Used to create random seeds. See
      @{tf.set_random_seed}
      for behavior.
    dtype: The data type. Only floating point types are supported.
  Returns:
    An initializer.
  """
  return variance_scaling_initializer(scale=1.0,
                                      mode="fan_avg",
                                      distribution="normal",
                                      seed=seed,
                                      dtype=dtype)
# Utility functions.
def _compute_fans(shape):
  """Computes the number of input and output units for a weight shape.
  Arguments:
    shape: Integer shape tuple or TF tensor shape.
  Returns:
    A tuple of scalars (fan_in, fan_out).
  """
  if len(shape) < 1:  # Just to avoid errors for constants.
    fan_in = fan_out = 1
  elif len(shape) == 1:
    fan_in = fan_out = shape[0]
  elif len(shape) == 2:
    fan_in = shape[0]
    fan_out = shape[1]
  else:
    # Assuming convolution kernels (2D, 3D, or more).
    # kernel shape: (..., input_depth, depth)
    receptive_field_size = 1.
    for dim in shape[:-2]:
      receptive_field_size *= dim
    fan_in = shape[-2] * receptive_field_size
    fan_out = shape[-1] * receptive_field_size
  return fan_in, fan_out
def _assert_float_dtype(dtype):
  """Validate and return floating point type based on `dtype`.
  `dtype` must be a floating point type.
  Args:
    dtype: The data type to validate.
  Returns:
    Validated type.
  Raises:
    ValueError: if `dtype` is not a floating point type.
  """
  if not dtype.is_floating:
    raise ValueError("Expected floating point type, got %s." % dtype)
  return dtype

1、tf.constant_initializer()

也可以简写为tf.Constant()

初始化为常数,这个非常有用,通常偏置项就是用它初始化的。

由它衍生出的两个初始化方法:

a、 tf.zeros_initializer(), 也可以简写为tf.Zeros()

b、tf.ones_initializer(), 也可以简写为tf.Ones()

例:在卷积层中,将偏置项b初始化为0,则有多种写法:

conv1 = tf.layers.conv2d(batch_images,
                         filters=64,
                         kernel_size=7,
                         strides=2,
                         activation=tf.nn.relu,
                         kernel_initializer=tf.TruncatedNormal(stddev=0.01)
                         bias_initializer=tf.Constant(0),
                        )

或者:

bias_initializer=tf.constant_initializer(0)

或者:

bias_initializer=tf.zeros_initializer()

或者:

bias_initializer=tf.Zeros()

例:如何将W初始化成拉普拉斯算子?

value = [1, 1, 1, 1, -8, 1, 1, 1,1]
init = tf.constant_initializer(value)
W= tf.get_variable('W', shape=[3, 3], initializer=init)

2、tf.truncated_normal_initializer()

或者简写为tf.TruncatedNormal()

生成截断正态分布的随机数,这个初始化方法好像在tf中用得比较多。

它有四个参数(mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32),分别用于指定均值、标准差、随机数种子和随机数的数据类型,一般只需要设置stddev这一个参数就可以了。

例:

conv1 = tf.layers.conv2d(batch_images,
                         filters=64,
                         kernel_size=7,
                         strides=2,
                         activation=tf.nn.relu,
                         kernel_initializer=tf.TruncatedNormal(stddev=0.01)
                         bias_initializer=tf.Constant(0),
                        )

或者:

conv1 = tf.layers.conv2d(batch_images,
                         filters=64,
                         kernel_size=7,
                         strides=2,
                         activation=tf.nn.relu,
                         kernel_initializer=tf.truncated_normal_initializer(stddev=0.01)
                         bias_initializer=tf.zero_initializer(),
                        )

3、tf.random_normal_initializer()

可简写为 tf.RandomNormal()

生成标准正态分布的随机数,参数和truncated_normal_initializer一样。

4、random_uniform_initializer = RandomUniform()

可简写为tf.RandomUniform()

生成均匀分布的随机数,参数有四个(minval=0, maxval=None, seed=None, dtype=dtypes.float32),分别用于指定最小值,最大值,随机数种子和类型。

5、tf.uniform_unit_scaling_initializer()

可简写为tf.UniformUnitScaling()

和均匀分布差不多,只是这个初始化方法不需要指定最小最大值,是通过计算出来的。参数为(factor=1.0, seed=None, dtype=dtypes.float32)

max_val = math.sqrt(3 / input_size) * factor

这里的input_size是指输入数据的维数,假设输入为x, 运算为x * W,则input_size= W.shape[0]

它的分布区间为[ -max_val, max_val]

6、tf.variance_scaling_initializer()

可简写为tf.VarianceScaling()

参数为(scale=1.0,mode="fan_in",distribution="normal",seed=None,dtype=dtypes.float32)

scale: 缩放尺度(正浮点数)

mode:  "fan_in", "fan_out", "fan_avg"中的一个,用于计算标准差stddev的值。

distribution:分布类型,"normal"或“uniform"中的一个。

当 distribution="normal" 的时候,生成truncated normal   distribution(截断正态分布) 的随机数,其中stddev = sqrt(scale / n) ,n的计算与mode参数有关。

  • 如果mode = "fan_in", n为输入单元的结点数;
  • 如果mode = "fan_out",n为输出单元的结点数;
  • 如果mode = "fan_avg",n为输入和输出单元结点数的平均值。

当distribution="uniform”的时候 ,生成均匀分布的随机数,假设分布区间为[-limit, limit],则

limit = sqrt(3 * scale / n)

7、tf.orthogonal_initializer()

简写为tf.Orthogonal()

生成正交矩阵的随机数。

当需要生成的参数是2维时,这个正交矩阵是由均匀分布的随机数矩阵经过SVD分解而来。

8、tf.glorot_uniform_initializer()

也称之为Xavier uniform initializer,由一个均匀分布(uniform distribution)来初始化数据。

假设均匀分布的区间是[-limit, limit],则

limit=sqrt(6 / (fan_in + fan_out))

其中的fan_in和fan_out分别表示输入单元的结点数和输出单元的结点数。

9、glorot_normal_initializer()

也称之为 Xavier normal initializer. 由一个 truncated normal distribution来初始化数据.

stddev = sqrt(2 / (fan_in + fan_out))

其中的fan_in和fan_out分别表示输入单元的结点数和输出单元的结点数。

以上就是python深度学习tensorflow1.0参数初始化initializer的详细内容,更多关于python tensorflow1.0参数initializer的资料请关注我们其它相关文章!

(0)

相关推荐

  • python深度学习TensorFlow神经网络模型的保存和读取

    目录 之前的笔记里实现了softmax回归分类.简单的含有一个隐层的神经网络.卷积神经网络等等,但是这些代码在训练完成之后就直接退出了,并没有将训练得到的模型保存下来方便下次直接使用.为了让训练结果可以复用,需要将训练好的神经网络模型持久化,这就是这篇笔记里要写的东西. TensorFlow提供了一个非常简单的API,即tf.train.Saver类来保存和还原一个神经网络模型. 下面代码给出了保存TensorFlow模型的方法: import tensorflow as tf # 声明两个变量

  • python深度学习tensorflow实例数据下载与读取

    目录 一.mnist数据 二.CSV数据 三.cifar10数据 一.mnist数据 深度学习的入门实例,一般就是mnist手写数字分类识别,因此我们应该先下载这个数据集. tensorflow提供一个input_data.py文件,专门用于下载mnist数据,我们直接调用就可以了,代码如下: import tensorflow.examples.tutorials.mnist.input_data mnist = input_data.read_data_sets("MNIST_data/&q

  • python深度学习tensorflow入门基础教程示例

    目录 正文 1.编辑器 2.常量 3.变量 4.占位符 5.图(graph) 例子1:hello world 例子2:加法和乘法 例子3: 矩阵乘法 正文 TensorFlow用张量这种数据结构来表示所有的数据. 用一阶张量来表示向量,如:v = [1.2, 2.3, 3.5] ,如二阶张量表示矩阵,如:m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],可以看成是方括号嵌套的层数. 1.编辑器 编写tensorflow代码,实际上就是编写py文件,最好找一个好用的编辑器

  • python神经网络tensorflow利用训练好的模型进行预测

    目录 学习前言 载入模型思路 实现代码 学习前言 在神经网络学习中slim常用函数与如何训练.保存模型文章里已经讲述了如何使用slim训练出来一个模型,这篇文章将会讲述如何预测. 载入模型思路 载入模型的过程主要分为以下四步: 1.建立会话Session: 2.将img_input的placeholder传入网络,建立网络结构: 3.初始化所有变量: 4.利用saver对象restore载入所有参数. 这里要注意的重点是,在利用saver对象restore载入所有参数之前,必须要建立网络结构,因

  • python深度学习tensorflow卷积层示例教程

    目录 一.旧版本(1.0以下)的卷积函数:tf.nn.conv2d 二.1.0版本中的卷积函数:tf.layers.conv2d 一.旧版本(1.0以下)的卷积函数:tf.nn.conv2d 在tf1.0中,对卷积层重新进行了封装,比原来版本的卷积层有了很大的简化. conv2d( input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None ) 该函数定义在tensorflow/pytho

  • python深度学习tensorflow安装调试教程

    目录 正文 一.安装anaconda 二.安装tensorflow 三.调试 正文 用过一段时间的caffe后,对caffe有两点感受:1.速度确实快; 2. 太不灵活了. 深度学习技术一直在发展,但是caffe的更新跟不上进度,也许是维护团队的关系:CAFFE团队成员都是业余时间在维护和更新.导致的结果就是很多新的技术在caffe里用不了,比如RNN, LSTM,batch-norm等.当然这些现在也算是旧的东西了,也许caffe已经有了,我已经很久没有关注caffe的新版本了.它的不灵活之处

  • python深度学习tensorflow1.0参数初始化initializer

    目录 正文 所有初始化方法定义 1.tf.constant_initializer() 2.tf.truncated_normal_initializer() 3.tf.random_normal_initializer() 4.random_uniform_initializer = RandomUniform() 5.tf.uniform_unit_scaling_initializer() 6.tf.variance_scaling_initializer() 7.tf.orthogona

  • python深度学习tensorflow1.0参数和特征提取

    目录 tf.trainable_variables()提取训练参数 具体实例 tf.trainable_variables()提取训练参数 在tf中,参与训练的参数可用 tf.trainable_variables()提取出来,如: #取出所有参与训练的参数 params=tf.trainable_variables() print("Trainable variables:------------------------") #循环列出参数 for idx, v in enumera

  • Python深度学习之图像标签标注软件labelme详解

    前言 labelme是一个非常好用的免费的标注软件,博主看了很多其他的博客,有的直接是翻译稿,有的不全面.对于新手入门还是有点困难.因此,本文的主要是详细介绍labelme该如何使用. 一.labelme是什么? labelme是图形图像注释工具,它是用Python编写的,并将Qt用于其图形界面.说直白点,它是有界面的, 像软件一样,可以交互,但是它又是由命令行启动的,比软件的使用稍微麻烦点.其界面如下图: 它的功能很多,包括: 对图像进行多边形,矩形,圆形,多段线,线段,点形式的标注(可用于目

  • Python深度学习之实现卷积神经网络

    一.卷积神经网络 Yann LeCun 和Yoshua Bengio在1995年引入了卷积神经网络,也称为卷积网络或CNN.CNN是一种特殊的多层神经网络,用于处理具有明显网格状拓扑的数据.其网络的基础基于称为卷积的数学运算. 卷积神经网络(CNN)的类型 以下是一些不同类型的CNN: 1D CNN:1D CNN 的输入和输出数据是二维的.一维CNN大多用于时间序列. 2D CNNN:2D CNN的输入和输出数据是三维的.我们通常将其用于图像数据问题. 3D CNNN:3D CNN的输入和输出数

  • Python深度学习pytorch神经网络图像卷积运算详解

    目录 互相关运算 卷积层 特征映射 由于卷积神经网络的设计是用于探索图像数据,本节我们将以图像为例. 互相关运算 严格来说,卷积层是个错误的叫法,因为它所表达的运算其实是互相关运算(cross-correlation),而不是卷积运算.在卷积层中,输入张量和核张量通过互相关运算产生输出张量. 首先,我们暂时忽略通道(第三维)这一情况,看看如何处理二维图像数据和隐藏表示.下图中,输入是高度为3.宽度为3的二维张量(即形状为 3 × 3 3\times3 3×3).卷积核的高度和宽度都是2. 注意,

  • Python深度学习实战PyQt5信号与槽的连接

    目录 1. 信号与槽(Signals and slots) 1.1 信号与槽的原理 1.2 信号发送者与槽的接收者 2. QtDesigner 建立信号与槽的连接 2.1 信号与槽的连接:不同的发送者与接收者,槽函数为控件的内置函数 QtDesigner 设置信号/槽的连接的操作步骤如下: 2.2 信号与槽的连接:不同的发送者与接收者,槽函数为自定义函数 QtDesigner 设置信号/槽的连接的操作步骤如下: 2.3 信号与槽的连接:相同的发送者与接收者,槽函数为控件的内置函数 2.4 信号与

  • Python深度学习之Unet 语义分割模型(Keras)

    目录 前言 一.什么是语义分割 二.Unet 1.基本原理 2.mini_unet 3. Mobilenet_unet 4.数据加载部分 参考 前言 最近由于在寻找方向上迷失自我,准备了解更多的计算机视觉任务重的模型.看到语义分割任务重Unet一个有意思的模型,我准备来复现一下它. 一.什么是语义分割 语义分割任务,如下图所示: 简而言之,语义分割任务就是将图片中的不同类别,用不同的颜色标记出来,每一个类别使用一种颜色.常用于医学图像,卫星图像任务. 那如何做到将像素点上色呢? 其实语义分割的输

  • Python深度学习之简单实现猫狗图像分类

    一.前言 本文使用的是 kaggle 猫狗大战的数据集 训练集中有 25000 张图像,测试集中有 12500 张图像.作为简单示例,我们用不了那么多图像,随便抽取一小部分猫狗图像到一个文件夹里即可. 通过使用更大.更复杂的模型,可以获得更高的准确率,预训练模型是一个很好的选择,我们可以直接使用预训练模型来完成分类任务,因为预训练模型通常已经在大型的数据集上进行过训练,通常用于完成大型的图像分类任务. tf.keras.applications中有一些预定义好的经典卷积神经网络结构(Applic

随机推荐