
'''simple docstring'''



import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				int(SCREAMING_SNAKE_CASE_						)
   _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				t // 36_00, (t // 60) % 60, t % 60
   return F"{h}:{m:02d}:{s:02d}" if h != 0 else F"{m:02d}:{s:02d}"
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_=3_00						)     ->     Union[str, Any]:




   """simple docstring"""
   # docstyle-ignore
   return F"\n    <div>\n      {prefix}\n      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>\n      {label}\n    </div>\n    "
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     Tuple:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE      =				"""<table border=\"1\" class=\"dataframe\">\n"""
   html_code += """  <thead>\n <tr style="text-align: left;">\n"""
   for i in items[0]:
      html_code += F"      <th>{i}</th>\n"
   html_code += "    </tr>\n  </thead>\n  <tbody>\n"
   for line in items[1:]:
      html_code += "    <tr>\n"
      for elt in line:
         _SCREAMING_SNAKE_CASE      =				F"{elt:.6f}" if isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						) else str(SCREAMING_SNAKE_CASE_						)
         html_code += F"      <td>{elt}</td>\n"
      html_code += "    </tr>\n"
   html_code += "  </tbody>\n</table><p>"
   return html_code

class    _a				:





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  5
       SCREAMING_SNAKE_CASE      =  0.2






       def __init__(							self       ,							A__       ,							A__ = None       ,							A__ = True       ,							A__ = None       ,							A__ = 3_00       ,							)    ->			int:
          _SCREAMING_SNAKE_CASE      =				total
          _SCREAMING_SNAKE_CASE      =				"""""" if prefix is None else prefix
          _SCREAMING_SNAKE_CASE      =				leave
          _SCREAMING_SNAKE_CASE      =				parent
          _SCREAMING_SNAKE_CASE      =				width
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				None






       def        UpperCamelCase				(							self       ,							A__       ,							A__ = False       ,							A__ = None      )    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				value
          if comment is not None:
             _SCREAMING_SNAKE_CASE      =				comment
          if self.last_value is None:
             _SCREAMING_SNAKE_CASE      =				_SCREAMING_SNAKE_CASE      =				time.time()
             _SCREAMING_SNAKE_CASE      =				_SCREAMING_SNAKE_CASE      =				value
             _SCREAMING_SNAKE_CASE      =				_SCREAMING_SNAKE_CASE      =				None
             _SCREAMING_SNAKE_CASE      =				self.warmup
             _SCREAMING_SNAKE_CASE      =				1
             self.update_bar(A__      )
          elif value <= self.last_value and not force_update:
             return
          elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for       ,							self.total      ):
             if self.first_calls > 0:
                self.first_calls -= 1
             _SCREAMING_SNAKE_CASE      =				time.time()
             _SCREAMING_SNAKE_CASE      =				current_time - self.start_time
             # We could have value = self.start_value if the update is called twixe with the same start value.
             if value > self.start_value:
                _SCREAMING_SNAKE_CASE      =				self.elapsed_time / (value - self.start_value)
             else:
                _SCREAMING_SNAKE_CASE      =				None
             if value >= self.total:
                _SCREAMING_SNAKE_CASE      =				self.total
                _SCREAMING_SNAKE_CASE      =				None
                if not self.leave:
                   self.close()
             elif self.average_time_per_item is not None:
                _SCREAMING_SNAKE_CASE      =				self.average_time_per_item * (self.total - value)
             self.update_bar(A__      )
             _SCREAMING_SNAKE_CASE      =				value
             _SCREAMING_SNAKE_CASE      =				current_time
             if self.average_time_per_item is None:
                _SCREAMING_SNAKE_CASE      =				1
             else:
                _SCREAMING_SNAKE_CASE      =				max(int(self.update_every / self.average_time_per_item      )       ,							1      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__=None      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				""" """ * (len(str(self.total      )      ) - len(str(A__      )      )) + str(A__      )
          if self.elapsed_time is None:
             _SCREAMING_SNAKE_CASE      =				F"[{spaced_value}/{self.total} : < :"
          elif self.predicted_remaining is None:
             _SCREAMING_SNAKE_CASE      =				F"[{spaced_value}/{self.total} {format_time(self.elapsed_time      )}"
          else:
             _SCREAMING_SNAKE_CASE      =				(
                 F"[{spaced_value}/{self.total} {format_time(self.elapsed_time      )} <"
                 F" {format_time(self.predicted_remaining      )}"
             )
             self.label += F", {1/self.average_time_per_item:.2f} it/s"
          self.label += "]" if self.comment is None or len(self.comment      ) == 0 else F", {self.comment}]"
          self.display()






       def        UpperCamelCase				(							self      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				html_progress_bar(self.value       ,							self.total       ,							self.prefix       ,							self.label       ,							self.width      )
          if self.parent is not None:
             # If this is a child bar, the parent will take care of the display.
             self.parent.display()
             return
          if self.output is None:
             _SCREAMING_SNAKE_CASE      =				disp.display(disp.HTML(self.html_code      )       ,							display_id=A__      )
          else:
             self.output.update(disp.HTML(self.html_code      )      )






       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          if self.parent is None and self.output is not None:
             self.output.update(disp.HTML(""""""      )      )






class    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__=None      )    ->			Optional[int]:
          super().__init__(A__      )
          _SCREAMING_SNAKE_CASE      =				None if column_names is None else [column_names]
          _SCREAMING_SNAKE_CASE      =				None






       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				html_progress_bar(self.value       ,							self.total       ,							self.prefix       ,							self.label       ,							self.width      )
          if self.inner_table is not None:
             self.html_code += text_to_html_table(self.inner_table      )
          if self.child_bar is not None:
             self.html_code += self.child_bar.html_code
          if self.output is None:
             _SCREAMING_SNAKE_CASE      =				disp.display(disp.HTML(self.html_code      )       ,							display_id=A__      )
          else:
             self.output.update(disp.HTML(self.html_code      )      )






       def        UpperCamelCase				(							self       ,							A__      )    ->			Any:
          if self.inner_table is None:
             _SCREAMING_SNAKE_CASE      =				[list(values.keys()      ), list(values.values()      )]
          else:
             _SCREAMING_SNAKE_CASE      =				self.inner_table[0]
             if len(self.inner_table      ) == 1:
                # We give a chance to update the column names at the first iteration
                for key in values.keys():
                   if key not in columns:
                      columns.append(A__      )
                _SCREAMING_SNAKE_CASE      =				columns
             self.inner_table.append([values[c] for c in columns]      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__=None       ,							A__=3_00      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				NotebookProgressBar(A__       ,							prefix=A__       ,							parent=self       ,							width=A__      )
          return self.child_bar






       def        UpperCamelCase				(							self      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				None
          self.display()






class    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self      )    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				None
          _SCREAMING_SNAKE_CASE      =				False






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							**A__      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				"""Epoch""" if args.evaluation_strategy == IntervalStrategy.EPOCH else """Step"""
          _SCREAMING_SNAKE_CASE      =				0
          _SCREAMING_SNAKE_CASE      =				0
          _SCREAMING_SNAKE_CASE      =				[self.first_column] + ["""Training Loss"""]
          if args.evaluation_strategy != IntervalStrategy.NO:
             column_names.append("""Validation Loss"""      )
          _SCREAMING_SNAKE_CASE      =				NotebookTrainingTracker(state.max_steps       ,							A__      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							**A__      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				int(state.epoch      ) if int(state.epoch      ) == state.epoch else F"{state.epoch:.2f}"
          self.training_tracker.update(
              state.global_step + 1       ,							comment=F"Epoch {epoch}/{state.num_train_epochs}"       ,							force_update=self._force_next_update       ,							)
          _SCREAMING_SNAKE_CASE      =				False






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__=None       ,							**A__      )    ->			Union[str, Any]:
          if not has_length(A__      ):
             return
          if self.prediction_bar is None:
             if self.training_tracker is not None:
                _SCREAMING_SNAKE_CASE      =				self.training_tracker.add_child(len(A__      )      )
             else:
                _SCREAMING_SNAKE_CASE      =				NotebookProgressBar(len(A__      )      )
             self.prediction_bar.update(1      )
          else:
             self.prediction_bar.update(self.prediction_bar.value + 1      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							**A__      )    ->			List[Any]:
          if self.prediction_bar is not None:
             self.prediction_bar.close()
          _SCREAMING_SNAKE_CASE      =				None






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__=None       ,							**A__      )    ->			Optional[int]:
          # Only for when there is no evaluation
          if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
             _SCREAMING_SNAKE_CASE      =				{"""Training Loss""": logs["""loss"""]}
             # First column is necessarily Step sine we're not in epoch eval strategy
             _SCREAMING_SNAKE_CASE      =				state.global_step
             self.training_tracker.write_line(A__      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							A__=None       ,							**A__      )    ->			Dict:
          if self.training_tracker is not None:
             _SCREAMING_SNAKE_CASE      =				{"""Training Loss""": """No log""", """Validation Loss""": """No log"""}
             for log in reversed(state.log_history      ):
                if "loss" in log:
                   _SCREAMING_SNAKE_CASE      =				log["""loss"""]
                   break

             if self.first_column == "Epoch":
                _SCREAMING_SNAKE_CASE      =				int(state.epoch      )
             else:
                _SCREAMING_SNAKE_CASE      =				state.global_step
             _SCREAMING_SNAKE_CASE      =				"""eval"""
             for k in metrics:
                if k.endswith("""_loss"""      ):
                   _SCREAMING_SNAKE_CASE      =				re.sub(R"""\_loss$"""       ,							""""""       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop("""total_flos"""       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop("""epoch"""       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop(F"{metric_key_prefix}_runtime"       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop(F"{metric_key_prefix}_samples_per_second"       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop(F"{metric_key_prefix}_steps_per_second"       ,							A__      )
             _SCREAMING_SNAKE_CASE      =				metrics.pop(F"{metric_key_prefix}_jit_compilation_time"       ,							A__      )
             for k, v in metrics.items():
                if k == F"{metric_key_prefix}_loss":
                   _SCREAMING_SNAKE_CASE      =				v
                else:
                   _SCREAMING_SNAKE_CASE      =				k.split("""_"""      )
                   _SCREAMING_SNAKE_CASE      =				""" """.join([part.capitalize() for part in splits[1:]]      )
                   _SCREAMING_SNAKE_CASE      =				v
             self.training_tracker.write_line(A__      )
             self.training_tracker.remove_child()
             _SCREAMING_SNAKE_CASE      =				None
             # Evaluation takes a long time so we should force the next update.
             _SCREAMING_SNAKE_CASE      =				True






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__       ,							**A__      )    ->			Dict:
          self.training_tracker.update(
              state.global_step       ,							comment=F"Epoch {int(state.epoch      )}/{state.num_train_epochs}"       ,							force_update=A__      )
          _SCREAMING_SNAKE_CASE      =				None








'''simple docstring'''



from sklearn.metrics import matthews_corrcoef

import datasets


UpperCamelCase__      :		List[str]       							=  "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

UpperCamelCase__      :		List[Any]       							=  "\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

UpperCamelCase__      :		Any       							=  "\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,					_KWARGS_DESCRIPTION)
class    _a				(datasets.Metric):





       """simple docstring"""




       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          return datasets.MetricInfo(
              description=_DESCRIPTION       ,							citation=_CITATION       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
                  {
                      """predictions""": datasets.Value("""int32"""      ),
                      """references""": datasets.Value("""int32"""      ),
                  }      )       ,							reference_urls=[
                  """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"""
              ]       ,							)






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__=None      )    ->			List[str]:
          return {
              "matthews_correlation": float(matthews_corrcoef(A__       ,							A__       ,							sample_weight=A__      )      ),
          }






