最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast)

 更新時(shí)間:2020年06月29日 09:09:37   作者:C小C  
這篇文章主要介紹了淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

一、K.prod

prod

keras.backend.prod(x, axis=None, keepdims=False)

功能:在某一指定軸,計(jì)算張量中的值的乘積。

參數(shù)

x: 張量或變量。

axis: 一個(gè)整數(shù)需要計(jì)算乘積的軸。

keepdims: 布爾值,是否保留原尺寸。 如果 keepdims 為 False,則張量的秩減 1。 如果 keepdims 為 True,縮小的維度保留為長度 1。

返回

x 的元素的乘積的張量。

Numpy 實(shí)現(xiàn)

def prod(x, axis=None, keepdims=False):
  if isinstance(axis, list):
    axis = tuple(axis)
  return np.prod(x, axis=axis, keepdims=keepdims)

具體例子:

import numpy as np
x=np.array([[2,4,6],[2,4,6]])
 
scaling = np.prod(x, axis=1, keepdims=False)
print(x)
print(scaling)

【運(yùn)行結(jié)果】

二、K.cast

cast

keras.backend.cast(x, dtype)

功能:將張量轉(zhuǎn)換到不同的 dtype 并返回。

你可以轉(zhuǎn)換一個(gè) Keras 變量,但它仍然返回一個(gè) Keras 張量。

參數(shù)

x: Keras 張量(或變量)。

dtype: 字符串, ('float16', 'float32' 或 'float64')。

返回

Keras 張量,類型為 dtype。

例子

>>> from keras import backend as K
>>> input = K.placeholder((2, 3), dtype='float32')
>>> input
<tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>
# It doesn't work in-place as below.
>>> K.cast(input, dtype='float16')
<tf.Tensor 'Cast_1:0' shape=(2, 3) dtype=float16>
>>> input
<tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>
# you need to assign it.
>>> input = K.cast(input, dtype='float16')
>>> input
<tf.Tensor 'Cast_2:0' shape=(2, 3) dtype=float16>

補(bǔ)充知識(shí):keras源碼之backend庫目錄

backend庫目錄

先看common.py

一上來是一些說明

# the type of float to use throughout the session. 整個(gè)模塊都是用浮點(diǎn)型數(shù)據(jù)
_FLOATX = 'float32' # 數(shù)據(jù)類型為32位浮點(diǎn)型
_EPSILON = 1e-7 # 很小的常數(shù)
_IMAGE_DATA_FORMAT = 'channels_last' # 圖像數(shù)據(jù)格式 最后顯示通道,tensorflow格式

接下來看里面的一些函數(shù)

def epsilon():
  """Returns the value of the fuzz factor used in numeric expressions. 
    返回?cái)?shù)值表達(dá)式中使用的模糊因子的值
    
  # Returns
    A float.
  # Example
  ```python
    >>> keras.backend.epsilon()
    1e-07
  ```
  """
  return _EPSILON

該函數(shù)定義了一個(gè)常量,值為1e-07,在終端可以直接輸出,如下:

def set_epsilon(e):
  """Sets the value of the fuzz factor used in numeric expressions.
  # Arguments
    e: float. New value of epsilon.
  # Example
  ```python
    >>> from keras import backend as K
    >>> K.epsilon()
    1e-07
    >>> K.set_epsilon(1e-05)
    >>> K.epsilon()
    1e-05
  ```
  """
  global _EPSILON
  _EPSILON = e

該函數(shù)允許自定義值

以string的形式返回默認(rèn)的浮點(diǎn)類型:

def floatx():
  """Returns the default float type, as a string.
  (e.g. 'float16', 'float32', 'float64').
  # Returns
    String, the current default float type.
  # Example
  ```python
    >>> keras.backend.floatx()
    'float32'
  ```
  """
  return _FLOATX

把numpy數(shù)組投影到默認(rèn)的浮點(diǎn)類型:

def cast_to_floatx(x):
  """Cast a Numpy array to the default Keras float type.把numpy數(shù)組投影到默認(rèn)的浮點(diǎn)類型
  # Arguments
    x: Numpy array.
  # Returns
    The same Numpy array, cast to its new type.
  # Example
  ```python
    >>> from keras import backend as K
    >>> K.floatx()
    'float32'
    >>> arr = numpy.array([1.0, 2.0], dtype='float64')
    >>> arr.dtype
    dtype('float64')
    >>> new_arr = K.cast_to_floatx(arr)
    >>> new_arr
    array([ 1., 2.], dtype=float32)
    >>> new_arr.dtype
    dtype('float32')
  ```
  """
  return np.asarray(x, dtype=_FLOATX)

