<jupyter_start><jupyter_text>Deep Learning=============Assignment 1------------The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.This notebook uses the [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) dataset to be used with python experiments. This dataset is designed to look like the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST.<jupyter_code># These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle

# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline<jupyter_output><empty_output><jupyter_text>First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labeled examples. Given these sizes, it should be possible to train models quickly on any machine.<jupyter_code>url = 'https://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None
data_root = '.' # Change me to store data elsewhere

def download_progress_hook(count, blockSize, totalSize):
  """A hook to report the progress of a download. This is mostly intended for users with
  slow internet connections. Reports every 5% change in download progress.
  """
  global last_percent_reported
  percent = int(count * blockSize * 100 / totalSize)

  if last_percent_reported != percent:
    if percent % 5 == 0:
      sys.stdout.write("%s%%" % percent)
      sys.stdout.flush()
    else:
      sys.stdout.write(".")
      sys.stdout.flush()
      
    last_percent_reported = percent
        
def maybe_download(filename, expected_bytes, force=False):
  """Download a file if not present, and make sure it's the right size."""
  dest_filename = os.path.join(data_root, filename)
  if force or not os.path.exists(dest_filename):
    print('Attempting to download:', filename) 
    filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)
    print('\nDownload Complete!')
  statinfo = os.stat(dest_filename)
  if statinfo.st_size == expected_bytes:
    print('Found and verified', dest_filename)
  else:
    raise Exception(
      'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')
  return dest_filename

train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)
test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)<jupyter_output>Found and verified ./notMNIST_large.tar.gz
Found and verified ./notMNIST_small.tar.gz<jupyter_text>Extract the dataset from the compressed .tar.gz file.This should give you a set of directories, labeled A through J.<jupyter_code>num_classes = 10
np.random.seed(133)

def maybe_extract(filename, force=False):
  root = os.path.splitext(os.path.splitext(filename)[0])[0]  # remove .tar.gz
  if os.path.isdir(root) and not force:
    # You may override by setting force=True.
    print('%s already present - Skipping extraction of %s.' % (root, filename))
  else:
    print('Extracting data for %s. This may take a while. Please wait.' % root)
    tar = tarfile.open(filename)
    sys.stdout.flush()
    tar.extractall(data_root)
    tar.close()
  data_folders = [
    os.path.join(root, d) for d in sorted(os.listdir(root))
    if os.path.isdir(os.path.join(root, d))]
  if len(data_folders) != num_classes:
    raise Exception(
      'Expected %d folders, one per class. Found %d instead.' % (
        num_classes, len(data_folders)))
  print(data_folders)
  return data_folders
  
train_folders = maybe_extract(train_filename)
test_folders = maybe_extract(test_filename)<jupyter_output>./notMNIST_large already present - Skipping extraction of ./notMNIST_large.tar.gz.
['./notMNIST_large/A', './notMNIST_large/B', './notMNIST_large/C', './notMNIST_large/D', './notMNIST_large/E', './notMNIST_large/F', './notMNIST_large/G', './notMNIST_large/H', './notMNIST_large/I', './notMNIST_large/J']
./notMNIST_small already present - Skipping extraction of ./notMNIST_small.tar.gz.
['./notMNIST_small/A', './notMNIST_small/B', './notMNIST_small/C', './notMNIST_small/D', './notMNIST_small/E', './notMNIST_small/F', './notMNIST_small/G', './notMNIST_small/H', './notMNIST_small/I', './notMNIST_small/J']<jupyter_text>---Problem 1---------Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display.---<jupyter_code>import random
#Image(filename='test.png') 


#Taken from https://stackoverflow.com/questions/36006136/how-to-display-images-in-a-row-with-ipython-display/38556650
from matplotlib.pyplot import figure, imshow, axis
from matplotlib.image import imread

def showImagesHorizontally(list_of_files):
    fig = figure()
    number_of_files = len(list_of_files)
    for i in range(number_of_files):
        a=fig.add_subplot(1,number_of_files,i+1)  # nrows, ncols, index. So, add a subplot at that position.
        image = imread(list_of_files[i])  # apparently you can read a list of files as one image?
        imshow(image,cmap='Greys_r')  # show image as grey
