Пример #1
0
        public void TestFlattenTypeGetGraphVizMrecords()
        {
            var testAsm = GetTestAsm();

            Assert.IsNotNull(testAsm);

            var testGia = new FlattenTypeArgs()
            {
                Assembly     = testAsm,
                UseTypeNames = false,
                Separator    = "-",
                TypeFullName = "AdventureWorks.Person.Person",
                Depth        = 16
            };
            var flattenedType = Flatten.FlattenType(testGia);

            var testResult = flattenedType.GetGraphVizMrecords;

            Assert.IsNotNull(testResult);
            Assert.AreNotEqual(0, testResult.Count);
            foreach (var fj in testResult)
            {
                Console.WriteLine(fj.ToGraphVizString());
            }
        }
Пример #2
0
        //    if (ParentProject != null)
        //        ParentProject.Compile ();

        //    CSharpCodeProvider cp = new CSharpCodeProvider ();
        //    CompilerParameters parameters = new CompilerParameters ();

        //    foreach (ProjectReference pr in flattenNodes.OfType<ProjectReference> ()) {
        //        Project p = solution.Projects.FirstOrDefault (pp => pp.ProjectGuid == pr.ProjectGUID);
        //        if (p == null)
        //            throw new Exception ("referenced project not found");
        //        parameters.ReferencedAssemblies.Add (p.Compile ());
        //    }

        //    string outputDir = getDirectoryWithTokens (this.OutputPath);
        //    string objDir = getDirectoryWithTokens (this.IntermediateOutputPath);

        //    Directory.CreateDirectory (outputDir);
        //    Directory.CreateDirectory (objDir);

        //    parameters.OutputAssembly = System.IO.Path.Combine (outputDir, this.AssemblyName);

        //    // True - exe file generation, false - dll file generation
        //    if (this.OutputType == "Library") {
        //        parameters.GenerateExecutable = false;
        //        parameters.CompilerOptions += " /target:library";
        //        parameters.OutputAssembly += ".dll";
        //    } else {
        //        parameters.GenerateExecutable = true;
        //        parameters.CompilerOptions += " /target:exe";
        //        parameters.OutputAssembly += ".exe";
        //        parameters.MainClass = this.StartupObject;
        //    }

        //    parameters.GenerateInMemory = false;
        //    parameters.IncludeDebugInformation = this.DebugSymbols;
        //    parameters.TreatWarningsAsErrors = this.TreatWarningsAsErrors;
        //    parameters.WarningLevel = this.WarningLevel;
        //    parameters.CompilerOptions += " /noconfig";
        //    if (this.AllowUnsafeBlocks)
        //        parameters.CompilerOptions += " /unsafe";
        //    parameters.CompilerOptions += " /delaysign+";
        //    parameters.CompilerOptions += " /debug:full /debug+";
        //    parameters.CompilerOptions += " /optimize-";
        //    parameters.CompilerOptions += " /define:\"DEBUG;TRACE\"";
        //    parameters.CompilerOptions += " /nostdlib";



        //    foreach (ProjectItem pi in flattenNodes.Where (p => p.Type == ItemType.Reference)) {

        //        if (string.IsNullOrEmpty (pi.HintPath)) {
        //            parameters.CompilerOptions += " /reference:/usr/lib/mono/4.5/" + pi.Path + ".dll";
        //            continue;
        //        }
        //        parameters.ReferencedAssemblies.Add (pi.Path);
        //        string fullHintPath = System.IO.Path.GetFullPath (System.IO.Path.Combine (RootDir, pi.HintPath.Replace ('\\', '/')));
        //        if (File.Exists (fullHintPath)) {
        //            string outPath = System.IO.Path.Combine (outputDir, System.IO.Path.GetFileName (fullHintPath));
        //            if (!File.Exists (outPath))
        //                File.Copy (fullHintPath, outPath);
        //        }
        //    }
        //    parameters.CompilerOptions += " /reference:/usr/lib/mono/4.5/System.Core.dll";
        //    parameters.CompilerOptions += " /reference:/usr/lib/mono/4.5/mscorlib.dll";
        //    //parameters.ReferencedAssemblies.Add ("System.Core");
        //    //parameters.ReferencedAssemblies.Add ("mscorlib.dll");


        //    IEnumerable<ProjectFile> pfs = flattenNodes.OfType<ProjectFile> ();

        //    foreach (ProjectFile pi in pfs.Where (p => p.Type == ItemType.EmbeddedResource)) {

        //        string absPath = pi.AbsolutePath;
        //        string logicName = pi.LogicalName;
        //        if (string.IsNullOrEmpty (logicName))
        //            parameters.CompilerOptions += string.Format (" /resource:{0},{1}", absPath, this.Name + "." + pi.Path.Replace ('/', '.'));
        //        else
        //            parameters.CompilerOptions += string.Format (" /resource:{0},{1}", absPath, logicName);
        //    }
        //    foreach (ProjectFile pi in pfs.Where (p => p.Type == ItemType.None)) {
        //        if (pi.CopyToOutputDirectory == CopyToOutputState.Never)
        //            continue;
        //        string source = pi.AbsolutePath;
        //        string target = System.IO.Path.Combine (outputDir, pi.Path);
        //        Directory.CreateDirectory (System.IO.Path.GetDirectoryName (target));

        //        if (File.Exists (target)) {
        //            if (pi.CopyToOutputDirectory == CopyToOutputState.PreserveNewest) {
        //                if (DateTime.Compare (
        //                        System.IO.File.GetLastWriteTime (source),
        //                        System.IO.File.GetLastWriteTime (target)) < 0)
        //                    continue;
        //            }
        //            File.Delete (target);
        //        }
        //        System.Diagnostics.Debug.WriteLine ("copy " + source + " to " + target);
        //        File.Copy (source, target);
        //    }
        //    string[] files = pfs.Where (p => p.Type == ItemType.Compile).Select (p => p.AbsolutePath).ToArray ();

        //    System.Diagnostics.Debug.WriteLine ("---- start compilation of :" + parameters.OutputAssembly);
        //    System.Diagnostics.Debug.WriteLine (parameters.CompilerOptions);

        //    CompilationResults = cp.CompileAssemblyFromFile (parameters, files);

        //    solution.UpdateErrorList ();

        //    return parameters.OutputAssembly;
        //}

        public bool TryGetProjectFileFromPath(string path, out ProjectFileNode pi)
        {
            if (path.StartsWith("#", StringComparison.Ordinal))
            {
                pi = Flatten.OfType <ProjectFileNode> ().FirstOrDefault
                         (f => f.Type == ItemType.EmbeddedResource && f.LogicalName == path.Substring(1));
            }
            else
            {
                pi = Flatten.OfType <ProjectFileNode> ().FirstOrDefault(pp => pp.FullPath == path);
            }

            if (pi != null)
            {
                return(true);
            }

            foreach (ProjectItemNode pr in Flatten.OfType <ProjectItemNode> ().Where(pn => pn.Type == ItemType.ProjectReference))
            {
                ProjectView p = solution.Projects.FirstOrDefault(pp => pp.FullPath == pr.FullPath);
                if (p == null)
                {
                    continue;
                }
                if (p.TryGetProjectFileFromPath(path, out pi))
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #3
0
        public void Initialize()
        {
            _sut         = new Flatten();
            _sut.Result += _ => _fragments = new List <object>(_);

            _fragments = new List <object>();
        }
Пример #4
0
        public void TestFlattenTypeMembersWithLimit()
        {
            var limitOn = "System.String";
            var testAsm = GetTestAsm();

            Assert.IsNotNull(testAsm);

            var testGia = new FlattenTypeArgs()
            {
                Assembly        = testAsm,
                UseTypeNames    = false,
                Separator       = "-",
                TypeFullName    = "AdventureWorks.Person.Person",
                Depth           = 16,
                LimitOnThisType = limitOn
            };
            var testPrint = Flatten.FlattenType(testGia);

            Assert.IsNotNull(testPrint);
            var printLines = testPrint.PrintLines();

            Assert.IsNotNull(printLines);
            System.IO.File.WriteAllLines(AsmDiagramTests.GetTestFileDirectory() + @"\FlattenedExample.txt", printLines);
            foreach (var p in printLines)
            {
                Console.WriteLine(p);
            }
        }
Пример #5
0
    protected ValueTuple <Tensor, List <Tensor> > CreateVisualEncoder(Tensor visualInput, List <SimpleDenseLayerDef> denseLayers, string scope)
    {
        //use the same encoder as in UnityML's python codes
        Tensor        temp;
        List <Tensor> returnWeights = new List <Tensor>();

        using (Current.K.name_scope(scope))
        {
            var conv1 = new Conv2D(16, new int[] { 8, 8 }, new int[] { 4, 4 }, use_bias: visualEncoderBias, kernel_initializer: new GlorotUniform(scale: visualEncoderInitialScale), activation: new ELU());
            var conv2 = new Conv2D(32, new int[] { 4, 4 }, new int[] { 2, 2 }, use_bias: visualEncoderBias, kernel_initializer: new GlorotUniform(scale: visualEncoderInitialScale), activation: new ELU());

            temp = conv1.Call(visualInput)[0];
            temp = conv2.Call(temp)[0];

            var flatten = new Flatten();
            //temp = Current.K.batch_flatten(temp);
            temp = flatten.Call(temp)[0];
            returnWeights.AddRange(conv1.weights);
            returnWeights.AddRange(conv2.weights);
        }

        var output     = BuildSequentialLayers(denseLayers, temp, scope);
        var hiddenFlat = output.Item1;

        returnWeights.AddRange(output.Item2);


        return(ValueTuple.Create(hiddenFlat, returnWeights));
    }
Пример #6
0
        public static void Run()
        {
            var input = new Input(new Keras.Shape(32, 32));
            //var a = new CuDNNLSTM(32).Set(input);
            var a = new Dense(32, activation: "sigmoid").Set(input);
            //a.Set(input);
            var output = new Dense(1, activation: "sigmoid").Set(a);
            //output.Set(a);

            var model = new Keras.Models.Model(new Input[] { input }, new BaseLayer[] { output });

            //Load train data
            Numpy.NDarray x = np.array(new float[, ] {
                { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }
            });
            NDarray y = np.array(new float[] { 0, 1, 1, 0 });

            var input1   = new Input(new Shape(32, 32, 3));
            var conv1    = new Conv2D(32, (4, 4).ToTuple(), activation: "relu").Set(input1);
            var pool1    = new MaxPooling2D((2, 2).ToTuple()).Set(conv1);
            var flatten1 = new Flatten().Set(pool1);

            var input2   = new Input(new Shape(32, 32, 3));
            var conv2    = new Conv2D(16, (8, 8).ToTuple(), activation: "relu").Set(input2);
            var pool2    = new MaxPooling2D((2, 2).ToTuple()).Set(conv2);
            var flatten2 = new Flatten().Set(pool2);

            var merge = new Concatenate(flatten1, flatten2);
        }
Пример #7
0
        public virtual ICollection <T> Get(params string[] ids)
        {
            var idParameter = new ParameterBuilder <string>()
                              .WithName("Ids").WithValue(Flatten.Strings(ids)).Build();

            return(Marshal(
                       Database.Query($"SELECT * FROM [{Entity}] WHERE Id IN (@Ids)", idParameter)));
        }
Пример #8
0
        public virtual ICollection <T> Filter(ICollection <Filter> filters)
        {
            var parameters   = Pluck.Field <SqlParameter>("Parameter").From(filters);
            var queryFilters = Flatten.Filters(filters);

            return(Marshal(
                       Database.Query($"SELECT * FROM [{Entity}] WHERE {queryFilters}", parameters)));
        }
Пример #9
0
    public override Node Clone(Model.NodeData newData)
    {
        var newNode = new Flatten();

        newNode.m_myValue = new SerializableMultiTargetString(m_myValue);
        newData.AddDefaultInputPoint();
        newData.AddDefaultOutputPoint();
        return(newNode);
    }
    private static bool flattenTest1()
    {
        int[,] input = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        int[] output = Flatten.compute(input);

        return(output.Length == 9 &&
               output[0] == 1 && output[1] == 2 &&
               output[2] == 3 && output[3] == 4 &&
               output[4] == 5 && output[5] == 6 &&
               output[6] == 7 && output[7] == 8 &&
               output[8] == 9);
    }
Пример #11
0
        public static Symbol CreateLenet()
        {
            Symbol data       = Symbol.Variable("data");
            Symbol data_label = Symbol.Variable("data_label");

            // first conv

            //  mx.symbol.Convolution(data = data, kernel = (5, 5), num_filter = 20)
            Symbol conv1 = new Convolution(new Shape(5, 5), 20).CreateSymbol(data);
            // tanh1 = mx.symbol.Activation(data=conv1, act_type="tanh")
            Symbol tanh1 = new Activation().CreateSymbol(conv1);
            // pool1 = mx.symbol.Pooling(data=tanh1, pool_type="max", kernel = (2,2), stride = (2,2))
            Symbol pool1 = new Pooling(new Shape(2, 2), new Shape(2, 2)).CreateSymbol(tanh1);
            // second conv
            // conv2 = mx.symbol.Convolution(data=pool1, kernel=(5,5), num_filter=50)
            Symbol conv2 = new Convolution(new Shape(5, 5), 50).CreateSymbol(pool1);
            // tanh2 = mx.symbol.Activation(data=conv2, act_type="tanh")
            Symbol tanh2 = new Activation().CreateSymbol(conv2);
            // pool2 = mx.symbol.Pooling(data=tanh2, pool_type="max", kernel = (2,2), stride = (2,2))
            Symbol pool2 = new Pooling(new Shape(2, 2), new Shape(2, 2)).CreateSymbol(tanh2);

            // first fullc
            // flatten = mx.symbol.Flatten(data=pool2)
            Symbol flatten = new Flatten().CreateSymbol(pool2);
            // fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=500)
            Symbol fc1 = new FullyConnected(500).CreateSymbol(flatten);
            // tanh3 = mx.symbol.Activation(data=fc1, act_type="tanh")
            Symbol tanh3 = new Activation().CreateSymbol(fc1);

            // second fullc
            // fc2 = mx.symbol.FullyConnected(data=tanh3, num_hidden=num_classes)
            Symbol fc2 = new FullyConnected(10).CreateSymbol(tanh3);

            // loss
            // lenet = mx.symbol.SoftmaxOutput(data=fc2, name='softmax')
            Symbol lenet = new SoftmaxOutput().CreateSymbol(fc2, data_label);

            System.IO.File.WriteAllText("lenet.json", lenet.ToJSON());

            foreach (var item in lenet.ListAuxiliaryStates())
            {
                Console.WriteLine(item);
            }

            return(lenet);
        }
Пример #12
0
        public override byte[] Execute(byte[] arg)
        {
            MyProgram.PrintToConsole("GetFlattenAssembly invoked");
            MyProgram.ProgressMessageState = null;

            try
            {
                if (arg == null || arg.Length <= 0)
                {
                    throw new ItsDeadJim("No Path to an assembly was passed to the GetFlattenAssembly command.");
                }

                var asmPath = Encoding.UTF8.GetString(arg);

                if (!File.Exists(asmPath))
                {
                    throw new ItsDeadJim("There isn't a file at the location: " + asmPath);
                }

                NfConfig.AssemblySearchPaths.Add(Path.GetDirectoryName(asmPath));

                var asm = NfConfig.UseReflectionOnlyLoad
                    ? Util.Binary.Asm.NfReflectionOnlyLoadFrom(asmPath)
                    : Util.Binary.Asm.NfLoadFrom(asmPath);
                Action <ProgressMessage> myProgress = message => MyProgram.PrintToConsole(message);
                var flatAsm = Flatten.GetFlattenedAssembly(new FlattenLineArgs {
                    Assembly = asm, Depth = _maxDepth
                }, myProgress);
                flatAsm.Path = asmPath;

                return(JsonEncodedResponse(flatAsm));
            }
            catch (Exception ex)
            {
                Console.WriteLine('\n');
                MyProgram.PrintToConsole(ex);
                return(JsonEncodedResponse(
                           new FlattenAssembly {
                    AllLines = new List <FlattenedLine> {
                        new NullFlattenedLine(ex)
                    }
                }));
            }
        }
Пример #13
0
        public void TestFlattentypeToGraphVizString()
        {
            var testAsm = GetTestAsm();

            Assert.IsNotNull(testAsm);

            var testGia = new FlattenTypeArgs()
            {
                Assembly     = testAsm,
                UseTypeNames = false,
                Separator    = "-",
                TypeFullName = "AdventureWorks.Person.Person",
                Depth        = 16
            };
            var flattenedType = Flatten.FlattenType(testGia);

            var testResult = flattenedType.ToGraphVizString();

            Assert.IsFalse(string.IsNullOrWhiteSpace(testResult));
            System.IO.File.WriteAllText(AsmDiagramTests.GetTestFileDirectory() + @"\TestGraphVizFlatType.gv", testResult);
        }
Пример #14
0
        public DuelingDQN(Shape inputShape, int numberOfActions, int[] hiddenLayersNeurons, float learningRate, float discountFactor, int batchSize, BaseExperienceReplay memory)
            : base(inputShape, numberOfActions, hiddenLayersNeurons, learningRate, discountFactor, batchSize, memory)
        {
            Net = new NeuralNetwork("DuelingDQN");
            var       input     = new Flatten(inputShape);
            LayerBase lastLayer = input;

            for (int i = 0; i < hiddenLayersNeurons.Length; ++i)
            {
                lastLayer = new Dense(lastLayer, hiddenLayersNeurons[i], Activation.ReLU);
            }

            LayerBase stateValue = new Dense(lastLayer, 1);

            stateValue = new Lambda(new [] { stateValue }, new Shape(1, numberOfActions), (inps, outp) => { outp.Zero(); }, (outpG, inpsG) => { });

            var actionAdvantage = new Dense(lastLayer, numberOfActions);

            var output = new Merge(new [] { stateValue, actionAdvantage }, Merge.Mode.Sum, Activation.Linear);

            Net.Model = new Flow(new [] { input }, new [] { output });
        }
Пример #15
0
        public Illustration2Vec()
        {
            var inputTensor = new InputLayer(new int?[] { 224, 224, 3 });

            var vgg16_model = VGG16Model.CreateModel("");

            foreach (var layer in vgg16_model.layers.Take(12))
            {
                layer.trainable = false;
            }

            var x = vgg16_model.layers.Last().output;

            // List <KerasSharp.Engine.Topology.Tensor> x = null;
            x = new Flatten().Call(x);
            x = new BatchNormalization().Call(x);
            x = new Dense(5000, activation: "relu").Call(x);
            x = new Dropout(0.3).Call(x);
            x = new Dense(5000, activation: "sigmoid").Call(x);

            model = new Model(vgg16_model.input, x, "altI2v");
            model.Compile(new Adam(), new BinaryCrossEntropy());
        }
Пример #16
0
        public void GetDefaultTemplates()
        {
            IEnumerable <ProjectFileNode> tmpFiles =
                Flatten.OfType <ProjectFileNode> ().Where(pp => pp.Type == ItemType.EmbeddedResource && pp.Extension == ".template");

            foreach (ProjectFileNode pi in tmpFiles)
            {
            }
            //    string clsName = System.IO.Path.GetFileNameWithoutExtension (pi.Path);
            //    if (solution.DefaultTemplates.ContainsKey (clsName))
            //        continue;
            //    solution.DefaultTemplates[clsName] = pi.AbsolutePath;
            //}
            //foreach (ProjectFile pi in tmpFiles.Where (pp => pp.Type == ItemType.EmbeddedResource)) {
            //    string resId = pi.ResourceID;
            //    string clsName = resId.Substring (0, resId.Length - 9);
            //    if (solution.DefaultTemplates.ContainsKey (clsName))
            //        continue;
            //    solution.DefaultTemplates[clsName] = pi.Path;
            //}

            //foreach (Project p in ReferencedProjects)
            //p.GetDefaultTemplates ();
        }
Пример #17
0
        public void GetStyling()
        {
            try {
                foreach (ProjectFileNode pi in Flatten.OfType <ProjectFileNode> ().Where(pp => pp.Type == ItemType.EmbeddedResource && pp.Extension == ".style"))
                {
                    using (Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(pi.Source))) {
                        new StyleReader(solution.Styling, s, pi.LogicalName);
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
            foreach (ProjectItemNode pr in Flatten.OfType <ProjectItemNode> ().Where(pn => pn.Type == ItemType.ProjectReference))
            {
                ProjectView p = solution.Projects.FirstOrDefault(pp => pp.FullPath == pr.FullPath);
                if (p != null)
                {
                    //throw new Exception ("referenced project not found");
                    p.GetStyling();
                }
            }

            //TODO:get styling from referenced assemblies
        }
Пример #18
0
        private List <IKernelDescriptor> ReadDescriptors(JObject model)
        {
            List <IKernelDescriptor> dscps = model.SelectToken("descriptors").Select(layer => {
                IKernelDescriptor descriptor = null;

                String layerName = (String)layer.SelectToken("layer");

                switch (layerName)
                {
                case "AvgPooling1D":
                    descriptor = new AvgPooling1D(
                        (int)layer.SelectToken("padding"),
                        (int)layer.SelectToken("stride"),
                        (int)layer.SelectToken("kernel_size"));
                    break;

                case "GlobalAveragePooling1D":
                    descriptor = new GlobalAvgPooling1D();
                    break;

                case "AvgPooling2D":
                    descriptor = new AvgPooling2D((int)layer.SelectToken("padding_vl"), (int)layer.SelectToken("padding_hz"),
                                                  (int)layer.SelectToken("stride_vl"), (int)layer.SelectToken("stride_hz"),
                                                  (int)layer.SelectToken("kernel_height"), (int)layer.SelectToken("kernel_width"));
                    break;

                case "GlobalAveragePooling2D":
                    descriptor = new GlobalAvgPooling2D();
                    break;

                case "BatchNormalization":
                    descriptor = new BatchNormalization(
                        (int)layer.SelectToken("epsilon"));
                    break;

                case "Cropping1D":
                    descriptor = new Cropping1D(
                        (int)layer.SelectToken("trimBegin"),
                        (int)layer.SelectToken("trimEnd"));
                    break;

                case "Cropping2D":
                    descriptor = new Cropping2D(
                        (int)layer.SelectToken("topTrim"),
                        (int)layer.SelectToken("bottomTrim"),
                        (int)layer.SelectToken("leftTrim"),
                        (int)layer.SelectToken("rightTrim"));
                    break;

                case "MaxPooling1D":
                    descriptor = new MaxPooling1D(
                        (int)layer.SelectToken("padding"),
                        (int)layer.SelectToken("stride"),
                        (int)layer.SelectToken("kernel_size"));
                    break;

                case "GlobalMaxPooling1D":
                    descriptor = new GlobalMaxPooling1D();
                    break;

                case "MaxPooling2D":
                    descriptor = new MaxPooling2D((int)layer.SelectToken("padding_vl"), (int)layer.SelectToken("padding_hz"),
                                                  (int)layer.SelectToken("stride_vl"), (int)layer.SelectToken("stride_hz"),
                                                  (int)layer.SelectToken("kernel_height"), (int)layer.SelectToken("kernel_width"));
                    break;

                case "GlobalMaxPooling2D":
                    descriptor = new GlobalMaxPooling2D();
                    break;

                case "Convolution1D":
                    descriptor = new Convolution1D(
                        (int)layer.SelectToken("padding"),
                        (int)layer.SelectToken("stride"),
                        (int)layer.SelectToken("kernel_size"),
                        (int)layer.SelectToken("kernel_num"));
                    break;

                case "Convolution2D":
                    descriptor = new Convolution2D((int)layer.SelectToken("padding_vl"), (int)layer.SelectToken("padding_hz"),
                                                   (int)layer.SelectToken("stride_vl"), (int)layer.SelectToken("stride_hz"),
                                                   (int)layer.SelectToken("kernel_height"), (int)layer.SelectToken("kernel_width"),
                                                   (int)layer.SelectToken("kernel_num"));
                    break;

                case "Dense2D":
                    descriptor = new Dense2D((int)layer.SelectToken("units"));
                    break;

                case "Input2D":
                    descriptor = new Input2D((int)layer.SelectToken("height"), (int)layer.SelectToken("width"),
                                             (int)layer.SelectToken("channel"), (int)layer.SelectToken("batch"));
                    break;

                case "Bias2D":
                    descriptor = new Bias2D();
                    break;

                case "Permute":
                    descriptor = new Permute(
                        (int)layer.SelectToken("dim1"),
                        (int)layer.SelectToken("dim2"),
                        (int)layer.SelectToken("dim3"));
                    break;

                case "Reshape":
                    descriptor = new Reshape2D(
                        (int)layer.SelectToken("height"),
                        (int)layer.SelectToken("width"),
                        (int)layer.SelectToken("channel"),
                        1);
                    break;

                case "RepeatVector":
                    descriptor = new RepeatVector(
                        (int)layer.SelectToken("num"));
                    break;

                case "SimpleRNN":
                    descriptor = new SimpleRNN(
                        (int)layer.SelectToken("units"),
                        (int)layer.SelectToken("input_dim"),
                        ANR((string)layer.SelectToken("activation")));
                    break;

                case "LSTM":
                    descriptor = new LSTM(
                        (int)layer.SelectToken("units"),
                        (int)layer.SelectToken("input_dim"),
                        ANR((string)layer.SelectToken("activation")),
                        ANR((string)layer.SelectToken("rec_act")));
                    break;

                case "GRU":
                    descriptor = new GRU(
                        (int)layer.SelectToken("units"),
                        (int)layer.SelectToken("input_dim"),
                        ANR((string)layer.SelectToken("activation")),
                        ANR((string)layer.SelectToken("rec_act")));
                    break;

                case "ELu":
                    descriptor = new ELu(1);
                    break;

                case "HardSigmoid":
                    descriptor = new HardSigmoid();
                    break;

                case "ReLu":
                    descriptor = new ReLu();
                    break;

                case "Sigmoid":
                    descriptor = new Sigmoid();
                    break;

                case "Flatten":
                    descriptor = new Flatten();
                    break;

                case "Softmax":
                    descriptor = new Softmax();
                    break;

                case "SoftPlus":
                    descriptor = new SoftPlus();
                    break;

                case "SoftSign":
                    descriptor = new Softsign();
                    break;

                case "TanH":
                    descriptor = new TanH();
                    break;

                default:
                    throw new Exception("Unknown layer type!");
                }

                return(descriptor);
            }).ToList();

            return(dscps);
        }
Пример #19
0
        public static void Main(string[] args)
        {
            var p = new GraphVizProgram(args);

            try
            {
                p.StartConsole();

                if (p.PrintHelp())
                {
                    return;
                }

                p.ParseProgramArgs();

                ValidateBinDir();

                switch (p.DiagramType)
                {
                case Settings.FLATTENED_DIAGRAM:

                    var ft =
                        Flatten.FlattenType(new FlattenTypeArgs
                    {
                        Assembly        = p.Assembly,
                        Depth           = p.MaxDepth,
                        Separator       = "-",
                        UseTypeNames    = false,
                        TypeFullName    = p.TypeName,
                        LimitOnThisType = p.LimitOn?.ToString(),
                        DisplayEnums    = p.DisplayEnums
                    });
                    p.GraphText      = ft.ToGraphVizString();
                    p.OutputFileName = $"{p.TypeName.Replace(".", "")}Flattened.gv";
                    break;

                case Settings.CLASS_DIAGRAM:
                    p.GraphText      = Etc.GetClassDiagram(p.Assembly, p.TypeName);
                    p.OutputFileName = $"{p.TypeName.Replace(".", "")}ClassDiagram.gv";
                    break;

                case Settings.ASM_OBJ_GRAPH_DIAGRAM:
                    var asmDia = p.WithNamespaceOutlines
                            ? new AsmDiagram(p.Assembly, true)
                            : new AsmDiagram(p.Assembly);
                    p.GraphText      = asmDia.ToGraphVizString();
                    p.OutputFileName = $"{p.Assembly.GetName().Name}AsmDiagram.gv";
                    break;

                case Settings.ASM_ADJ_GRAPH:
                    var asmAdj = new AsmDiagram(p.Assembly);
                    p.OutputFileName = $"{p.Assembly.GetName().Name}AsmAdj.json";
                    p.GraphText      = asmAdj.GetAdjacencyMatrixJson();
                    break;
                }

                p.OutputFileName = Path.Combine(NfConfig.TempDirectories.Graph, p.OutputFileName);
                File.WriteAllText(p.OutputFileName, p.GraphText);

                using (var sw = new StreamWriter(Console.OpenStandardOutput(), Encoding.UTF8))
                {
                    sw.Write(p.OutputFileName);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                p.PrintToConsole(ex);
            }
            Thread.Sleep(20); //slight pause
        }
 private static bool flattenTest2()
 {
     int[,] input = {};
     int[] output = Flatten.compute(input);
     return(output.Length == 0);
 }
Пример #21
0
        public void Run()
        {
            PrintCPUInfo();

            const int dimensionSize  = 256; // the dimension size for arrays.
            const int iterationCount = 10;  // how many iterations should we go for?

            // load the tests
            var multidimensionalArray = new Multidimensional(dimensionSize);
            var jaggedArray           = new Jagged(dimensionSize);
            var flattenArray          = new Flatten(dimensionSize);

            // timespans for measuring averages
            var timeSpanMultiSequentals   = new TimeSpan[iterationCount];
            var timeSpanJaggedSeqentals   = new TimeSpan[iterationCount];
            var timeSpanFlattenSequentals = new TimeSpan[iterationCount];
            var timeSpanMultiRandoms      = new TimeSpan[iterationCount];
            var timeSpanJaggedRandoms     = new TimeSpan[iterationCount];
            var timeSpanFlattenRandoms    = new TimeSpan[iterationCount];

            Console.WriteLine("Array size: {0}*{0}*{0}", dimensionSize);

            // test the sequental access
            Console.WriteLine("________________________________________________________________________________");
            Console.WriteLine("Itr.\tMulti.\tJagged\tFlatten\t(Sequental)");
            Console.WriteLine("________________________________________________________________________________");

            for (int i = 0; i < iterationCount; i++)
            {
                Console.Write("#{0}\t", i + 1);

                TimeSpan multidimensionalSequental = multidimensionalArray.AccessSequental();
                timeSpanMultiSequentals[i] = multidimensionalSequental;
                Console.Write(String.Format("{0:00}.{1:000}s\t", multidimensionalSequental.Seconds, multidimensionalSequental.Milliseconds));

                TimeSpan jaggedSequental = jaggedArray.AccessSequental();
                timeSpanJaggedSeqentals[i] = jaggedSequental;
                Console.Write(String.Format("{0:00}.{1:000}s\t", jaggedSequental.Seconds, jaggedSequental.Milliseconds));

                TimeSpan flattenSequental = flattenArray.AccessSequental();
                timeSpanFlattenSequentals[i] = flattenSequental;
                Console.Write(String.Format("{0:00}.{1:000}s\t", flattenSequental.Seconds, flattenSequental.Milliseconds));

                Console.WriteLine();
            }

            // averages for sequentals
            Console.Write("~Avg\t");

            TimeSpan multidimensionalSequentalAvg = CalculateAverageTimeSpan(timeSpanMultiSequentals);

            Console.Write(String.Format("{0:00}.{1:000}s\t", multidimensionalSequentalAvg.Seconds, multidimensionalSequentalAvg.Milliseconds));

            TimeSpan timeSpanJaggedSeqentalsAvg = CalculateAverageTimeSpan(timeSpanJaggedSeqentals);

            Console.Write(String.Format("{0:00}.{1:000}s\t", timeSpanJaggedSeqentalsAvg.Seconds, timeSpanJaggedSeqentalsAvg.Milliseconds));

            TimeSpan timeSpanFlattenSequentalsAvg = CalculateAverageTimeSpan(timeSpanFlattenSequentals);

            Console.Write(String.Format("{0:00}.{1:000}s\t", timeSpanFlattenSequentalsAvg.Seconds, timeSpanFlattenSequentalsAvg.Milliseconds));

            // test the random access

            Console.WriteLine("\n________________________________________________________________________________");
            Console.WriteLine("Itr.\tMulti.\tJagged\tFlatten\t(Random)");
            Console.WriteLine("________________________________________________________________________________");

            for (int i = 0; i < iterationCount; i++)
            {
                Console.Write("#{0}\t", i + 1);

                TimeSpan multidimensionalRandom = multidimensionalArray.AccessRandom();
                timeSpanMultiRandoms[i] = multidimensionalRandom;
                Console.Write(String.Format("{0:00}.{1:000}s\t", multidimensionalRandom.Seconds, multidimensionalRandom.Milliseconds));

                TimeSpan jaggedRandom = jaggedArray.AccessRandom();
                timeSpanJaggedRandoms[i] = jaggedRandom;
                Console.Write(String.Format("{0:00}.{1:000}s\t", jaggedRandom.Seconds, jaggedRandom.Milliseconds));

                TimeSpan flattenRandom = flattenArray.AccessRandom();
                timeSpanFlattenRandoms[i] = flattenRandom;
                Console.Write(String.Format("{0:00}.{1:000}s\t", flattenRandom.Seconds, flattenRandom.Milliseconds));

                Console.WriteLine();
            }

            // averages for sequentals
            Console.Write("~Avg\t");

            TimeSpan multidimensionalRandomAvg = CalculateAverageTimeSpan(timeSpanMultiRandoms);

            Console.Write(String.Format("{0:00}.{1:000}s\t", multidimensionalRandomAvg.Seconds, multidimensionalRandomAvg.Milliseconds));

            TimeSpan jaggedRandomAvg = CalculateAverageTimeSpan(timeSpanJaggedRandoms);

            Console.Write(String.Format("{0:00}.{1:000}s\t", jaggedRandomAvg.Seconds, jaggedRandomAvg.Milliseconds));

            TimeSpan flattenRandomAvg = CalculateAverageTimeSpan(timeSpanFlattenRandoms);

            Console.Write(String.Format("{0:00}.{1:000}s\t", flattenRandomAvg.Seconds, flattenRandomAvg.Milliseconds));

            Console.ReadLine();
        }