Exemplo n.º 1
0
        public Tensor categorical_crossentropy(Tensor target, Tensor output, bool from_logits = false)
        {
            // https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/backend/cntk_backend.py#L1480

            var _output = In(output);
            var _target = In(target);

            if (from_logits)
            {
                var result = C.CrossEntropyWithSoftmax(_output, _target);
                // cntk's result shape is (batch, 1), while keras expect (batch, )
                CNTK.Function r = C.Reshape(result, NDShape.CreateNDShape(new int[] { }));
                return(Out(r));
            }
            else
            {
                // scale preds so that the class probas of each sample sum to 1
                var o     = C.ElementDivide(_output.function, C.ReduceSum(_output, Axis.EndStaticAxis()));
                var eps   = Constant.Scalar(epsilon(), DeviceDescriptor.CPUDevice);
                var omeps = Constant.Scalar(1.0 - epsilon(), DeviceDescriptor.CPUDevice);
                // avoid numerical instability with _EPSILON clipping
                o = C.Clip(o, eps, omeps);
                CNTK.Function r = C.Negate(C.ReduceSum(C.ElementTimes(_target, C.Log(_output)), Axis.EndStaticAxis()));
                return(Out(r));
            }
        }
Exemplo n.º 2
0
        C.Function squash(C.Function vectors, string name, int axis)
        {
            var squared_values         = CC.Square(vectors);
            var s_squared_sum          = CC.ReduceSum(squared_values, new C.AxisVector(new C.Axis[] { new C.Axis(axis) }), keepDims: true);
            var epsilon                = C.Constant.Scalar(C.DataType.Float, 1e-7, computeDevice);
            var one                    = C.Constant.Scalar(C.DataType.Float, 1.0, computeDevice);
            var normalize_factor       = CC.Plus(CC.Sqrt(s_squared_sum), epsilon);
            var one_plus_s_squared_sum = CC.Plus(s_squared_sum, one);
            var scale                  = CC.ElementDivide(s_squared_sum, one_plus_s_squared_sum);

            scale = CC.ElementDivide(scale, normalize_factor);
            var result = CC.ElementTimes(scale, vectors, name);

            return(result);
        }
Exemplo n.º 3
0
 public Tensor Div(float a, Tensor b)
 {
     return(Out(C.ElementDivide(In(a, b.Shape), In(b))));
 }
Exemplo n.º 4
0
 public Tensor Div(Tensor a, float b)
 {
     return(Out(C.ElementDivide(In(a), In(b, a.Shape))));
 }
Exemplo n.º 5
0
 public Tensor Div(Tensor a, Tensor b)
 {
     return(Out(C.ElementDivide(In(a), In(b))));
 }
Exemplo n.º 6
0
 public Tensor div <T>(Tensor a, T b)
 {
     return(Out(C.ElementDivide(In(a), InGeneric(b))));
 }
Exemplo n.º 7
0
        void create_network()
        {
            imageVariable = Util.inputVariable(input_shape, "image");
            var conv1 = Layers.Convolution2D(
                imageVariable, 256, new int[] { 9, 9 }, computeDevice,
                use_padding: false, activation: CC.ReLU, name: "conv1");

            var primarycaps = create_primary_cap(
                conv1, dim_capsule: 8, n_channels: 32,
                kernel_size: new int[] { 9, 9 }, strides: new int[] { 2, 2 }, pad: false);

            var digitcaps = create_capsule_layer(
                primarycaps, num_capsule: 10, dim_capsule: 16,
                routings: routings, name: "digitcaps");

            var out_caps = get_length_and_remove_last_dimension(digitcaps, name: "capsnet");

            categoricalLabel = Util.inputVariable(new int[] { 10 }, "label");
            var masked_by_y = get_mask_and_infer_from_last_dimension(digitcaps, CC.Combine(new C.VariableVector()
            {
                categoricalLabel
            }));
            var masked = get_mask_and_infer_from_last_dimension(digitcaps, null);

            var decoder = create_decoder(masked.Output.Shape.Dimensions.ToArray());
            var decoder_output_training   = Model.invoke_model(decoder, new C.Variable[] { masked_by_y });
            var decoder_output_evaluation = Model.invoke_model(decoder, new C.Variable[] { masked });

            network = CC.Combine(new C.VariableVector()
            {
                out_caps, decoder_output_training
            }, "overall_training_network");
            Logging.log_number_of_parameters(network);

            // first component of the loss
            var y_true     = categoricalLabel;
            var y_pred     = out_caps;
            var digit_loss = CC.Plus(
                CC.ElementTimes(y_true, CC.Square(CC.ElementMax(DC(0), CC.Minus(DC(0.9), y_pred), ""))),
                CC.ElementTimes(DC(0.5),
                                CC.ElementTimes(CC.Minus(DC(1), y_true), CC.Square(CC.ElementMax(DC(0), CC.Minus(y_pred, DC(0.1)), "")))));

            digit_loss = CC.ReduceSum(digit_loss, C.Axis.AllStaticAxes());

            // second component of the loss
            var num_pixels_at_output = Util.np_prod(decoder_output_training.Output.Shape.Dimensions.ToArray());
            var squared_error        = CC.SquaredError(decoder_output_training, imageVariable);
            var image_mse            = CC.ElementDivide(squared_error, DC(num_pixels_at_output));

            loss_function = CC.Plus(digit_loss, CC.ElementTimes(DC(0.35), image_mse));
            eval_function = CC.ClassificationError(y_pred, y_true);

            learner = CC.AdamLearner(
                new C.ParameterVector(network.Parameters().ToArray()),
                new C.TrainingParameterScheduleDouble(0.001 * batch_size, (uint)batch_size),
                new C.TrainingParameterScheduleDouble(0.9),
                true,
                new C.TrainingParameterScheduleDouble(0.99));

            trainer   = CC.CreateTrainer(network, loss_function, eval_function, new C.LearnerVector(new C.Learner[] { learner }));
            evaluator = CC.CreateEvaluator(eval_function);
        }