0
class ConvolutionalNetwork(nn.Module):
    def __init__(self, in_features):
        super().__init__()
        self.in_features = in_features
        # this computes num features outputted from the two conv layers
        c1 = int(((self.in_features - 2)) / 64)  # this is to account for the loss due to conversion to int type
        c2 = int((c1-2)/64)
        self.n_conv = int(c2*16)
        #self.n_conv = int((( ( (self.in_features - 2)/4 ) - 2 )/4 ) * 16) 
        self.conv1 = nn.Conv1d(1, 16, 3, 1)
        self.conv1_bn = nn.BatchNorm1d(16)
        self.conv2 = nn.Conv1d(16, 16, 3, 1)
        self.conv2_bn = nn.BatchNorm1d(16)
        self.dp = nn.Dropout(trial.suggest_uniform('dropout_rate',0,1.0))
        self.fc3 = nn.Linear(self.n_conv, 2)

正如你所看到的,def __init__已经有了selfin_features作为变量。我正在考虑添加另一个变量trial(它是 Optuna 包的一部分)以适应

    self.dp = nn.Dropout(trial.suggest_uniform('dropout_rate',0,1.0))

在上面的代码中。请告知如何,大多数只有来源只有def __init__ (self, trial),这非常简单,但就我而言,我有 3 个变量要在目标中传递。

4

1 回答 1

0

你可以这样做:

class ConvolutionalNetwork(nn.Module):
    def __init__(self, trial, in_features):
        # code for initialization
        ..........

def objective(trial):
    # code to create in_features
    in_features = ......
    #generate the model
    model = ConvolutionalNetwork(trial, in_features)
    ..................
    # code to run the CNN and calculate the accuracy.
    return accuracy

# Create study and optimise the objective function.
study = optuna.create_study()
study.optimize(objective, n_trails=100, timeout=600)
于 2021-01-15T12:57:31.273 回答