IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 人工智能 -> keras 和 tensorflow的结合 -> 正文阅读

[人工智能]keras 和 tensorflow的结合

tensorflow keras详细的api

https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer

keras内部的核心函数

  • build(self, input_shape): This method can be used to create weights that depend on the shape(s) of the input(s), using?add_weight().?__call__()?will automatically build the layer (if it has not been built yet) by calling?build().
  • # 主要定义模型的构成(各层及其参数)
  • call(self, inputs, *args, **kwargs): Called in?__call__?after making sure?build()?has been called.?call()?performs the logic of applying the layer to the input tensors (which should be passed in as argument). Two reserved keyword arguments you can optionally use in?call()?are:
    • training?(boolean, whether the call is in inference mode or training mode). See more details in?the layer/model subclassing guide
    • mask?(boolean tensor encoding masked timesteps in the input, used in RNN layers). See more details in?the layer/model subclassing guide?A typical signature for this method is?call(self, inputs), and user could optionally add?training?and?mask?if the layer need them.?*args?and?**kwargs?is only useful for future extension when more input parameters are planned to be added.
    • #call主要定义层的计算逻辑

tensorflow session.run函数的api

??????https://github.com/tensorflow/docs/blob/r1.14/site/en/api_docs/python/tf/Session.md#run

run(
? ? fetches,
? ? feed_dict=None,
? ? options=None,
? ? run_metadata=None
)

Runs operations and evaluates tensors in?fetches.

This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every?Operation?and evaluate every?Tensor?in?fetches, substituting the values in?feed_dict?for the corresponding input values.

The?fetches?argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types:

  • A?tf.Operation. The corresponding fetched value will be?None.
  • A?tf.Tensor. The corresponding fetched value will be a numpy ndarray containing the value of that tensor.
  • A?tf.SparseTensor. The corresponding fetched value will be a?tf.compat.v1.SparseTensorValue?containing the value of that sparse tensor.
  • A?get_tensor_handle?op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.
  • A?string?which is the name of a tensor or operation in the graph.

The value returned by?run()?has the same shape as the?fetches?argument, where the leaves are replaced by the corresponding values returned by TensorFlow.

# session.run第一个参数必须对应特定的数据类型。

The optional?feed_dict?argument allows the caller to override the value of tensors in the graph. Each key in?feed_dict?can be one of the following types:

  • If the key is a?tf.Tensor, the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same?dtype?as that tensor. Additionally, if the key is a?tf.compat.v1.placeholder, the shape of the value will be checked for compatibility with the placeholder.
  • If the key is a?tf.SparseTensor, the value should be a?tf.compat.v1.SparseTensorValue.
  • If the key is a nested tuple of?Tensors or?SparseTensors, the value should be a nested tuple with the same structure that maps to their corresponding values as above.
  • #feed_dict格式为dict,key必须对应特定的数据类型

Each value in?feed_dict?must be convertible to a numpy array of the dtype of the corresponding key.

The optional?options?argument expects a [RunOptions] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).

The optional?run_metadata?argument expects a [RunMetadata] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in?options, the profiled info will be collected into this argument and passed back.

Args:

  • fetches: A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above).
  • feed_dict: A dictionary that maps graph elements to values (described above).
  • options: A [RunOptions] protocol buffer
  • run_metadata: A [RunMetadata] protocol buffer

Returns:

Either a single value if?fetches?is a single graph element, or a list of values if?fetches?is a list, or a dictionary with the same keys as?fetches?if that is a dictionary (described above). Order in which?fetches?operations are evaluated inside the call is undefined.

Raises:

  • RuntimeError: If this?Session?is in an invalid state (e.g. has been closed).
  • TypeError: If?fetches?or?feed_dict?keys are of an inappropriate type.
  • ValueError: If?fetches?or?feed_dict?keys are invalid or refer to a?Tensor?that doesn't exist.

分析?

由以上内容可知,基于keras定义的模型对应的数据类型通常为tf.Module,tf.layers.Layer或tf.models.Model,并非session允许的数据类型。

因此,如要基于session运行模型,我们需要从keras中获取session要求的数据;

经分析发现,keras内部的call函数在定义完整的计算逻辑后会返回模型的output,该output对应的数据类型为tf.Tensor;故我们将该output作为session.run的fetches参数。

example:

Class KerasModel(tf.models.Model)

def __init__(self):
    self._build()
def _build(self):
    # 定义model的核心层
    self.layera = tf.layer.A
    self.layerb = tf.layer.B

def call(input,training):
    # 定义各层的计算逻辑
    x = inputs
    x = self.layera(x)
    x = self.layerb(x)
    return x

==============run the KerasModel========
input_shape = [1,2,3]
inputs = tf.placeholder(shape=input_shape,dtype=y)
inputs_data = np.random.rand(*input_shape)
model = KerasModel()
outputs = model.call(inputs,False)
with tf.Session(tf.ConfigProto()) as sess:
    sess.run(outputs,inputs:input_data)

  人工智能 最新文章
2022吴恩达机器学习课程——第二课(神经网
第十五章 规则学习
FixMatch: Simplifying Semi-Supervised Le
数据挖掘Java——Kmeans算法的实现
大脑皮层的分割方法
【翻译】GPT-3是如何工作的
论文笔记:TEACHTEXT: CrossModal Generaliz
python从零学(六)
详解Python 3.x 导入(import)
【答读者问27】backtrader不支持最新版本的
上一篇文章      下一篇文章      查看所有文章
加:2021-09-20 15:47:40  更:2021-09-20 15:49:19 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/21 19:29:14-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码