zoukankan      html  css  js  c++  java
  • keras Model 1 入门篇

    1 入门

    2 多个输入和输出

    3 共享层

    最近在学习keras,它有一些实现好的特征提取的模型:resNet、vgg。而且是带权重的。用来做特诊提取比较方便

    首先要知道keras有两种定义模型的方式:

    1、 序列模型  The Sequential model

    2、 函数式模型  the Keras functional 

    主要关注函数式模型:

    函数式模型用来构造比较复杂的模型 ,比如说有多个输出的模型,有向非循环图,或者有共享层的模型

    入门例子:密集连接的网络。可能这样的网络用Sequential模型实现起来更好,但是为了入门,就先做这样的一个简单的网络。

    1、 每个layer实例都是可以调用的,它返回一个tensor

    2、 输入tensor和输出tensor可以用来定义一个Model

    3、 函数式的模型也可以像 Sequential模型一样训练。

    from keras.layers import Input, Dense
    from keras.models import Model
    
    # This returns a tensor
    inputs = Input(shape=(784,))
    
    # a layer instance is callable on a tensor, and returns a tensor
    x = Dense(64, activation='relu')(inputs)
    x = Dense(64, activation='relu')(x)
    predictions = Dense(10, activation='softmax')(x)
    
    # This creates a model that includes
    # the Input layer and three Dense layers
    model = Model(inputs=inputs, outputs=predictions)
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    model.fit(data, labels)  # starts training

    生成的模型与layer一样,也是可以被调用的。

    在函数式模型中,对一个模型的重用(reuse)是很简单的。只要把这个模型当成一个layer,然后在tensor上调用它即可。

    要注意的是:这样调用的modle,不仅仅是它的结构被调用了,它权重也在被重用。

    x = Input(shape=(784,))
    # This works, and returns the 10-way softmax we defined above.
    y = model(x)

    这样的话,我们就可以快速的创建能够处理序列化的输入的模型。比如说,我们把一个图片分类模型,应用到一个视频分类模型中,只需要一行代码即可

    from keras.layers import TimeDistributed
    
    # Input tensor for sequences of 20 timesteps,
    # each containing a 784-dimensional vector
    input_sequences = Input(shape=(20, 784))
    
    # This applies our previous model to every timestep in the input sequences.
    # the output of the previous model was a 10-way softmax,
    # so the output of the layer below will be a sequence of 20 vectors of size 10.
    processed_sequences = TimeDistributed(model)(input_sequences)
  • 相关阅读:
    李宏毅2021春机器学习课程笔记——通过训练集上的Loss可获得的信息
    python学习-NotImplementedError的使用
    代码运行优化
    django实现上传文件读取文件内容
    django-admin上传下载文件
    AtCoder Beginner Contest 191 F
    敏感词过滤 AC自动机
    面经知识点
    select poll epoll实例
    socket用法
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/10972881.html
Copyright © 2011-2022 走看看