Пример #1
0
 public static NDarray NormCDF(NDarray X)
 {
     return(0.5 * (1 + ERF(X / np.sqrt((NDarray)2))));
 }
Пример #2
0
        /// <summary>
        /// Returns the loss value & metrics values for the model in test mode.        Computation is done in batches.
        /// </summary>
        /// <param name="x"> Numpy array of test data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs). If input layers in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. x can be None (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).</param>
        /// <param name="y"> Numpy array of target (label) data (if the model has a single output), or list of Numpy arrays (if the model has multiple outputs). If output layers in the model are named, you can also pass a dictionary mapping output names to Numpy arrays. y can be None (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).</param>
        /// <param name="batch_size"> Integer or None. Number of samples per evaluation step. If unspecified, batch_sizewill default to 32.</param>
        /// <param name="verbose"> 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.</param>
        /// <param name="sample_weight"> Optional Numpy array of weights for the test samples, used for weighting the loss function. You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specifysample_weight_mode="temporal" in compile().</param>
        /// <param name="steps"> Integer or None. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of None.</param>
        /// <param name="callbacks"> List of keras.callbacks.Callback instances. List of callbacks to apply during evaluation. See callbacks.</param>
        /// <returns>Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.</returns>
        public double[] Evaluate(NDarray x, NDarray y, int?batch_size = null, int verbose = 1, NDarray sample_weight = null, int?steps = null, Callback[] callbacks = null)
        {
            var args = new Dictionary <string, object>();

            args["x"]             = x.PyObject;
            args["y"]             = y.PyObject;
            args["batch_size"]    = batch_size;
            args["verbose"]       = verbose;
            args["sample_weight"] = sample_weight;
            args["steps"]         = steps;
            args["callbacks"]     = callbacks != null ? callbacks : null;

            return(InvokeMethod("evaluate", args)?.As <double[]>());
        }
Пример #3
0
 public static NDarray NormPDF(NDarray X)
 {
     return((1 / np.sqrt((NDarray)2 * Math.PI)) * np.exp(-0.5 * X * X));
 }
Пример #4
0
 public static NDarray DeNormalize(NDarray features)
 {
     return((features + 0.5) * 9);
 }
Пример #5
0
        public void Evaluate(NDarray x, NDarray y, int?batch_size = null, int verbose = 1, NDarray sample_weight = null, int?steps = null, Callback[] callbacks = null)
        {
            var args = new Dictionary <string, object>();

            args["x"]             = x;
            args["y"]             = y;
            args["batch_size"]    = batch_size;
            args["verbose"]       = verbose;
            args["sample_weight"] = sample_weight;
            args["steps"]         = steps;
            args["callbacks"]     = callbacks != null?callbacks.ToList() : null;

            InvokeMethod("evaluate", args);
        }
Пример #6
0
        /// <summary>
        /// Flows the specified x.
        /// </summary>
        /// <param name="x"> Input data. Numpy array of rank 4 or a tuple. If tuple, the first element should contain the images and the second element another numpy array or a list of numpy arrays that gets passed to the output without any modifications. Can be used to feed the model miscellaneous data along with the images. In case of grayscale data, the channels axis of the image array should have value 1, in case of RGB data, it should have value 3, and in case of RGBA data, it should have value 4.</param>
        /// <param name="y"> Labels.</param>
        /// <param name="batch_size"> Int (default: 32).</param>
        /// <param name="shuffle"> Boolean (default: True).</param>
        /// <param name="sample_weight"> Sample weights.</param>
        /// <param name="seed"> Int (default: None).</param>
        /// <param name="save_to_dir"> None or str (default: None). This allows you to optionally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing).</param>
        /// <param name="save_prefix"> Str (default: ''). Prefix to use for filenames of saved pictures (only relevant if save_to_dir is set).</param>
        /// <param name="save_format"> one of "png", "jpeg" (only relevant if save_to_dir is set). Default: "png".</param>
        /// <param name="subset"> Subset of data ("training" or "validation") if validation_split is set in ImageDataGenerator.</param>
        /// <returns>An Iterator yielding tuples of (x, y) where x is a numpy array of image data (in the case of a single image input) or a list of numpy arrays (in the case with additional inputs) and y is a numpy array of corresponding labels. If 'sample_weight' is not None, the yielded tuples are of the form (x, y, sample_weight). If y is None, only the numpy array x is returned.</returns>
        public KerasIterator Flow(NDarray x, NDarray y = null, int batch_size   = 32, bool shuffle       = true, NDarray sample_weight = null, int?seed = null,
                                  string save_to_dir   = "", string save_prefix = "", string save_format = "png", string subset        = "")
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters["x"]             = x;
            parameters["y"]             = y;
            parameters["batch_size"]    = batch_size;
            parameters["shuffle"]       = shuffle;
            parameters["sample_weight"] = sample_weight;
            parameters["seed"]          = seed;
            parameters["save_to_dir"]   = save_to_dir;
            parameters["save_prefix"]   = save_prefix;
            parameters["save_format"]   = save_format;
            parameters["subset"]        = subset;

            return(new KerasIterator(InvokeMethod("flow", parameters)));
        }
Пример #7
0
 public static NDarray Normalize(NDarray features)
 {
     return((features / 9) - 0.5);
 }
Пример #8
0
 public NDarray <U> Grad(NDarray <U> X) => DRelu(X);
Пример #9
0
 public NDarray <U> Func(NDarray <U> X) => Relu(X);
