metrics.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  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. # ==============================================================================
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import numpy as np
  19. def accuracy(logits, labels):
  20. """
  21. Return accuracy of the array of logits (or label predictions) wrt the labels
  22. :param logits: this can either be logits, probabilities, or a single label
  23. :param labels: the correct labels to match against
  24. :return: the accuracy as a float
  25. """
  26. assert len(logits) == len(labels)
  27. if len(np.shape(logits)) > 1:
  28. # Predicted labels are the argmax over axis 1
  29. predicted_labels = np.argmax(logits, axis=1)
  30. else:
  31. # Input was already labels
  32. assert len(np.shape(logits)) == 1
  33. predicted_labels = logits
  34. # Check against correct labels to compute correct guesses
  35. correct = np.sum(predicted_labels == labels.reshape(len(labels)))
  36. # Divide by number of labels to obtain accuracy
  37. accuracy = float(correct) / len(labels)
  38. # Return float value
  39. return accuracy