淺談Keras的Sequential與PyTorch的Sequential的區別
阿新 • • 發佈:2020-06-18
深度學習庫Keras中的Sequential是多個網路層的線性堆疊,在實現AlexNet與VGG等網路方面比較容易,因為它們沒有ResNet那樣的shortcut連線。在Keras中要實現ResNet網路則需要Model模型。
下面是Keras的Sequential具體示例:
可以通過向Sequential模型傳遞一個layer的list來構造該模型:
from keras.models import Sequential from keras.layers import Dense,Activation model = Sequential([ Dense(32,input_dim=784),Activation('relu'),Dense(10),Activation('softmax'),])
也可以通過.add()方法一個個的將layer加入模型中:
model = Sequential() model.add(Dense(32,input_dim=784)) model.add(Activation('relu'))
Keras可以通過泛型模型(Model)實現複雜的網路,如ResNet,Inception等,具體示例如下:
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(input=inputs,output=predictions) model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy']) model.fit(data,labels) # starts training
在目前的PyTorch版本中,可以僅通過Sequential實現線性模型和複雜的網路模型。PyTorch中的Sequential具體示例如下:
model = torch.nn.Sequential( torch.nn.Linear(D_in,H),torch.nn.ReLU(),torch.nn.Linear(H,D_out),)
也可以通過.add_module()方法一個個的將layer加入模型中:
layer1 = nn.Sequential() layer1.add_module('conv1',nn.Conv2d(3,32,3,1,padding=1)) layer1.add_module('relu1',nn.ReLU(True)) layer1.add_module('pool1',nn.MaxPool2d(2,2))
由上可以看出,PyTorch建立網路的方法與Keras類似,PyTorch借鑑了Keras的一些優點。
以上這篇淺談Keras的Sequential與PyTorch的Sequential的區別就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。