Warm tip: This article is reproduced from serverfault.com, please click

How can I convert this keras cnn model to pytorch version

发布于 2020-02-11 15:45:05

This is the example keras code that I want to convert to pytorch. My input dataset is 10000*1*102 (two dimensions for labels). The dataset includes 10000 samples. Each sample contains one row with 102 features. I am thinking to use 1dcnn for regression.

PS: hyper-parameter (e.g. filters, kernel_size, stride, padding) could be adjusted based on my 10000*1*102 dataset.

model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_timesteps,n_features)))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(n_outputs, activation='softmax'))
Questioner
Simon Wei
Viewed
0
ychnh 2020-02-12 08:34:39

Welcome to pytorch. :) I am really glad you decide to switch from Keras to PyTorch. It was an important step for me to understand how NNs work in more detail. If you have any specific questions about code or if it isn't working please let me know.

import torch.nn as nn
a0 = nn.Conv1D(n_timesteps, 64, 3)
a1 = nn.Relu()
b0 = nn.Conv1D(64, 64, 3)
b1 = nn.Relu()
c0 = torch.nn.Dropout(p=0.5)
d0 = nn.MaxPool1d(2)
e0 = nn.Flatten()
e1 = nn.Linear(32*n_timesteps,100)
e2 = nn.Relu()
e3 = nn.Linear(n_outputs)
f0 = nn.Softmax(dim=1)

model = nn.Sequential(a0,a1,b0,b1,c0,d0,e0,e1,e2,e3,f0)