#         imshow(image)  # yup, looks odd if you don't use the cmap
        axis('off')   # turn off axis lines and labels.
        
#END COPIED CODE FROM https://stackoverflow.com/questions/36006136/how-to-display-images-in-a-row-with-ipython-display/38556650        

exemplars_per_folder = 10  #note that the images are scaled to 

exemplars_by_folder = []
for folder in test_folders:
    filenames = os.listdir(folder)
    folder_exemplars = []
    for i in range(0, exemplars_per_folder):
        
        file_choice = random.choice(filenames)
        path_to_chosen_file = os.path.join(folder, file_choice)
        folder_exemplars.append(path_to_chosen_file)
    exemplars_by_folder.append(folder_exemplars)

    
for folder in exemplars_by_folder:
    # using code from https://stackoverflow.com/questions/36006136/how-to-display-images-in-a-row-with-ipython-display/38556650        
    showImagesHorizontally(folder)
    
    # the way I did it at first: 
#     for exemplar in folder:
#         display(Image(exemplar))<jupyter_output><empty_output><jupyter_text>Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size.We'll 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. A few images might not be readable, we'll just skip them.<jupyter_code>image_size = 28  # Pixel width and height.
pixel_depth = 255.0  # Number of levels per pixel.

def load_letter(folder, min_num_images):
  """Load the data for a single letter label."""
  image_files = os.listdir(folder)
  dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
                         dtype=np.float32)
  print(folder)
  num_images = 0
  for image in image_files:
    image_file = os.path.join(folder, image)
    try:
      image_data = (imageio.imread(image_file).astype(float) - 
                    pixel_depth / 2) / pixel_depth
      if image_data.shape != (image_size, image_size):
        raise Exception('Unexpected image shape: %s' % str(image_data.shape))
      dataset[num_images, :, :] = image_data
      num_images = num_images + 1
    except (IOError, ValueError) as e:
      print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
    
  dataset = dataset[0:num_images, :, :]
  if num_images < min_num_images:
    raise Exception('Many fewer images than expected: %d < %d' %
                    (num_images, min_num_images))
    
  print('Full dataset tensor:', dataset.shape)
  print('Mean:', np.mean(dataset))
  print('Standard deviation:', np.std(dataset))
  return dataset
        
def maybe_pickle(data_folders, min_num_images_per_class, force=False):
  dataset_names = []
  for folder in data_folders:
    set_filename = folder + '.pickle'
    dataset_names.append(set_filename)
    if os.path.exists(set_filename) and not force:
      # You may override by setting force=True.
      print('%s already present - Skipping pickling.' % set_filename)
    else:
      print('Pickling %s.' % set_filename)
      dataset = load_letter(folder, min_num_images_per_class)
      try:
        with open(set_filename, 'wb') as f:
          pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)
      except Exception as e:
        print('Unable to save data to', set_filename, ':', e)
  
  return dataset_names

train_datasets = maybe_pickle(train_folders, 45000)
test_datasets = maybe_pickle(test_folders, 1800)<jupyter_output>./notMNIST_large/A.pickle already present - Skipping pickling.
./notMNIST_large/B.pickle already present - Skipping pickling.
./notMNIST_large/C.pickle already present - Skipping pickling.
./notMNIST_large/D.pickle already present - Skipping pickling.
./notMNIST_large/E.pickle already present - Skipping pickling.
./notMNIST_large/F.pickle already present - Skipping pickling.
./notMNIST_large/G.pickle already present - Skipping pickling.
./notMNIST_large/H.pickle already present - Skipping pickling.
./notMNIST_large/I.pickle already present - Skipping pickling.
./notMNIST_large/J.pickle already present - Skipping pickling.
./notMNIST_small/A.pickle already present - Skipping pickling.
./notMNIST_small/B.pickle already present - Skipping pickling.
./notMNIST_small/C.pickle already present - Skipping pickling.
./notMNIST_small/D.pickle already present - Skipping pickling.
./notMNIST_small/E.pickle already present - Skipping pickling.
./notMNIST_small/F.pickle already present - Skipping pi[...]<jupyter_text>---Problem 2---------Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot.---<jupyter_code>#<NAME>'s solution to Problem 2. 
# unpickling takes forever so I'm breaking it out into its own cell

