Search in sources :

Example 6 with Matrix

use of org.apache.ignite.ml.math.primitives.matrix.Matrix in project ignite by apache.

the class SparseMatrix method copy.

/**
 * {@inheritDoc}
 */
@Override
public Matrix copy() {
    Matrix cp = like(rowSize(), columnSize());
    cp.assign(this);
    return cp;
}
Also used : Matrix(org.apache.ignite.ml.math.primitives.matrix.Matrix) AbstractMatrix(org.apache.ignite.ml.math.primitives.matrix.AbstractMatrix)

Example 7 with Matrix

use of org.apache.ignite.ml.math.primitives.matrix.Matrix in project ignite by apache.

the class StackingTest method testSimpleStack.

/**
 * Tests simple stack training.
 */
@Test
public void testSimpleStack() {
    StackedDatasetTrainer<Vector, Vector, Double, LinearRegressionModel, Double> trainer = new StackedDatasetTrainer<>();
    UpdatesStrategy<SmoothParametrized, SimpleGDParameterUpdate> updatesStgy = new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG);
    MLPArchitecture arch = new MLPArchitecture(2).withAddedLayer(10, true, Activators.RELU).withAddedLayer(1, false, Activators.SIGMOID);
    MLPTrainer<SimpleGDParameterUpdate> trainer1 = new MLPTrainer<>(arch, LossFunctions.MSE, updatesStgy, 3000, 10, 50, 123L);
    // Convert model trainer to produce Vector -> Vector model
    DatasetTrainer<AdaptableDatasetModel<Vector, Vector, Matrix, Matrix, MultilayerPerceptron>, Double> mlpTrainer = AdaptableDatasetTrainer.of(trainer1).beforeTrainedModel((Vector v) -> new DenseMatrix(v.asArray(), 1)).afterTrainedModel((Matrix mtx) -> mtx.getRow(0)).withConvertedLabels(VectorUtils::num2Arr);
    final double factor = 3;
    StackedModel<Vector, Vector, Double, LinearRegressionModel> mdl = trainer.withAggregatorTrainer(new LinearRegressionLSQRTrainer().withConvertedLabels(x -> x * factor)).addTrainer(mlpTrainer).withAggregatorInputMerger(VectorUtils::concat).withSubmodelOutput2VectorConverter(IgniteFunction.identity()).withVector2SubmodelInputConverter(IgniteFunction.identity()).withOriginalFeaturesKept(IgniteFunction.identity()).withEnvironmentBuilder(TestUtils.testEnvBuilder()).fit(getCacheMock(xor), parts, new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST));
    assertEquals(0.0 * factor, mdl.predict(VectorUtils.of(0.0, 0.0)), 0.3);
    assertEquals(1.0 * factor, mdl.predict(VectorUtils.of(0.0, 1.0)), 0.3);
    assertEquals(1.0 * factor, mdl.predict(VectorUtils.of(1.0, 0.0)), 0.3);
    assertEquals(0.0 * factor, mdl.predict(VectorUtils.of(1.0, 1.0)), 0.3);
}
Also used : VectorUtils(org.apache.ignite.ml.math.primitives.vector.VectorUtils) DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) LinearRegressionModel(org.apache.ignite.ml.regressions.linear.LinearRegressionModel) MLPArchitecture(org.apache.ignite.ml.nn.architecture.MLPArchitecture) MLPTrainer(org.apache.ignite.ml.nn.MLPTrainer) SimpleGDParameterUpdate(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDParameterUpdate) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) LinearRegressionLSQRTrainer(org.apache.ignite.ml.regressions.linear.LinearRegressionLSQRTrainer) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) Matrix(org.apache.ignite.ml.math.primitives.matrix.Matrix) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) AdaptableDatasetModel(org.apache.ignite.ml.trainers.AdaptableDatasetModel) StackedDatasetTrainer(org.apache.ignite.ml.composition.stacking.StackedDatasetTrainer) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) SmoothParametrized(org.apache.ignite.ml.optimization.SmoothParametrized) UpdatesStrategy(org.apache.ignite.ml.nn.UpdatesStrategy) TrainerTest(org.apache.ignite.ml.common.TrainerTest) Test(org.junit.Test)

Example 8 with Matrix

use of org.apache.ignite.ml.math.primitives.matrix.Matrix in project ignite by apache.

the class TracerTest method testHtmlMatrixTracer.

/**
 */
@Test
public void testHtmlMatrixTracer() throws IOException {
    Matrix mtx1 = makeRandomMatrix(100, 100);
    // Custom color mapping.
    verifyShowHtml(() -> Tracer.showHtml(mtx1, COLOR_MAPPER));
    Matrix mtx2 = new DenseMatrix(100, 100);
    double MAX = (double) (mtx2.rowSize() * mtx2.columnSize());
    mtx2.assign((x, y) -> (double) (x * y) / MAX);
    verifyShowHtml(() -> Tracer.showHtml(mtx2));
}
Also used : Matrix(org.apache.ignite.ml.math.primitives.matrix.Matrix) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) Test(org.junit.Test)

