/tensorflow/contrib/learn/python/learn/datasets/base.py

https://gitlab.com/hrishikeshvganu/tensorflow · Python · 101 lines · 64 code · 13 blank · 24 comment · 6 complexity · 5709c9185a888443d800e9303648144a MD5 · raw file

  1. """Base utilities for loading datasets."""
  2. # Copyright 2015-present The Scikit Flow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import csv
  19. import collections
  20. import os
  21. from os import path
  22. import tempfile
  23. from six.moves import urllib
  24. import numpy as np
  25. from tensorflow.python.platform import gfile
  26. Dataset = collections.namedtuple('Dataset', ['data', 'target'])
  27. Datasets = collections.namedtuple('Datasets', ['train', 'validation', 'test'])
  28. def load_csv(filename, target_dtype, target_column=-1, has_header=True):
  29. with gfile.Open(filename) as csv_file:
  30. data_file = csv.reader(csv_file)
  31. if has_header:
  32. header = next(data_file)
  33. n_samples = int(header[0])
  34. n_features = int(header[1])
  35. target_names = np.array(header[2:])
  36. data = np.empty((n_samples, n_features))
  37. target = np.empty((n_samples,), dtype=np.int)
  38. for i, ir in enumerate(data_file):
  39. target[i] = np.asarray(ir.pop(target_column), dtype=target_dtype)
  40. data[i] = np.asarray(ir, dtype=np.float64)
  41. else:
  42. data, target = [], []
  43. for ir in data_file:
  44. target.append(ir.pop(target_column))
  45. data.append(ir)
  46. return Dataset(data=data, target=target)
  47. def load_iris():
  48. """Load Iris dataset.
  49. Returns:
  50. Dataset object containing data in-memory.
  51. """
  52. module_path = path.dirname(__file__)
  53. return load_csv(
  54. path.join(module_path, 'data', 'iris.csv'),
  55. target_dtype=np.int)
  56. def load_boston():
  57. """Load Boston housing dataset.
  58. Returns:
  59. Dataset object containing data in-memory.
  60. """
  61. module_path = path.dirname(__file__)
  62. return load_csv(
  63. path.join(module_path, 'data', 'boston_house_prices.csv'),
  64. target_dtype=np.float)
  65. def maybe_download(filename, work_directory, source_url):
  66. """Download the data from source url, unless it's already here.
  67. Args:
  68. filename: string, name of the file in the directory.
  69. work_directory: string, path to working directory.
  70. source_url: url to download from if file doesn't exist.
  71. Returns:
  72. Path to resulting file.
  73. """
  74. if not gfile.Exists(work_directory):
  75. gfile.MakeDirs(work_directory)
  76. filepath = os.path.join(work_directory, filename)
  77. if not gfile.Exists(filepath):
  78. with tempfile.NamedTemporaryFile() as tmpfile:
  79. temp_file_name = tmpfile.name
  80. urllib.request.urlretrieve(source_url, temp_file_name)
  81. gfile.Copy(temp_file_name, filepath)
  82. with gfile.GFile(filepath) as f:
  83. size = f.Size()
  84. print('Successfully downloaded', filename, size, 'bytes.')
  85. return filepath