def load_pickled_dataset(name_of_pickle_file):
    pkl_file = open(name_of_pickle_file, 'rb')
    data = pickle.load(pkl_file)
    return data


def unpickle_datasets(datasets):
    unpickled_datasets = []
    for dataset in datasets:
        print("unpickling dataset {}...".format(dataset))
        data = load_pickled_dataset(dataset)

        unpickled_datasets.append(data)
    return unpickled_datasets

unpickled_train = unpickle_datasets(train_datasets)
unpickled_test = unpickle_datasets(test_datasets)

#Problem 2 solution, part 2: pick at random from unpickled data, and display.
def show_images(list_of_images):
    fig = figure()
    number_of_images = len(list_of_images)
    for i in range(number_of_images):
        a=fig.add_subplot(1,number_of_images,i+1)  # nrows, ncols, index. So, add a subplot at that position.
        image = list_of_images[i]
        imshow(image,cmap='Greys_r')  # show image as grey
        axis('off')   # turn off axis lines and labels.
    plt.show()
        


def get_one_sample_from_each_dataset(datasets):
    
    samples = []
    for dataset in datasets:
        pic = random.choice(dataset)
        samples.append(pic)
    return samples
        

    
train_samples = get_one_sample_from_each_dataset(unpickled_train)
test_samples = get_one_sample_from_each_dataset(unpickled_train)

# print(train_samples)

show_images(train_samples)
show_images(test_samples)<jupyter_output><empty_output><jupyter_text>---Problem 3---------Another check: we expect the data to be balanced across classes. Verify that.---<jupyter_code># how the heck do I do that. 

def get_some_exemplars(unpickled_class_dataset, number=5):
    exemplars = []
    for i in range(0,number):
        exemplars.append(random.choice(unpickled_class_dataset))
        
    return exemplars
    

def get_dataset_stats(unpickled_datasets, name):
    for index, class_dataset in enumerate(unpickled_datasets):
        class_exemplars = get_some_exemplars(class_dataset)
        
        print("Getting examples for {0}, class #{1}".format(name, index))
        print("Some examples of this class:")
        show_images(class_exemplars)        
        print("for this class we have {0} data items\n\n".format(len(class_dataset)))
        
    
get_dataset_stats(unpickled_train, "train data")
get_dataset_stats(unpickled_test, "test data")<jupyter_output>Getting examples for train data, class #0
Some examples of this class:<jupyter_text>Merge and prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune `train_size` as needed. The labels will be stored into a separate array of integers 0 through 9.Also create a validation dataset for hyperparameter tuning.<jupyter_code>def make_arrays(nb_rows, img_size):
  if nb_rows:
    dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)
    labels = np.ndarray(nb_rows, dtype=np.int32)
  else:
    dataset, labels = None, None
  return dataset, labels

def merge_datasets(pickle_files, train_size, valid_size=0):
  num_classes = len(pickle_files)
  valid_dataset, valid_labels = make_arrays(valid_size, image_size)
  train_dataset, train_labels = make_arrays(train_size, image_size)
  vsize_per_class = valid_size // num_classes
  tsize_per_class = train_size // num_classes
    
  start_v, start_t = 0, 0
  end_v, end_t = vsize_per_class, tsize_per_class
  end_l = vsize_per_class+tsize_per_class
  for label, pickle_file in enumerate(pickle_files):       
    try:
      with open(pickle_file, 'rb') as f:
        letter_set = pickle.load(f)
        # let's shuffle the letters to have random validation and training set
        np.random.shuffle(letter_set)
        if valid_dataset is not None:
          valid_letter = letter_set[:vsize_per_class, :, :]
          valid_dataset[start_v:end_v, :, :] = valid_letter
          valid_labels[start_v:end_v] = label
          start_v += vsize_per_class
          end_v += vsize_per_class
                    
        train_letter = letter_set[vsize_per_class:end_l, :, :]
        train_dataset[start_t:end_t, :, :] = train_letter
        train_labels[start_t:end_t] = label
        start_t += tsize_per_class
        end_t += tsize_per_class
    except Exception as e:
      print('Unable to process data from', pickle_file, ':', e)
      raise
    
  return valid_dataset, valid_labels, train_dataset, train_labels
            
            
