天天看點

DL架構之Keras:深度學習架構Keras架構的簡介、安裝(Python庫)、相關概念、Keras模型使用、使用方法之詳細攻略(二)

Keras的安裝

pip install Keras

python -m pip install keras

DL架構之Keras:深度學習架構Keras架構的簡介、安裝(Python庫)、相關概念、Keras模型使用、使用方法之詳細攻略(二)

哈哈,大功告成!繼續學習去啦!

pip install --upgrade Kera

DL架構之Keras:深度學習架構Keras架構的簡介、安裝(Python庫)、相關概念、Keras模型使用、使用方法之詳細攻略(二)

190827更新到2.2.5

DL架構之Keras:深度學習架構Keras架構的簡介、安裝(Python庫)、相關概念、Keras模型使用、使用方法之詳細攻略(二)

190827再次還原到2.2.4

DL架構之Keras:深度學習架構Keras架構的簡介、安裝(Python庫)、相關概念、Keras模型使用、使用方法之詳細攻略(二)

相關文章

Py之keras-resnet:keras-resnet的簡介、安裝、使用方法之詳細攻略

Keras的使用方法

0、三種API方式:The Sequential Model (序列模型)、The functional API (函數式API)、Model subclassing(模型子類化)

from keras.models import Model

from keras.callbacks import ModelCheckpoint

from keras.layers import Conv2D, MaxPool2D, Flatten, Dropout, Dense, Input

from keras.optimizers import Adam

from keras.backend.tensorflow_backend import set_session

from keras.utils.vis_utils import model_to_dot

import tensorflow as tf

np.random.seed(5)

config = tf.ConfigProto()

config.gpu_options.allow_growth=True

set_session(tf.Session(config=config))

1、The Sequential Model 序列模型

-非常簡單

-僅适用于單輸入,單輸出,順序的層堆疊

-适用于70%以上的用例

Sequential 序列模型如所示

可以簡單地使用.add() 來堆疊模型

在完成了模型的建構後, 可以使用.compile() 來配置學習過程:

如果需要,還可以進一步地配置優化器:

批量地在訓練資料上進行疊代: # x_train 和y_train 是Numpy 數組--就像在Scikit-Learn API 中一樣

或者,可以手動地将批次的資料提供給模型:

一行代碼就能評估模型性能:

對新的資料生成預測

1、快速開始序貫(Sequential)模型  

序貫模型是多個網絡層的線性堆疊,也就是“一條路走到黑”。  

(1)、可以通過向Sequential模型傳遞一個layer的list來構造該模型:  

from keras.models import Sequential

from keras.layers import Dense, Activation  

model = Sequential([ Dense(32, units=784), Activation('relu'), Dense(10), Activation('softmax'), ])

(2)、也可以通過.add()方法一個個的将layer加入模型中:  

model = Sequential() model.add(Dense(32, input_shape=(784,)))

model.add(Activation('relu'))

#引入Sequential,Dense,Activation

from keras.models import Sequential

from keras.layers import Dense, Activation

#向layer添加list方式

model = Sequential([Dense(32, input_dim=784),Activation('relu'),Dense(10),Activation('softmax'),])

#通過.add()方式

model = Sequential()

model.add(Dense(32, input_dim=784))

model.add(Activation('relu'))

2、The functional API 函數式API

-象玩樂高積木

-多輸入,多輸出,任意靜态圖拓撲

-适用于95%的用例

Keras 函數式API 是定義複雜模型(如多輸出模型、有向無環圖,或具有共享層的模型)的方法。

例一:全連接配接網絡

3、Model subclassing 模型子類化

-最大的靈活性

-更大的可能錯誤面

(1)、通過對tf.keras.Model 進行子類化并定義你自己的前向傳播來建構完全可自定義的模型。在__init__ 方法中建立層并将它們設定為類執行個體的屬性。在call 方法中定義前向傳播。

(2)、在啟用Eager Execution 時,模型子類化特别有用,因為可以指令式地編寫前向傳播。

(3)、以下示例展示了使用自定義前向傳播進行子類化的tf.keras.Model

class MyModel(tf.keras.Model):

   def __init__(self, num_classes=10):

       super(MyModel, self).__init__(name='my_model')

       self.num_classes = num_classes  

       # Define your layers here.

       self.dense_1 = layers.Dense(32, activation='relu')

       self.dense_2 = layers.Dense(num_classes, activation='sigmoid')

   def call(self, inputs):

       # Define your forward pass here,

       # using layers you previously defined (in `__init__`).

       x = self.dense_1(inputs)

       return self.dense_2(x)

   def compute_output_shape(self, input_shape):

       # You need to override this function if you want to use the subclassed model

       # as part of a functional-style model.# Otherwise, this method is optional.

       shape = tf.TensorShape(input_shape).as_list()

       shape[-1] = self.num_classes

       return tf.TensorShape(shape)

執行個體化新模型類

model = MyModel(num_classes=10) # The compile step specifies the training configuration.

model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),

             loss='categorical_crossentropy',

             metrics=['accuracy'])

# Trains for 5 epochs.

model.fit(data, labels, batch_size=32, epochs=5)