001/*
002 * Copyright (c) 2015-2020, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.evaluation.metrics;
018
019import org.tribuo.Dataset;
020import org.tribuo.Model;
021import org.tribuo.Output;
022import org.tribuo.Prediction;
023
024import java.util.List;
025
026/**
027 * A metric that can be calculated for the specified output type.
028 * @param <T> The output type.
029 * @param <C> The context (information necessary to calculate this metric).
030 */
031public interface EvaluationMetric<T extends Output<T>, C extends MetricContext<T>> {
032
033    /**
034     * Compute the result of this metric from the input context.
035     * @param context The context to use.
036     * @return The value of the metric.
037     */
038    public double compute(C context);
039
040    /**
041     * The target for this metric instance.
042     * @return The metric target.
043     */
044    public MetricTarget<T> getTarget();
045
046    /**
047     * The name of this metric.
048     * @return The name.
049     */
050    public String getName();
051
052    /**
053     * The metric ID, a combination of the metric target and metric name.
054     * @return The metric ID.
055     */
056    public default MetricID<T> getID() {
057        return new MetricID<>(getTarget(), getName());
058    }
059
060    /**
061     * Creates the context this metric uses to compute it's value.
062     * @param model The model to use.
063     * @param predictions The predictions to use.
064     * @return The metric context.
065     */
066    public C createContext(Model<T> model, List<Prediction<T>> predictions);
067
068    /**
069     * Creates the metric context used to compute this metric's value,
070     * generating {@link org.tribuo.Prediction}s for each {@link org.tribuo.Example} in
071     * the supplied dataset.
072     * @param model The model to use.
073     * @param dataset The dataset to predict outputs for.
074     * @return The metric context.
075     */
076    public default C createContext(Model<T> model, Dataset<T> dataset) {
077        return createContext(model, model.predict(dataset));
078    }
079
080    /**
081     * Specifies what form of average to use for a {@link EvaluationMetric}.
082     */
083    // Note, if we extend this enum, update MetricTarget with new singletons.
084    enum Average {
085        MACRO,
086        MICRO
087    }
088}