train_size = 200000
valid_size = 10000
test_size = 10000

valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(
  train_datasets, train_size, valid_size)
_, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)

print('Training:', train_dataset.shape, train_labels.shape)
print('Validation:', valid_dataset.shape, valid_labels.shape)
print('Testing:', test_dataset.shape, test_labels.shape)<jupyter_output>Training: (200000, 28, 28) (200000,)
Validation: (10000, 28, 28) (10000,)
Testing: (10000, 28, 28) (10000,)<jupyter_text>Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match.<jupyter_code>def randomize(dataset, labels):
  permutation = np.random.permutation(labels.shape[0])
  shuffled_dataset = dataset[permutation,:,:]
  shuffled_labels = labels[permutation]
  return shuffled_dataset, shuffled_labels
train_dataset, train_labels = randomize(train_dataset, train_labels)
test_dataset, test_labels = randomize(test_dataset, test_labels)
valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)<jupyter_output><empty_output><jupyter_text>---Problem 4---------Convince yourself that the data is still good after shuffling!---<jupyter_code>#problem 4 solution:
label_to_char = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j'}
    

def labels_to_chars(labels):
    label_chars =[]
    for label in labels:
        label_char = label_to_char[label]
        label_chars.append(label_char)
    return label_chars
    
def get_matching_items_randomly_from_two_lists(first, second, num_tuples=5):
    #assuming the length is the same...
    max_index = len(first)-1
    
    #solution adapted from https://stackoverflow.com/questions/19485641/python-random-sample-of-two-arrays-but-matching-indices
    idx = np.random.choice(np.arange(len(first)), num_tuples, replace=False)
    
#     print("picking {0} random items using idx {1}".format(num_tuples, idx))
#     print(type(idx))
    first_samples = first[idx]
    second_samples = second[idx]
    
    return first_samples, second_samples

def check_after_shuffle(dataset_name, dataset_to_check, labels_to_check, num_samples=15):

    imgs, labels = get_matching_items_randomly_from_two_lists(dataset_to_check, labels_to_check,num_samples)


    label_chars = labels_to_chars(labels)

    print("sample {0} labels:{1}".format(dataset_name,label_chars))
    show_images(imgs)    

num_samples = 12
check_after_shuffle("train", train_dataset, train_labels, num_samples)    
check_after_shuffle("val", valid_dataset, valid_labels, num_samples)    
check_after_shuffle("test", test_dataset, test_labels, num_samples)<jupyter_output>sample train labels:['i', 'd', 'i', 'd', 'i', 'i', 'f', 'd', 'b', 'g', 'c', 'i']<jupyter_text>Finally, let's save the data for later reuse:<jupyter_code>pickle_file = os.path.join(data_root, 'notMNIST.pickle')

try:
  f = open(pickle_file, 'wb')
  save = {
    'train_dataset': train_dataset,
    'train_labels': train_labels,
    'valid_dataset': valid_dataset,
    'valid_labels': valid_labels,
    'test_dataset': test_dataset,
    'test_labels': test_labels,
    }
  pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)
  f.close()
except Exception as e:
  print('Unable to save data to', pickle_file, ':', e)
  raise
statinfo = os.stat(pickle_file)
print('Compressed pickle size:', statinfo.st_size)<jupyter_output>Compressed pickle size: 690800441<jupyter_text>---Problem 5---------By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it.Measure how much overlap there is between training, validation and test samples.Optional questions:- What about near duplicates between datasets? (images that are almost identical)- Create a sanitized validation and test set, and compare your accuracy on those in subsequent assignments.---<jupyter_code># train_dataset = test_dataset
# valid_dataset = test_dataset

