baotrung217

notMNIST-deeplearning

Nov 30th, 2017
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.11 KB | None | 0 0
  1. # These are all the modules we'll be using later. Make sure you can import them
  2. # before proceeding further.
  3. from __future__ import print_function
  4. import imageio
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. import os
  8. import sys
  9. import tarfile
  10. from IPython.display import display, Image
  11. from sklearn.linear_model import LogisticRegression
  12. from six.moves.urllib.request import urlretrieve
  13. from six.moves import cPickle as pickle
  14.  
  15. url = 'https://commondatastorage.googleapis.com/books1000/'
  16. last_percent_reported = None
  17. data_root = '.' # Change me to store data elsewhere
  18.  
  19. def download_progress_hook(count, blockSize, totalSize):
  20.   """A hook to report the progress of a download. This is mostly intended for users with
  21.  slow internet connections. Reports every 5% change in download progress.
  22.  """
  23.   global last_percent_reported
  24.   percent = int(count * blockSize * 100 / totalSize)
  25.  
  26.   if last_percent_reported != percent:
  27.     if percent % 5 == 0:
  28.       sys.stdout.write("%s%%" % percent)
  29.       sys.stdout.flush()
  30.     else:
  31.       sys.stdout.write(".")
  32.       sys.stdout.flush()
  33.      
  34.     last_percent_reported = percent
  35.        
  36. def maybe_download(filename, expected_bytes, force=False):
  37.   """Download a file if not present, and make sure it's the right size."""
  38.   dest_filename = os.path.join(data_root, filename)
  39.   if force or not os.path.exists(dest_filename):
  40.     print('Attempting to download:', filename)
  41.     filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
  42.     print('\nDownload Complete!')
  43.   statinfo = os.stat(dest_filename)
  44.   if statinfo.st_size == expected_bytes:
  45.     print('Found and verified', dest_filename)
  46.   else:
  47.     raise Exception(
  48.       'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
  49.   return dest_filename
  50.  
  51. train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)
  52. test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)
  53.  
  54. ######################################################################
  55. num_classes = 10
  56. np.random.seed(133)
  57.  
  58. def maybe_extract(filename, force=False):
  59.   root = os.path.splitext(os.path.splitext(filename)[0])[0]  # remove .tar.gz
  60.   if os.path.isdir(root) and not force:
  61.     # You may override by setting force=True.
  62.     print('%s already present - Skipping extraction of %s.' % (root, filename))
  63.   else:
  64.     print('Extracting data for %s. This may take a while. Please wait.' % root)
  65.     tar = tarfile.open(filename)
  66.     sys.stdout.flush()
  67.     tar.extractall(data_root)
  68.     tar.close()
  69.   data_folders = [
  70.     os.path.join(root, d) for d in sorted(os.listdir(root))
  71.     if os.path.isdir(os.path.join(root, d))]
  72.   if len(data_folders) != num_classes:
  73.     raise Exception(
  74.       'Expected %d folders, one per class. Found %d instead.' % (
  75.         num_classes, len(data_folders)))
  76.   print(data_folders)
  77.   return data_folders
  78.  
  79. train_folders = maybe_extract(train_filename)
  80. test_folders = maybe_extract(test_filename)
  81.  
  82. ################################################################
  83. ## PROBLEM 1
  84. ################################################################
  85. #display(Image(filename="notMNIST_small/A/Q0NXaWxkV29yZHMtQm9sZEl0YWxpYy50dGY=.png"))
  86.  
  87. #def show_some_data(folder):
  88. #    image_files = os.listdir(folder)
  89. #    for i in range(5):
  90. #        display(Image(filename=folder + "\\" + image_files[i]))
  91. #
  92. #print("\n")
  93. #for i in range(5):
  94. #    print(train_folders[i])
  95. #    show_some_data(train_folders[i])
  96.    
  97. ################################################################
  98. # convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road.
  99. image_size = 28  # Pixel width and height.
  100. pixel_depth = 255.0  # Number of levels per pixel.
  101.  
  102. def load_letter(folder, min_num_images):
  103.   """Load the data for a single letter label."""
  104.   image_files = os.listdir(folder)
  105.   dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
  106.                          dtype=np.float32)
  107.   print(folder)
  108.   num_images = 0
  109.   for image in image_files:
  110.     image_file = os.path.join(folder, image)
  111.     try:
  112.       image_data = (imageio.imread(image_file).astype(float) -
  113.                     pixel_depth / 2) / pixel_depth
  114.       if image_data.shape != (image_size, image_size):
  115.         raise Exception('Unexpected image shape: %s' % str(image_data.shape))
  116.       dataset[num_images, :, :] = image_data
  117.       num_images = num_images + 1
  118.     except (IOError, ValueError) as e:
  119.       print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
  120.    
  121.   dataset = dataset[0:num_images, :, :]
  122.   if num_images < min_num_images:
  123.     raise Exception('Many fewer images than expected: %d < %d' %
  124.                     (num_images, min_num_images))
  125.    
  126.   print('Full dataset tensor:', dataset.shape)
  127.   print('Mean:', np.mean(dataset))
  128.   print('Standard deviation:', np.std(dataset))
  129.   return dataset
  130.        
  131. def maybe_pickle(data_folders, min_num_images_per_class, force=False):
  132.   dataset_names = []
  133.   for folder in data_folders:
  134.     set_filename = folder + '.pickle'
  135.     dataset_names.append(set_filename)
  136.     if os.path.exists(set_filename) and not force:
  137.       # You may override by setting force=True.
  138.       print('%s already present - Skipping pickling.' % set_filename)
  139.     else:
  140.       print('Pickling %s.' % set_filename)
  141.       dataset = load_letter(folder, min_num_images_per_class)
  142.       try:
  143.         with open(set_filename, 'wb') as f:
  144.           pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)
  145.       except Exception as e:
  146.         print('Unable to save data to', set_filename, ':', e)
  147.  
  148.   return dataset_names
  149.  
  150. train_datasets = maybe_pickle(train_folders, 45000)
  151. test_datasets = maybe_pickle(test_folders, 1800)
  152.  
  153. ################################################################
  154. ## PROBLEM 2
  155. ################################################################
  156. #np.random.seed(42)
  157. #for i in range(10):
  158. #    pickle_file = train_datasets[i]  # index 0 should be all As, 1 = all Bs, etc.
  159. #    with open(pickle_file, 'rb') as f:
  160. #        letter_set = pickle.load(f)  # unpickle
  161. #        sample_idx = np.random.randint(len(letter_set))  # pick a random image index
  162. #        sample_image = letter_set[sample_idx, :, :]  # extract a 2D slice
  163. #        plt.figure()
  164. #        plt.imshow(sample_image)  # display it
  165.        
  166. ################################################################
  167. # Merge and prune the training data as needed
  168. def make_arrays(nb_rows, img_size):
  169.   if nb_rows:
  170.     dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)
  171.     labels = np.ndarray(nb_rows, dtype=np.int32)
  172.   else:
  173.     dataset, labels = None, None
  174.   return dataset, labels
  175.  
  176. def merge_datasets(pickle_files, train_size, valid_size=0):
  177.   num_classes = len(pickle_files)
  178.   valid_dataset, valid_labels = make_arrays(valid_size, image_size)
  179.   train_dataset, train_labels = make_arrays(train_size, image_size)
  180.   vsize_per_class = valid_size // num_classes
  181.   tsize_per_class = train_size // num_classes
  182.    
  183.   start_v, start_t = 0, 0
  184.   end_v, end_t = vsize_per_class, tsize_per_class
  185.   end_l = vsize_per_class+tsize_per_class
  186.   for label, pickle_file in enumerate(pickle_files):      
  187.     try:
  188.       with open(pickle_file, 'rb') as f:
  189.         letter_set = pickle.load(f)
  190.         # let's shuffle the letters to have random validation and training set
  191.         np.random.shuffle(letter_set)
  192.         if valid_dataset is not None:
  193.           valid_letter = letter_set[:vsize_per_class, :, :]
  194.           valid_dataset[start_v:end_v, :, :] = valid_letter
  195.           valid_labels[start_v:end_v] = label
  196.           start_v += vsize_per_class
  197.           end_v += vsize_per_class
  198.                    
  199.         train_letter = letter_set[vsize_per_class:end_l, :, :]
  200.         train_dataset[start_t:end_t, :, :] = train_letter
  201.         train_labels[start_t:end_t] = label
  202.         start_t += tsize_per_class
  203.         end_t += tsize_per_class
  204.     except Exception as e:
  205.       print('Unable to process data from', pickle_file, ':', e)
  206.       raise
  207.    
  208.   return valid_dataset, valid_labels, train_dataset, train_labels
  209.            
  210.            
  211. train_size = 200000
  212. valid_size = 10000
  213. test_size = 10000
  214.  
  215. valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(
  216.   train_datasets, train_size, valid_size)
  217. _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)
  218.  
  219. print('Training:', train_dataset.shape, train_labels.shape)
  220. print('Validation:', valid_dataset.shape, valid_labels.shape)
  221. print('Testing:', test_dataset.shape, test_labels.shape)
  222.  
  223. # Randomize the data
  224. def randomize(dataset, labels):
  225.   permutation = np.random.permutation(labels.shape[0])
  226.   shuffled_dataset = dataset[permutation,:,:]
  227.   shuffled_labels = labels[permutation]
  228.   return shuffled_dataset, shuffled_labels
  229. train_dataset, train_labels = randomize(train_dataset, train_labels)
  230. test_dataset, test_labels = randomize(test_dataset, test_labels)
  231. valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)
  232.  
  233. ################################################################
  234. ## PROBLEM 4
  235. ################################################################
  236. #for i in range(10):
  237. #    print("Train label ", train_labels[i], " :")
  238. #    plt.show()
  239. #    plt.imshow(train_dataset[i])
  240.  
  241. ###############################################################    
  242. # Save the data for later reuse
  243. pickle_file = os.path.join(data_root, 'notMNIST.pickle')
  244.  
  245. try:
  246.   f = open(pickle_file, 'wb')
  247.   save = {
  248.     'train_dataset': train_dataset,
  249.     'train_labels': train_labels,
  250.     'valid_dataset': valid_dataset,
  251.     'valid_labels': valid_labels,
  252.     'test_dataset': test_dataset,
  253.     'test_labels': test_labels,
  254.     }
  255.   pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)
  256.   f.close()
  257. except Exception as e:
  258.   print('Unable to save data to', pickle_file, ':', e)
  259.   raise
  260.    
  261. statinfo = os.stat(pickle_file)
  262. print('Compressed pickle size:', statinfo.st_size)
  263.  
  264. ################################################################
  265. ## PROBLEM 5
  266. ################################################################
  267. #import time
  268. #
  269. #def check_overlaps(images1, images2):
  270. #    images1.flags.writeable=False
  271. #    images2.flags.writeable=False
  272. #    start = time.clock()
  273. #    hash1 = set([hash(bytes(image1)) for image1 in images1])
  274. #    hash2 = set([hash(bytes(image2)) for image2 in images2])
  275. #    all_overlaps = set.intersection(hash1, hash2)
  276. #    return all_overlaps, time.clock()-start
  277. #
  278. #print("\n")
  279. #r, execTime = check_overlaps(train_dataset, test_dataset)    
  280. #print('Number of overlaps between training and test sets: {}. Execution time: {}.'.format(len(r), execTime))
  281. #
  282. #r, execTime = check_overlaps(train_dataset, valid_dataset)  
  283. #print('Number of overlaps between training and validation sets: {}. Execution time: {}.'.format(len(r), execTime))
  284. #
  285. #r, execTime = check_overlaps(valid_dataset, test_dataset)
  286. #print('Number of overlaps between validation and test sets: {}. Execution time: {}.'.format(len(r), execTime))
  287.  
  288. ################################################################
  289. ## PROBLEM 6
  290. ################################################################
  291. # Here we have 200000 samples
  292. # 28 x 28 features
  293. # We have to reshape them because scikit-learn expects (n_samples, n_features)
  294.  
  295. # Prepare training data
  296. samples, width, height = train_dataset[:].shape
  297. X_train = np.reshape(train_dataset[:],(samples,width*height))
  298. y_train = train_labels[:]
  299. #print(y_train)
  300. #for i in range(10):
  301. #    plt.show()
  302. #    plt.imshow(train_dataset[i])
  303.  
  304. # Prepare testing data
  305. samples, width, height = test_dataset.shape
  306. X_test = np.reshape(test_dataset,(samples,width*height))
  307. y_test = test_labels
  308.  
  309. # Instantiate
  310. lg = LogisticRegression(multi_class='multinomial', solver='saga', random_state=42, verbose=1, max_iter=1000, n_jobs=-1)
  311. #lg = LogisticRegression(C=50. / train_dataset.shape[0], multi_class='multinomial', penalty='l1', solver='saga', tol=0.1)
  312.  
  313. # Fit
  314. lg.fit(X_train, y_train)
  315.  
  316. # Predict
  317. y_pred = lg.predict(X_test)
  318.  
  319. # Score
  320. from sklearn import metrics
  321. print(metrics.accuracy_score(y_test, y_pred))
Advertisement
Add Comment
Please, Sign In to add comment