Exemplo n.º 1
0
 private static Vector <float> PointFToVector(PointF p)
 {
     float[] xy = new float[2];
     xy[0] = p.X;
     xy[1] = p.Y;
     return(CreateVector.DenseOfArray(xy));
 }
Exemplo n.º 2
0
        public double[,] SortRank(double[,] orgRanks)
        {
            Matrix <double> matRanks = CreateMatrix.DenseOfArray(orgRanks);

            double[] projects = matRanks.Column(0).ToArray();
            double[] ranks    = matRanks.Column(1).ToArray();

            Array.Sort(ranks, projects, Comparer <double> .Create((a, b) =>
            {
                if (a == 0 && b != 0)
                {
                    return(1);
                }
                if (a != 0 && b == 0)
                {
                    return(-1);
                }
                if (a > b)
                {
                    return(1);
                }
                if (a < b)
                {
                    return(-1);
                }
                return(0);
            }));

            matRanks.SetColumn(0, CreateVector.DenseOfArray(projects));
            matRanks.SetColumn(1, CreateVector.DenseOfArray(ranks));

            return(matRanks.ToArray());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs through the network and makes a prediction.
        /// </summary>
        /// <param name="input">The input image to run the prediction on.</param>
        /// <returns>The values from the final layer. The largest value is the networks prediction.</returns>
        public double[] FeedForward(double[] input)
        {
            Matrix <double> _currentImages = CreateMatrix.DenseOfRowVectors(CreateVector.DenseOfArray <double>(input));

            foreach (ILayerInformation _layerInformation in this.LayerInformation)
            {
                switch (_layerInformation.LayerType)
                {
                case (LayerType.Convolutional):
                    ConvolutionalLayerInformation _convInfo = _layerInformation as ConvolutionalLayerInformation;
                    _currentImages = this.Convolve(_convInfo, _currentImages);
                    break;

                case (LayerType.Pooling):
                    PoolingLayerInformation _poolInfo = _layerInformation as PoolingLayerInformation;
                    _currentImages = this.Pool(_poolInfo, _currentImages);
                    break;

                case (LayerType.NonLinear):
                    NonLinearLayerInformation _nonLinearInfo = _layerInformation as NonLinearLayerInformation;
                    _currentImages = this.NonLinear(_nonLinearInfo, _currentImages);
                    break;
                }
            }

            double[] _fullyConnectedInput = CreateVector.DenseOfEnumerable <double>(_currentImages.EnumerateRows().SelectMany(a => a)).ToArray();

            return(this.FullyConnectedNetwork.FeedForward(_currentImages.Enumerate().ToArray()));
        }
Exemplo n.º 4
0
    //Called after gathering training data
    public Vector <double>[] Solve(double[,] X, double[,] yArray)
    {
        //Solve matrix to generate weights for runtime calibration

        double[]          y     = new double[yArray.GetLength(0)];
        Vector <double>[] theta = new Vector <double> [yArray.GetLength(1)];

        //Process each collum one by one
        for (int i = 0; i < yArray.GetLength(1); i++)
        {
            //Clone raw data to manipulate
            double[,] Xclone = X.Clone() as double[, ];

            //Disable channels not used for this solve
            Xclone = DisableChannels(Xclone, ActiveSensors, i);

            Matrix <double> XMatrix = CreateMatrix.DenseOfArray(Xclone);

            RemoveChannels temp = RemoveEmptyChannels(XMatrix);
            XMatrix = temp.ReducedMatrix;
            //Get a solution vector
            y = getCollumn(yArray, i);
            Matrix <double> tempMat = XMatrix;

            //Perform Regression fit
            Vector <double> yVector = CreateVector.DenseOfArray(y);
            theta[i] = MultipleRegression.Svd <double>(tempMat, yVector);

            //Add removed collumns
            theta[i] = PadArray(temp.usedCol, theta[i]);
        }

        return(theta);
    }
Exemplo n.º 5
0
        public void TrainingSet(double[,] x, int[] y)
        {
            if (x.GetUpperBound(0) + 1 < y.Length)
            {
                throw new Exception("You have more labels than training examples!");
            }
            if (x.GetUpperBound(0) + 1 > y.Length)
            {
                throw new Exception("You have more training examples than labels!");
            }

            int cv_size = (int)(0.2 * (x.GetUpperBound(0) + 1));

            double[] _y = new double[y.Length - 2 * cv_size];

            y = (int[])y.Clone();
            X = CreateMatrix.DenseOfArray(x);

            Random r = new Random();

            for (int i = 0; i < X.RowCount - 2; i++)
            {
                int j = r.Next(i, X.RowCount);
                var a = X.Row(i);
                var b = X.Row(j);
                X.SetRow(j, a);
                X.SetRow(i, b);

                int t = y[i];
                y[i] = y[j];
                y[j] = t;
            }

            CV   = CreateMatrix.DenseOfRowVectors(X.Row(0));
            X    = X.RemoveRow(0);
            Test = CreateMatrix.DenseOfRowVectors(X.Row(0));
            X    = X.RemoveRow(0);
            for (int i = 0; i < cv_size - 1; i++)
            {
                CV   = CV.InsertRow(i + 1, X.Row(0));
                X    = X.RemoveRow(0);
                Test = Test.InsertRow(i + 1, X.Row(0));
                X    = X.RemoveRow(0);
            }
            double[] _cvy   = new double[cv_size];
            double[] _testy = new double[cv_size];
            for (int i = 0; i < 2 * cv_size; i++)
            {
                _cvy[i / 2]   = y[i++];
                _testy[i / 2] = y[i];
            }
            for (int i = 2 * cv_size; i < y.Length; i++)
            {
                _y[i - 2 * cv_size] = y[i];
            }
            Y     = CreateVector.DenseOfArray(_y);
            CVY   = CreateVector.DenseOfArray(_cvy);
            TestY = CreateVector.DenseOfArray(_testy);
        }
Exemplo n.º 6
0
 public int Predict(double[] x)
 {
     if (x.Length != Layers[0])
     {
         throw new Exception("The input layer requires " + Layers[0] + " values. You gave " + x.Length + ".");
     }
     return(Predict(CreateVector.DenseOfArray(x)));
 }
Exemplo n.º 7
0
    Vector <double> CurrentStateVector()
    {
        float angularRotation = GetAngularRotationInRadians();

        double[] newStateArray = { _rb.position.x,  _rb.velocity.x,
                                   _rb.position.y,  _rb.velocity.y,
                                   angularRotation, _rb.angularVelocity };
        return(CreateVector.DenseOfArray <double>(newStateArray));
    }
Exemplo n.º 8
0
 public static Vector <double> Normalize(byte[] data)
 {
     double[] ret = new double[data.Length];
     for (int i = 0; i < ret.Length; i++)
     {
         ret[i] = data[i] / 255.0;
     }
     return(CreateVector.DenseOfArray <double>(ret));
 }
Exemplo n.º 9
0
 public VectorBentimark()
 {
     vec1     = Enumerable.Range(0, size).Select(x => (float)x).ToArray();
     vec2     = Enumerable.Range(0, size).Select(x => (float)x).ToArray();
     this.v1  = CreateVector.DenseOfArray(vec1);
     this.v2  = CreateVector.DenseOfArray(vec2);
     this.mv1 = new Vector(vec1);
     this.mv2 = new Vector(vec2);
 }
Exemplo n.º 10
0
        public void feedForward(double[] pattern)
        {
            Neurons[0] = CreateVector.DenseOfArray(pattern);

            for (int l = 0, ln = Biases.Length; l < ln; l++)
            {
                Neurons[l + 1] = (Weights[l].LeftMultiply(Neurons[l])).Add(Biases[l]);
                Neurons[l + 1].MapInplace(Activations[l]);
            }
        }
Exemplo n.º 11
0
        public VerifyResult VerifyRank(double[,] initRanks, double[,] expAwards)
        {
            // init
            Matrix <double> matInitRanks = CreateMatrix.DenseOfArray(initRanks).Clone(); // make a copy so don't effect the original ranks
            Matrix <double> matExpAwards = CreateMatrix.DenseOfArray(expAwards);

            // clean up matRanks to filter out the rows have rank of 0
            Tuple <int, double> zero = matInitRanks.Column(1).Find(r => r == 0.0d, Zeros.Include);

            if (zero != null && zero.Item1 > 0)
            {
                matInitRanks = matInitRanks.SubMatrix(0, zero.Item1, 0, matInitRanks.ColumnCount);
            }

            Vector <double> vecActRankNumber = matInitRanks.Column(1);
            Vector <double> vecExpAwards     = CreateVector.DenseOfArray(To1DAwards(expAwards));

            // init dimension
            int row    = Math.Max(vecActRankNumber.Count, vecExpAwards.Count);
            int column = matExpAwards.RowCount;

            // matrix of Actual
            Matrix <double> matActRankNo = ToRankMatrix(row, column, vecActRankNumber.ToArray());
            // matrix of Expected
            Matrix <double> matExpAwardsNo = ToRankMatrix(row, column, vecExpAwards.ToArray());

            // diff between the matrix of Actual and the matrix of Expected
            Matrix <double> matDiff = matExpAwardsNo.Subtract(matActRankNo);

            if (matDiff.ForAll(d => d == 0.0d) /*.Equals(CreateMatrix.Dense(row, column, 0.0d)*/)
            {
                return(new VerifyResult()
                {
                    Pass = true,
                    OptRanks = matInitRanks.ToArray(),
                    OrgRanks = initRanks
                });
            }
            else
            {
                double[,] actAwards = To2DAwards(vecActRankNumber.ToArray());

                return(new VerifyResult()
                {
                    Pass = false,
                    DiffMatrix = matDiff.ToArray(),
                    ActRankNoMatrix = matActRankNo.ToArray(),
                    ActAwards = actAwards,
                    ExpAwards = expAwards,
                    OptRanks = matInitRanks.ToArray(),
                    OrgRanks = initRanks
                });
            }
        }
Exemplo n.º 12
0
        public NonlinearMinimizationResult FindMinimum(IObjectiveModel objective, double[] initialGuess,
                                                       double[] lowerBound = null, double[] upperBound = null, double[] scales = null, bool[] isFixed = null)
        {
            var lb = (lowerBound == null) ? null : CreateVector.Dense <double>(lowerBound);
            var ub = (upperBound == null) ? null : CreateVector.Dense <double>(upperBound);
            var sc = (scales == null) ? null : CreateVector.Dense <double>(scales);
            var fx = (isFixed == null) ? null : isFixed.ToList();

            return(Minimum(Subproblem, objective, CreateVector.DenseOfArray <double>(initialGuess), lb, ub, sc, fx,
                           GradientTolerance, StepTolerance, FunctionTolerance, RadiusTolerance, MaximumIterations));
        }
Exemplo n.º 13
0
        public VectorBentimark(int size)
        {
            this.size = size;
            Random r = new Random(0);

            vec1     = Enumerable.Range(0, size).Select(x => (float)r.Next()).ToArray();
            vec2     = Enumerable.Range(0, size).Select(x => (float)r.Next()).ToArray();
            this.v1  = CreateVector.DenseOfArray(vec1);
            this.v2  = CreateVector.DenseOfArray(vec2);
            this.mv1 = new Vector(vec1);
            this.mv2 = new Vector(vec2);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            var matrix = CreateMatrix.DenseOfArray <double>(new double[, ] {
                { 1.0, -1.0, 2.0 },
                { 0.0, -3.0, 1.0 }
            });
            var vector = CreateVector.Dense <double>(new double[] { 2, 1, 0 });

            //Matrix-Vector product
            Console.WriteLine(MatrixDotVector(matrix, vector)); //Expected: [1 -3]

            //Hadamard Procut
            Console.WriteLine(HadamardProduct(vector, vector)); //Expected: [4,1,0]

            //Pointwise substraction
            Console.WriteLine(PointwiseSubstraction(vector, vector)); //Expected: [0,0,0]
            Console.WriteLine(PointwiseSubstraction(matrix, matrix)); //Expected: [0,0,0][0,0,0]

            //Mask a row/column (but not clear it)
            var uMatrix = CreateMatrix.Dense <double>(2, 3, 1.0);

            uMatrix.ClearColumns(0, 2);
            var cMatrix = CreateMatrix.Dense <double>(2, 3, 1.0);

            cMatrix.ClearColumn(1);
            //with 1st and 3rd columns masked
            var newMatrix = matrix.PointwiseMultiply(uMatrix);

            Console.WriteLine(newMatrix);
            //original matrix
            Console.WriteLine(matrix);
            //update the newMatrix
            newMatrix[0, 1] = 100;
            newMatrix[1, 1] = 200;
            Console.WriteLine(newMatrix);
            //push new values back to original
            matrix = matrix.PointwiseMultiply(cMatrix) + newMatrix.PointwiseMultiply(uMatrix);
            Console.WriteLine(matrix);

            //Vector equality
            Vector <double> a1 = CreateVector.DenseOfArray <double>(new double[] { 1.2, 3.4, 5.6 });
            Vector <double> a2 = CreateVector.DenseOfArray <double>(new double[] { 1.2, 3.4, 5.6 });

            Console.WriteLine(a1 == a2);
            Console.WriteLine(a1.Equals(a2));

            //Find biggest element in vector
            Vector <double> c = CreateVector.DenseOfArray <double>(new double[] { 1.2, 3.4, 5.6 });

            Console.WriteLine(c.MaximumIndex());
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        public void SetLocalPVectorCOG(Matrix <double> KeepMatrix)
        {
            int             ElementIndex = GetElementIndex();
            Vector <double> TestCOG      = CreateVector.DenseOfArray <double>(new double[3] {
                1, 2, 3
            });

            ///this.LocalPVectorCOG = this.KeepMatrixIdentity.Transpose() * GetLocalVectorMatrix(ElementIndex, Cog.Offset); /// Offset from parent origin to local origin missing
            this.LocalPVectorCOG = GetLocalVectorMatrix(ElementIndex, TestCOG);
            this.LocalPVectorCOG.InsertAtIndex(IdentityVectors.X, ElementIndex);
            this.LocalPVectorCOG.InsertAtIndex(IdentityVectors.Y, ElementIndex + 3);
            this.LocalPVectorCOG.InsertAtIndex(IdentityVectors.Z, ElementIndex + 6);
            this.LocalPVectorCOG = KeepMatrix * this.LocalPVectorCOG;
        }
Exemplo n.º 16
0
        public void IterateKalman()
        {
            if (pauseWhileNotMoving && prevMousePos == curMousePos)
            {
                return;
            }

            // add mesurement spread to the mouse pos
            var mesuredPos = curMousePos;

            mesuredPos.Offset(rnd.NextDouble(), rnd.NextDouble());

            // prepare mesurement Vector
            var M = CreateVector.DenseOfArray(new[] {
                mesuredPos.X,
                mesuredPos.Y,
            });

            // calc state vector prediction
            var Xkp = A * Xprev + B * a;

            // calc covariance matrix prediction
            var Pkp = A * (Pprev * A.Transpose()) + Q;

            // calc kalman gain
            var K = (Pkp * H.Transpose()) * (H * (Pkp * H.Transpose()) + R).Inverse();

            // calc new state
            var Xk = Xkp + K * (M - H * Xkp);

            // calc new covariance matrix
            var Pk = (CreateMatrix.DiagonalIdentity <double>(4) - K * H) * Pkp;

            // save current state for next iteration
            Xprev = Xk;
            Pprev = Pk;

            // update UI
            OnPropertyChanged(nameof(XSpeed));
            OnPropertyChanged(nameof(YSpeed));

            // draw predicted line
            AddToLine(inkCanvasEstimated1, new Point(Xkp[0], Xkp[1]), Colors.Blue);
            // draw corrected line
            AddToLine(inkCanvasEstimated2, new Point(Xprev[0], Xprev[1]), Colors.Green);
            // draw mesurment points
            DrawPoint(mesuredPos, Colors.Red);

            prevMousePos = curMousePos;
        }
Exemplo n.º 17
0
        private void DLSIterate()
        {
            var jacobian = ComputeJacobian();
            var deltaE   = SafeDeltaE(goal, baseJoint.EndEffector);

            var jacobianMat = CreateMatrix.Dense(2, jacobian.Count, (row, col) => row == 0 ? jacobian[col].X : jacobian[col].Y);

            var lambda       = .5f;
            var lambdaMatrix = lambda * lambda * CreateMatrix.DenseIdentity <float>(jacobianMat.RowCount);
            var deltaPhiVec  =
                jacobianMat.Transpose() *
                (jacobianMat * jacobianMat.Transpose() + (lambdaMatrix)).Inverse() *
                CreateVector.DenseOfArray(new float[] { deltaE.X, deltaE.Y });
            var deltaPhi = new LinkedList <float>(deltaPhiVec.ToArray());

            baseJoint.ApplyDofDeltas(deltaPhi);
        }
        public void IterateDLS(Hinge joint, Vector2 goal)
        {
            var jacobian = ComputeJacobian(joint);
            var deltaE   = ClampDeltaE(goal, joint.EndEffector);

            var jacobianMat = CreateMatrix.Dense(2, jacobian.Count, (row, col) => row == 0 ? jacobian[col].X : jacobian[col].Y);

            var lambda       = DLSLambda;
            var lambdaMatrix = lambda * lambda * CreateMatrix.DenseIdentity <float>(jacobianMat.RowCount);
            var deltaPhiVec  =
                jacobianMat.Transpose() *
                (jacobianMat * jacobianMat.Transpose() + (lambdaMatrix)).Inverse() *
                CreateVector.DenseOfArray(new float[] { deltaE.X, deltaE.Y });
            var deltaPhi = new LinkedList <float>(deltaPhiVec.ToArray());

            joint.ApplyDofDeltas(deltaPhi);
        }
Exemplo n.º 19
0
        /// <summary>
        /// [offset] [type]          [value]          [description]
        ///0000     32 bit integer  0x00000801(2049) magic number(MSB first)
        ///0004     32 bit integer  60000            number of items
        ///0008     unsigned byte   ??               label
        ///0009     unsigned byte   ??               label
        ///........
        ///xxxx unsigned byte   ??               label
        ///The labels values are 0 to 9.
        /// </summary>
        /// <param name="labelFile"></param>
        /// <returns></returns>
        public static List <Vector <double> > LoadLabels(string labelFile)
        {
            if (!File.Exists(labelFile))
            {
                throw new FileNotFoundException();
            }
            List <byte> ret = new List <byte>();

            using (FileStream stream = File.OpenRead(labelFile))
            {
                using (GZipStream uncompressed = new GZipStream(stream, CompressionMode.Decompress))
                {
                    using (BinaryReader reader = new BinaryReader(uncompressed))
                    {
                        int magicNumber = toLittleEndian(reader.ReadInt32());
                        if (magicNumber != 0x801)
                        {
                            throw new InvalidDataException("0x801 is expected at offset 000");
                        }
                        int labelCount = toLittleEndian(reader.ReadInt32());
                        ret.AddRange(reader.ReadBytes(labelCount));
                    }
                }
            }
            List <Vector <double> > vectors = new List <Vector <double> >();

            foreach (var label in ret)
            {
                vectors.Add(CreateVector.DenseOfArray <double>(
                                new double[]
                {
                    label == 0? 1.0:0.0,
                    label == 1? 1.0:0.0,
                    label == 2? 1.0:0.0,
                    label == 3? 1.0:0.0,
                    label == 4? 1.0:0.0,
                    label == 5? 1.0:0.0,
                    label == 6? 1.0:0.0,
                    label == 7? 1.0:0.0,
                    label == 8? 1.0:0.0,
                    label == 9? 1.0:0.0
                }));
            }
            return(vectors);
        }
        public NonlinearMinimizationResult FindMinimum(IObjectiveModel objective, double[] initialGuess,
                                                       double[] lowerBound = null, double[] upperBound = null, double[] scales = null, bool[] isFixed = null)
        {
            if (objective == null)
            {
                throw new ArgumentNullException("objective");
            }
            if (initialGuess == null)
            {
                throw new ArgumentNullException("initialGuess");
            }

            var lb = (lowerBound == null) ? null : CreateVector.Dense <double>(lowerBound);
            var ub = (upperBound == null) ? null : CreateVector.Dense <double>(upperBound);
            var sc = (scales == null) ? null : CreateVector.Dense <double>(scales);
            var fx = (isFixed == null) ? null : isFixed.ToList();

            return(Minimum(objective, CreateVector.DenseOfArray <double>(initialGuess), lb, ub, sc, fx, InitialMu, GradientTolerance, StepTolerance, FunctionTolerance, MaximumIterations));
        }
Exemplo n.º 21
0
        public static List <Vector <double> > GetOAT(Matrix <double> rot33)
        {
            var    TOLERANCE = 1E-09;
            var    st2 = Math.Sqrt(rot33[0, 2] * rot33[0, 2] + rot33[1, 2] * rot33[1, 2]);
            double a1, o1, t1;
            double a2, o2, t2;

            if (TOLERANCE < Math.Abs(st2))
            {
                var st = st2;
                a1 = Math.Atan2(+st, rot33[2, 2]);
                a2 = Math.Atan2(-st, rot33[2, 2]);

                o1 = Math.Atan2(rot33[1, 2], +rot33[0, 2]);
                o2 = Math.Atan2(rot33[1, 2], -rot33[0, 2]);

                t1 = Math.Atan2(rot33[2, 1], -rot33[2, 0]);
                t2 = Math.Atan2(rot33[2, 1], +rot33[2, 0]);
            }
            else
            {
                //o1+t1=Math.Atan2(rot33[1, 0], rot33[1, 1]) を満たす (o1, t1)の組み合わせは無数にある。
                //ここでは、t1=0 という解を得ることにする。
                o1 = Math.Atan2(rot33[1, 0], rot33[1, 1]);
                a1 = (1d - rot33[2, 2]) * Math.PI / 2d;
                t1 = 0d;

                o2 = double.NaN;
                a2 = double.NaN;
                t2 = double.NaN;
            }

            var ans = new List <Vector <double> >();

            ans.Add(CreateVector.DenseOfArray(new double[] { o1, a1, t1 }));
            if (!double.IsNaN(a2) || !double.IsNaN(a2) || !double.IsNaN(t2))
            {
                ans.Add(CreateVector.DenseOfArray(new double[] { o2, a2, t2 }));
            }

            return(ans);
        }
Exemplo n.º 22
0
    //Add zeroed channels to align weights with their appropriate value
    private Vector <double> PadArray(bool [] usedCol, Vector <double> theta)
    {
        //Add removed collumns to array to make later calcs easier
        int index = 0;

        double[] tempArray = new double[usedCol.Length];
        for (int j = 0; j < usedCol.Length; j++)
        {
            if (usedCol[j])
            {
                tempArray[j] = theta.At(index);
                index++;
            }
            else
            {
                tempArray[j] = 0;
            }
        }
        return(CreateVector.DenseOfArray(tempArray));
    }
Exemplo n.º 23
0
    void PlotOutputs()
    {
        if (!HasPerceptron)
        {
            return;
        }

        // precompute
        int    ax     = comboX.Active;
        int    ay     = comboY.Active;
        int    volume = DISCRET_LEVEL * DISCRET_LEVEL;
        double step   = 2.0 / (DISCRET_LEVEL + 1.0);

        // create points
        Vector3D[][] points = new Vector3D[conf.numOutputs][];
        for (int o = 0; o < conf.numOutputs; o++)
        {
            points[o] = new Vector3D[volume];
        }

        // fill points
        int c = 0;

        for (int ix = 1; ix <= DISCRET_LEVEL; ix++)
        {
            sector[ax] = step * ix;
            for (int iy = 1; iy <= DISCRET_LEVEL; iy++)
            {
                sector[ay] = step * iy;
                Vector <double> point  = CreateVector.DenseOfArray(sector);
                double[]        values = ann.Response(point).ToArray();
                for (int o = 0; o < conf.numOutputs; o++)
                {
                    points[o][c++] = new Vector3D(sector[ax], sector[ay], values[o]);
                }
            }
        }

        // render points
        rs3DP.Render(points, surf.Width, surf.Height);
    }
Exemplo n.º 24
0
        public void MoveCar()
        {
            if (_car.HasCollidedWithWall)
            {
                _car.Move(0f, -1f);
                return;
            }

            float speedNormalized = _car.CurrentSpeed / _car.MaxSpeed;

            float[] sensorDistancesNormalized = new float[_probe.SensorCount];
            _probe.SensorDistances.CopyTo(sensorDistancesNormalized, 0);
            Array.ForEach(sensorDistancesNormalized, distance => distance = distance / _probe.MaxSensorDistance);

            float[] networkInputs = new float[_probe.SensorCount + 1];
            networkInputs[0] = speedNormalized;
            sensorDistancesNormalized.CopyTo(networkInputs, 1);

            Vector <float> networkOutputs = _network.FeedForward(CreateVector.DenseOfArray(networkInputs));

            _car.Move(networkOutputs[0], networkOutputs[1]);
        }
Exemplo n.º 25
0
        public static Layer Load(StreamReader reader)
        {
            var strContent = reader.ReadLine();
            var values     = strContent.Split(';');
            int biascount  = int.Parse(values[0]);
            int colCount   = int.Parse(values[1]);
            int rowCount   = int.Parse(values[2]);

            strContent = reader.ReadLine();
            values     = strContent.Split(';');
            var biasArray = new double[biascount];

            for (int i = 0; i < biascount; i++)
            {
                biasArray[i] = double.Parse(values[i]);
            }
            var bias = CreateVector.DenseOfArray <double>(biasArray);

            if (colCount != 0 && rowCount != 0)
            {
                double[,] mValues = new double[rowCount, colCount];
                for (int y = 0; y < rowCount; y++)
                {
                    strContent = reader.ReadLine();
                    values     = strContent.Split(';');
                    for (int x = 0; x < colCount; x++)
                    {
                        mValues[y, x] = double.Parse(values[x]);
                    }
                }
                var weights = CreateMatrix.DenseOfArray(mValues);
                return(new Layer(bias, weights));
            }
            else
            {
                return(new Layer(bias, null));
            }
        }
Exemplo n.º 26
0
        private OrgRank SplitRank(Matrix <double> matRanks, int rank_length, double[] awardNos, double[,] awards)
        {
            Vector <double> vecAwardNos = CreateVector.DenseOfArray(awardNos);
            //fill the rest of ranks as the last award
            double next_award = vecAwardNos[rank_length];

            for (int i = rank_length; i < matRanks.RowCount; i++)
            {
                if (i < matRanks.RowCount)
                {
                    matRanks[i, 1] = next_award;
                }
            }

            OrgRank orgRank = new OrgRank(matRanks.ToArray(), awards);

            // split ranks into two groups
            Matrix <double> matRanks1 = matRanks.SubMatrix(0, rank_length, 0, matRanks.ColumnCount);

            // split award_numbers into two sub_awards
            double[,] awards1 = To2DAwards(vecAwardNos.SubVector(0, rank_length).ToArray());
            Rank rank1 = new Rank(matRanks1.ToArray(), awards1);

            orgRank.AddSubRank(rank1);

            // split ranks into two groups
            int             length    = matRanks.RowCount - rank_length;
            Matrix <double> matRanks2 = matRanks.SubMatrix(rank_length, length, 0, matRanks.ColumnCount);

            // split award_numbers into two sub_awards
            length            = awardNos.Length - rank_length;
            double[,] awards2 = To2DAwards(vecAwardNos.SubVector(rank_length, length).ToArray());
            Rank rank2 = new Rank(matRanks2.ToArray(), awards2);

            orgRank.AddSubRank(rank2);

            return(orgRank);
        }
Exemplo n.º 27
0
        public vnnCm(double[][,] W, double[][] B, Func <double, double>[] activations)
        {
            Activations = activations;

            Weights = new Matrix <double> [W.Length];
            for (int i = 0; i < W.Length; i++)
            {
                Weights[i] = CreateMatrix.DenseOfArray(W[i]);
            }

            Biases = new Vector <double> [B.Length];
            for (int i = 0; i < B.Length; i++)
            {
                Biases[i] = CreateVector.DenseOfArray(B[i]);
            }

            Neurons = new Vector <double> [B.Length + 1];
            //Neurons[0] = CreateVector.DenseOfArray(new double[Weights[0].RowCount]);
            for (int i = 1; i < Neurons.Length; i++)
            {
                Neurons[i] = CreateVector.DenseOfArray(new double[Biases[i - 1].Count]);
            }
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            NeuralNetwork nn = new NeuralNetwork(0.001f, 1f, 2, 2, 2);

            //Console.WriteLine(nn.ToString());
            double[]        arr1 = { 0, 0 };
            double[]        arr2 = { 0, 1 };
            double[]        arr3 = { 1, 1 };
            double[]        arr4 = { 1, 0 };
            double[]        t1   = { 0 };
            double[]        t2   = { 1 };
            double[]        t3   = { 0 };
            double[]        t4   = { 1 };
            Vector <double> v1   = CreateVector.DenseOfArray(arr1);
            Vector <double> v2   = CreateVector.DenseOfArray(arr2);
            Vector <double> v3   = CreateVector.DenseOfArray(arr3);
            Vector <double> v4   = CreateVector.DenseOfArray(arr4);
            Vector <double> w1   = CreateVector.DenseOfArray(t1);
            Vector <double> w2   = CreateVector.DenseOfArray(t2);
            Vector <double> w3   = CreateVector.DenseOfArray(t3);
            Vector <double> w4   = CreateVector.DenseOfArray(t4);

            Vector <double>[] input  = { v1, v2, v3, v4 };
            Vector <double>[] result = { w1, w2, w3, w4 };

            //Console.WriteLine(v1);
            //Console.WriteLine(nn.AddBias(v1));
            //Console.WriteLine(nn.FeedForward(v2));

            nn.Train(input, result);

            //Console.WriteLine();
            Console.Write("Input vector\n" + v1.ToString() + "Prediction\n" + nn.FeedForward(v1) + "\nCorrect result\n" + w1.ToString());
            Console.Write("Input vector\n" + v2.ToString() + "Prediction\n" + nn.FeedForward(v2) + "\nCorrect result\n" + w2.ToString());
            Console.Write("Input vector\n" + v3.ToString() + "Prediction\n" + nn.FeedForward(v3) + "\nCorrect result\n" + w3.ToString());
            Console.Write("Input vector\n" + v4.ToString() + "Prediction\n" + nn.FeedForward(v4) + "\nCorrect result\n" + w4.ToString());
        }
Exemplo n.º 29
0
        public Point SolveRayScreenVector(Point3D vec, ScreenProperties properties)
        {
            var unitPermm = UnitPerMM;

            var tempVec   = CreateVector.Dense(vec.ToArray());
            var tempScale = Math.Abs(LandmarkTransformVector[2] / tempVec[2]);

            tempVec = tempVec * tempScale;
            tempVec = tempVec + CreateVector.DenseOfArray(LandmarkTransformVector);

            if (tempVec[2] > 0.001)
            {
                Logger.Error("Wrong Vector try to solve");
            }

            var tempScr = properties.ToScreenCoordinate(unitPermm, new Point3D(tempVec.ToArray()));

            //tempScr.X = properties.PixelSize.Width - Util.FixZero(tempScr.X);
            //tempScr.Y = -Util.FixZero(tempScr.Y);
            tempScr.X = Util.FixZero(tempScr.X);
            tempScr.Y = Util.FixZero(tempScr.Y);

            return(tempScr);
        }
Exemplo n.º 30
0
 static Vector <double> makeSpock()
 {
     return(CreateVector.DenseOfArray <double>(new double[] { 0, 0, 0, 0, 1 }));
 }