# Checking overlap: how the heck would I do this? Check filenames? Hashing?
def generate_hashes(list_of_numpy_arrays):
    list_of_numpy_arrays.flags.writeable=False
    hashes=[hash(item.data) for item in list_of_numpy_arrays]
    return hashes


def check_within_dataset(hashes, hashes_set, name):
    hashes_len = len(hashes)
    set_len = len(hashes_set)
    diff = hashes_len-set_len
    print("within {0} dataset, there are {1} items, but only {2} unique items, which works out to {3} items that are repeats".format(name, hashes_len, set_len, diff))
    return diff

    
def check_intersections(set1, set2, name1, name2):
    intersections=set1.intersection(set2)
    print("between {0} and {1} there are {2} unique items that are in both at least once".format(name1,name2,len(intersections)))
    return intersections
    

    
    
train_hashes = generate_hashes(train_dataset)
valid_hashes = generate_hashes(valid_dataset)
test_hashes = generate_hashes(test_dataset)


# train_hashes = [1, 2, 3]
# valid_hashes = [1, 2, 3]
# test_hashes = [1, 2, 3, 3]

train_hashes_set=set(train_hashes)
train_repeats = check_within_dataset(train_hashes,train_hashes_set, "train")


valid_hashes_set = set(valid_hashes)
valid_repeats = check_within_dataset(valid_hashes,valid_hashes_set, "valid")


test_hashes_set=set(test_hashes)
test_repeats = check_within_dataset(test_hashes,test_hashes_set, "test") 

repeats_within_datasets = train_repeats + valid_repeats + test_repeats
print("Total repeats within datasets: {}".format(repeats_within_datasets))

train_val_intersections = check_intersections(train_hashes_set, valid_hashes_set, "train", "valid")
train_test_intersections = check_intersections(train_hashes_set, test_hashes_set, "train", "valid")
val_test_intersections = check_intersections(valid_hashes_set, test_hashes_set, "valid", "test")

intersected_train_items = train_val_intersections.union(train_test_intersections)
intersected_valid_items = train_val_intersections.union(val_test_intersections)
intersected_test_items = train_test_intersections.union(val_test_intersections)

print("Number of unique items in {} that can be found in other sets: {}".format("train",len(intersected_train_items)))
print("Number of unique items in {} that can be found in other sets: {}".format("valid",len(intersected_valid_items)))
print("Number of unique items in {} that can be found in other sets: {}".format("test",len(intersected_test_items)))

all_hashes = train_hashes+valid_hashes+test_hashes
all_hashes_set = set(all_hashes)
all_repeats = check_within_dataset(all_hashes, all_hashes_set, "all")
repeats_percent = float(all_repeats)/float(len(all_hashes)) * 100



items_only_in_train = train_hashes_set - valid_hashes_set - test_hashes_set
items_only_in_valid = valid_hashes_set - train_hashes_set - test_hashes_set
items_only_in_test = test_hashes_set - train_hashes_set - valid_hashes_set

print("There are {} items that only exist in train".format(len(items_only_in_train)))
print("There are {} items that only exist in valid".format(len(items_only_in_valid)))
print("There are {} items that only exist in test".format(len(items_only_in_test)))


set([1, 2, 3]) - set([2]) - set([3])


