浅谈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 相关文章推荐
linux系统使用python获取内存使用信息脚本分享
Jan 15 Python
Python操作列表的常用方法分享
Feb 13 Python
举例讲解如何在Python编程中进行迭代和遍历
Jan 19 Python
python 列表删除所有指定元素的方法
Apr 19 Python
python实现txt文件格式转换为arff格式
May 31 Python
pycharm下查看python的变量类型和变量内容的方法
Jun 26 Python
Python实现查找最小的k个数示例【两种解法】
Jan 08 Python
Python列表常见操作详解(获取,增加,删除,修改,排序等)
Feb 18 Python
Django 自动生成api接口文档教程
Nov 19 Python
flask框架自定义url转换器操作详解
Jan 25 Python
什么是Python变量作用域
Jun 03 Python
用Python提取PDF表格的方法
Apr 11 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
php 7新特性之类型申明详解
2017/06/06 PHP
jQuery Ajax文件上传(php)
2009/06/16 Javascript
javascript 进度条 实现代码
2009/07/30 Javascript
扩展javascript的Date方法实现代码(prototype)
2010/11/20 Javascript
jquery及原生js获取select下拉框选中的值示例
2013/10/25 Javascript
JS过滤url参数特殊字符的实现方法
2013/12/24 Javascript
node.js中的fs.realpath方法使用说明
2014/12/16 Javascript
JS获取及设置TextArea或input文本框选择文本位置的方法
2015/03/24 Javascript
javascript实现输出指定行数正方形图案的方法
2015/08/03 Javascript
jQuery Validate表单验证插件 添加class属性形式的校验
2016/01/18 Javascript
JS动态插入并立即执行回调函数的方法
2016/04/21 Javascript
JQuery解析XML数据的几个简单实例
2016/05/18 Javascript
JS实现二叉查找树的建立以及一些遍历方法实现
2017/04/17 Javascript
javascript代码优化的8点总结
2018/01/29 Javascript
Vue下路由History模式打包后页面空白的解决方法
2018/06/29 Javascript
JSON数据中存在单个转义字符“\”的处理方法
2018/07/11 Javascript
Vue递归实现树形菜单方法实例
2018/11/06 Javascript
element-ui多文件上传的实现示例
2019/04/10 Javascript
Vue基于iview实现登录密码的显示与隐藏功能
2020/03/06 Javascript
[04:05]TI9战队采访 - Natus Vincere
2019/08/22 DOTA
python OpenCV学习笔记直方图反向投影的实现
2018/02/07 Python
python flask实现分页的示例代码
2018/08/02 Python
Python时间序列处理之ARIMA模型的使用讲解
2019/04/02 Python
W3C公布最新的HTML5标准草案
2008/10/17 HTML / CSS
使用HTML5的File实现base64和图片的互转
2013/08/01 HTML / CSS
澳大利亚自然和有机的健康美容产品一站式商店:Ziani Beauty
2017/12/28 全球购物
NFL欧洲商店(德国):NFL Europe Shop DE
2018/11/03 全球购物
自荐信怎么写好
2013/11/11 职场文书
中秋寄语大全
2014/04/11 职场文书
银行职员自我鉴定
2014/04/20 职场文书
2019企业给员工的慰问信
2019/06/24 职场文书
如何用python识别滑块验证码中的缺口
2021/04/01 Python
Go语言中的UTF-8实现
2021/04/26 Golang
Python数据可视化之用Matplotlib绘制常用图形
2021/06/03 Python
对象析构函数__del__在Python中何时使用
2022/03/22 Python
如何解决flex文本溢出问题小结
2022/07/15 HTML / CSS