Example 9 with Matrix

use of org.apache.ignite.ml.math.primitives.matrix.Matrix in project ignite by apache.

the class TracerTest method testHtmlMatrixTracerWithAsciiFallback.

/**
 */
@Test
public void testHtmlMatrixTracerWithAsciiFallback() throws IOException {
    Matrix mtx1 = makeRandomMatrix(100, 100);
    // Custom color mapping.
    Tracer.showHtml(mtx1, COLOR_MAPPER, true);
    Matrix mtx2 = new DenseMatrix(100, 100);
    double MAX = (double) (mtx2.rowSize() * mtx2.columnSize());
    mtx2.assign((x, y) -> (double) (x * y) / MAX);
    Tracer.showHtml(mtx2, true);
}
Also used : Matrix(org.apache.ignite.ml.math.primitives.matrix.Matrix) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) DenseMatrix(org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix) Test(org.junit.Test)

Example 10 with Matrix

use of org.apache.ignite.ml.math.primitives.matrix.Matrix in project ignite by apache.

the class GmmTrainer method updateModel.

/**
 * Gets older model and returns updated model on given data.
 *
 * @param dataset Dataset.
 * @param model Model.
 * @return Updated model.
 */
@NotNull
private UpdateResult updateModel(Dataset<EmptyContext, GmmPartitionData> dataset, GmmModel model) {
    boolean isConverged = false;
    int countOfIterations = 0;
    double maxProbInDataset = Double.NEGATIVE_INFINITY;
    while (!isConverged) {
        MeanWithClusterProbAggregator.AggregatedStats stats = MeanWithClusterProbAggregator.aggreateStats(dataset, countOfComponents);
        Vector clusterProbs = stats.clusterProbabilities();
        Vector[] newMeans = stats.means().toArray(new Vector[countOfComponents]);
        A.ensure(newMeans.length == model.countOfComponents(), "newMeans.size() == count of components");
        A.ensure(newMeans[0].size() == initialMeans[0].size(), "newMeans[0].size() == initialMeans[0].size()");
        List<Matrix> newCovs = CovarianceMatricesAggregator.computeCovariances(dataset, clusterProbs, newMeans);
        try {
            List<MultivariateGaussianDistribution> components = buildComponents(newMeans, newCovs);
            GmmModel newModel = new GmmModel(clusterProbs, components);
            countOfIterations += 1;
            isConverged = isConverged(model, newModel) || countOfIterations > maxCountOfIterations;
            model = newModel;
            maxProbInDataset = GmmPartitionData.updatePcxiAndComputeLikelihood(dataset, clusterProbs, components);
        } catch (SingularMatrixException | IllegalArgumentException e) {
            String msg = "Cannot construct non-singular covariance matrix by data. " + "Try to select other initial means or other model trainer. Iterations will stop.";
            environment.logger().log(MLLogger.VerboseLevel.HIGH, msg);
            isConverged = true;
        }
    }
    return new UpdateResult(model, maxProbInDataset);
}
Also used : Matrix(org.apache.ignite.ml.math.primitives.matrix.Matrix) MultivariateGaussianDistribution(org.apache.ignite.ml.math.stat.MultivariateGaussianDistribution) SingularMatrixException(org.apache.ignite.ml.math.exceptions.math.SingularMatrixException) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Matrix (org.apache.ignite.ml.math.primitives.matrix.Matrix)31 DenseMatrix (org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix)24 Test (org.junit.Test)12 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)8 MLPArchitecture (org.apache.ignite.ml.nn.architecture.MLPArchitecture)8 DenseVector (org.apache.ignite.ml.math.primitives.vector.impl.DenseVector)7 SparseMatrix (org.apache.ignite.ml.math.primitives.matrix.impl.SparseMatrix)6 VectorizedViewMatrix (org.apache.ignite.ml.math.primitives.vector.impl.VectorizedViewMatrix)5 RendezvousAffinityFunction (org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction)2 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)2 ViewMatrix (org.apache.ignite.ml.math.primitives.matrix.impl.ViewMatrix)2 DelegatingVector (org.apache.ignite.ml.math.primitives.vector.impl.DelegatingVector)2 SparseVector (org.apache.ignite.ml.math.primitives.vector.impl.SparseVector)2 MLPTrainer (org.apache.ignite.ml.nn.MLPTrainer)2 SimpleGDParameterUpdate (org.apache.ignite.ml.optimization.updatecalculators.SimpleGDParameterUpdate)2 SimpleGDUpdateCalculator (org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator)2 LabeledVector (org.apache.ignite.ml.structures.LabeledVector)2 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 Random (java.util.Random)1