print("Total percentage of repeat items in all datasets is about {:.2f} %".format(repeats_percent))
print("Total number of repeat items in all datasets is {}".format(all_repeats))
repeats_due_to_overlap = all_repeats - repeats_within_datasets
overlap_percent = float(repeats_due_to_overlap)/float(len(all_hashes)) *100
print("We previously found that repeats within datasets totaled to {}".format(repeats_within_datasets))
print("Repeats due to overlap is therefore {0}. \nOut of {1} total items, that gives an overlap percentage of {2:.2f}%".format(repeats_due_to_overlap, len(all_hashes), overlap_percent))<jupyter_output>within train dataset, there are 200000 items, but only 187350 unique items, which works out to 12650 items that are repeats
within valid dataset, there are 10000 items, but only 9863 unique items, which works out to 137 items that are repeats
within test dataset, there are 10000 items, but only 9802 unique items, which works out to 198 items that are repeats
Total repeats within datasets: 12985
between train and valid there are 1003 unique items that are in both at least once
between train and valid there are 1174 unique items that are in both at least once
between valid and test there are 72 unique items that are in both at least once
Number of unique items in train that can be found in other sets: 2153
Number of unique items in valid that can be found in other sets: 1051
Number of unique items in test that can be found in other sets: 1222
within all dataset, there are 220000 items, but only 204790 unique items, which works out to 15210 items that are repeats
There are 185197 items th[...]<jupyter_text>---Problem 6---------Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it.Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model.Optional question: train an off-the-shelf model on all the data!---<jupyter_code>#Training time. 

def reshape_to_sklearn_format(dataset):
    num_items, nx, ny = dataset.shape
    return dataset.reshape(num_items, nx*ny)
    
    

default_settings_classifier = LogisticRegression()


num_to_train_with = 500
#num_to_train_with = len(train_dataset)
#sample_data_for_training, sample_labels_for_training = train_dataset[:num_to_train_with], train_labels[:num_to_train_with]
sample_data_for_training, sample_labels_for_training = get_matching_items_randomly_from_two_lists(train_dataset, train_labels, num_to_train_with)

num_to_test_with = 1010
sample_data_for_testing, sample_labels_for_testing = get_matching_items_randomly_from_two_lists(train_dataset, train_labels, num_to_test_with)

# Gotta reshape, according to https://stackoverflow.com/questions/34972142/sklearn-logistic-regression-valueerror-found-array-with-dim-3-estimator-expec
# Basically we want the 28x28 images flattened out. 
sample_data_for_training = reshape_to_sklearn_format(sample_data_for_training)
sample_data_for_testing = reshape_to_sklearn_format(sample_data_for_testing) 




default_settings_classifier.fit(sample_data_for_training, sample_labels_for_training)
df_score = default_settings_classifier.score(sample_data_for_testing, sample_labels_for_testing)

# Settings lifted from 
# http://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html
# without understanding
fancy_settings_classifier = LogisticRegression(C=50. / num_to_train_with,
                         multi_class='multinomial',
                         penalty='l1', solver='saga', tol=0.1)
fancy_settings_classifier.fit(sample_data_for_training, sample_labels_for_training)
fs_score = fancy_settings_classifier.score(sample_data_for_testing, sample_labels_for_testing)


fancy_settings_classifier_l2 = LogisticRegression(C=50. / num_to_train_with,
                         multi_class='multinomial',
                         penalty='l2', solver='saga', tol=0.1)
fancy_settings_classifier_l2.fit(sample_data_for_training, sample_labels_for_training)
fs_l2_score = fancy_settings_classifier_l2.score(sample_data_for_testing, sample_labels_for_testing)

print("Score for classifier with default settings: {}".format(df_score))
print("Score for classifier with fancy settings and l1: {}".format(fs_score))
print("Score for classifier with fancy settings and l2: {}".format(fs_l2_score))

solver_list = ['newton-cg', 'lbfgs', 'sag', 'saga']

for choice in solver_list:
    print("trying solver {}".format(choice)))
    classifier = LogisticRegression(solver=choice, penalty='l2')
    classifier.fit(sample_data_for_training, sample_labels_for_training)
    classifier.score(sample_data_for_testing, sample_labels_for_testing)
    print("Score for classifier using solver {0}: {1}".format(choice, df_score))<jupyter_output>Score for classifier with default settings: 0.774257425743
Score for classifier with fancy settings: 0.70396039604
Score for classifier with fancy settings and l2: 0.805940594059
Score for classifier using solver newton-cg: 0.774257425743
Score for classifier using solver lbfgs: 0.774257425743
Score for classifier using solver sag: 0.774257425743
Score for classifier using solver saga: 0.774257425743
StarcoderdataJupyterStructuredCleanDedup