datasets

Форк
0
111 строк · 4.4 Кб
1
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
"""MAE - Mean Absolute Error Metric"""
15

16
from sklearn.metrics import mean_absolute_error
17

18
import datasets
19

20

21
_CITATION = """\
22
@article{scikit-learn,
23
 title={Scikit-learn: Machine Learning in {P}ython},
24
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
25
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
26
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
27
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
28
 journal={Journal of Machine Learning Research},
29
 volume={12},
30
 pages={2825--2830},
31
 year={2011}
32
}
33
"""
34

35
_DESCRIPTION = """\
36
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
37
values.
38
"""
39

40

41
_KWARGS_DESCRIPTION = """
42
Args:
43
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
44
        Estimated target values.
45
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
46
        Ground truth (correct) target values.
47
    sample_weight: array-like of shape (n_samples,), default=None
48
        Sample weights.
49
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
50
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.
51

52
                 "raw_values" : Returns a full set of errors in case of multioutput input.
53

54
                 "uniform_average" : Errors of all outputs are averaged with uniform weight.
55

56
Returns:
57
    mae : mean absolute error.
58
        If multioutput is "raw_values", then mean absolute error is returned for each output separately. If multioutput is "uniform_average" or an ndarray of weights, then the weighted average of all output errors is returned.
59
        MAE output is non-negative floating point. The best value is 0.0.
60
Examples:
61

62
    >>> mae_metric = datasets.load_metric("mae")
63
    >>> predictions = [2.5, 0.0, 2, 8]
64
    >>> references = [3, -0.5, 2, 7]
65
    >>> results = mae_metric.compute(predictions=predictions, references=references)
66
    >>> print(results)
67
    {'mae': 0.5}
68

69
    If you're using multi-dimensional lists, then set the config as follows :
70

71
    >>> mae_metric = datasets.load_metric("mae", "multilist")
72
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
73
    >>> references = [[0, 2], [-1, 2], [8, -5]]
74
    >>> results = mae_metric.compute(predictions=predictions, references=references)
75
    >>> print(results)
76
    {'mae': 0.75}
77
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
78
    >>> print(results)
79
    {'mae': array([0.5, 1. ])}
80
"""
81

82

83
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
84
class Mae(datasets.Metric):
85
    def _info(self):
86
        return datasets.MetricInfo(
87
            description=_DESCRIPTION,
88
            citation=_CITATION,
89
            inputs_description=_KWARGS_DESCRIPTION,
90
            features=datasets.Features(self._get_feature_types()),
91
            reference_urls=[
92
                "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"
93
            ],
94
        )
95

96
    def _get_feature_types(self):
97
        if self.config_name == "multilist":
98
            return {
99
                "predictions": datasets.Sequence(datasets.Value("float")),
100
                "references": datasets.Sequence(datasets.Value("float")),
101
            }
102
        else:
103
            return {
104
                "predictions": datasets.Value("float"),
105
                "references": datasets.Value("float"),
106
            }
107

108
    def _compute(self, predictions, references, sample_weight=None, multioutput="uniform_average"):
109
        mae_score = mean_absolute_error(references, predictions, sample_weight=sample_weight, multioutput=multioutput)
110

111
        return {"mae": mae_score}
112

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.