_lfw.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. """Labeled Faces in the Wild (LFW) dataset
  2. This dataset is a collection of JPEG pictures of famous people collected
  3. over the internet, all details are available on the official website:
  4. http://vis-www.cs.umass.edu/lfw/
  5. """
  6. # Copyright (c) 2011 Olivier Grisel <olivier.grisel@ensta.org>
  7. # License: BSD 3 clause
  8. import logging
  9. from numbers import Integral, Real
  10. from os import PathLike, listdir, makedirs, remove
  11. from os.path import exists, isdir, join
  12. import numpy as np
  13. from joblib import Memory
  14. from ..utils import Bunch
  15. from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params
  16. from ._base import (
  17. RemoteFileMetadata,
  18. _fetch_remote,
  19. get_data_home,
  20. load_descr,
  21. )
  22. logger = logging.getLogger(__name__)
  23. # The original data can be found in:
  24. # http://vis-www.cs.umass.edu/lfw/lfw.tgz
  25. ARCHIVE = RemoteFileMetadata(
  26. filename="lfw.tgz",
  27. url="https://ndownloader.figshare.com/files/5976018",
  28. checksum="055f7d9c632d7370e6fb4afc7468d40f970c34a80d4c6f50ffec63f5a8d536c0",
  29. )
  30. # The original funneled data can be found in:
  31. # http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz
  32. FUNNELED_ARCHIVE = RemoteFileMetadata(
  33. filename="lfw-funneled.tgz",
  34. url="https://ndownloader.figshare.com/files/5976015",
  35. checksum="b47c8422c8cded889dc5a13418c4bc2abbda121092b3533a83306f90d900100a",
  36. )
  37. # The original target data can be found in:
  38. # http://vis-www.cs.umass.edu/lfw/pairsDevTrain.txt',
  39. # http://vis-www.cs.umass.edu/lfw/pairsDevTest.txt',
  40. # http://vis-www.cs.umass.edu/lfw/pairs.txt',
  41. TARGETS = (
  42. RemoteFileMetadata(
  43. filename="pairsDevTrain.txt",
  44. url="https://ndownloader.figshare.com/files/5976012",
  45. checksum="1d454dada7dfeca0e7eab6f65dc4e97a6312d44cf142207be28d688be92aabfa",
  46. ),
  47. RemoteFileMetadata(
  48. filename="pairsDevTest.txt",
  49. url="https://ndownloader.figshare.com/files/5976009",
  50. checksum="7cb06600ea8b2814ac26e946201cdb304296262aad67d046a16a7ec85d0ff87c",
  51. ),
  52. RemoteFileMetadata(
  53. filename="pairs.txt",
  54. url="https://ndownloader.figshare.com/files/5976006",
  55. checksum="ea42330c62c92989f9d7c03237ed5d591365e89b3e649747777b70e692dc1592",
  56. ),
  57. )
  58. #
  59. # Common private utilities for data fetching from the original LFW website
  60. # local disk caching, and image decoding.
  61. #
  62. def _check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True):
  63. """Helper function to download any missing LFW data"""
  64. data_home = get_data_home(data_home=data_home)
  65. lfw_home = join(data_home, "lfw_home")
  66. if not exists(lfw_home):
  67. makedirs(lfw_home)
  68. for target in TARGETS:
  69. target_filepath = join(lfw_home, target.filename)
  70. if not exists(target_filepath):
  71. if download_if_missing:
  72. logger.info("Downloading LFW metadata: %s", target.url)
  73. _fetch_remote(target, dirname=lfw_home)
  74. else:
  75. raise OSError("%s is missing" % target_filepath)
  76. if funneled:
  77. data_folder_path = join(lfw_home, "lfw_funneled")
  78. archive = FUNNELED_ARCHIVE
  79. else:
  80. data_folder_path = join(lfw_home, "lfw")
  81. archive = ARCHIVE
  82. if not exists(data_folder_path):
  83. archive_path = join(lfw_home, archive.filename)
  84. if not exists(archive_path):
  85. if download_if_missing:
  86. logger.info("Downloading LFW data (~200MB): %s", archive.url)
  87. _fetch_remote(archive, dirname=lfw_home)
  88. else:
  89. raise OSError("%s is missing" % archive_path)
  90. import tarfile
  91. logger.debug("Decompressing the data archive to %s", data_folder_path)
  92. tarfile.open(archive_path, "r:gz").extractall(path=lfw_home)
  93. remove(archive_path)
  94. return lfw_home, data_folder_path
  95. def _load_imgs(file_paths, slice_, color, resize):
  96. """Internally used to load images"""
  97. try:
  98. from PIL import Image
  99. except ImportError:
  100. raise ImportError(
  101. "The Python Imaging Library (PIL) is required to load data "
  102. "from jpeg files. Please refer to "
  103. "https://pillow.readthedocs.io/en/stable/installation.html "
  104. "for installing PIL."
  105. )
  106. # compute the portion of the images to load to respect the slice_ parameter
  107. # given by the caller
  108. default_slice = (slice(0, 250), slice(0, 250))
  109. if slice_ is None:
  110. slice_ = default_slice
  111. else:
  112. slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice))
  113. h_slice, w_slice = slice_
  114. h = (h_slice.stop - h_slice.start) // (h_slice.step or 1)
  115. w = (w_slice.stop - w_slice.start) // (w_slice.step or 1)
  116. if resize is not None:
  117. resize = float(resize)
  118. h = int(resize * h)
  119. w = int(resize * w)
  120. # allocate some contiguous memory to host the decoded image slices
  121. n_faces = len(file_paths)
  122. if not color:
  123. faces = np.zeros((n_faces, h, w), dtype=np.float32)
  124. else:
  125. faces = np.zeros((n_faces, h, w, 3), dtype=np.float32)
  126. # iterate over the collected file path to load the jpeg files as numpy
  127. # arrays
  128. for i, file_path in enumerate(file_paths):
  129. if i % 1000 == 0:
  130. logger.debug("Loading face #%05d / %05d", i + 1, n_faces)
  131. # Checks if jpeg reading worked. Refer to issue #3594 for more
  132. # details.
  133. pil_img = Image.open(file_path)
  134. pil_img = pil_img.crop(
  135. (w_slice.start, h_slice.start, w_slice.stop, h_slice.stop)
  136. )
  137. if resize is not None:
  138. pil_img = pil_img.resize((w, h))
  139. face = np.asarray(pil_img, dtype=np.float32)
  140. if face.ndim == 0:
  141. raise RuntimeError(
  142. "Failed to read the image file %s, "
  143. "Please make sure that libjpeg is installed" % file_path
  144. )
  145. face /= 255.0 # scale uint8 coded colors to the [0.0, 1.0] floats
  146. if not color:
  147. # average the color channels to compute a gray levels
  148. # representation
  149. face = face.mean(axis=2)
  150. faces[i, ...] = face
  151. return faces
  152. #
  153. # Task #1: Face Identification on picture with names
  154. #
  155. def _fetch_lfw_people(
  156. data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0
  157. ):
  158. """Perform the actual data loading for the lfw people dataset
  159. This operation is meant to be cached by a joblib wrapper.
  160. """
  161. # scan the data folder content to retain people with more that
  162. # `min_faces_per_person` face pictures
  163. person_names, file_paths = [], []
  164. for person_name in sorted(listdir(data_folder_path)):
  165. folder_path = join(data_folder_path, person_name)
  166. if not isdir(folder_path):
  167. continue
  168. paths = [join(folder_path, f) for f in sorted(listdir(folder_path))]
  169. n_pictures = len(paths)
  170. if n_pictures >= min_faces_per_person:
  171. person_name = person_name.replace("_", " ")
  172. person_names.extend([person_name] * n_pictures)
  173. file_paths.extend(paths)
  174. n_faces = len(file_paths)
  175. if n_faces == 0:
  176. raise ValueError(
  177. "min_faces_per_person=%d is too restrictive" % min_faces_per_person
  178. )
  179. target_names = np.unique(person_names)
  180. target = np.searchsorted(target_names, person_names)
  181. faces = _load_imgs(file_paths, slice_, color, resize)
  182. # shuffle the faces with a deterministic RNG scheme to avoid having
  183. # all faces of the same person in a row, as it would break some
  184. # cross validation and learning algorithms such as SGD and online
  185. # k-means that make an IID assumption
  186. indices = np.arange(n_faces)
  187. np.random.RandomState(42).shuffle(indices)
  188. faces, target = faces[indices], target[indices]
  189. return faces, target, target_names
  190. @validate_params(
  191. {
  192. "data_home": [str, PathLike, None],
  193. "funneled": ["boolean"],
  194. "resize": [Interval(Real, 0, None, closed="neither"), None],
  195. "min_faces_per_person": [Interval(Integral, 0, None, closed="left"), None],
  196. "color": ["boolean"],
  197. "slice_": [tuple, Hidden(None)],
  198. "download_if_missing": ["boolean"],
  199. "return_X_y": ["boolean"],
  200. },
  201. prefer_skip_nested_validation=True,
  202. )
  203. def fetch_lfw_people(
  204. *,
  205. data_home=None,
  206. funneled=True,
  207. resize=0.5,
  208. min_faces_per_person=0,
  209. color=False,
  210. slice_=(slice(70, 195), slice(78, 172)),
  211. download_if_missing=True,
  212. return_X_y=False,
  213. ):
  214. """Load the Labeled Faces in the Wild (LFW) people dataset \
  215. (classification).
  216. Download it if necessary.
  217. ================= =======================
  218. Classes 5749
  219. Samples total 13233
  220. Dimensionality 5828
  221. Features real, between 0 and 255
  222. ================= =======================
  223. Read more in the :ref:`User Guide <labeled_faces_in_the_wild_dataset>`.
  224. Parameters
  225. ----------
  226. data_home : str or path-like, default=None
  227. Specify another download and cache folder for the datasets. By default
  228. all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
  229. funneled : bool, default=True
  230. Download and use the funneled variant of the dataset.
  231. resize : float or None, default=0.5
  232. Ratio used to resize the each face picture. If `None`, no resizing is
  233. performed.
  234. min_faces_per_person : int, default=None
  235. The extracted dataset will only retain pictures of people that have at
  236. least `min_faces_per_person` different pictures.
  237. color : bool, default=False
  238. Keep the 3 RGB channels instead of averaging them to a single
  239. gray level channel. If color is True the shape of the data has
  240. one more dimension than the shape with color = False.
  241. slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
  242. Provide a custom 2D slice (height, width) to extract the
  243. 'interesting' part of the jpeg files and avoid use statistical
  244. correlation from the background.
  245. download_if_missing : bool, default=True
  246. If False, raise an OSError if the data is not locally available
  247. instead of trying to download the data from the source site.
  248. return_X_y : bool, default=False
  249. If True, returns ``(dataset.data, dataset.target)`` instead of a Bunch
  250. object. See below for more information about the `dataset.data` and
  251. `dataset.target` object.
  252. .. versionadded:: 0.20
  253. Returns
  254. -------
  255. dataset : :class:`~sklearn.utils.Bunch`
  256. Dictionary-like object, with the following attributes.
  257. data : numpy array of shape (13233, 2914)
  258. Each row corresponds to a ravelled face image
  259. of original size 62 x 47 pixels.
  260. Changing the ``slice_`` or resize parameters will change the
  261. shape of the output.
  262. images : numpy array of shape (13233, 62, 47)
  263. Each row is a face image corresponding to one of the 5749 people in
  264. the dataset. Changing the ``slice_``
  265. or resize parameters will change the shape of the output.
  266. target : numpy array of shape (13233,)
  267. Labels associated to each face image.
  268. Those labels range from 0-5748 and correspond to the person IDs.
  269. target_names : numpy array of shape (5749,)
  270. Names of all persons in the dataset.
  271. Position in array corresponds to the person ID in the target array.
  272. DESCR : str
  273. Description of the Labeled Faces in the Wild (LFW) dataset.
  274. (data, target) : tuple if ``return_X_y`` is True
  275. A tuple of two ndarray. The first containing a 2D array of
  276. shape (n_samples, n_features) with each row representing one
  277. sample and each column representing the features. The second
  278. ndarray of shape (n_samples,) containing the target samples.
  279. .. versionadded:: 0.20
  280. """
  281. lfw_home, data_folder_path = _check_fetch_lfw(
  282. data_home=data_home, funneled=funneled, download_if_missing=download_if_missing
  283. )
  284. logger.debug("Loading LFW people faces from %s", lfw_home)
  285. # wrap the loader in a memoizing function that will return memmaped data
  286. # arrays for optimal memory usage
  287. m = Memory(location=lfw_home, compress=6, verbose=0)
  288. load_func = m.cache(_fetch_lfw_people)
  289. # load and memoize the pairs as np arrays
  290. faces, target, target_names = load_func(
  291. data_folder_path,
  292. resize=resize,
  293. min_faces_per_person=min_faces_per_person,
  294. color=color,
  295. slice_=slice_,
  296. )
  297. X = faces.reshape(len(faces), -1)
  298. fdescr = load_descr("lfw.rst")
  299. if return_X_y:
  300. return X, target
  301. # pack the results as a Bunch instance
  302. return Bunch(
  303. data=X, images=faces, target=target, target_names=target_names, DESCR=fdescr
  304. )
  305. #
  306. # Task #2: Face Verification on pairs of face pictures
  307. #
  308. def _fetch_lfw_pairs(
  309. index_file_path, data_folder_path, slice_=None, color=False, resize=None
  310. ):
  311. """Perform the actual data loading for the LFW pairs dataset
  312. This operation is meant to be cached by a joblib wrapper.
  313. """
  314. # parse the index file to find the number of pairs to be able to allocate
  315. # the right amount of memory before starting to decode the jpeg files
  316. with open(index_file_path, "rb") as index_file:
  317. split_lines = [ln.decode().strip().split("\t") for ln in index_file]
  318. pair_specs = [sl for sl in split_lines if len(sl) > 2]
  319. n_pairs = len(pair_specs)
  320. # iterating over the metadata lines for each pair to find the filename to
  321. # decode and load in memory
  322. target = np.zeros(n_pairs, dtype=int)
  323. file_paths = list()
  324. for i, components in enumerate(pair_specs):
  325. if len(components) == 3:
  326. target[i] = 1
  327. pair = (
  328. (components[0], int(components[1]) - 1),
  329. (components[0], int(components[2]) - 1),
  330. )
  331. elif len(components) == 4:
  332. target[i] = 0
  333. pair = (
  334. (components[0], int(components[1]) - 1),
  335. (components[2], int(components[3]) - 1),
  336. )
  337. else:
  338. raise ValueError("invalid line %d: %r" % (i + 1, components))
  339. for j, (name, idx) in enumerate(pair):
  340. try:
  341. person_folder = join(data_folder_path, name)
  342. except TypeError:
  343. person_folder = join(data_folder_path, str(name, "UTF-8"))
  344. filenames = list(sorted(listdir(person_folder)))
  345. file_path = join(person_folder, filenames[idx])
  346. file_paths.append(file_path)
  347. pairs = _load_imgs(file_paths, slice_, color, resize)
  348. shape = list(pairs.shape)
  349. n_faces = shape.pop(0)
  350. shape.insert(0, 2)
  351. shape.insert(0, n_faces // 2)
  352. pairs.shape = shape
  353. return pairs, target, np.array(["Different persons", "Same person"])
  354. @validate_params(
  355. {
  356. "subset": [StrOptions({"train", "test", "10_folds"})],
  357. "data_home": [str, PathLike, None],
  358. "funneled": ["boolean"],
  359. "resize": [Interval(Real, 0, None, closed="neither"), None],
  360. "color": ["boolean"],
  361. "slice_": [tuple, Hidden(None)],
  362. "download_if_missing": ["boolean"],
  363. },
  364. prefer_skip_nested_validation=True,
  365. )
  366. def fetch_lfw_pairs(
  367. *,
  368. subset="train",
  369. data_home=None,
  370. funneled=True,
  371. resize=0.5,
  372. color=False,
  373. slice_=(slice(70, 195), slice(78, 172)),
  374. download_if_missing=True,
  375. ):
  376. """Load the Labeled Faces in the Wild (LFW) pairs dataset (classification).
  377. Download it if necessary.
  378. ================= =======================
  379. Classes 2
  380. Samples total 13233
  381. Dimensionality 5828
  382. Features real, between 0 and 255
  383. ================= =======================
  384. In the official `README.txt`_ this task is described as the
  385. "Restricted" task. As I am not sure as to implement the
  386. "Unrestricted" variant correctly, I left it as unsupported for now.
  387. .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt
  388. The original images are 250 x 250 pixels, but the default slice and resize
  389. arguments reduce them to 62 x 47.
  390. Read more in the :ref:`User Guide <labeled_faces_in_the_wild_dataset>`.
  391. Parameters
  392. ----------
  393. subset : {'train', 'test', '10_folds'}, default='train'
  394. Select the dataset to load: 'train' for the development training
  395. set, 'test' for the development test set, and '10_folds' for the
  396. official evaluation set that is meant to be used with a 10-folds
  397. cross validation.
  398. data_home : str or path-like, default=None
  399. Specify another download and cache folder for the datasets. By
  400. default all scikit-learn data is stored in '~/scikit_learn_data'
  401. subfolders.
  402. funneled : bool, default=True
  403. Download and use the funneled variant of the dataset.
  404. resize : float, default=0.5
  405. Ratio used to resize the each face picture.
  406. color : bool, default=False
  407. Keep the 3 RGB channels instead of averaging them to a single
  408. gray level channel. If color is True the shape of the data has
  409. one more dimension than the shape with color = False.
  410. slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
  411. Provide a custom 2D slice (height, width) to extract the
  412. 'interesting' part of the jpeg files and avoid use statistical
  413. correlation from the background.
  414. download_if_missing : bool, default=True
  415. If False, raise an OSError if the data is not locally available
  416. instead of trying to download the data from the source site.
  417. Returns
  418. -------
  419. data : :class:`~sklearn.utils.Bunch`
  420. Dictionary-like object, with the following attributes.
  421. data : ndarray of shape (2200, 5828). Shape depends on ``subset``.
  422. Each row corresponds to 2 ravel'd face images
  423. of original size 62 x 47 pixels.
  424. Changing the ``slice_``, ``resize`` or ``subset`` parameters
  425. will change the shape of the output.
  426. pairs : ndarray of shape (2200, 2, 62, 47). Shape depends on ``subset``
  427. Each row has 2 face images corresponding
  428. to same or different person from the dataset
  429. containing 5749 people. Changing the ``slice_``,
  430. ``resize`` or ``subset`` parameters will change the shape of the
  431. output.
  432. target : numpy array of shape (2200,). Shape depends on ``subset``.
  433. Labels associated to each pair of images.
  434. The two label values being different persons or the same person.
  435. target_names : numpy array of shape (2,)
  436. Explains the target values of the target array.
  437. 0 corresponds to "Different person", 1 corresponds to "same person".
  438. DESCR : str
  439. Description of the Labeled Faces in the Wild (LFW) dataset.
  440. """
  441. lfw_home, data_folder_path = _check_fetch_lfw(
  442. data_home=data_home, funneled=funneled, download_if_missing=download_if_missing
  443. )
  444. logger.debug("Loading %s LFW pairs from %s", subset, lfw_home)
  445. # wrap the loader in a memoizing function that will return memmaped data
  446. # arrays for optimal memory usage
  447. m = Memory(location=lfw_home, compress=6, verbose=0)
  448. load_func = m.cache(_fetch_lfw_pairs)
  449. # select the right metadata file according to the requested subset
  450. label_filenames = {
  451. "train": "pairsDevTrain.txt",
  452. "test": "pairsDevTest.txt",
  453. "10_folds": "pairs.txt",
  454. }
  455. if subset not in label_filenames:
  456. raise ValueError(
  457. "subset='%s' is invalid: should be one of %r"
  458. % (subset, list(sorted(label_filenames.keys())))
  459. )
  460. index_file_path = join(lfw_home, label_filenames[subset])
  461. # load and memoize the pairs as np arrays
  462. pairs, target, target_names = load_func(
  463. index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_
  464. )
  465. fdescr = load_descr("lfw.rst")
  466. # pack the results as a Bunch instance
  467. return Bunch(
  468. data=pairs.reshape(len(pairs), -1),
  469. pairs=pairs,
  470. target=target,
  471. target_names=target_names,
  472. DESCR=fdescr,
  473. )