浅谈keras中的后端backend及其相关函数(K.prod,K.cast)


Posted in Python onJune 29, 2020

一、K.prod

prod

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

功能:在某一指定轴,计算张量中的值的乘积。

参数

x: 张量或变量。

axis: 一个整数需要计算乘积的轴。

keepdims: 布尔值,是否保留原尺寸。 如果 keepdims 为 False,则张量的秩减 1。 如果 keepdims 为 True,缩小的维度保留为长度 1。

返回

x 的元素的乘积的张量。

Numpy 实现

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)

【运行结果】

浅谈keras中的后端backend及其相关函数(K.prod,K.cast)

二、K.cast

cast

keras.backend.cast(x, dtype)

功能:将张量转换到不同的 dtype 并返回。

你可以转换一个 Keras 变量,但它仍然返回一个 Keras 张量。

参数

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>

补充知识:keras源码之backend库目录

backend库目录

先看common.py

一上来是一些说明

# the type of float to use throughout the session. 整个模块都是用浮点型数据
_FLOATX = 'float32' # 数据类型为32位浮点型
_EPSILON = 1e-7 # 很小的常数
_IMAGE_DATA_FORMAT = 'channels_last' # 图像数据格式 最后显示通道,tensorflow格式

接下来看里面的一些函数

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

该函数定义了一个常量,值为1e-07,在终端可以直接输出,如下:

浅谈keras中的后端backend及其相关函数(K.prod,K.cast)

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

该函数允许自定义值

浅谈keras中的后端backend及其相关函数(K.prod,K.cast)

以string的形式返回默认的浮点类型:

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

浅谈keras中的后端backend及其相关函数(K.prod,K.cast)

把numpy数组投影到默认的浮点类型:

def cast_to_floatx(x):
  """Cast a Numpy array to the default Keras float type.把numpy数组投影到默认的浮点类型
  # 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)

默认数据格式、自定义数据格式和检查数据格式:

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

剩余的关于维度顺序和数据格式的方法:

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之后有三个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

接下来是检查环境变量与配置文件,设置backend和format,默认的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: # 环境变量
  _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. 默认后台是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中的函数说明,详细内容请参考tensorflow有关资料。

以上这篇浅谈keras中的后端backend及其相关函数(K.prod,K.cast)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python中处理XML的教程
Apr 29 Python
Python实现计算两个时间之间相差天数的方法
May 10 Python
python实现求最长回文子串长度
Jan 22 Python
python实现图像识别功能
Jan 29 Python
python matlibplot绘制多条曲线图
Feb 19 Python
Python中生成一个指定长度的随机字符串实现示例
Nov 06 Python
关于Numpy中的行向量和列向量详解
Nov 30 Python
Python开发企业微信机器人每天定时发消息实例
Mar 17 Python
在python中利用pycharm自定义代码块教程(三步搞定)
Apr 15 Python
使用 Python 读取电子表格中的数据实例详解
Apr 17 Python
详解python的变量缓存机制
Jan 24 Python
Python实现位图分割的效果
Nov 20 Python
如何使用python记录室友的抖音在线时间
Jun 29 #Python
Python sublime安装及配置过程详解
Jun 29 #Python
keras K.function获取某层的输出操作
Jun 29 #Python
Python pytesseract验证码识别库用法解析
Jun 29 #Python
用Python开发app后端有优势吗
Jun 29 #Python
在keras里实现自定义上采样层
Jun 28 #Python
Python如何对XML 解析
Jun 28 #Python
You might like
destoon实现底部添加你是第几位访问者的方法
2014/07/15 PHP
Laravel实现autoload方法详解
2017/05/07 PHP
php模仿qq空间或朋友圈发布动态、评论动态、回复评论、删除动态或评论的功能(中)
2017/06/11 PHP
PHP 二维array转换json的实例讲解
2018/08/21 PHP
PHP 出现 http500 错误的解决方法
2021/03/09 PHP
一款JavaScript压缩工具:X2JSCompactor
2007/06/13 Javascript
使用SyntaxHighlighter实现HTML高亮显示代码的方法
2010/02/04 Javascript
JavaScript高级程序设计 学习笔记 js高级技巧
2011/09/20 Javascript
jquery中选择块并改变属性值的方法
2013/07/31 Javascript
Iframe 自动适应页面的高度示例代码
2014/02/26 Javascript
JavaScript和CSS交互的方法汇总
2014/12/02 Javascript
JS多物体实现缓冲运动效果示例
2016/12/20 Javascript
js判断用户是输入的地址请求的路径(实例讲解)
2017/07/18 Javascript
JS使用正则表达式找出最长连续子串长度
2017/10/26 Javascript
详解webpack 热更新优化
2018/09/13 Javascript
layui添加动态菜单与选项卡
2019/07/26 Javascript
[04:48]DOTA2上海特锦赛小组赛第三日 TOP10精彩集锦
2016/02/28 DOTA
Python变量作用范围实例分析
2015/07/07 Python
对python函数签名的方法详解
2019/01/22 Python
PyQt5 QTable插入图片并动态更新的实例
2019/06/18 Python
Python处理时间日期坐标轴过程详解
2019/06/25 Python
简单了解python 邮件模块的使用方法
2019/07/24 Python
解决Django layui {{}}冲突的问题
2019/08/29 Python
Python中低维数组填充高维数组的实现
2019/12/02 Python
美国婚礼礼品网站:MyWeddingFavors
2018/09/26 全球购物
奥林匹亚体育:Olympia Sports
2020/12/30 全球购物
介绍一下Java的安全机制
2012/06/28 面试题
汽车运用工程毕业生自荐信
2013/10/29 职场文书
感恩教育月活动总结
2014/07/07 职场文书
处级领导班子全部召开专题民主生活会情况汇报
2014/09/27 职场文书
班主任师德师风自我剖析材料
2014/10/02 职场文书
经理助理岗位职责
2015/02/02 职场文书
爱护公物主题班会
2015/08/17 职场文书
终止合同协议书范本
2016/03/22 职场文书
JavaScript如何优化逻辑判断代码详解
2021/06/08 Javascript
Sql Server 行数据的某列值想作为字段列显示的方法
2022/04/20 SQL Server