默認(rèn)數(shù)據(jù)格式、自定義數(shù)據(jù)格式和檢查數(shù)據(jù)格式:

 def image_data_format():
  """Returns the default image data format convention ('channels_first' or 'channels_last').
  # Returns
    A string, either `'channels_first'` or `'channels_last'`
  # Example
  ```python
    >>> keras.backend.image_data_format()
    'channels_first'
  ```
  """
  return _IMAGE_DATA_FORMAT
 
 
def set_image_data_format(data_format):
  """Sets the value of the data format convention.
  # Arguments
    data_format: string. `'channels_first'` or `'channels_last'`.
  # Example
  ```python
    >>> from keras import backend as K
    >>> K.image_data_format()
    'channels_first'
    >>> K.set_image_data_format('channels_last')
    >>> K.image_data_format()
    'channels_last'
  ```
  """
  global _IMAGE_DATA_FORMAT
  if data_format not in {'channels_last', 'channels_first'}:
    raise ValueError('Unknown data_format:', data_format)
  _IMAGE_DATA_FORMAT = str(data_format)
 
def normalize_data_format(value):
  """Checks that the value correspond to a valid data format.
  # Arguments
    value: String or None. `'channels_first'` or `'channels_last'`.
  # Returns
    A string, either `'channels_first'` or `'channels_last'`
  # Example
  ```python
    >>> from keras import backend as K
    >>> K.normalize_data_format(None)
    'channels_first'
    >>> K.normalize_data_format('channels_last')
    'channels_last'
  ```
  # Raises
    ValueError: if `value` or the global `data_format` invalid.
  """
  if value is None:
    value = image_data_format()
  data_format = value.lower()
  if data_format not in {'channels_first', 'channels_last'}:
    raise ValueError('The `data_format` argument must be one of '
             '"channels_first", "channels_last". Received: ' +
             str(value))
  return data_format

剩余的關(guān)于維度順序和數(shù)據(jù)格式的方法:

def set_image_dim_ordering(dim_ordering):
  """Legacy setter for `image_data_format`.
  # Arguments
    dim_ordering: string. `tf` or `th`.
  # Example
  ```python
    >>> from keras import backend as K
    >>> K.image_data_format()
    'channels_first'
    >>> K.set_image_data_format('channels_last')
    >>> K.image_data_format()
    'channels_last'
  ```
  # Raises
    ValueError: if `dim_ordering` is invalid.
  """
  global _IMAGE_DATA_FORMAT
  if dim_ordering not in {'tf', 'th'}:
    raise ValueError('Unknown dim_ordering:', dim_ordering)
  if dim_ordering == 'th':
    data_format = 'channels_first'
  else:
    data_format = 'channels_last'
  _IMAGE_DATA_FORMAT = data_format
 
 
def image_dim_ordering():
  """Legacy getter for `image_data_format`.
  # Returns
    string, one of `'th'`, `'tf'`
  """
  if _IMAGE_DATA_FORMAT == 'channels_first':
    return 'th'
  else:
    return 'tf'

在common.py之后有三個(gè)backend,分別是cntk,tensorflow和theano。

__init__.py

首先從common.py中引入了所有需要的東西

from .common import epsilon
from .common import floatx
from .common import set_epsilon
from .common import set_floatx
from .common import cast_to_floatx
from .common import image_data_format
from .common import set_image_data_format
from .common import normalize_data_format

接下來是檢查環(huán)境變量與配置文件,設(shè)置backend和format,默認(rèn)的backend是tensorflow。

# Set Keras base dir path given KERAS_HOME env variable, if applicable.
# Otherwise either ~/.keras or /tmp.
if 'KERAS_HOME' in os.environ: # 環(huán)境變量
  _keras_dir = os.environ.get('KERAS_HOME')
else:
  _keras_base_dir = os.path.expanduser('~')
  if not os.access(_keras_base_dir, os.W_OK):
    _keras_base_dir = '/tmp'
  _keras_dir = os.path.join(_keras_base_dir, '.keras')
 
# Default backend: TensorFlow. 默認(rèn)后臺(tái)是TensorFlow
_BACKEND = 'tensorflow'
 