Пример #10
0
        private UserInput ParseUserInputFromArgs(string[] args)
        {
            int n = 0;

            var methodType = ParseMethodType(args[n++]);

            double?beta = null;

            if (methodType == MinimizationMethodType.SimpleGradient || methodType == MinimizationMethodType.SimpleGradientNum)
            {
                beta = ParseBeta(args[n++]);
            }

            var C = ParseC(args[n++]);
            var B = ParseB(args[n++]);
            var A = ParseA(args[n++]);

            NDarray X0 = null;

            int    argsCountForLU = 0, argsCountForX0 = 0;
            double?l = null, u = null;

            if (methodType == MinimizationMethodType.SimpleGradient || methodType == MinimizationMethodType.SimpleGradientNum)
            {
                argsCountForLU = 9;
                argsCountForX0 = 8;
            }
            else
            {
                argsCountForLU = 8;
                argsCountForX0 = 7;
            }

            if (args.Length == argsCountForX0)
            {
                X0 = ParseX0(args[n++]);
            }
            else if (args.Length == argsCountForLU)
            {
                l = ParseL(args[n++]);
                u = ParseU(args[n++], l.Value);
            }

            var desiredJofX = ParseDesiredJOfX(args[n++]);

            var batchMode = ParseBatchModeN(args[n++]);

            return(new UserInput
            {
                MinimizationMethodType = methodType,
                BatchModeN = batchMode,
                Beta = beta,
                C = C,
                B = B,
                A = A,
                X0 = X0,
                DesiredJOfX = desiredJofX,
                L = l,
                U = u,
            });
        }
        private Mat DetectMask(Mat frame)
        {
            Mat result = frame;
            Mat blob   = CvDnn.BlobFromImage(result, 1, new OpenCvSharp.Size(300, 300), new OpenCvSharp.Scalar(104, 177, 123));

            facenet.SetInput(blob, "data");
            Mat dets = facenet.Forward();
            int w    = result.Width;
            int h    = result.Height;
            Mat p    = dets.Reshape(1, dets.Size(2));

            for (int i = 0; i < dets.Size(2); i++) //  prob.Size(2)=얼굴이라고 판단된 BOX의 개수
            {
                float confidence = p.At <float>(i, 2);

                if (confidence < 0.5)
                {
                    continue;
                }
                // 바운딩 박스를 구함 (얼굴영역을 의미)
                int x1 = (int)(w * p.At <float>(i, 3)); // 특정 array element를 반환
                int y1 = (int)(h * p.At <float>(i, 4));
                int x2 = (int)(w * p.At <float>(i, 5));
                int y2 = (int)(h * p.At <float>(i, 6));

                try
                {
                    //원본 이미지에서 얼굴 부분만 추출
                    Mat face = result.SubMat(new Rect(x1, y1, x2 - y1, x2 - y1));

                    //이미지 전처리
                    Mat face_input = new Mat(face.Size(), MatType.CV_8UC3);
                    Cv2.Resize(face, face_input, new OpenCvSharp.Size(224, 224));       //Cv2.Resize*(원본 이미지, 결과 이미지, 절대 크기, 상대 크기(X), 상대 크기(Y), 보간법)
                    Cv2.CvtColor(face_input, face_input, ColorConversionCodes.BGR2RGB); //컬러변환
                    Cv2.ImWrite("face0.bmp", face_input);
                    string  img_path = "face0.bmp";
                    dynamic img1     = ImageUtil.LoadImg(img_path);
                    dynamic x        = ImageUtil.ImageToArray(img1);

                    // Numsharp<->Numpy 변환불가
                    //var mat2 = new SharpCV.Mat(face_input.CvPtr);  //OpenCVsharp의 Mat Matrix를 SharpCV Mat으로 가져옴.
                    //var x = mat2.GetData();   //Mat으로부터 NDarray 가져옴

                    x = mobilenetv2.PreprocessInput(x);
                    x = np.expand_dims(x, axis: 0);

                    //마스크 판별
                    NDarray preds = model.Predict(x);

                    //차원 중 사이즈가 1인 것을 찾아 제거
                    preds = np.squeeze(preds);
                    //예측값 가져오기
                    //var a = preds.ToString();
                    //Scalar b = preds.asscalar<Scalar>();
                    //var b = preds.;
                    var maxIndex = preds.argmax();
                    var max      = maxIndex.ToString();
                    //byte[] b = preds.tobytes();
                    //var result = b.ToArray<byte>();
                    Scalar color;
                    string label;
                    //Console.WriteLine(preds);
                    Console.WriteLine(preds);
                    Console.WriteLine(max);
                    //Console.WriteLine(d);

                    /*
                     * 1/1 [==============================] - 0s 0s/step
                     * [0.02961567 0.97038436]
                     * 이게 위의 출력 양식
                     * string 처리해서 출력해본 결과 preds는 이렇게 출력된다.
                     * [0.02961567 0.97038436]
                     */
                    //Console.WriteLine("Mask : "+mask + " NoMask : " + nomask);
                    if (max.Equals("0"))
                    {
                        Console.WriteLine("Mask");
                        color = new Scalar(0, 255, 0);
                        label = "Mask";
                    }
                    else
                    {
                        Console.WriteLine("No Mask");
                        color = new Scalar(0, 0, 255);
                        label = "No Mask";
                    }
                    Cv2.Rectangle(result, new Rect(x1, y1, x2 - y1, x2 - y1), color, 2);
                    OpenCvSharp.Size textSize = Cv2.GetTextSize("face", HersheyFonts.HersheyTriplex, 0.5, 1, out var baseline); //추후 string 부분 수정 예정.
                    Cv2.PutText(result, label, new OpenCvSharp.Point(x1, y1), HersheyFonts.HersheyTriplex, 0.5, color);
                    return(result);
                }
                catch (OpenCVException ex)
                {
                    Console.WriteLine(" ");
                    return(result);
                }
            }
            return(result);
        }
Пример #12
0
 public override NDarray <double> Acc(NDarray <U> y, NDarray <U> p) => accExpr.Evaluate(("y", y), ("p", p));