天天看點

Keras中的Sequential與PyTorch中的Sequential對比

深度學習庫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對比

繼續閱讀