public static void Run() { //Load train data NDarray x = np.array(new float[, ] { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } }); NDarray y = np.array(new float[] { 0, 1, 1, 0 }); //Build sequential model var model = new Sequential(); model.Add(new Dense(32, activation: "relu", input_shape: new Shape(2))); model.Add(new Dense(64, activation: "relu")); model.Add(new Dense(1, activation: "sigmoid")); //Compile and train model.Compile(optimizer: new Adam(), loss: "binary_crossentropy", metrics: new string[] { "accuracy" }); var history = model.Fit(x, y, batch_size: 2, epochs: 10, verbose: 1); var weights = model.GetWeights(); model.SetWeights(weights); var logs = history.HistoryLogs; //Save model and weights string json = model.ToJson(); File.WriteAllText("model.json", json); model.SaveWeight("model.h5"); //Load model and weight var loaded_model = Sequential.ModelFromJson(File.ReadAllText("model.json")); loaded_model.LoadWeight("model.h5"); }
public void Dense_CustomKRegularizerAndKInitParams() { NDarray x = np.array(new float[, ] { { 1, 0 }, { 1, 1 }, { 1, 0 }, { 1, 1 } }); NDarray y = np.array(new float[] { 0, 1, 1, 0 }); var model = new Sequential(); model.Add(new Dense(1, activation: "sigmoid", input_shape: new Shape(x.shape[1]), kernel_regularizer: new L1L2(1000, 2000), kernel_initializer: new Constant(100))); var modelAsJson = JsonConvert.DeserializeObject <dynamic>(model.ToJson()); Assert.AreEqual("Sequential", modelAsJson.class_name.Value); int i = 0; while (modelAsJson.config.layers[i].config.kernel_initializer == null && i < 3) { i++; } Assert.AreEqual(100, modelAsJson.config.layers[i].config.kernel_initializer.config.value.Value); Assert.AreEqual("Constant", modelAsJson.config.layers[i].config.kernel_initializer.class_name.Value); Assert.AreEqual("L1L2", modelAsJson.config.layers[i].config.kernel_regularizer.class_name.Value); Assert.AreEqual(1000, modelAsJson.config.layers[i].config.kernel_regularizer.config.l1.Value); Assert.AreEqual(2000, modelAsJson.config.layers[i].config.kernel_regularizer.config.l2.Value); // Compile and train model.Compile(optimizer: new Adam(lr: 0.001F), loss: "binary_crossentropy", metrics: new string[] { "accuracy" }); model.Fit(x, y, batch_size: x.shape[0], epochs: 100, verbose: 0); Assert.AreEqual(2, model.GetWeights().Count); }