user14977424
user14977424

Reputation:

Keras.NET Using a Model as a Layer

In Python you can use a pretrained model as a layer as shown below (source here)

import keras

from keras.applications import VGG16

from keras import models
from keras import layers


conv_base = VGG16(weights='imagenet',
                  include_top=False,
                  input_shape=(150, 150, 3))

model = models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

My question is simple: is there a way to do it in C#? I need to:

C# code below.

using Keras;
using Keras.Applications.VGG;
using Keras.Layers;
using Keras.Models;

VGG16 conv_base = new VGG16(
    weights: "imagenet",
    include_top: false,
    input_shape: (150, 150, 3)
);

Sequential model = new Sequential();

model.Add(conv_base); // obviously doesn't work
model.Add(new Flatten());
model.Add(new Dense(256, activation: "relu"));
model.Add(new Dense(1, activation: "sigmoid"));

Upvotes: 2

Views: 767

Answers (1)

user14977424
user14977424

Reputation:

Solved using this API modification in Sequential.cs:

/// <summary>
/// [CUSTOM] You can also add models via the .AddModel() method
/// </summary>
/// <param name="model">The model.</param>
public void AddModel(BaseModel model)
{
    var layers = model.ToPython().GetAttr("layers");
    foreach (var layer in layers)
    {
        PyInstance.add(layer: new BaseLayer(layer as PyObject).PyInstance);
    }
}

Upvotes: 1

Related Questions