from caffe2.python import core, model_helper, workspace # Define ModelHelper model = model_helper.ModelHelper(name="my_model") # Define the input data dimension data = model.AddInput("data", shape=[1, 3, 224, 224]) # Define Convolutional layer conv1 = model.Conv( data, "conv1", dim_in=3, dim_out=32, kernel=3, pad=1, stride=1 ) # Add ReLU activation function relu1 = model.Relu(conv1, "relu1") # Define Max-pooling layer pool1 = model.MaxPool(relu1, "pool1", kernel=2, stride=2) # Define the output dimension of the fully connected layer fc_dim_out = 10 # Define the output layer fc = model.FC(pool1, "fc", dim_in=32 * 112 * 112, dim_out=fc_dim_out) # Add the Softmax layer softmax = model.Softmax(fc, "softmax") # Define the label data dimension label = model.AddInput("label", shape=[1]) # Calculate the loss xent = model.LabelCrossEntropy([softmax, label], "xent") # Add the accuracy metric accuracy = model.Accuracy([softmax, label], "accuracy") # Set up the learning rate and optimizer optimizer_conf = optimizer.build_sgd( lr=0.1, momentum=0.9, nesterov=1, weight_decay=0.0005 ) model.AddGradientOperators([xent]) model.AddOptimizerOperators(optimizer_conf) # Initialize the workspace workspace.RunNetOnce(model.param_init_net) # Create the training data and labels data_array = np.random.rand(1, 3, 224, 224).astype(np.float32) label_array = np.random.rand(1).astype(np.int32) # Feed the data to the workspace workspace.FeedBlob("data", data_array) workspace.FeedBlob("label", label_array) # Run the network for training for i in range(10): workspace.RunNet(model.net)This example builds a small convolutional neural network, defines a loss function and an optimizer, and trains the network for a few iterations. The code uses the `caffe2.python` package library. Overall, `ModelHelper` API in Caffe2 makes it straightforward to specify and train custom models.