# Attempt to read Keras config file.讀取keras配置文件
_config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json'))
if os.path.exists(_config_path):
  try:
    with open(_config_path) as f:
      _config = json.load(f)
  except ValueError:
    _config = {}
  _floatx = _config.get('floatx', floatx())
  assert _floatx in {'float16', 'float32', 'float64'}
  _epsilon = _config.get('epsilon', epsilon())
  assert isinstance(_epsilon, float)
  _backend = _config.get('backend', _BACKEND)
  _image_data_format = _config.get('image_data_format',
                   image_data_format())
  assert _image_data_format in {'channels_last', 'channels_first'}
 
  set_floatx(_floatx)
  set_epsilon(_epsilon)
  set_image_data_format(_image_data_format)
  _BACKEND = _backend

之后的tensorflow_backend.py文件是一些tensorflow中的函數(shù)說明,詳細(xì)內(nèi)容請(qǐng)參考tensorflow有關(guān)資料。

以上這篇淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python 數(shù)據(jù)結(jié)構(gòu)之旋轉(zhuǎn)鏈表

    Python 數(shù)據(jù)結(jié)構(gòu)之旋轉(zhuǎn)鏈表

    這篇文章主要介紹了Python 數(shù)據(jù)結(jié)構(gòu)之旋轉(zhuǎn)鏈表的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • 如何利用Playwright庫進(jìn)行電影網(wǎng)站數(shù)據(jù)的獲取

    如何利用Playwright庫進(jìn)行電影網(wǎng)站數(shù)據(jù)的獲取

    playwright庫是微軟開源的一個(gè)庫,這個(gè)庫的功能更加的強(qiáng)大,除了可以實(shí)現(xiàn)同步操作,同樣也可以實(shí)現(xiàn)異步的操作,這篇文章主要介紹了如何利用Playwright庫進(jìn)行電影網(wǎng)站數(shù)據(jù)的獲取,需要的朋友可以參考下
    2023-05-05
  • pytorch中可視化之hook鉤子

    pytorch中可視化之hook鉤子

    本文主要介紹了pytorch中可視化之hook鉤子,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • python爬蟲進(jìn)階之協(xié)程詳解

    python爬蟲進(jìn)階之協(xié)程詳解

    這篇文章主要介紹了python爬蟲進(jìn)階之協(xié)程詳解,coroutine中文翻譯叫協(xié)程,在 Python 中昌指代為協(xié)程對(duì)象類型,可以將協(xié)程對(duì)象注冊(cè)到時(shí)間循環(huán)中被調(diào)用,需要的朋友可以參考下
    2023-08-08
  • 詳解python的函數(shù)遞歸與調(diào)用

    詳解python的函數(shù)遞歸與調(diào)用

    Python中的函數(shù)遞歸是一種函數(shù)調(diào)用自身的編程技術(shù),遞歸可以用來解決問題,特別是那些可以分解為更小、相似子問題的問題,本文將給大家詳細(xì)的講解一下python的函數(shù)遞歸與調(diào)用,需要的朋友可以參考下
    2023-10-10
  • 使用python實(shí)現(xiàn)畫AR模型時(shí)序圖

    使用python實(shí)現(xiàn)畫AR模型時(shí)序圖

    今天小編就為大家分享一篇使用python實(shí)現(xiàn)畫AR模型時(shí)序圖,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • 詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理

    詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理

    這篇文章主要介紹了詳解Python各大聊天系統(tǒng)的屏蔽臟話功能原理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。
    2016-12-12
  • pandas學(xué)習(xí)之df.set_index的具體使用

    pandas學(xué)習(xí)之df.set_index的具體使用

    本文主要介紹了pandas學(xué)習(xí)之df.set_index的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • python requests更換代理適用于IP頻率限制的方法

    python requests更換代理適用于IP頻率限制的方法

    今天小編就為大家分享一篇python requests更換代理適用于IP頻率限制的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • pandas計(jì)數(shù) value_counts()的使用

    pandas計(jì)數(shù) value_counts()的使用

    這篇文章主要介紹了pandas計(jì)數(shù) value_counts()的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06

最新評(píng)論

黑河市| 吴桥县| 栾川县| 阿拉善盟| 驻马店市| 邵武市| 梅河口市| 靖州| 彩票| 平江县| 民和| 罗甸县| 寿光市| 饶河县| 武隆县| 康平县| 武穴市| 自治县| 绥中县| 建湖县| 长兴县| 邵阳县| 淳化县| 景宁| 宁化县| 布尔津县| 洪泽县| 荆州市| 浦江县| 翁牛特旗| 江都市| 三河市| 昌吉市| 和政县| 健康| 兴安县| 长垣县| 漠河县| 淳化县| 兰溪市| 万宁市|