path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
algoExpert/boggle_board/solution.ipynb
###Markdown Boggle Board[link](https://www.algoexpert.io/questions/Boggle%20Board) My Solution ###Code def boggleBoard(board, words): # Write your code here. t = Trie() t.addWords(words) wordsSet = set() for i in range(len(board)): for j in range(len(board[i])): coor = (i, j) traverseCheck(board, coor, t, set(), wordsSet) return list(wordsSet) def traverseCheck(board, coor, trie, visited, wordsSet): i, j = coor if trie.isWordEnd == True: wordsSet.add(trie.fullword) if trie.chars == {}: return True if i < 0 or i >= len(board): return False if j < 0 or j >= len(board[i]): return False if (i, j) in visited: return False c = board[i][j] if c not in trie.chars: return False visited.add((i, j)) nextTrie = trie.chars[c] nextCoors = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1), \ (i - 1, j - 1), (i + 1, j + 1), (i - 1, j + 1), (i + 1, j - 1)] for coor in nextCoors: traverseCheck(board, coor, nextTrie, visited, wordsSet) visited.remove((i, j)) class Trie: def __init__(self, isWordEnd=False): self.chars = {} self.isWordEnd = isWordEnd self.fullword = "" def addWord(self, word): currentTrie = self for c in word: if c not in currentTrie.chars: currentTrie.chars[c] = Trie() currentTrie = currentTrie.chars[c] currentTrie.isWordEnd = True currentTrie.fullword = word def addWords(self, words): for word in words: self.addWord(word) ###Output _____no_output_____ ###Markdown Expert Solution ###Code # O(nm*8^s + ws) time | O(nm + ws) space def boggleBoard(board, words): trie = Trie() for word in words: trie.add(word) finalWords = {} visited = [[False for letter in row] for row in board] for i in range(len(board)): for j in range(len(board[i])): explore(i, j, board, trie.root, visited, finalWords) return list(finalWords.keys()) def explore(i, j, board, trieNode, visited, finalWords): if visited[i][j]: return letter = board[i][j] if letter not in trieNode: return visited[i][j] = True trieNode = trieNode[letter] if "*" in trieNode: finalWords[trieNode["*"]] = True neighbors = getNeighbors(i, j, board) for neighbor in neighbors: explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords) visited[i][j] = False def getNeighbors(i, j, board): neighbors = [] if i > 0 and j > 0: neighbors.append([i - 1, j - 1]) if i > 0 and j < len(board[0]) - 1: neighbors.append([i - 1, j + 1]) if i < len(board) - 1 and j < len(board[0]) - 1: neighbors.append([i + 1, j + 1]) if i < len(board) - 1 and j > 0: neighbors.append([i + 1, j - 1]) if i > 0: neighbors.append([i - 1, j]) if i < len(board) - 1: neighbors.append([i + 1, j]) if j > 0: neighbors.append([i, j - 1]) if j < len(board[0]) - 1: neighbors.append([i, j + 1]) return neighbors class Trie: def __init__(self): self.root ={} self.endSymbol = "*" def add(self, word): current = self.root for letter in word: if letter not in current: current[letter] = {} current = current[letter] current[self.endSymbol] = word ###Output _____no_output_____
LexiconSize/.ipynb_checkpoints/Create English Language Complete Set (preprocessing with lemmatization)-checkpoint.ipynb
###Markdown Google Ngrams Analysis An Evolutionary InvestigationThe purpose of this is to filter through the entire dataset without limiting years. It will create \*\-COMPLETE.json files. It can be used to find the size of the lexicon. [Original Ngrams analysis](https://github.com/Aaronasnx/Google-preprocessing/blob/main/ngram%20project.ipynb) ###Code import os import gzip import json #for progress bars from tqdm import tqdm from nltk import WordNetLemmatizer lemmatizer = WordNetLemmatizer() #For checking if the word has any non-English-alphabetical letters #import sys #!{sys.executable} -m pip install Unidecode from unidecode import unidecode import re #For the Google POS tagging mapping underscore = re.compile('_{1}') ###Output _____no_output_____ ###Markdown [NLTK POS Lemmatizer](https://www.nltk.org/_modules/nltk/stem/wordnet.html)The Part Of Speech tag. Valid options are `"n"` for nouns, `"v"` for verbs, `"a"` for adjectives, `"r"` for adverbs and `"s"` for [satellite adjectives](https://stackoverflow.com/questions/18817396/what-part-of-speech-does-s-stand-for-in-wordnet-synsets). Syntax:`lemmatizer.lemmatize(word)` [Google Tags](https://books.google.com/ngrams/info)These tags can either stand alone (\_PRON\_) or can be appended to a word (she_PRON)- _NOUN_ - _VERB_ - _ADJ_ adjective- _ADV_ adverb- _PRON_ pronoun- _DET_ determiner or article- _ADP_ an adposition: either a preposition or a postposition- _NUM_ numeral- _CONJ_ conjunction- _PRT_ particle Define sets which are going to be used in the unigram tests ###Code import string PUNCTUATION = set(char for char in string.punctuation).union({'“','”'}) #ALPHABET = set(string.ascii_letters) DIGITS = set(string.digits) VOWELS = set("aeiouyAEIOUY") #Excluding '_' (underscore) from DASHES precludes the tagged 1grams "_NOUN", add it to also include the tagged 1grams DASHES = {'—','–','—','―','‒','-','_'} PUNCTUATION.difference_update(DASHES) STOPS = PUNCTUATION.union(DIGITS) #GOOGLE_TAGS = {'_NOUN','_VERB','_ADJ','_ADV','_PRON','_DET','_ADP','_NUM','_CONJ','_PRT'} #Demo of unidecode to show how will use it to filter out accents and non-English letters unidecode('días', errors='replace') unigram = 'kožušček' test = unidecode(unigram, errors='replace') if test == unigram: print('yes') pass else: print("no") ###Output no ###Markdown [How to open Gzip files](https://stackoverflow.com/questions/31028815/how-to-unzip-gz-file-using-python) ###Code def open_gzip(directory,file_path): with gzip.open(directory+file_path,'r') as f_in: rows = [x.decode('utf8').strip() for x in f_in.readlines()] return rows def save_json(ngram_dict,directory,file_path): output = file_path[:-3]+'-COMPLETE.json' if len(ngram_dict)>0: with open(directory+output, 'w') as f_out: json.dump(ngram_dict, f_out) print('SAVED: ',output,len(ngram_dict)) else: print('unigram dict empty',output) def csv2tuple(string): year,match_count,volume_count = tuple(string.split(',')) return int(year),int(match_count),int(volume_count) def unigram_tests(unigram): #Exclude words with more than one underscore, can make this != to only include tagged words if len(underscore.findall(unigram))!=1: return False #Checks each character in the unigram against the characters in the STOP set. (character level filtering) - no punctuation or digits allowed if set(unigram).intersection(STOPS): return False #Excluded all of the form _PRON_ (or anything that starts or ends with an underscore) if unigram[0] == '_' or unigram[-1] == '_': return False #must have a vowel (presupposes that it must also have a letter of the alphabet inside) if not set(unigram).intersection(VOWELS): return False #Words cannot start or end with dashes if unigram[0] in DASHES or unigram[-1] in DASHES: return False #must have 0 non-english letters test = unidecode(unigram, errors='replace') if test != unigram: return False #Can implement more tests here if you need to do more filtering else: return True #maps Google pos_tag to Wordnet pos_tag def POS_mapper(pos_tag): if pos_tag == 'NOUN': return "n" if pos_tag == 'VERB': return "v" if pos_tag == 'ADJ': return "a" if pos_tag == 'ADV': return "r" else: return "n" #Default for wordnet lemmatizer def preprocess_ngrams(directory,file_path): #rows = open_gzip(directory,file_path) ngram_dict = dict() #This implementation uses {1gram:{year:match_count ...} ...} i=0 for row in tqdm(open_gzip(directory,file_path)): columns = row.split('\t') #unigram is the first entry, the rest of the entries are of the form year,match_count,volume_count\t n times, where n is variable each line unigram = columns[0] #If it passes the word tests continue parsing and lemmatizing the unigram if unigram_tests(unigram): pos = "n" #Default for wordnet lemmatizer word_tag = underscore.split(unigram) # list of [word,tag] #maps Google tag to Wordnet tag pos = POS_mapper(word_tag[1]) #Removes the tag before processing unigram string unigram = word_tag[0] #Lemmatize based on POS unigram = lemmatizer.lemmatize(unigram.lower().strip(),pos) #Adds the tag back onto the unigram unigram+='_'+word_tag[1] #Parse the new entry and create a dictionary of records in form {year:match_count} records = dict() for entry in columns[1:]: year,match_count,volume_count = csv2tuple(str(entry)) #This is the crucial filtering by volume count because only words in >1 volume are reasonably assumed to be used by >1 person #Words only used by one person - which translates the computational parameter 1 volume - are not considered part of the lexicon if volume_count>1: records[year] = match_count #Modify the dictionary if new entry is already there, else just add it as a new unigram:records to the dict if unigram in ngram_dict.keys(): #accessing the ngram dictionary and seeing if each year is present, if so add match count, else add a new record entry to the dictionary. for yr, match_ct in records.items(): #each record should be of the form {year:match_count} #If the year in the new record is in the dict for this 1gram, then find where it is. if yr in ngram_dict[unigram].keys(): ngram_dict[unigram][yr] += match_ct else: #This just adds the record to the end, will need to sort later ngram_dict[unigram][yr] = match_ct else: ngram_dict[unigram] = records #Save as JSON save_json(ngram_dict,directory,file_path) %%time directory = '../Ngrams/unigram_data/' files = os.listdir(directory) for file_path in files: if '.gz' in file_path and not '.json' in file_path: preprocess_ngrams(directory,file_path) ###Output 100%|██████████| 2396510/2396510 [00:16<00:00, 142907.61it/s]
notebooks/model_generation/machine_learning_model_3_removed.ipynb
###Markdown Load libraries Base Imports ###Code import pandas as pd #import seaborn as sns import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown ML imports ###Code from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor from sklearn.ensemble import BaggingRegressor, AdaBoostRegressor, ExtraTreesRegressor from sklearn.neighbors import KNeighborsRegressor, RadiusNeighborsRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.linear_model import LinearRegression, SGDRegressor from sklearn.linear_model import Ridge, RidgeCV, BayesianRidge from sklearn.linear_model import HuberRegressor, TheilSenRegressor, RANSACRegressor from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import OneHotEncoder, StandardScaler, RobustScaler from sklearn.metrics import mean_squared_error, median_absolute_error, mean_absolute_error from sklearn.metrics import r2_score, explained_variance_score ###Output _____no_output_____ ###Markdown Load the datasets - Dataset de testing --> Febrero - 2019- Dataset de training --> Datos Anuales - 2018 ###Code train_data = pd.read_csv('C:\\Users\\yhoz\\Documents\\dataanalytics.predictive\\data\\ausol\\anual_data_18_mod.csv', delimiter=";") test_data = pd.read_csv('C:\\Users\\yhoz\\Documents\\dataanalytics.predictive\\data\\ausol\\monthly\\02-19.csv', delimiter=";") ###Output _____no_output_____ ###Markdown Filter & Clean the datasets ###Code # ----> train data # Clean train_data = train_data.drop_duplicates(['MES','FECHA', 'ID_SEGMENT'], keep='first').fillna(method='ffill') # fill with the last value train_data = train_data.dropna(how='all') train_data.rename(columns={'ID_SEGMENTO': 'ID_SEGMENT'}, inplace=True) # Add temporal features train_data['TIME'] =pd.to_datetime(train_data['FECHA']).map(lambda x: x.strftime('%d %H:%M:%S')) train_data.sort_values(by=['MES','TIME'], inplace=True) train_data = train_data.reset_index(drop=True) train_data['DIA']=pd.to_datetime(train_data['FECHA']).dt.day train_data = train_data.set_index(pd.DatetimeIndex(train_data['FECHA'])) # ----> test data # Clean test_data = test_data.drop_duplicates(['MES','FECHA', 'ID_SEGMENT'], keep='first').fillna(method='ffill') # fill with the last value test_data = test_data.dropna(how='all') # Add temporal features test_data['TIME'] =pd.to_datetime(test_data['FECHA']).map(lambda x: x.strftime('%d %H:%M:%S')) test_data.sort_values(by=['TIME'], inplace=True) test_data = test_data.reset_index(drop=True) test_data['DIA']=pd.to_datetime(test_data['FECHA']).dt.day test_data = test_data.set_index(pd.DatetimeIndex(test_data['FECHA'])) test_data.iloc[:,7:-1].loc[test_data['ID_SEGMENT']==1]['2019-02-01 00:00:00':'2019-02-02 00:00:00'].plot(linewidth=0.9, figsize=(20, 8)) ###Output _____no_output_____ ###Markdown Test specification Build the training sets ###Code cluster_features = ['ID_SEGMENT']#, 'COD_LABORALIDAD', 'MES'] excluded_features = ['TIME','FECHA'] excluded_features.extend(cluster_features) forecast_horizon = [15, 60, 120] print(excluded_features) #'models ids are based on cluster_code + '_' + 'time_horizon' mlmodels_dict = {'linear_regression':{'is_active': True, 'train_model': True, 'method':LinearRegression() }, 'ada_boost':{'is_active': True, 'train_model': True, 'method':AdaBoostRegressor() }, 'random_forest':{'is_active': True, 'train_model': True, 'method': RandomForestRegressor() }, 'extra_trees_1':{'is_active': True, 'train_model': True, 'method': ExtraTreesRegressor() }, 'extra_trees_2':{'is_active': True, 'train_model': True, 'method': ExtraTreesRegressor(min_samples_leaf=10) }, 'gradient_boosting':{'is_active': True, 'train_model': True, 'method': GradientBoostingRegressor() }, 'bagging_regressor':{'is_active': True, 'train_model': True, 'method': BaggingRegressor() }, 'mlp_neural_network':{'is_active': True,'train_model': True, 'method': MLPRegressor()}, 'kn_neighbors':{'is_active': True,'train_model': True,'method': KNeighborsRegressor(n_neighbors=2) }} ###Output _____no_output_____ ###Markdown Model training ###Code # It splits train data in clusters # cluster features should be provided based on a descriptive analytics # these features will be used for agent model specialization # an expert model will be specilized on different feature values ''' algorithm_name = 'RandomForest' model_expertise = { 'target': 'TOTAL_VEHICULOS', 'excluded_features': ['TIME','FECHA','ID_SEGMENTO', 'COD_LABORALIDAD'], 'cluster_features' : ['ID_SEGMENT', 'MES', 'COD_LABORALIDAD'], 'apply_rules': { 'rule':{ 'on_feature':'ID_SEGMENT', 'exclude_values': [], } }, } forecast_strategy = { 'method' : 'direct', # https://machinelearningmastery.com/multi-step-time-series-forecasting/ 'forecast_horizon' : [15, 60, 120], # minutes } ''' import itertools import copy clusters_codes = [element for element in itertools.product(*list(map(lambda x: train_data[x].unique().tolist(), cluster_features)))] if len(cluster_features)==1: clusters_codes = [code[0] for code in clusters_codes ] #print(clusters_codes) training_sets = dict.fromkeys(clusters_codes) # key: expert_code | value: train_set # fill the training sets Python dict for expert_code in training_sets: df_train = train_data # restore pandas dataframe if len(cluster_features)==1: df_train = df_train.loc[df_train[str(cluster_features[0])]==expert_code] else: for key, value in zip(cluster_features, expert_code): df_train = copy.deepcopy(df_train.loc[df_train[key]==value]) training_sets[expert_code] = copy.deepcopy(df_train) #print(training_sets[clusters_codes[1]].shape) clusters_codes[2] training_sets[clusters_codes[2]] import pickle store_model = True import copy def regression(regressor, regr_name, x_train, y_train): reg = copy.deepcopy(regressor.fit(x_train, y_train)) param_grid = {}#'n_estimators': [500], 'max_features': [10,15,20]} #reg = GridSearchCV(estimator=reg, param_grid=param_grid, n_jobs=1, cv=10, scoring='neg_mean_squared_error') print('Precision del modelo:') precision = reg.score(x_train, y_train) print(precision) if store_model: save_dir = os.path.join(os.getcwd(), regr_name) if not os.path.exists(save_dir): os.makedirs(save_dir) model_id = regr_name + '_' + str(cluster_code) + '_' + str(horizon) print("Model " + str(model_id) + " succesfully generated! Saving it...") model_path = os.path.join(regr_name, model_id + ".sav") pickle.dump(reg, open(model_path, 'wb')) return reg import os import copy for regr_name, regr_properties in mlmodels_dict.items(): if regr_properties['train_model']==True and regr_properties['is_active']==True: for cluster_code, trainset in training_sets.items(): # access the training sets for horizon in forecast_horizon: step = int(horizon/15) x_train = trainset.loc[:, trainset.columns.difference(excluded_features)][:-step] y_train = trainset['TOTAL_VEHICULOS'][step:] mlmodels_dict[regr_name][str(cluster_code) + '_' + str(horizon)] = regression(regr_properties['method'], regr_name, x_train, y_train) ###Output Precision del modelo: 0.9194649453245873 Model linear_regression_1_15 succesfully generated! Saving it... Precision del modelo: 0.837700129070815 Model linear_regression_1_60 succesfully generated! Saving it... Precision del modelo: 0.7182023628053515 Model linear_regression_1_120 succesfully generated! Saving it... Precision del modelo: 0.8942864563301446 Model linear_regression_2_15 succesfully generated! Saving it... Precision del modelo: 0.7683372655576228 Model linear_regression_2_60 succesfully generated! Saving it... Precision del modelo: 0.6286688707496167 Model linear_regression_2_120 succesfully generated! Saving it... Precision del modelo: 0.9214979898742744 Model linear_regression_3_15 succesfully generated! Saving it... Precision del modelo: 0.8397484158622748 Model linear_regression_3_60 succesfully generated! Saving it... Precision del modelo: 0.7181536280797448 Model linear_regression_3_120 succesfully generated! Saving it... Precision del modelo: 0.9079180958246043 Model linear_regression_4_15 succesfully generated! Saving it... Precision del modelo: 0.8085642814418569 Model linear_regression_4_60 succesfully generated! Saving it... Precision del modelo: 0.6612262575676795 Model linear_regression_4_120 succesfully generated! Saving it... Precision del modelo: 0.9072289888434618 Model linear_regression_6_15 succesfully generated! Saving it... Precision del modelo: 0.8080776718228382 Model linear_regression_6_60 succesfully generated! Saving it... Precision del modelo: 0.6608369997119046 Model linear_regression_6_120 succesfully generated! Saving it... Precision del modelo: 0.9366778109987591 Model linear_regression_7_15 succesfully generated! Saving it... Precision del modelo: 0.830008969514934 Model linear_regression_7_60 succesfully generated! Saving it... Precision del modelo: 0.6871736019184904 Model linear_regression_7_120 succesfully generated! Saving it... Precision del modelo: 0.8722529972493285 Model linear_regression_8_15 succesfully generated! Saving it... Precision del modelo: 0.7380935464852532 Model linear_regression_8_60 succesfully generated! Saving it... Precision del modelo: 0.571318939881945 Model linear_regression_8_120 succesfully generated! Saving it... Precision del modelo: 0.9330695177433604 Model linear_regression_9_15 succesfully generated! Saving it... Precision del modelo: 0.8253210639097354 Model linear_regression_9_60 succesfully generated! Saving it... Precision del modelo: 0.6875017965579626 Model linear_regression_9_120 succesfully generated! Saving it... Precision del modelo: 0.9168091884454104 Model linear_regression_10_15 succesfully generated! Saving it... Precision del modelo: 0.7797778461588301 Model linear_regression_10_60 succesfully generated! Saving it... Precision del modelo: 0.5805517703047103 Model linear_regression_10_120 succesfully generated! Saving it... Precision del modelo: 0.9389163697990169 Model linear_regression_11_15 succesfully generated! Saving it... Precision del modelo: 0.8338390899997274 Model linear_regression_11_60 succesfully generated! Saving it... Precision del modelo: 0.6764880247315886 Model linear_regression_11_120 succesfully generated! Saving it... Precision del modelo: 0.9179629145030358 Model linear_regression_12_15 succesfully generated! Saving it... Precision del modelo: 0.8069453439554384 Model linear_regression_12_60 succesfully generated! Saving it... Precision del modelo: 0.6658035741881945 Model linear_regression_12_120 succesfully generated! Saving it... Precision del modelo: 0.9096311586656031 Model linear_regression_13_15 succesfully generated! Saving it... Precision del modelo: 0.7567816473666185 Model linear_regression_13_60 succesfully generated! Saving it... Precision del modelo: 0.5343049707001409 Model linear_regression_13_120 succesfully generated! Saving it... Precision del modelo: 0.924659323545013 Model linear_regression_14_15 succesfully generated! Saving it... Precision del modelo: 0.8005055428174066 Model linear_regression_14_60 succesfully generated! Saving it... Precision del modelo: 0.6391935990568107 Model linear_regression_14_120 succesfully generated! Saving it... Precision del modelo: 0.9311097543514166 Model linear_regression_15_15 succesfully generated! Saving it... Precision del modelo: 0.8205247963598525 Model linear_regression_15_60 succesfully generated! Saving it... Precision del modelo: 0.6419363392029329 Model linear_regression_15_120 succesfully generated! Saving it... Precision del modelo: 0.9274386871485067 Model linear_regression_16_15 succesfully generated! Saving it... Precision del modelo: 0.8315281458161856 Model linear_regression_16_60 succesfully generated! Saving it... Precision del modelo: 0.6618841094700815 Model linear_regression_16_120 succesfully generated! Saving it... Precision del modelo: 0.8915962975774024 Model linear_regression_17_15 succesfully generated! Saving it... Precision del modelo: 0.7987095321591092 Model linear_regression_17_60 succesfully generated! Saving it... Precision del modelo: 0.6372207390642852 Model linear_regression_17_120 succesfully generated! Saving it... Precision del modelo: 0.8950210765762542 Model linear_regression_18_15 succesfully generated! Saving it... Precision del modelo: 0.7895534710876112 Model linear_regression_18_60 succesfully generated! Saving it... Precision del modelo: 0.6479201202032964 Model linear_regression_18_120 succesfully generated! Saving it... Precision del modelo: 0.8709342542742274 Model linear_regression_19_15 succesfully generated! Saving it... Precision del modelo: 0.6932169857211912 Model linear_regression_19_60 succesfully generated! Saving it... Precision del modelo: 0.48960723225955943 Model linear_regression_19_120 succesfully generated! Saving it... Precision del modelo: 0.6986802731341415 Model linear_regression_20_15 succesfully generated! Saving it... Precision del modelo: 0.5529430000292128 Model linear_regression_20_60 succesfully generated! Saving it... Precision del modelo: 0.3908285437974205 Model linear_regression_20_120 succesfully generated! Saving it... Precision del modelo: 0.9278986032180265 Model linear_regression_21_15 succesfully generated! Saving it... Precision del modelo: 0.8483431976049316 Model linear_regression_21_60 succesfully generated! Saving it... Precision del modelo: 0.6969323135333065 Model linear_regression_21_120 succesfully generated! Saving it... Precision del modelo: 0.9315713728363106 Model linear_regression_22_15 succesfully generated! Saving it... Precision del modelo: 0.8438103724145254 Model linear_regression_22_60 succesfully generated! Saving it... Precision del modelo: 0.6808545689317927 Model linear_regression_22_120 succesfully generated! Saving it... Precision del modelo: 0.9547680827678521 Model linear_regression_30_15 succesfully generated! Saving it... Precision del modelo: 0.8638807940021054 Model linear_regression_30_60 succesfully generated! Saving it... Precision del modelo: 0.6883533388066612 Model linear_regression_30_120 succesfully generated! Saving it... Precision del modelo: 0.9609086985716617 Model linear_regression_31_15 succesfully generated! Saving it... Precision del modelo: 0.8118689230123914 Model linear_regression_31_60 succesfully generated! Saving it... Precision del modelo: 0.5753916064988354 Model linear_regression_31_120 succesfully generated! Saving it... Precision del modelo: 0.9665857870076506 Model linear_regression_32_15 succesfully generated! Saving it... Precision del modelo: 0.8744698088243457 Model linear_regression_32_60 succesfully generated! Saving it... Precision del modelo: 0.7351003661694985 Model linear_regression_32_120 succesfully generated! Saving it... Precision del modelo: 0.9305524059447162 Model linear_regression_33_15 succesfully generated! Saving it... Precision del modelo: 0.8094562636992118 Model linear_regression_33_60 succesfully generated! Saving it... Precision del modelo: 0.6434487137041287 Model linear_regression_33_120 succesfully generated! Saving it... Precision del modelo: 0.9301469241227747 Model linear_regression_34_15 succesfully generated! Saving it... Precision del modelo: 0.8091488721931972 Model linear_regression_34_60 succesfully generated! Saving it... Precision del modelo: 0.6432014184564352 Model linear_regression_34_120 succesfully generated! Saving it... Precision del modelo: 0.9301465758075571 Model linear_regression_35_15 succesfully generated! Saving it... ###Markdown Sanity test ###Code mlmodels_dict['extra_trees_2'] import pickle store_results=True if store_results: save_path = os.path.join(os.getcwd(), 'direct_mlmodels_dict_' + str(cluster_features) + str(forecast_horizon) +'.sav') pickle.dump(mlmodels_dict, open(save_path, 'wb')) ###Output _____no_output_____ ###Markdown Model restoring ###Code import os import pickle for regr_name, regr_properties in mlmodels_dict.items(): if regr_properties['is_active']==True: for cluster_code, trainset in training_sets.items(): for horizon in forecast_horizon: model_file = regr_name + '_' + str(cluster_code) + '_' + str(horizon) + ".sav" model_path = os.path.join(os.getcwd(),regr_name, model_file) model_file = pickle.load( open(model_path, "rb" ) ) mlmodels_dict[regr_name][str(cluster_code) + '_' + str(horizon)] = model_file ###Output _____no_output_____ ###Markdown Model Evaluation ###Code store_results = True score_metrics = { 'score_metrics' : { 'ev': {'train':0, 'test':0}, 'r2': {'train':0, 'test':0}, 'mse': {'train':0, 'test':0}, 'mdae': {'train':0, 'test':0}, 'mae': {'train':0, 'test':0}, }, 'y_pred': {'train':0, 'test':0}, } def scores(model_id, regressor, model_name, x_train, x_test, y_train, y_test): evaluation_toolset=dict() y_train_reg=0 y_test_reg=0 evaluation_toolset[str(model_name)] = score_metrics y_train_reg = model.predict(x_train) evaluation_toolset[str(model_name)]['y_pred']['train'] = y_train_reg y_test_reg = model.predict(x_test) evaluation_toolset[str(model_name)]['y_pred']['test'] = y_test_reg evaluation_toolset[str(model_name)]['score_metrics']['ev']['train'] = explained_variance_score(y_train, y_train_reg) evaluation_toolset[str(model_name)]['score_metrics']['ev']['test'] = explained_variance_score(y_test, y_test_reg) evaluation_toolset[str(model_name)]['score_metrics']['r2']['train'] = r2_score(y_train, y_train_reg) evaluation_toolset[str(model_name)]['score_metrics']['r2']['test'] = r2_score(y_test, y_test_reg) evaluation_toolset[str(model_name)]['score_metrics']['mse']['train'] = mean_squared_error(y_train, y_train_reg) evaluation_toolset[str(model_name)]['score_metrics']['mse']['test'] = mean_squared_error(y_test, y_test_reg) evaluation_toolset[str(model_name)]['score_metrics']['mae']['train'] = mean_absolute_error(y_train, y_train_reg) evaluation_toolset[str(model_name)]['score_metrics']['mae']['test'] = mean_absolute_error(y_test, y_test_reg) evaluation_toolset[str(model_name)]['score_metrics']['mdae']['train'] = median_absolute_error(y_train, y_train_reg) evaluation_toolset[str(model_name)]['score_metrics']['mdae']['test'] = median_absolute_error(y_test, y_test_reg) print("______________________________________________________________________________") print(str(model_id)) print("______________________________________________________________________________") print("EV score. Train: ", evaluation_toolset[str(model_name)]['score_metrics']['ev']['train']) print("EV score. Test: ", evaluation_toolset[str(model_name)]['score_metrics']['ev']['test']) print("---------") print("R2 score. Train: ", evaluation_toolset[str(model_name)]['score_metrics']['r2']['train']) print("R2 score. Test: ", evaluation_toolset[str(model_name)]['score_metrics']['r2']['test']) print("---------") print("MSE score. Train: ", evaluation_toolset[str(model_name)]['score_metrics']['mse']['train']) print("MSE score. Test: ", evaluation_toolset[str(model_name)]['score_metrics']['mse']['test']) print("---------") print("MAE score. Train: ", evaluation_toolset[str(model_name)]['score_metrics']['mae']['train']) print("MAE score. Test: ", evaluation_toolset[str(model_name)]['score_metrics']['mae']['test'] ) print("---------") print("MdAE score. Train: ", evaluation_toolset[str(model_name)]['score_metrics']['mdae']['train']) print("MdAE score. Test: ", evaluation_toolset[str(model_name)]['score_metrics']['mdae']['test']) return evaluation_toolset # get the scores evals = [] for regr_name, regr_properties in mlmodels_dict.items(): if regr_properties['is_active']==True: for expert_code, trainset in training_sets.items(): for horizon in forecast_horizon: x_train = trainset.loc[:, trainset.columns.difference(excluded_features)][:-int(horizon/15)] y_train = trainset['TOTAL_VEHICULOS'][int(horizon/15):] df_test = test_data # restore pandas dataframe for key, value in zip(cluster_features, expert_code): x_test = df_test.loc[:, df_test.columns.difference(excluded_features)][:-int(horizon/15)] y_test = df_test['TOTAL_VEHICULOS'][int(horizon/15):] if regr_name == 'kn_neighbors': pass else: model = mlmodels_dict[regr_name][str(expert_code) + '_' + str(horizon)] model_id = regr_name + '_' + str(expert_code) + '_' + str(horizon) print(model_id) evals.append(scores(model_id, regr_properties['method'], model, x_train, x_test, y_train, y_test)) import pickle if store_results = True: save_path = os.path.join(os.getcwd(), 'test_result_' + str(cluster_features) + str(forecast_horizon) +'.sav') pickle.dump(reg, open(save_path, 'wb')) ### Result visualization import numpy as np import matplotlib.pyplot as plt ''' # data to plot n_groups = 4 means_frank = (90, 55, 40, 65) means_guido = (85, 62, 54, 20) # create plot fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.35 opacity = 0.8 rects1 = plt.bar(index, means_frank, bar_width, alpha=opacity, color='b', label='Frank') rects2 = plt.bar(index + bar_width, means_guido, bar_width, alpha=opacity, color='g', label='Guido') plt.xlabel('Person') plt.ylabel('Scores') plt.title('Scores by person') plt.xticks(index + bar_width, ('A', 'B', 'C', 'D')) plt.legend() plt.tight_layout() plt.show() algorithm_names = ['linear_regression', 'ada_boost', 'random_forest', 'extra_trees_1', 'extra_trees_2', 'gradient_boosting', 'bagging_regressor', 'mlp_neural_network', 'kn_neighbors' ''' for score_name, values in score_metrics['score_metrics'].items(): fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.35 opacity = 0.8 algorithm_names = [] score_train = [] score_test = [] for algorithm in evals: algo_name = algorithm.key algorithm_names.append(algo_name) score_train.append(algorithm.value['score_metrics'][str(score_name)]['train']) score_test.append(algorithm.value['score_metrics'][str(score_name)]['test']) rects1 = plt.bar(index, score_train, bar_width, alpha=opacity, color='b', label='train') rects2 = plt.bar(index, score_test, bar_width, alpha=opacity, color='g', label='test') plt.xlabel('Algorithm') plt.ylabel('Scores') plt.title('Scores by algorithm') plt.xticks(index + bar_width, (algorithm_names)) plt.legend() plt.tight_layout() plt.show() # model selection 'ID_SEGMENT', 'COD_LABORALIDAD', 'MES' i_segment = 1.0 i_mes = 3.0 i_cod_laboralidad = 2.0 regr_name = 'extra_trees_2' #train_data_march = train_data.loc[(train_data['ID_SEGMENT']==i_segment) & (train_data['MES']==i_mes) & (train_data['COD_LABORALIDAD']==i_cod_laboralidad)] model_id = '(1.0, 2.0, 1.0)_120' # '('+str(i_segment) + ', ' + str(i_mes) + ', ' +str(i_cod_laboralidad)+ ')_15' x_test_time = None test_data_2 = test_data.loc[(test_data['ID_SEGMENT']==1.0) & (test_data['MES']==2.0) & (test_data['COD_LABORALIDAD']==1)] # 'COD_LABORALIDAD', 'MES', cols = test_data_2.columns.difference(['FECHA','ID_SEGMENT','COD_LABORALIDAD', 'MES','TIME']).tolist() #'COD_LABORALIDAD', 'MES' x_test = test_data_2[cols] #test_data_2 %matplotlib inline #plt.figure(figsize=(40,40)) #plt.title("TOTAL VEHICULOS Regressors' Predictions vs Real Data" , fontsize=30) #plt.plot(test_data.TIME[0:400], y_test[0:400],'-o', markerfacecolor="blue", label='Real Data', linewidth=2, alpha=0.8) #plt.plot(train_data.TIME[0:400], y_train[0:400],'-o', markerfacecolor="orange", label='Train Data', linewidth=2, alpha=0.5) #y_test_pred = model.predict(test_data) ''' plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='MLPRegressor', linewidth=1, alpha=0.8) y_test_pred = ExtraTreesRegressor_2.predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='ExtraTreesRegressor', linewidth=1, alpha=0.8) y_test_pred = MLPRegressor.predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='MLPRegressor', linewidth=1, alpha=0.8) y_test_pred = RandomForestRegressor.predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='ExtraTreesRegressor', linewidth=1, alpha=0.8) ''' #for horizon, values in forecast_horizon: plt.figure(figsize=(40,40)) plt.title("120 TOTAL VEHICULOS Regressors' Predictions vs Real Data" , fontsize=30) y_test = test_data_2['2019-02-03 00:00:00':'2019-02-04 00:00:00']['TOTAL_VEHICULOS'] plt.plot(test_data_2['2019-02-03 00:00:00':'2019-02-04 00:00:00']['TIME'], y_test,'-o', markerfacecolor="blue", label='Real Data', linewidth=2, alpha=0.8) y_test_pred = mlmodels_dict[regr_name][model_id].predict(test_data_2['2019-02-03 00:00:00':'2019-02-04 00:00:00'][cols]) plt.plot(test_data_2['2019-02-03 00:00:00':'2019-02-04 00:00:00']['TIME'], y_test_pred,'-o', markerfacecolor="None" , label=regr_name, linewidth=1, alpha=0.8) plt.legend(loc='best', fontsize=30) plt.show() ###Output _____no_output_____ ###Markdown Comparativa ExtraTree Regressor & MLP Neural Network ###Code %matplotlib inline plt.figure(figsize=(40,40)) plt.title("TOTAL VEHICULOS Regressors' Predictions vs Real Data" , fontsize=30) plt.plot(test_data.TIME[0:400], y_test[0:400],'-o', markerfacecolor="blue", label='Real Data', linewidth=2, alpha=0.8) #plt.plot(train_data.TIME[0:400], y_train[0:400],'-o', markerfacecolor="orange", label='Train Data', linewidth=2, alpha=0.5) y_test_pred = mlmodels_dict[str('RandomForestRegressor')]['model'].predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='RandomForestRegressor', linewidth=1, alpha=0.8) y_test_pred = mlmodels_dict[str('ExtraTreesRegressor_2')]['model'].predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='ExtraTreesRegressor_2', linewidth=1, alpha=0.8) y_test_pred = mlmodels_dict[str('MLPRegressor')]['model'].predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='MLPRegressor', linewidth=1, alpha=0.8) plt.legend(loc='best', fontsize=30) plt.show() ###Output _____no_output_____ ###Markdown Comparativa Real y Train ###Code train_data = train_data.loc[train_data['MES']==2] # cogemos el mes 2 %matplotlib inline plt.figure(figsize=(40,40)) plt.title("TOTAL VEHICULOS Regressors' Predictions vs Real Data MES FEBRERO" , fontsize=30) plt.plot(test_data.TIME[0:400], y_test[0:400],'-o', markerfacecolor="blue", label='Real Data', linewidth=2, alpha=0.8) plt.plot(train_data.TIME[0:400], y_train[0:400],'-o', markerfacecolor="orange", label='Last Year Data', linewidth=2, alpha=0.5) y_test_pred = mlmodels_dict[str('MLPRegressor')]['model'].predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='MLPRegressor', linewidth=1, alpha=1) plt.legend(loc='best', fontsize=30) plt.show() %matplotlib inline plt.figure(figsize=(40,40)) plt.title("TOTAL VEHICULOS Regressors' Predictions vs Real Data MES FEBRERO" , fontsize=30) plt.plot(test_data.TIME[0:400], y_test[0:400],'-o', markerfacecolor="blue", label='Real Data', linewidth=2, alpha=0.8) plt.plot(train_data.TIME[0:400], y_train[0:400],'-o', markerfacecolor="orange", label='Last Year Data', linewidth=2, alpha=0.5) y_test_pred = mlmodels_dict[str('MLPRegressor')]['model'].predict(x_test) plt.plot(test_data.TIME[0:400], y_test_pred[0:400],'-o', markerfacecolor="None" , label='MLPRegressor', linewidth=1, alpha=1) plt.legend(loc='best', fontsize=30) plt.show() train_data.head() test_data.head() ###Output _____no_output_____
ocean_python_tutorial/Intro_07_Xarray_and_plotting_with_cartopy.ipynb
###Markdown This is the in situ and SSS collocation code. ###Code import numpy as np import matplotlib.pyplot as plt import xarray as xr import cartopy.crs as ccrs ###Output _____no_output_____ ###Markdown Read in data using xarray- Read in the Saildrone USV file either from a local disc or using OpenDAP.- add room to write collocated data to in situ dataset ###Code filename_usv = './data/saildrone-gen_5-antarctica_circumnavigation_2019-sd1020-20190119T040000-20190803T043000-1440_minutes-v1.1564857794963.nc' ds_usv = xr.open_dataset(filename_usv) ds_usv = ds_usv.rename({'longitude':'lon','latitude':'lat'}) #print dataset ds_usv ###Output _____no_output_____ ###Markdown explore the in situ data and quickly plot using cartopy ###Code #for polar data ax = plt.axes(projection=ccrs.SouthPolarStereo()) cs1 = ax.scatter(ds_usv.lon, ds_usv.lat, transform=ccrs.PlateCarree(),s=10.0, c=ds_usv.TEMP_CTD_MEAN, edgecolor='none', cmap='jet',vmin=0,vmax=12) ax.set_extent([-180, 180, -90, -45], crs=ccrs.PlateCarree()) ax.background_img('ne_shaded') ax.coastlines(resolution='50m') cax = plt.colorbar(cs1) cax.set_label('SST (K)') #fig_fname = 'C:/Users/gentemann/Google Drive/f_drive/docs/projects/misst-arctic/mmdb/'+usvname+'_location.png' #plt.savefig(fig_fname, transparent=False, format='png') #plot salinity ax = plt.axes(projection=ccrs.SouthPolarStereo()) cs1 = ax.scatter(ds_usv.lon, ds_usv.lat, transform=ccrs.PlateCarree(),s=10.0, c=ds_usv.SAL_MEAN, edgecolor='none', cmap='jet',vmin=33.6,vmax=34.4) ax.set_extent([-180, 180, -90, -45], crs=ccrs.PlateCarree()) ax.background_img('ne_shaded') ax.coastlines(resolution='50m') cax = plt.colorbar(cs1) cax.set_label('SSS (psu)') #fig_fname = 'C:/Users/gentemann/Google Drive/f_drive/docs/projects/misst-arctic/mmdb/'+usvname+'_sal_location.png' #plt.savefig(fig_fname, transparent=False, format='png') #read in the Baja Saildrone data url = 'https://podaac-opendap.jpl.nasa.gov/opendap/hyrax/allData/insitu/L2/saildrone/Baja/saildrone-gen_4-baja_2018-sd1002-20180411T180000-20180611T055959-1_minutes-v1.nc' ds_usv = xr.open_dataset(url) ds_usv = ds_usv.rename({'longitude':'lon','latitude':'lat'}) ds_usv #for NON polar data ax = plt.axes(projection=ccrs.PlateCarree()) #ds_usv = ds_usv.where(np.isfinite(ds_usv.lon)) cs1 = ax.scatter(ds_usv.lon, ds_usv.lat, s=3.0, c=ds_usv.TEMP_CTD_MEAN, edgecolor='none', cmap='jet',vmin=13,vmax=21) ax.coastlines(resolution='50m') x1,x2,y1,y2 = ds_usv.lon.min().data-2,ds_usv.lon.max().data+2,ds_usv.lat.min().data-2,ds_usv.lat.max().data+2 ax.set_xlim(x1,x2) ax.set_ylim(y1,y2) ax.background_img('ne_shaded') ax.set_xticks(np.arange(x1,x2,4)) ax.set_yticks(np.arange(y1,y2,5)) cax = plt.colorbar(cs1) cax.set_label('SST (K)') #fig_fname = 'C:/Users/gentemann/Google Drive/f_drive/docs/projects/misst-arctic/mmdb/'+usvname+'_location.png' #plt.savefig(fig_fname, transparent=False, format='png') #plt.clf() ###Output _____no_output_____ ###Markdown Plotting with cartopy ###Code import numpy as np import matplotlib.pyplot as plt import xarray as xr import cartopy.crs as ccrs ###Output _____no_output_____ ###Markdown Read in data using xarray- Read in the Saildrone USV file either from a local disc or using OpenDAP.`xr.open_dataset(filename_usv).rename({'longitude':'lon','latitude':'lat'})` ###Code filename_usv = './data/saildrone-gen_5-antarctica_circumnavigation_2019-sd1020-20190119T040000-20190803T043000-1440_minutes-v1.1564857794963.nc' ds_usv = ###Output _____no_output_____ ###Markdown * Read in satellite data. Mask land using `.where(ds_sst.mask==1)` and plot the results ###Code #If you are offline use the first url #url = './data/20111101120000-CMC-L4_GHRSST-SSTfnd-CMC0.2deg-GLOB-v02.0-fv02.0.nc') url = 'https://podaac-opendap.jpl.nasa.gov/opendap/allData/ghrsst/data/GDS2/L4/GLOB/CMC/CMC0.2deg/v2/2011/305/20111101120000-CMC-L4_GHRSST-SSTfnd-CMC0.2deg-GLOB-v02.0-fv02.0.nc' ds_sst = ###Output _____no_output_____ ###Markdown explore the in situ data and quickly plot using cartopy* first set up the axis with the projection you want: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html* plot to that axis and tell the projection that your data is in* set a background image* draw coastlines* add a colorbary and label it ###Code #for polar data, plot temperature ax = plt.axes(projection=ccrs.SouthPolarStereo()) (ds_sst.analysed_sst-273.15).plot(ax=ax, transform=ccrs.PlateCarree(),vmin=0,vmax=12) cs1 = ax.scatter(ds_usv.lon, ds_usv.lat, transform=ccrs.PlateCarree(),s=10.0, c=ds_usv.TEMP_CTD_MEAN, edgecolor='none', cmap='jet',vmin=0,vmax=12) ax.set_extent([-180, 180, -90, -45], crs=ccrs.PlateCarree()) ax.background_img('ne_shaded') ax.coastlines(resolution='50m') cax = plt.colorbar(cs1) cax.set_label('SST (K)') ###Output _____no_output_____ ###Markdown Exercise! ###Code #now you try to plot plot salinity ds_usv.SAL_MEAN ###Output _____no_output_____ ###Markdown Read in Baja Saildrone data* rename lat and lon`xr.open_dataset(url).rename({'longitude':'lon','latitude':'lat'})` ###Code #read in the Baja Saildrone data url = 'https://podaac-opendap.jpl.nasa.gov/opendap/hyrax/allData/insitu/L2/saildrone/Baja/saildrone-gen_4-baja_2018-sd1002-20180411T180000-20180611T055959-1_minutes-v1.nc' ds_usv = ###Output _____no_output_____ ###Markdown Exercise! Plot the Baja data and set the extent of your figure ###Code #for NON polar ds_usv data, use ccrs.PlateCarree() lonmin,lonmax = ds_usv.lon.min().data-2,ds_usv.lon.max().data+2 latmin,latmax = ds_usv.lat.min().data-2,ds_usv.lat.max().data+2 # now add an extent to your figure ax.set_xlim(lonmin,lonmax) ax.set_ylim(latmin,latmax) ###Output _____no_output_____
Lesson6-Visualization.ipynb
###Markdown Lesson 6 - Visualizationtime: 30mLearning outcomes:The student should be aware of different methods to plot functions of 1 and 2 variables:- plot- plot3d- complex_plot- density_plot- being aware of matplotlib- exporting plots- graphics formats- include plots in LaTeXWe now have an implementation to compute the Riemann zeta function and would like to study its properties. To get a rough idea of what to expect it is sometimes useful to make some plots. (If you dont have a sucessful implementation to compute zeta you can use the builtin function at this stage if you like. Reference for 3D plotting: https://doc.sagemath.org/html/en/reference/plot3d/One option would be to use the 3d plot: ###Code # By successive plots in various ranges we find that the first zero seems to be around 1/2 + 14*I # var('x','y') plot3d(lambda x,y: abs(zeta(CC(x,y))),(x,0,2),(y,0,10),viewer='canvas3d') ###Output _____no_output_____ ###Markdown There are different viewer and some might not work in your browser e.g. `threejs` does not work on my laptop... Valid options for viewers are- threejs (default)- jmol- canvas3d- tachyon (a static image) ###Code plot3d? #Alternatively p = plot3d(lambda x,y: abs(zeta(CC(x,y))),(x,0,2),(y,10,15)) p.show(viewer='jmol') ###Output _____no_output_____ ###Markdown Depending on parameter settings the plot might be distorted or fail completely dut to the pole at s=1. **Exercise** Introduce a condition in the lambda function in the plot to be able to plot zeta in a neighbourhood of (x,y)=(0,1) without distorting the figure too much.**Exercise**Use the function `complex_plot` to make another plot of `zeta` in a way which high-lights the first zero. ###Code p1 = plot(sin,0,10);p1 latex(p1) p2=plot3d(lambda x,y: abs(zeta(CC(x,y))),(x,0,1),(y,10,15)) p2.show(viewer='tachyon') ###Output _____no_output_____ ###Markdown As an alternative here we can save the figure as png: ###Code p2.save_image('test.png',dpi=600) ###Output _____no_output_____ ###Markdown Note that 2-d plots can be saved as pdf but 3d plots not ###Code p1.save_image('test1.pdf') ###Output _____no_output_____ ###Markdown Lesson 6 - Visualizationtime: 30 min Learning outcomesThe student should be aware of different methods to plot functions of 1 and 2 variables:- plot- plot3d- complex_plot- density_plot- being aware of matplotlib- exporting plots- graphics formats- include plots in LaTeXWe now have an implementation to compute the Riemann zeta function and would like to study its properties. To get a rough idea of what to expect it is sometimes useful to make some plots. (If you dont have a sucessful implementation to compute zeta you can use the builtin function at this stage if you like. Reference for 3D plotting: https://doc.sagemath.org/html/en/reference/plot3d/One option would be to use the 3d plot: ###Code # By successive plots in various ranges we find that the first zero seems to be around 1/2 + 14*I plot3d(lambda x, y: abs(zeta(CC(x, y))), (0, 2), (0, 10), viewer='canvas3d') ###Output _____no_output_____ ###Markdown There are different viewer and some might not work in your browser e.g. `threejs` does not work on my laptop... Valid options for viewers are- threejs (default)- jmol- canvas3d- tachyon (a static image) ###Code plot3d? # Alternatively p = plot3d(lambda x, y: abs(zeta(CC(x, y))), (0, 2), (10, 15)) p.show(viewer='jmol') ###Output _____no_output_____ ###Markdown Depending on parameter settings the plot might be distorted or fail completely dut to the pole at s=1. **Exercise** Introduce a condition in the lambda function in the plot to be able to plot zeta in a neighbourhood of (x,y)=(0,1) without distorting the figure too much.**Exercise**Use the function `complex_plot` to make another plot of `zeta` in a way which high-lights the first zero. ###Code p1 = plot(sin, 0, 10) p1 latex(p1) p2 = plot3d(lambda x, y: abs(zeta(CC(x, y))), (0, 1), (10, 15)) p2.show(viewer='tachyon') ###Output _____no_output_____ ###Markdown As an alternative here we can save the figure as png: ###Code p2.save_image('test.png', dpi=600) ###Output _____no_output_____ ###Markdown Note that 2-d plots can be saved as pdf but 3d plots not ###Code p1.save_image('test1.pdf') ###Output _____no_output_____
0.15/_downloads/plot_ica_from_raw.ipynb
###Markdown Compute ICA on MEG data and remove artifacts============================================ICA is fit to MEG raw data.The sources matching the ECG and EOG are automatically found and displayed.Subsequently, artifact detection and rejection quality are assessed. ###Code # Authors: Denis Engemann <[email protected]> # Alexandre Gramfort <[email protected]> # # License: BSD (3-clause) import numpy as np import mne from mne.preprocessing import ICA from mne.preprocessing import create_ecg_epochs, create_eog_epochs from mne.datasets import sample ###Output _____no_output_____ ###Markdown Setup paths and prepare raw data. ###Code data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.filter(1, 45, n_jobs=1, l_trans_bandwidth=0.5, h_trans_bandwidth=0.5, filter_length='10s', phase='zero-double', fir_design='firwin2') raw.annotations = mne.Annotations([1], [10], 'BAD') raw.plot(block=True) # For the sake of example we annotate first 10 seconds of the recording as # 'BAD'. This part of data is excluded from the ICA decomposition by default. # To turn this behavior off, pass ``reject_by_annotation=False`` to # :meth:`mne.preprocessing.ICA.fit`. raw.annotations = mne.Annotations([0], [10], 'BAD') ###Output _____no_output_____ ###Markdown 1) Fit ICA model using the FastICA algorithm. ###Code # Other available choices are `infomax` or `extended-infomax` # We pass a float value between 0 and 1 to select n_components based on the # percentage of variance explained by the PCA components. ica = ICA(n_components=0.95, method='fastica') picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False, exclude='bads') ica.fit(raw, picks=picks, decim=3, reject=dict(mag=4e-12, grad=4000e-13)) # maximum number of components to reject n_max_ecg, n_max_eog = 3, 1 # here we don't expect horizontal EOG components ###Output _____no_output_____ ###Markdown 2) identify bad components by analyzing latent sources. ###Code title = 'Sources related to %s artifacts (red)' # generate ECG epochs use detection via phase statistics ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks) ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps') ica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg') show_picks = np.abs(scores).argsort()[::-1][:5] ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=title % 'ecg') ica.plot_components(ecg_inds, title=title % 'ecg', colorbar=True) ecg_inds = ecg_inds[:n_max_ecg] ica.exclude += ecg_inds # detect EOG by correlation eog_inds, scores = ica.find_bads_eog(raw) ica.plot_scores(scores, exclude=eog_inds, title=title % 'eog', labels='eog') show_picks = np.abs(scores).argsort()[::-1][:5] ica.plot_sources(raw, show_picks, exclude=eog_inds, title=title % 'eog') ica.plot_components(eog_inds, title=title % 'eog', colorbar=True) eog_inds = eog_inds[:n_max_eog] ica.exclude += eog_inds ###Output _____no_output_____ ###Markdown 3) Assess component selection and unmixing quality. ###Code # estimate average artifact ecg_evoked = ecg_epochs.average() ica.plot_sources(ecg_evoked, exclude=ecg_inds) # plot ECG sources + selection ica.plot_overlay(ecg_evoked, exclude=ecg_inds) # plot ECG cleaning eog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average() ica.plot_sources(eog_evoked, exclude=eog_inds) # plot EOG sources + selection ica.plot_overlay(eog_evoked, exclude=eog_inds) # plot EOG cleaning # check the amplitudes do not change ica.plot_overlay(raw) # EOG artifacts remain # To save an ICA solution you can say: # ica.save('my_ica.fif') # You can later load the solution by saying: # from mne.preprocessing import read_ica # read_ica('my_ica.fif') # Apply the solution to Raw, Epochs or Evoked like this: # ica.apply(epochs) ###Output _____no_output_____
feature_selection.ipynb
###Markdown Hey folks, I'm just trying out a proof-of-concept jupyter notebook that uses our data retrieval code.I got sick of working with environment variables so I switched to a new method to store our DB password: 1. Create a file called config.json in the project root. 2. Inside, config.json should look like this: { "database_url":"database_url_goes_here" }TableReader's other vector methods are geodata_vector() and reviews_vector(). Be sure to call close() when you're done so it terminates the connection to the DB. ###Code tr = TableReader() df = tr.properties_vector(include_amenitites=True) tr.close() features = df[df.columns.drop(['price', 'listingID'])] label = df['price'] model = ElasticNet() esfm = SelectFromModel(model) esfm.fit(features, label) print(list(features.iloc[:, esfm.get_support(indices=True)])) model = Lasso() sfm = SelectFromModel(model) sfm.fit(features, label) print(list(features.iloc[:, sfm.get_support(indices=True)])) model = Ridge() sfm = SelectFromModel(model) sfm.fit(features, label) print(list(features.iloc[:, sfm.get_support(indices=True)])) elastic_data = df[list(features.iloc[:, esfm.get_support(indices=True)])] corr = elastic_data.corr() plt.figure(figsize=(12, 12)) ax = sns.heatmap( corr, vmin=-1, vmax=1, center=0, cmap=sns.diverging_palette(20, 220, n=200), square=True ) ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right' ); ###Output _____no_output_____ ###Markdown 1. Feature SelectionChi-squared (chi²) statistical test for non-negative features to select 20 of the best features from the Mobile Price Range Prediction Dataset. ###Code import pandas as pd import numpy as np from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 #apply SelectKBest class to extract top 20 best features bestfeatures = SelectKBest(score_func=chi2, k=20) fit = bestfeatures.fit(features,label) dfscores = pd.DataFrame(fit.scores_) dfcolumns = pd.DataFrame(features.columns) #concat two dataframes for better visualization featureScores = pd.concat([dfcolumns,dfscores],axis=1) featureScores.columns = ['Specs','Score'] #naming the dataframe columns print(featureScores.nlargest(20,'Score')) #print 20 best features ###Output Specs Score 0 accomodates 4182.805494 12 Shared room 3562.161252 11 Private room 2338.639850 3 beds 2282.643948 2 bedrooms 1703.326123 8 Serviced apartment 1617.581016 10 Entire home/apt 1323.337616 73 Pool 1152.489301 58 Gym 1135.608306 16 Bathtub 1033.628165 29 Hot tub 1025.131564 34 Elevator 815.988801 39 Wheelchair accessible 806.710766 50 Oven 760.496541 32 Family/kid friendly 734.473870 7 House 728.354252 71 Pets allowed 718.182247 67 Cable TV 676.059273 1 bathrooms 656.021416 25 Dishwasher 637.031893 ###Markdown 2. Feature Importance Model ###Code from sklearn.ensemble import ExtraTreesClassifier import matplotlib.pyplot as plt model = ExtraTreesClassifier() model.fit(features,label) print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers #plot graph of feature importances for better visualization feat_importances = pd.Series(model.feature_importances_, index=features.columns) feat_importances.nlargest(20).plot(kind='barh') plt.show() ###Output /anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:245: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22. "10 in version 0.20 to 100 in 0.22.", FutureWarning) ###Markdown Dataset link: https://www.kaggle.com/tejashvi14/employee-future-prediction Uploading dataset ###Code from google.colab import files files.upload() ###Output _____no_output_____ ###Markdown Initialization ###Code import pandas as pd from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder from sklearn.linear_model import LogisticRegression import warnings warnings.filterwarnings('ignore') df = pd.read_csv('Employee.csv') X = df.drop(['LeaveOrNot'], axis=1) y = df['LeaveOrNot'] ###Output _____no_output_____ ###Markdown Preparing data ###Code X_full_train, X_test, y_full_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_train, X_val, y_train, y_val = train_test_split(X_full_train, y_full_train, test_size=0.25, random_state=42) numerical = ['Age'] categorical = ['Education', 'JoiningYear', 'City', 'PaymentTier', 'Gender', 'EverBenched', 'ExperienceInCurrentDomain'] ###Output _____no_output_____ ###Markdown Creating Pipeline ###Code def create_new_pipeline(numerical, categorical): numerical_transformer = SimpleImputer(strategy='median') categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='most_frequent')), ('encoding', OneHotEncoder(drop='first')) ]) preprocessor = ColumnTransformer( transformers=[ ('numerical', numerical_transformer, numerical), ('categorical', categorical_transformer, categorical) ]) model = LogisticRegression() pipeline = Pipeline( steps=[ ('preprocessing', preprocessor), ('model', model) ] ) return pipeline ###Output _____no_output_____ ###Markdown Deciding features to use based on their correlation with target (calculated during EDA) ###Code chi_square_drop_order = ['JoiningYear', 'ExperienceInCurrentDomain', 'PaymentTier', 'EverBenched', 'Education', 'Gender', 'City'] for i in range(len(chi_square_drop_order)): pipeline = create_new_pipeline(numerical, chi_square_drop_order[i:]) pipeline.fit(X_train.drop(chi_square_drop_order[:i], axis=1), y_train) print(f'Features included: {chi_square_drop_order[i:]}') print(f'Training score: {pipeline.score(X_train.drop(chi_square_drop_order[:i], axis=1), y_train)}') print(f'Validation score: {pipeline.score(X_val.drop(chi_square_drop_order[:i], axis=1), y_val)}') print() print() ###Output Features included: ['JoiningYear', 'ExperienceInCurrentDomain', 'PaymentTier', 'EverBenched', 'Education', 'Gender', 'City'] Training score: 0.802221426012182 Validation score: 0.8098818474758325 Features included: ['ExperienceInCurrentDomain', 'PaymentTier', 'EverBenched', 'Education', 'Gender', 'City'] Training score: 0.7284127552848442 Validation score: 0.7411385606874329 Features included: ['PaymentTier', 'EverBenched', 'Education', 'Gender', 'City'] Training score: 0.714797563597277 Validation score: 0.7346938775510204 Features included: ['EverBenched', 'Education', 'Gender', 'City'] Training score: 0.7312791114295951 Validation score: 0.7443609022556391 Features included: ['Education', 'Gender', 'City'] Training score: 0.7319957004657829 Validation score: 0.7551020408163265 Features included: ['Gender', 'City'] Training score: 0.7327122895019706 Validation score: 0.7551020408163265 Features included: ['City'] Training score: 0.6589036187746328 Validation score: 0.6680988184747583 ###Markdown We can conclude that we cannot drop any feature based on Chi Square test. ###Code mutual_info_drop_order = ['ExperienceInCurrentDomain', 'Education', 'EverBenched', 'City', 'Gender', 'PaymentTier', 'JoiningYear'] for i in range(len(mutual_info_drop_order)): pipeline = create_new_pipeline(numerical, mutual_info_drop_order[i:]) pipeline.fit(X_train.drop(mutual_info_drop_order[:i], axis=1), y_train) print(f'Features included: {mutual_info_drop_order[i:]}') print(f'Training score: {pipeline.score(X_train.drop(mutual_info_drop_order[:i], axis=1), y_train)}') print(f'Validation score: {pipeline.score(X_val.drop(mutual_info_drop_order[:i], axis=1), y_val)}') print() print() ###Output Features included: ['ExperienceInCurrentDomain', 'Education', 'EverBenched', 'City', 'Gender', 'PaymentTier', 'JoiningYear'] Training score: 0.8029380150483698 Validation score: 0.8098818474758325 Features included: ['Education', 'EverBenched', 'City', 'Gender', 'PaymentTier', 'JoiningYear'] Training score: 0.7968470082407739 Validation score: 0.8120300751879699 Features included: ['EverBenched', 'City', 'Gender', 'PaymentTier', 'JoiningYear'] Training score: 0.7975635972769617 Validation score: 0.7980665950590763 Features included: ['City', 'Gender', 'PaymentTier', 'JoiningYear'] Training score: 0.7957721246864923 Validation score: 0.8023630504833512 Features included: ['Gender', 'PaymentTier', 'JoiningYear'] Training score: 0.790756001433178 Validation score: 0.7969924812030075 Features included: ['PaymentTier', 'JoiningYear'] Training score: 0.7832318165532067 Validation score: 0.7862513426423201 Features included: ['JoiningYear'] Training score: 0.7219634539591544 Validation score: 0.7561761546723953 ###Markdown ###Code import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # for feature selection from sklearn.linear_model import Lasso from sklearn.feature_selection import SelectFromModel pd.pandas.set_option('display.max_columns',None) %pwd import os os.chdir('/content/drive/My Drive/Data_science_projects/Advance_House_Price_prediction/house-prices-advanced-regression-techniques') %pwd ###Output _____no_output_____ ###Markdown New Section ###Code from google.colab import drive drive.mount('/content/drive') dataset = pd.read_csv('X_train.csv') dataset.head() ###Output _____no_output_____ ###Markdown Only for official daily data ###Code X = pd.read_pickle("./data_for_models/X.pkl") y = pd.read_pickle("./data_for_models/y.pkl") len(X.columns) def input_scale(X): imputer = SimpleImputer(strategy='median') scaler = StandardScaler() X_t = imputer.fit_transform(X.values) X_t = scaler.fit_transform(X_t) return X_t def input_(X): imputer = SimpleImputer(strategy='median') X_t = imputer.fit_transform(X.values) return X_t X_t = input_scale(X) ###Output _____no_output_____ ###Markdown PCA ###Code pca = PCA(n_components=0.97) pca.fit(X_t) pca.explained_variance_ratio_ np.isnan(X_t).sum() ###Output _____no_output_____ ###Markdown RFE ###Code from sklearn.linear_model import LinearRegression from sklearn.linear_model import LassoCV from sklearn.feature_selection import RFE l = LassoCV() rfe = RFE(l, 10) rfe.fit(X_t, y.values.ravel()) X.columns[rfe.support_] rfe.ranking_ ###Output _____no_output_____ ###Markdown LassoCV ###Code from sklearn.linear_model import LassoCV reg = LassoCV() reg.fit(X_t, y.values.ravel()) X.columns[reg.coef_ != 0] ###Output _____no_output_____ ###Markdown Select KBest ###Code from sklearn.feature_selection import SelectKBest, f_regression, mutual_info_regression best = SelectKBest(score_func=f_regression, k=15) best.fit(X_t, y.values.ravel()) X.columns[best.get_support()] ###Output _____no_output_____ ###Markdown Corr ###Code full = pd.read_pickle("./data_for_models/full.pkl") full.corr()['T_MEAN'] ###Output _____no_output_____ ###Markdown Feature SelectionThis notebook looks at feature correlations and removes any features that are highly correlated Import libraries ###Code import numpy as np import pandas as pd import seaborn as sns import pdb import glob import matplotlib.pyplot as plt import os import shutil ###Output _____no_output_____ ###Markdown Create the plots folder, or remove it if it exists ###Code try: if os.path.exists('plots'): shutil.rmtree('plots') os.makedirs('plots') except Exception as e: print(e) ###Output _____no_output_____ ###Markdown Load the data ###Code #load the training data train_files = glob.glob('feats/train_*.pkl') train = [] for train_file in train_files: train.append(pd.read_pickle(train_file)) train = pd.concat(train) #load the test data test_files = glob.glob('feats/test_*.pkl') test = [] for test_file in test_files: test.append(pd.read_pickle(test_file)) test = pd.concat(test) ###Output _____no_output_____ ###Markdown Look at feature correlations. In this case, there aren't any large correlations so just keep all the data ###Code #look at feature correlations corr = train.corr() mask = np.triu(np.ones_like(corr, dtype=np.bool)) cmap = sns.diverging_palette(220, 10, as_cmap=True) #make the heatmap plot plt.figure(figsize=(16,9)) sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) plt.tight_layout() plt.savefig('plots/heatmap.png', dpi=250) plt.show() #save the data train.to_pickle('train.pkl') test.to_pickle('test.pkl') ###Output _____no_output_____ ###Markdown Load Original Features ###Code feat_num = 449 #df_total = pd.read_csv('./data/features%s_add_card1_cnt.csv'%(feat_num)) with open('./data/features%s.pickle'%(feat_num), 'rb') as handle: df_total = pickle.load(handle) df_train = df_total[df_total['isFraud'].notnull()] df_train.shape ###Output _____no_output_____ ###Markdown Negative Downsampling ###Code train_pos = df_train[df_train['isFraud']==1] train_neg = df_train[df_train['isFraud']==0] train_neg = train_neg.sample(int(df_train.shape[0] * 0.2), random_state=42) df_train_sample = pd.concat([train_pos,train_neg]).sort_index() ###Output _____no_output_____ ###Markdown Prepare Data ###Code labels_train = df_train_sample['isFraud'] features_train = df_train_sample.drop(columns = ['isFraud', 'TransactionID']) features_train.shape features_train.head() with open('./data/feat%s_rm_pm_importance100.pickle'%(437), 'rb') as handle: to_drop = pickle.load(handle) for item in to_drop: if not 'V' in item: print(item) features_train = features_train.drop(list(to_drop),axis=1) categorical_raw = ['ProductCD', 'card2', 'card3', 'card4', 'card5','card6', 'addr1','addr2','P_email','R_email','M1','M2','M3', 'M4','M5','M6','M7','M8','M9','DeviceType','DeviceInfo','dow','hour', 'Device_name','Device_version','screen_width','screen_height', 'P_email_suffix','R_email_suffix','id_30_OS','id_30_version', 'is_card_freq_Device','is_wide','is_long','is_zero','is_win8_vista', 'is_windows_otheros','is_card_freq_pdc','is_card_freq_addr1'] # ids = [ 'id_%s'%(i) for i in range(12,39)] categorical_raw = categorical_raw + ids params = {'num_leaves': 491, 'min_child_weight': 0.03454472573214212, 'feature_fraction': 0.3797454081646243, 'bagging_fraction': 0.4181193142567742, 'min_data_in_leaf': 106, 'objective': 'binary', 'max_depth': -1, 'learning_rate': 0.006883242363721497, "boosting_type": "gbdt", "bagging_seed": 11, "metric": 'auc', "verbosity": -1, 'reg_alpha': 0.3899927210061127, 'reg_lambda': 0.6485237330340494, 'random_state': 47, #'num_threads':10 #'is_unbalance':True #'scale_pos_weight':9 } ###Output _____no_output_____ ###Markdown Select Features ###Code def train_selector(params,train_num,features_train,labels_train,categorical,verbose_eval=500): train_set = lgb.Dataset(features_train.iloc[0:train_num,:], label=labels_train.values[0:train_num], categorical_feature=categorical) valid_set = lgb.Dataset(features_train.iloc[train_num:,:], label=labels_train.values[train_num:], categorical_feature=categorical) valid_results = {} model = lgb.train(params,train_set,num_boost_round = 10000, valid_sets = [train_set, valid_set], verbose_eval= verbose_eval, early_stopping_rounds = 500, evals_result=valid_results) return model,valid_results def select_by_importance(model,features_train,importance=0,num_keep=None): fi = pd.DataFrame({'feature': features_train.columns, 'importance':model.feature_importance()}) fi = fi.sort_values('importance', ascending = False) if num_keep != None: to_drop = fi.iloc[num_keep:,:].feature else: to_drop = fi[fi.importance <= importance].feature return to_drop def fold_train_selector(Nfold,features_train,labels_train,categorical): splits = Nfold ave_auc = 0 valid_results = {} folds = KFold(n_splits = splits,random_state=RSEED) for fold_num, (trn_idx, val_idx) in enumerate(folds.split(features_train.values, labels_train.values)): print("Fold {}".format(fold_num)) train_df, y_train_df = features_train.iloc[trn_idx], labels_train.iloc[trn_idx] valid_df, y_valid_df = features_train.iloc[val_idx], labels_train.iloc[val_idx] trn_data = lgb.Dataset(train_df, label=y_train_df,categorical_feature=categorical) val_data = lgb.Dataset(valid_df, label=y_valid_df,categorical_feature=categorical) clf = lgb.train(params, trn_data, 10000, valid_sets = [trn_data, val_data], verbose_eval=500, early_stopping_rounds=500, evals_result=valid_results) pred = clf.predict(valid_df) auc_score = roc_auc_score(y_valid_df, pred) ave_auc += auc_score / splits print( " auc = ", auc_score ) return ave_auc def permutation_importance(model,features_valid,labels_valid): """calculate permutation importance of features Args: model: the trained model. features_valid: dataframe. The validation set of features. labels_valid: labels of validation set. Returns: df_fimportance: dataframe. The importances of features. """ base_score = roc_auc_score(labels_valid, model.predict(features_valid)) list_fimportance = [] for col in features_valid.columns: print(col) save = features_valid[col].copy() features_valid[col] = np.random.permutation(features_valid[col]) col_score = roc_auc_score(labels_valid, model.predict(features_valid)) features_valid[col] = save list_fimportance.append([col,base_score - col_score]) return pd.DataFrame(list_fimportance,columns = ['feature','importance']) ###Output _____no_output_____ ###Markdown PCA V Features ###Code def check_missing(df,cols=None,axis=0): """check data frame column missing situation Args df: data frame. cols: list. List of column names axis: int. 0 means column and 1 means row Returns missing_info: data frame. """ if cols != None: df = df[cols] missing_num = df.isnull().sum(axis).to_frame().rename(columns={0:'missing_num'}) missing_num['missing_percent'] = df.isnull().mean(axis)*100 return missing_num.sort_values(by='missing_percent',ascending = False) vfeatures = ['V'+str(i) for i in range(1,340)] scaler = StandardScaler() scaler.fit(features_train[vfeatures]) imp = Imputer(missing_values=np.nan , strategy='mean', axis=0) vfeature_impute = imp.fit_transform(features_train[vfeatures]) vfeature_impute_scale = scaler.transform(vfeature_impute) vfeature_impute_scale = pd.DataFrame(vfeature_impute_scale, columns=vfeatures) pca = PCA() vfeature_pca = pca.fit_transform(vfeature_impute_scale) # check components number should be the same as total features components_total = len(pca.explained_variance_ratio_) # generate sequence for plotting components = np.arange(components_total) fig, ax1 = plt.subplots(figsize=(15,5)) ax1.bar(components[0:100],pca.explained_variance_ratio_[0:100]) ax1.set_ylabel('Explained Variance', color="blue") ax1.set_xlabel('Number of Components') ax2 = ax1.twinx() ax2.plot(np.cumsum(pca.explained_variance_ratio_[0:100]), color="red",marker='o') ax2.set_ylabel('Cumulative Explained Variance', color="red") plt.title("Cumulative Explained Variance vs No. of Principal Components") np.cumsum(pca.explained_variance_ratio_[:30])[-1] # Re-apply PCA to the data while selecting for number of components to retain. pca_50 = PCA(n_components=30) vfeature_pca_50 = pca_50.fit_transform(vfeature_impute_scale) vfeature_pca_50_df = pd.DataFrame(vfeature_pca_50,columns= ['PCA'+str(i) for i in range(1,31)]) vfeature_pca_50_df.head() vfeature_pca_50_df.reset_index(drop=True,inplace=True) features_train.reset_index(drop=True,inplace=True) features_train.drop(vfeatures,axis=1,inplace=True) features_train = features_train.join(vfeature_pca_50_df) features_train.head() ###Output _____no_output_____ ###Markdown Train with all feature set ###Code train_num = int(138771*0.8)#160000 #features_train = features_train.drop(['C8'],axis=1) categorical = list(set(categorical_raw).intersection(features_train.columns)) model,valid_results = train_selector(params,train_num,features_train,labels_train, categorical,verbose_eval=500) model.num_trees() ###Output _____no_output_____ ###Markdown Permutation Importance ###Code lgb.plot_importance(model, max_num_features=50,figsize=(12,10)) fi_importance = permutation_importance(model,features_train.iloc[train_num:], labels_train.iloc[train_num:]) fi_importance.sort_values(by='importance',ascending=False)[0:50] fi_importance.sort_values(by='importance',ascending=False)[-10:] ###Output _____no_output_____ ###Markdown Feature Test Result ###Code features_train.head() categorical = list(set(categorical_raw).intersection(features_train.columns)) ave_auc = fold_train_selector(3,features_train,labels_train,categorical) # feat439 change id 30 --not confirmed from large dataset ave_auc # feat439 change device info --not confirmed from large dataset ave_auc # feat439 add card_mv_day_fq ave_auc # feat438 add addr1 cnt boost performance ave_auc # feat437 add card1 cnt boost performance ave_auc # feat436 add pdc_amt_std_ratio imporve but lower than pdc_amt_ratio ave_auc # feat437 add pdc_amt_std_ratio-- lower performance ave_auc # feat436 add pdc_amt_ratio-- very effective ave_auc # feat435 clean id 33 if not treat as categorical performance drop ave_auc # feat435 clean id 33 improve performance ave_auc # feat453 clean DeviceInfo and modify Device_name ave_auc # feat435 clean DeviceInfo lead to even lower performance ave_auc # feat435 clean id30 -- clean id_30 lead to lower performance ave_auc # feat434 clean P and R email -- very effective ave_auc # feat434 clean id31 -- very effective ave_auc # feat434 without any change ave_auc ###Output _____no_output_____ ###Markdown Feature selection by Importance ###Code #to_drop = list(select_by_importance(model,features_train,importance=0)) #to_drop = fi_importance[fi_importance.importance <0].feature #to_drop = fi_importance.sort_values(by='importance',ascending=False)[-50:].feature to_drop = ['P_email'] features_train_temp = features_train.drop(to_drop,axis=1) categorical_temp = list(set(categorical_raw).intersection(features_train_temp.columns)) print(features_train_temp.head()) ave_auc = fold_train_selector(3,features_train_temp,labels_train,categorical_temp) # feat439 add pemail fraud rate drop pemail ave_auc # # feat437 add card1 cnt drop fi_importance.sort_values(by='importance',ascending=False)[-50:].feature ave_auc # feat437 add card1 cnt drop 'V169' ave_auc # feat437 add card1 cnt drop 'D5' ave_auc # feat437 add card1 cnt drop fi_importance[fi_importance.importance <0].feature ave_auc # feat437 add card1 cnt drop fi_importance.sort_values(by='importance',ascending=False)[-100:].feature ave_auc # feat437 add card1 cnt drop transactionDT ave_auc to_drop = fi_importance.sort_values(by='importance',ascending=False)[-100:].feature with open('./data/feat437_rm_pm_importance100.pickle', 'wb') as handle: pickle.dump(to_drop, handle, protocol=pickle.HIGHEST_PROTOCOL) ###Output _____no_output_____ ###Markdown Recursive Eliminate Features ###Code # to_drop = {'P_email_suffix','R_email_suffix','dow','pdc_D1_ratio'} is useless # to_drop = {'card_TAmt_ratio','card_TAmt_std_ratio','is_card_freq_pdc','is_card_freq_addr1'}is useless # to_drop = {'TransactionAmt_decimal','is_wide','is_long','is_zero'} is useless # to_drop = {'card_D2_mean','card_D15_mean','card_D4_mean','card_id_02_mean'','card_D1_std', # 'card_D15_std','card_D1_mean','card_id_02_std','card_D3_mean} is useless # to_drop = {'addr1_D15_mean','addr1_D15_std'} is useless # to_drop = {'ProductCD_target_mean','M4_target_mean'} is useless # to_drop = {'card2_fq_enc','card3_fq_enc','card5_fq_enc','P_email_fq_enc','R_email_fq_enc'} is useless # to_drop = {'addr2_fq_enc',} # to_drop = {'R_email_fraud_rate','card6_fraud_rate','card4_fraud_rate'} all have boost performance # to_drop = {'card_addr_fq','card_mv_hour_fq','card_mv_hour_fq_ratio', # 'card_hour_Amt','card_hour_Amt_ratio', # 'card_mv_day_fq_ratio','card_day_Amt','card_day_Amt_ratio'} useless # to_drop = {'D6_fq_enc','D7_fq_enc','D8_fq_enc','D9_fq_enc','DeviceInfo_fq_enc', # 'id_30_fq_enc','id_31_fq_enc','screen_width_fq_enc'} # 大小数据集表现不一致 to_drop = {'DT_hour_Amt_ratio','DT_day_Amt_ratio','DT_month_Amt_ratio', 'DT_year_Amt_ratio','card2_Amt_ratio', 'card3_Amt_ratio','card4_Amt_ratio','card5_Amt_ratio','card6_Amt_ratio'} result = [] for col in to_drop: print(col) to_drop_temp = list(to_drop - set([col])) features_train_temp = features_train.drop(to_drop_temp,axis=1) print(features_train_temp.shape) categorical_temp = list(set(categorical_raw).intersection(features_train_temp.columns)) ave_auc = fold_train_selector(3,features_train_temp,labels_train,categorical_temp) print(ave_auc) result.append([col,ave_auc]) result result best = 0.921552900501287 result best = 0.9213639958310471 result 0.921645405116515 result ###Output _____no_output_____ ###Markdown Feature selectionVariables are extracted for prediction modelling using euroscore and hypothesis-free approaches. Outputs are written to CSV for downstream analysis ###Code import pandas as pd import numpy as np import seaborn as sns; sns.set() import matplotlib.pyplot as plt from datetime import datetime, timedelta from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.feature_selection import RFECV from sklearn.model_selection import StratifiedKFold from sklearn.metrics import r2_score from sklearn import metrics from sklearn.calibration import CalibratedClassifierCV, calibration_curve from pytest import approx sns.set(rc={'figure.figsize':(11.7,8.27)}) sns.set(style="white") #pd.set_option('display.max_rows', 500) #pd.set_option('display.max_columns', 500) #pd.set_option('display.width', 1000) ###Output _____no_output_____ ###Markdown Read in dataClean records and split procedures into test, train and validation by date ###Code # read from Excel dat = pd.read_excel("bhi_FINAL_VERSION_20_09_2019.xlsx") # fix dates def from_excel_ordinal(ordinal, _epoch0=datetime(1899, 12, 31)): if ordinal > 59: ordinal -= 1 # Excel leap year bug, 1900 is not a leap year! return (_epoch0 + timedelta(days=ordinal)).replace(microsecond=0) #malformed = dat['Date of operation'].astype(str).str.isdigit() #dat.loc[malformed, 'Date of operation'] = \ #dat.loc[malformed, 'Date of operation'] \ # .astype(int) \ # .apply(from_excel_ordinal) #dat['Date of operation'] = pd.to_datetime(dat['Date of operation'], errors='coerce') # drop malformed dates #dat = dat.loc[dat['Date of operation'].notna()] # sort by op date dat = dat.sort_values(by='Date of operation fixed') # check dates look OK dat['Date of operation fixed'].describe() # check age looks OK sns.distplot(dat['AGE'], hist=False, rug=True); # drop < 18 yrs dat = dat[dat.AGE >= 18] dat['AGE'].describe() # check bmi looks OK sns.distplot(dat['bmi'], hist=False, rug=True); # set BMI outliers to NA dat.loc[dat['bmi'] > 100, 'bmi'] = np.nan dat.loc[dat['bmi'] < 5, 'bmi'] = np.nan # check height looks OK sns.distplot(dat['2.37 Height'], hist=False, rug=True); # set height outliers to NA dat.loc[dat['2.37 Height'] > 210, '2.37 Height'] = np.nan dat.loc[dat['2.37 Height'] < 130, '2.37 Height'] = np.nan # check weight looks OK sns.distplot(dat['2.38 Weight'], hist=False, rug=True); # set weight outliers to NA dat.loc[dat['2.38 Weight'] > 150, '2.38 Weight'] = np.nan dat.loc[dat['2.38 Weight'] < 30, '2.38 Weight'] = np.nan # check creatinine looks OK sns.distplot(dat['2.12.0 Actual Creatinine at time of Surgery'], hist=False, rug=True); # population charectoristics dat.describe() def split_dat_by_time(dat): # count rows obs = dat.shape[0] test_n = int(np.round(obs * 0.3, 0)) train_n = obs - test_n # split data into train (70%) and test (30%) train = dat.head(train_n) test = dat.tail(test_n) assert (train.shape[0] + test.shape[0]) == obs return train, test ###Output _____no_output_____ ###Markdown EuroscoreExtract variables for Euroscore I and II and plot against provided calculations as sanity check EuroScore IEuropean Heart Journal (2003) 24, 1–2[10.1016/S0195-668X(02)00799-6](https://doi.org/10.1016/S0195-668X(02)00799-6)http://www.euroscore.org/euroscore_scoring.htm ###Code def format_euroscore_i_features(dat): features = pd.DataFrame(data={ 'Age (continuous)' : dat['AGE'], 'Female' : dat['SEX'] == "2. Female", 'Serum creatinine >200 µmol/l': dat['CKD'] == "2. Creatinine > 200 µmol/l", "Extracardiac arteriopathy" : dat['PVD'] == "1. Yes", "Pulmonary disease" : dat['PULMONARY'] == "1. COAD/Asthma/emphysema", "Neurological dysfunction": dat['NEURO_DYSF'] == "1. Yes", "Previous cardiac surgery" : dat['PRIOR_HEART_SURGERY'] == "1. Yes", 'Recent myocardial infarct': dat['MI'].isin(["4. MI 31-90 days", "3. MI 1-30 days", "2. MI 6-24 hours", "1. MI < 6 hours"]), "LVEF 30–50%" : dat['LVEF'] == "2. Fair (LVEF 30-49%)", "LVEF <30%": dat['LVEF'] == "3. Poor (LVEF < 30%)", "Systolic pulmonary pressure >60 mmHg" : dat['PHPT60_EU1'] == "1. Yes", "Active endocarditis" : dat['ACTIVE_ENDOCARDITIS'] == "1. Yes", "Unstable angina" : dat['IVNITRATES'] == "1. Yes", "Emergency operation": dat['PRIORITY'].isin(['3. Emergency', '4. Salvage']), "Critical preoperative state": (dat['2.18 Pre operative heart rhythm'] == "3. Ventricular fibrillation or ventricular tachycardia") | (dat['SHOCK'] == "1. Yes") | (dat['INOTROPS'] == "1. Yes") | (dat['VENTILATION'] == "1. Yes") | (dat['IABP'] == "1. Yes"), "Ventricular septal rupture" : dat['Post infarct septal rupture'] == "1. Yes", "Other than isolated coronary surgery": (dat['VALVE'] == "1. Yes") | (dat['ASD'] == "1. Yes") | (dat['LV_ANEURYSMECTOMY'] == "1. Yes") | (dat['AF_ABLATION'] == "1. Yes") | (dat['PERICARDIECTOMY'] == "1. Yes") | (dat['ATRIAL_MIXOMA'] == "1. Yes") | (dat['AORTIC_DISSECTION'] == "1. Yes"), "Thoracic aortic surgery": dat['Surgery on thoracic aorta'] == "1. Yes", # outcome 'STATUS_DISCHARGE': dat['STATUS_DISCHARGE'] == "1. Dead" }, index=dat.index) # drop samples with NAs features = features.dropna(axis='index') assert not features.isnull().values.any() return features # select features and drop NA esi_features = format_euroscore_i_features(dat) # count remaining patients print(esi_features.shape) # split into test & train train_pred_esi, test_pred_esi = split_dat_by_time(esi_features) # print op date range for train & test print(dat.loc[train_pred_esi.head(1).index.tolist()[0]]['Date of operation fixed']) print(dat.loc[train_pred_esi.tail(1).index.tolist()[0]]['Date of operation fixed']) print(dat.loc[test_pred_esi.head(1).index.tolist()[0]]['Date of operation fixed']) print(dat.loc[test_pred_esi.tail(1).index.tolist()[0]]['Date of operation fixed']) # write out to csv train_pred_esi.to_csv('train.esi.features.17.02.20.csv') test_pred_esi.to_csv('test.esi.features.17.02.20.csv') # write out provided ES calc for comparison dat.to_csv('Euroscore_additive.17.02.20.csv', columns=['Euroscore']) dat.to_csv('Euroscore_logistic.17.02.20.csv', columns=['Logistic_Euroscore']) ###Output (28720, 19) 1996-04-01 00:00:00 2011-09-27 00:00:00 2011-09-27 00:00:00 2017-12-30 13:30:00 ###Markdown EuroScore IIEuropean Journal of Cardio-Thoracic Surgery 41 (2012) 734–745[10.1093/ejcts/ezs043](https://doi.org/10.1093/ejcts/ezs043)http://euroscore.org/calc.html ###Code def count_procedures(dat): procedure_counts = [] for index, row in dat.iterrows(): count = 0 # note the space after key CABG if row['CABG '] == '1. Yes': count += 1 if row['VALVE'] == '1. Yes': count += 1 if row['Surgery on thoracic aorta'] == '1. Yes': count += 1 if row['Post infarct septal rupture'] == '1. Yes': count += 1 if ['ASD'] == '1. Yes': count += 1 if row['LV_ANEURYSMECTOMY'] == '1. Yes': count += 1 if row['AF_ABLATION'] == '1. Yes': count += 1 if row['PERICARDIECTOMY'] == '1.Yes': count += 1 if row['ATRIAL_MIXOMA'] == '1. Yes': count += 1 procedure_counts.append(count) assert len(procedure_counts) == dat.shape[0] return pd.DataFrame(data={'number of procedures': procedure_counts}, index=dat.index) # requires creatinine in umol/L def calc_cockcroft_gault(row): try: if row['SEX'] == "2. Female": n = (140 - row['AGE']) * row['2.38 Weight'] * 0.85 else: n = (140 - row['AGE']) * row['2.38 Weight'] # convert umol/L to mg/dL mg_dl = row['2.12.0 Actual Creatinine at time of Surgery'] * 0.0113 return n / (72 * mg_dl) except (TypeError, KeyError): return None # check func against http://touchcalc.com/calculators/cg assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': 65, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': 100}) == approx(71.83, rel=0.01) assert calc_cockcroft_gault({'SEX': '2. Female', 'AGE': 65, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': 100}) == approx(61.05, rel=0.01) assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': 65, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': 200}) == approx(35.91, rel=0.01) assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': 65, '2.38 Weight': 120, '2.12.0 Actual Creatinine at time of Surgery': 100}) == approx(110.05, rel=0.01) assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': 80, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': 100}) == approx(57.46, rel=0.01) assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': 65, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': None}) is None assert calc_cockcroft_gault({'SEX': '1. Male', 'AGE': None, '2.38 Weight': 78, '2.12.0 Actual Creatinine at time of Surgery': 100}) is None def get_creatinine_clearance(dat): creatinine_clearance = [] for index, row in dat.iterrows(): creatinine_clearance.append(calc_cockcroft_gault(row)) assert len(creatinine_clearance) == dat.shape[0] return pd.DataFrame(data={'CC' : creatinine_clearance}, index=dat.index) def format_euroscore_ii_features(dat): cc = get_creatinine_clearance(dat) no = count_procedures(dat) features = pd.DataFrame(data={ # New York Heart Association classification of heart failure 'NYHA - II' : dat['NYHA'] == "2. Slight limitation of ordinary physical activity", 'NYHA - III' : dat['NYHA'] == "3. Marked limitation of ordinary physical activity", 'NYHA - IV' : dat['NYHA'] == "4. Symptoms at rest or minimal activity", # Canadian Cardiovascular Society classification of angina 'CCS4' : dat['ANGINA'] == "4. Symptoms at rest or minimal activity", # Insulin-dependent diabetes mellitus 'IDDM' : dat['DIABETES'] == "3. Insulin", 'Age' : dat['AGE'], 'Female' : dat['SEX'] == "2. Female", # Extracardiac arteriopathy "ECA" : dat['PVD'] == "1. Yes", # Chronic pulmonary dysfunction "CPD" : dat['PULMONARY'] == "1. COAD/Asthma/emphysema", # Neurological or musculoskeletal dysfunction severely affecting mobility "N/M mob": dat['NEURO_DYSF'] == "1. Yes", # Previous cardiac surgery "Redo" : dat['PRIOR_HEART_SURGERY'] == "1. Yes", # Creatinine clearance 'Renal dysfunction - On dialysis' : dat['CKD'] == "4. Chronic Dialysis", 'Renal dysfunction - CC <= 50' : cc['CC'] <= 50, 'Renal dysfunction - CC 50−85' : (cc['CC'] > 50) & (cc['CC'] <= 85), # Active endocarditis "AE" : dat['ACTIVE_ENDOCARDITIS'] == "1. Yes", # Critical preoperative state "Critical": (dat['2.18 Pre operative heart rhythm'] == "3. Ventricular fibrillation or ventricular tachycardia") | (dat['SHOCK'] == "1. Yes") | (dat['INOTROPS'] == "1. Yes") | (dat['VENTILATION'] == "1. Yes") | (dat['IABP'] == "1. Yes"), # Left ventricle function "LV function - Moderate" : dat['LVEF'] == "2. Fair (LVEF 30-49%)", "LV function - Poor" : dat['LVEF'] == "3. Poor (LVEF < 30%)", # Recent myocardial infarct 'Recent MI': dat['MI'].isin(["4. MI 31-90 days", "3. MI 1-30 days", "2. MI 6-24 hours", "1. MI < 6 hours"]), # Pulmonary artery systolic pressure 'PA systolic pressure - 31–55 mmHg': dat['Pulmo_hy_Eu2'] == '31-55', 'PA systolic pressure - >=55 mmHg': dat['Pulmo_hy_Eu2'] == '>55', # Urgency "Urgency - Urgent": dat['PRIORITY'] == '2. Urgent', "Urgency - Emergency": dat['PRIORITY'] == '3. Emergency', "Urgency - Salvage": dat['PRIORITY'] == '4. Salvage', # Weight of procedure # note the space after key CABG 'Weight of procedure - 1 non-CABG' : (no['number of procedures'] == 1) & (dat['CABG '] == "0. No"), 'Weight of procedure - 2' : no['number of procedures'] == 2, 'Weight of procedure - 3+' : no['number of procedures'] >= 3, # surgery of thoracic aorta "Thoracic aorta": dat['Surgery on thoracic aorta'] == "1. Yes", # outcome 'STATUS_DISCHARGE': dat['STATUS_DISCHARGE'] == "1. Dead" }, index=dat.index) # set cc=NA correctly features['Renal dysfunction - CC <= 50'] = features['Renal dysfunction - CC <= 50'].where(cc['CC'].notnull(), np.nan) features['Renal dysfunction - CC 50−85'] = features['Renal dysfunction - CC 50−85'].where(cc['CC'].notnull(), np.nan) # drop samples with NAs features = features.dropna(axis='index') assert not features.isnull().values.any() return features # select features and drop NA esii_features = format_euroscore_ii_features(dat) # count remaining patients print(esii_features.shape) # split into test & train train_pred_esii, test_pred_esii = split_dat_by_time(esii_features) # write out to csv train_pred_esii.to_csv('train.esii.features.17.02.20.csv') test_pred_esii.to_csv('test.esii.features.17.02.20.csv') ###Output (6298, 29) ###Markdown Hypothesis-free feature selectionstart with the features selected by Umberto ###Code def format_features(df, keep_cols_with_frac_populated=0.8, fields_to_drop=None): # select predictors features = df[[ 'AGE', 'SEX', 'ANGINA', 'NYHA', 'MI', 'PCI', 'DIABETES', 'SMOKING', 'CKD', 'PULMONARY', 'STROKE', 'NEURO_DYSF', 'PVD', 'AF', 'Pulmo_hy_Eu2', 'PHPT60_EU1', 'LVEF', 'IVNITRATES', 'SHOCK', 'INOTROPS', 'VENTILATION', 'IABP', 'PRIORITY', 'PRIOR_HEART_SURGERY', 'BMI_cat', 'bmi', '2.37 Height', '2.38 Weight', 'YEAR', '3.06 First Operator Grade', 'CABG ', 'VALVE', 'Surgery on thoracic aorta', 'Post infarct septal rupture', 'ASD', 'LV_ANEURYSMECTOMY', 'AF_ABLATION', 'PERICARDIECTOMY', 'ATRIAL_MIXOMA', 'AORTIC_DISSECTION', 'ACTIVE_ENDOCARDITIS', 'AV', 'MV', 'TV', 'PV', 'FRR', 'type FRR', '2.12.0 Actual Creatinine at time of Surgery', 'STATUS_DISCHARGE' ]] # drop cols with high missing rate features = features.dropna(axis='columns', thresh=(features.shape[0] * keep_cols_with_frac_populated)) # drop samples with NAs features = features.dropna(axis='index') # select predictors predictors = features.drop(columns=['STATUS_DISCHARGE']) # select outcome outcome = features[['STATUS_DISCHARGE']] # identify categorical fields cat_columns = predictors.select_dtypes(['object']).columns # convert categorical variables to factors predictors[cat_columns] = predictors[cat_columns].astype('category') outcome = outcome.astype('category') # convert factor to int predictors[cat_columns] = predictors[cat_columns].apply(lambda x: x.cat.codes) outcome = outcome.apply(lambda x: x.cat.codes) assert not predictors.isnull().values.any() assert not outcome.isnull().values.any() # drop features if required if fields_to_drop is None: return predictors, outcome else: return predictors.drop(fields_to_drop, axis=1), outcome train, test = split_dat_by_time(dat) # format data train_pred, train_out = format_features(train) test_pred, test_out = format_features(train) ###Output _____no_output_____ ###Markdown Feature correlationEvaluate colinearity between variables which make the model complex but add nothing and may lead to overfitting ###Code # Compute the correlation matrix corr = train_pred.corr() # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) # print correlated pairs def get_redundant_pairs(df): '''Get diagonal and lower triangular pairs of correlation matrix''' pairs_to_drop = set() cols = df.columns for i in range(0, df.shape[1]): for j in range(0, i+1): pairs_to_drop.add((cols[i], cols[j])) return pairs_to_drop def get_top_abs_correlations(df, n=5): au_corr = df.corr().abs().unstack() labels_to_drop = get_redundant_pairs(df) au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False) return au_corr[0:n] print(get_top_abs_correlations(train_pred, 50)) ###Output bmi 2.38 Weight 0.828196 Pulmo_hy_Eu2 PHPT60_EU1 0.801640 VALVE AV 0.788179 CABG VALVE 0.687628 SEX 2.37 Height 0.655761 SHOCK INOTROPS 0.644499 Surgery on thoracic aorta FRR 0.609502 INOTROPS VENTILATION 0.562174 ANGINA CABG 0.539131 Surgery on thoracic aorta AORTIC_DISSECTION 0.523769 CABG AV 0.508859 VALVE MV 0.486161 ANGINA VALVE 0.477451 2.37 Height 2.38 Weight 0.467240 SHOCK VENTILATION 0.450585 STROKE NEURO_DYSF 0.400248 IVNITRATES PRIORITY 0.392485 CABG MV 0.369584 SEX 2.38 Weight 0.356421 MI CABG 0.347120 BMI_cat bmi 0.337534 AF MV 0.337184 MI VALVE 0.330393 ANGINA AV 0.320437 MV 0.299674 SHOCK PRIORITY 0.296401 CABG Surgery on thoracic aorta 0.279191 AGE PV 0.271799 PRIOR_HEART_SURGERY PV 0.268939 MI AV 0.268222 ANGINA YEAR 0.257793 MI LVEF 0.253838 AF VALVE 0.249876 BMI_cat 2.38 Weight 0.246785 PRIOR_HEART_SURGERY CABG 0.236723 INOTROPS PRIORITY 0.234727 ANGINA MI 0.229658 Surgery on thoracic aorta AV 0.229516 SEX CABG 0.227355 PRIORITY AORTIC_DISSECTION 0.224774 SHOCK Post infarct septal rupture 0.222321 AV FRR 0.221127 2.38 Weight VALVE 0.207627 AF CABG 0.207144 ANGINA IVNITRATES 0.206804 PRIORITY 0.203670 NYHA LVEF 0.193791 SEX VALVE 0.193620 NYHA VALVE 0.192885 INOTROPS Post infarct septal rupture 0.190426 dtype: float64 ###Markdown Feature importanceSelect is driven by Random forest feature importance metric ###Code def get_feature_importance(pred, out): # fit RF with all variables using five-fold CV clf = RandomForestClassifier(random_state=0, n_estimators=100) scores = cross_val_score(clf, pred, out.values.ravel(), cv=5, scoring='roc_auc') # get feature importance measures clf.fit(pred, out.values.ravel()) fi = pd.DataFrame(data={'predictor' : pred.columns, 'feature_importance': clf.feature_importances_}) return fi # plot feature importance measures fi = get_feature_importance(train_pred, train_out) ax = sns.barplot(y='predictor', x="feature_importance", data=fi.sort_values('feature_importance', ascending=False)) ###Output _____no_output_____ ###Markdown Recursive feature elimination with cross-validationStarting with all variables drop one-at-a-time starting with least importance and evaluate ROC AUC ###Code # using random forest classifier with feature importance measure perform feature elimination clf = RandomForestClassifier(random_state=0, n_estimators=100) rfecv = RFECV(estimator=clf, cv=5, scoring='roc_auc', n_jobs=-1) rfecv.fit(train_pred, train_out.values.ravel()) print("Optimal number of features : %d" % rfecv.n_features_) # Plot number of features VS. cross-validation scores plt.figure() plt.xlabel("Number of features selected") plt.ylabel("Cross validation score (roc auc)") plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_) plt.show() # Do the variables add something to the model? True=Yes rfecv.support_ # Get the roc auc scores for each model rfecv.grid_scores_ ###Output _____no_output_____ ###Markdown Drop specific variables to see if we can do withoutFeature elimination suggested to keep all variables so instead try eliminating manually ###Code def get_roc_for_rf(pred, out): clf = RandomForestClassifier(random_state=0, n_estimators=100) scores = cross_val_score(clf, pred, out.values.ravel(), cv=5, scoring='roc_auc') return "cross validation (k=5) roc auc: mean {}, std {}, variables {}".format(np.round(np.mean(scores), 3), np.round(np.std(scores), 3), len(pred.columns)) # All 47 variables get_roc_for_rf(train_pred, train_out) # use feature importance to drop the last 22 variables that do not add much to the model # drop highly correlated variables selecting the best feature importance measure fields_to_drop = list(fi.sort_values(by=['feature_importance'], ascending=True)[0:21]['predictor']) fields_to_drop.append('PHPT60_EU1') fields_to_drop.append('bmi') fields_to_drop.append('YEAR') # not useful for future prediction fields_to_drop.append('BMI_cat') print(fields_to_drop) train_pred_subset, train_out_subset = format_features(train, fields_to_drop=fields_to_drop) get_roc_for_rf(train_pred_subset, train_out_subset) train_pred_subset.columns ###Output _____no_output_____ ###Markdown select final predictors ###Code def format_final_features(df): final_predictors = ['AGE', 'SEX', 'ANGINA', 'NYHA', 'MI', 'DIABETES', 'SMOKING', 'PULMONARY', 'STROKE', 'PVD', 'AF', 'LVEF', 'IVNITRATES', 'SHOCK', 'CKD', 'INOTROPS', 'PRIORITY', 'PRIOR_HEART_SURGERY', '2.37 Height', '2.38 Weight', 'CABG ', 'Surgery on thoracic aorta', 'AV'] final_predictors.append('STATUS_DISCHARGE') # select predictors features = df[final_predictors] # drop samples with NAs features = features.dropna(axis='index') # select predictors predictors = features.drop(columns=['STATUS_DISCHARGE']) # select outcome outcome = features[['STATUS_DISCHARGE']] # identify categorical fields cat_columns = predictors.select_dtypes(['object']).columns # convert categorical variables to factors predictors[cat_columns] = predictors[cat_columns].astype('category') outcome = outcome.astype('category') # convert factor to int predictors[cat_columns] = predictors[cat_columns].apply(lambda x: x.cat.codes) outcome = outcome.apply(lambda x: x.cat.codes) assert not predictors.isnull().values.any() assert not outcome.isnull().values.any() return predictors, outcome # get final predictors and run the roc curve train_pred_final, train_out_final = format_final_features(train) get_roc_for_rf(train_pred_final, train_out_final) # plot feature importance measures fi = get_feature_importance(train_pred_final, train_out_final) ax = sns.barplot(y='predictor', x="feature_importance", data=fi.sort_values('feature_importance', ascending=False)) # save data to csv for model development train_pred_final, train_out_final = format_final_features(train) pd.concat([train_pred_final, train_out_final], axis=1).to_csv('train.selected.features.17.02.20.csv') test_pred_final, test_out_final = format_final_features(test) pd.concat([test_pred_final, test_out_final], axis=1).to_csv('test.selected.features.17.02.20.csv') test_pred_final.describe() ###Output _____no_output_____ ###Markdown Removing identifiers ###Code stats_df.drop([col for col in stats_df.columns if 'Id' in col], axis=1, inplace=True) ###Output _____no_output_____ ###Markdown Removing useless numeric columns ###Code stats_df.drop(['season', 'champLevel'], axis=1, inplace=True) ###Output _____no_output_____ ###Markdown Normalizing the rest of the stats by time Transform game duration format into minutes ###Code stats_df['gameDuration_in_minutes'] = stats_df.gameDuration / 60 ###Output _____no_output_____ ###Markdown Exclude columns that aren't affected by time ###Code stats_to_normalize = [col for col in stats_df.columns if '_at_' not in col and 'tt' not in col and 'gameDuration' not in col] stats_normalized_df = stats_df[stats_to_normalize].apply(lambda x: x / stats_df.gameDuration_in_minutes) not_time_affected_stats_df = stats_df[[col for col in stats_df.columns if '_at_' in col or 'tt' in col]] ###Output _____no_output_____ ###Markdown Clustering playstyles by position ###Code positions = slo_df.position.unique().tolist() positions stats_by_position = {} for i, p in enumerate(positions): # Preprocessing stats = stats_normalized_df[i::5] nan_cols = stats.iloc[:, stats.isnull().any().tolist()].columns stats.drop(nan_cols, axis=1, inplace=True) labels = slo_df[i::5].win # Clustering km = KMeans(n_clusters=3) clusters = km.fit_predict(X=stats) stats['clusters'] = clusters c0 = stats[stats.clusters == 0] c1 = stats[stats.clusters == 1] c2 = stats[stats.clusters == 2] clusters = [c0, c1, c2] stats_by_position[p] = {'X': stats, 'top_10_features_by_cluster': []} for i, c in enumerate(clusters): c_new = SelectKBest(chi2, k=10).fit(X=c, y=slo_df.ix[c.index].win) c_new_cols = c.iloc[:, c_new.get_support()].columns.tolist() stats_by_position[p]['top_10_features_by_cluster'].append(c_new_cols) stats_by_position['SUPP']['X'].clusters.value_counts() vt = VarianceThreshold(threshold=.5) vt.fit(X=top_c_2) top_stats.iloc[:, vt.get_support()].columns top_stats.iloc[:, vt.get_support()].columns top_stats.fillna(top_stats.mean()) ###Output _____no_output_____ ###Markdown How to choose useful features? 1. Removing features with low variance If one feature has a value whose count is more than 90% of all data. 2. RFE (Feature selection using SelectFromModel) In this note, I will show how to do rfe by sklearn. ###Code from sklearn.feature_selection import RFECV # we should choose a model before RFECV ###Output _____no_output_____ ###Markdown Feature Selection---Feature selection is the process of selecting the features that hold the most predictive power to the target. By removing unnecessary features, we reduce model complexity and minimize the computational resources required for training and inference. Feature selection is a crucial step that can have a great impact on model efficiency in production settings.The methods of feature selection we will perform are:* Filter Methods * Correlation * Univariate Feature Selection* Wrapper Methods * Forward Selection * Backward Selection * Recursive Feature Elimination* Embedded Methods * Feature Importance (Tree-based) * L1 RegularizationIn this notebook, we will demonstrate the feature selection methods above on the [Census Income](https://archive.ics.uci.edu/ml/datasets/Census-Income+%28KDD%29) dataset from the UCI repository. The dataset contains both numerical and categorical features with the goal to predict whether a person's salary is greater than or equal to $50k. Imports ###Code # for data processing and manipulation import pandas as pd import numpy as np # scikit-learn modules for feature selection and model evaluation from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import RFE, SelectKBest, SelectFromModel, SequentialFeatureSelector, chi2, f_classif from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, roc_auc_score, precision_score, recall_score, f1_score from sklearn.feature_selection import SelectFromModel from sklearn.preprocessing import StandardScaler, MinMaxScaler # libraries for visualization import seaborn as sns import matplotlib import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown ###Code !pip install -Uqq fastbook --quiet ! pip install pyfolio --quiet import fastbook # fastbook.setup_book() from fastbook import * from pandas.api.types import is_string_dtype, is_numeric_dtype, is_categorical_dtype from fastai.tabular.all import * from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from lightgbm import LGBMClassifier from xgboost import XGBClassifier from pyfolio.timeseries import perf_stats from pyfolio import create_simple_tear_sheet import os import re import random import numpy as np from sklearn.metrics import accuracy_score, confusion_matrix, classification_report import pandas as pd from pylab import mpl, plt plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' os.environ['PYTHONHASHSEED'] = '0' import warnings warnings.filterwarnings('ignore') pairs = ['AUDCAD', 'AUDCHF', 'AUDJPY', 'AUDNZD', 'AUDUSD', 'CAD', 'CADCHF', 'CADJPY', 'CHF', 'CHFJPY', 'EURAUD', 'EURCAD', 'EURCHF', 'EURGBP', 'EURJPY', 'EURNZD', 'EURUSD', 'GBPAUD', 'GBPCAD', 'GBPCHF', 'GBPJPY', 'GBPNZD', 'GBPUSD', 'JPY', 'NZDCAD', 'NZDCHF', 'NZDJPY', 'NZDUSD'] def get_data(pair): ''' Retrieves and prepares the data. ''' url = f'https://raw.githubusercontent.com/African-Quant/WQU_MScFE_Capstone_Grp9/master/Datasets/{pair}%3DX.csv' raw = pd.read_csv(url) raw = pd.DataFrame(raw).drop(['Adj Close', 'Volume'], axis=1) raw.iloc[:,0] = pd.to_datetime(raw.iloc[:,0]) raw.set_index('Date', inplace=True) return raw d = {a:b for a, b in enumerate(pairs)} print(d) # ATR def eATR(df1,n=14): """This calculates the Average True Range of of a dataframe of the open, high, low, and close data of an instrument""" df = df1[['Open', 'High', 'Low', 'Close']].copy() # True Range df['TR'] = 0 for i in range(len(df)): try: df.iloc[i, 4] = max(df.iat[i,1] - df.iat[i,2], abs(df.iat[i,1] - df.iat[i-1,3]), abs(df.iat[i,2] - df.iat[i-1,3])) except ValueError: pass # eATR df['eATR'] = df['TR'].ewm(span=n, adjust=False).mean() return df['eATR'] data = get_data(pairs[0]) data.head(1) def ssl(df1): df = df1.copy() df['smaHigh'] = df['High'].rolling(window=10).mean() df['smaLow'] = df['Low'].rolling(window=10).mean() df['hlv'] = 0 df['hlv'] = np.where(df['Close'] > df['smaHigh'],1,np.where(df['Close'] < df['smaLow'],-1,df['hlv'].shift(1))) df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow']) df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh']) df['sslPosition'] = np.where(df['Close'] > df['sslUp'], 1, np.where(df['Close'] < df['sslDown'], -1, 0)) return df[['sslDown', 'sslUp', 'sslPosition']] # Waddah Attar def WAE(df1): df = df1.copy() # EMA long_ema = df.loc[:,'Close'].ewm(span=40, adjust=False).mean() short_ema = df.loc[:,'Close'].ewm(span=20, adjust=False).mean() # MACD MACD = short_ema - long_ema # bBands sma20 = df.loc[:,'Close'].rolling(window=20).mean() # 20 SMA stddev = df.loc[:,'Close'].rolling(window=20).std() # 20 STDdev lower_band = sma20 - (2 * stddev) upper_band = sma20 + (2 * stddev) #Waddah Attar t1 = (MACD - MACD.shift(1))* 150 #t2 = MACD.shift(2) - MACD.shift(3) df['e1'] = upper_band - lower_band df['e2'] = -1 *df['e1'] #e2 = upper_band.shift(1) - lower_band.shift(1) df['trendUp'] = np.where(t1 > 0, t1, 0) df['trendDown'] = np.where(t1 < 0, t1, 0) df['waePosition'] = np.where(df['trendUp'] > 0, 1, np.where(df['trendDown'] < 0, -1, 0)) return df[['e1','e2','trendUp', 'trendDown', 'waePosition']] def lag_feat(data1): data = data1.copy() lags = 8 cols = [] for lag in range(1, lags + 1): col = f'lag_{lag}' data[col] = data['ret'].shift(lag) cols.append(col) return data[cols] def datepart_feat(df0, colname = 'Date'): """This function adds some common pandas date parts like 'year', 'month' etc as features to a dataframe """ df = df0.copy() df.reset_index(inplace=True) df1 = df.loc[:,colname] nu_feats = ['Year', 'Month', 'Day', 'Dayofweek', 'daysinmonth', 'Dayofyear', 'Is_month_end', 'Is_month_start', 'quarter', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'] targ_pre = re.sub('[Dd]ate$', '', colname) for n in nu_feats: df[targ_pre+n] = getattr(df1.dt,n.lower()) df[targ_pre+'week'] = df1.dt.isocalendar().week.astype(np.int64) df[targ_pre+'Elapsed'] = df1.astype(np.int64) // 10**9 nu_feats.extend(['week', 'Elapsed']) df.set_index(colname, inplace=True) return df[nu_feats] def gen_feat(pair): df0 = get_data(pair).iloc[-4200:,] df0['ret'] = df0['Close'].pct_change() df0['dir'] = np.sign(df0['ret']) eATR_ = eATR(df0).shift(1) wae = WAE(df0).shift(1) ssl1 = ssl(df0).shift(1) datepart = datepart_feat(df0) lags = lag_feat(df0) return pd.concat([df0, eATR_, wae, ssl1, datepart, lags], axis=1).dropna() dataset = gen_feat(pairs[0]) dataset.drop(['Open', 'High', 'Low'], axis=1, inplace=True) dataset.tail() cols = list(dataset.columns) print(cols) feats = cols[2:] df_train.info() df_train = dataset.iloc[:-1000,:] train = df_train.copy() df_test = dataset.iloc[-1000:,:] test = df_test.copy() dep_var = 'dir' ###Output _____no_output_____ ###Markdown Using *FastAI* and *Random Forest* to Predict Market Direction. ###Code procs = [Categorify, FillMissing] cond = df_train.Year<2015 train_idx = np.where(cond)[0] valid_idx = np.where(~cond)[0] splits = (list(train_idx),list(valid_idx)) cont,cat = cont_cat_split(train[feats], 1, dep_var=dep_var) to = TabularPandas(train[feats], procs, cat, cont, y_names=dep_var, splits=splits) len(to.train),len(to.valid) to.show(3) to.items.head(2) conti,categ = cont_cat_split(test[feats], 1, dep_var=dep_var) to_t = TabularPandas(test[feats], procs, categ, conti, y_names=dep_var, splits=None) save_pickle('to.pkl',to) to = load_pickle('to.pkl') xs,y = to.train.xs,to.train.y valid_xs,valid_y = to.valid.xs,to.valid.y def rfc(xs, y, n_estimators=40, max_samples=2000, max_features=0.5, min_samples_leaf=5, **kwargs): return RandomForestClassifier(n_jobs=-1, n_estimators=n_estimators, max_samples=max_samples, max_features=max_features, min_samples_leaf=min_samples_leaf, oob_score=True).fit(xs, y) m = rfc(xs, y); valid_pred = m.predict(valid_xs) valid_acc = accuracy_score(valid_y, valid_pred) print(f'Validation Accuracy: {valid_acc}') xs_t,y_t = to_t.train.xs, to_t.train.ys.values.ravel() test_pred = m.predict(test[feats[1:]]) test_acc = accuracy_score(test['dir'], test_pred) print(f'Test set Accuracy: {test_acc}') test['prediction'] = test_pred test['prediction'].value_counts() hits = np.sign(test['ret'] * test['prediction']).value_counts() hits test['strategy'] = (test['prediction'] * test['ret']) test[['ret', 'strategy']].sum().apply(np.exp) test[['ret', 'strategy']].cumsum( ).apply(np.exp).plot(figsize=(10, 6)); # plt.savefig('../../images/ch05/dl_plot_2.png') def feat_imp(m, df): return pd.DataFrame({'cols':df.columns, 'imp':m.feature_importances_} ).sort_values('imp', ascending=False) f_i = feat_imp(m, xs) f_i[:30] def plot_fi(fi): return fi.plot('cols', 'imp', 'barh', figsize=(15,10),title='Random forest - feature importance', xlabel='Features', legend=False), plt.axvline(0.01, color='r', ls='--') plot_fi(f_i[:30]); to_keep = f_i[f_i.imp>0.01].cols len(to_keep) xs_imp = xs[to_keep] valid_xs_imp = valid_xs[to_keep] m = rfc(xs_imp, y) valid_pred = m.predict(valid_xs_imp) valid_acc = accuracy_score(valid_y, valid_pred) print(f'Validation Accuracy: {valid_acc}') test_pred = m.predict(test[to_keep]) test_acc = accuracy_score(test['dir'], test_pred) print(f'Test set Accuracy: {test_acc}') len(xs.columns), len(xs_imp.columns) plot_fi(feat_imp(m, xs_imp)); cluster_columns(xs_imp) def get_oob(df): m = RandomForestClassifier(n_estimators=40, min_samples_leaf=15, max_samples=2000, max_features=0.5, n_jobs=-1, oob_score=True) m.fit(df, y) return m.oob_score_ get_oob(xs_imp) print(list(xs_imp.columns)) # {c:get_oob(xs_imp.drop(c, axis=1)) for c in ( # 'Month', 'Dayofyear', 'sslUp', 'sslDown')} # get_oob(xs_imp.drop('Month', axis=1)) test_imp = test[to_keep] xs_final = xs_imp#.drop('Month', axis=1) valid_xs_final = valid_xs_imp#.drop('Month', axis=1) test_imp_final = test_imp#.drop('Month', axis=1) save_pickle('xs_final.pkl', xs_final) save_pickle('valid_xs_final.pkl', valid_xs_final) save_pickle('test_imp_final.pkl', test_imp_final) xs_final = load_pickle('xs_final.pkl') valid_xs_final = load_pickle('valid_xs_final.pkl') test_imp_final = load_pickle('test_imp_final.pkl') m = rfc(xs_final, y) train_pred = m.predict(xs_final) train_acc = accuracy_score(y, train_pred) print(f'Train Set Accuracy: {train_acc}') print(confusion_matrix(y, train_pred)) print(classification_report(y, train_pred)) valid_pred = m.predict(valid_xs_final) valid_acc = accuracy_score(valid_y, valid_pred) print(f'Validation Set Accuracy: {valid_acc}') print(confusion_matrix(valid_y, valid_pred)) print(classification_report(valid_y, valid_pred)) test_pred = m.predict(test_imp_final) test_acc = accuracy_score(test['dir'], test_pred) print(f'Test Set Accuracy: {test_acc}') print(confusion_matrix(test['dir'], test_pred)) print(classification_report(test['dir'], test_pred)) ?create_simple_tear_sheet create_simple_tear_sheet(df_test['ret']*test_pred) ###Output _____no_output_____ ###Markdown $Imports$ ###Code import pandas as pd import numpy as np import pickle import os import matplotlib.pyplot as plt %matplotlib inline ## for feature slection from sklearn.linear_model import Lasso, LogisticRegression from sklearn.feature_selection import SelectFromModel # to visualise al the columns in the dataframe pd.pandas.set_option('display.max_columns', None) ###Output _____no_output_____ ###Markdown $Load-Data$ ###Code X_train = pd.read_csv("data/X_train.csv") y_train = pd.read_csv("data/y_train.csv") X_test = pd.read_csv("data/X_test.csv") y_test = pd.read_csv("data/y_test.csv") print(f"X_train data size is {X_train.shape}") print(f"y_train data size is {y_train.shape}") print(f"X_test data size is {X_test.shape}") print(f"y_test data size is {y_test.shape}") X_train.head() ###Output _____no_output_____ ###Markdown Apply Feature Selection ###Code # first, I specify the Lasso Regression model, and I # select a suitable alpha (equivalent of penalty). # The bigger the alpha the less features that will be selected. # Then I use the selectFromModel object from sklearn, which # will select the features which coefficients are non-zero feature_sel_model = SelectFromModel(LogisticRegression(C=1, penalty='l1', solver='liblinear')) feature_sel_model.fit(X_train, y_train) feature_sel_model.get_support() # let's print the number of total and selected features # this is how we can make a list of the selected features selected_feat = X_train.columns[(feature_sel_model.get_support())] # let's print some stats print(f'total features: {X_train.shape[1]}') print(f'selected features: {len(selected_feat)}') print(f'features with coefficients shrank to zero: {np.sum(feature_sel_model.estimator_.coef_ == 0)}') list(selected_feat) X_train=X_train[selected_feat] X_train.head() ###Output _____no_output_____ ###Markdown Pickle the Variables ###Code def save_or_pickle_var(myvar, name, location): file_path = os.path.join(location, f'{name}.pkl') with open(file_path, 'wb') as file: # A new file will be created pickle.dump(myvar, file) save_or_pickle_var(list(selected_feat), "selected_feat", "data") def load_pickle_var(path): with open(path, 'rb') as file: # Call load method to deserialze myvar = pickle.load(file) return myvar selected_feat = load_pickle_var("data/selected_feat.pkl") selected_feat ###Output _____no_output_____ ###Markdown Lab 6 - Feature Selection Analysis Elder de Sousa Whalen 10.16.2020 OverviewThis lab has the purpose of comparing four different models in regards to feature selection. The models used are: Logistic regression including all features, used as the base model; Logistic regression with stepwise selection based on p-values; Random forest based on principal compnent analysis feature selection; Random Forest based on feature importance.Logistic regression is a model that uses features to predict the output of a categorical variable.Random forest is an ensemble learning technique that consists of a collection of a number of decision trees. It outputs the class that is the mode of the classes for a categorical target variable.For this lab, Random forest will be used in combination with two different methods: feature importance and principal component analysis (PCA).Gini importance is a feature selection based on the random forest classifier that gives a score based on importance to each feature.PCA is a technique used to reduce the dimension of datasets, creating new variables that is a combination of the orignal variables while still being able to explain a great portion of the variance within the dataset.The performance measure used to compare the models will be the [accuracy score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html) imported from sklearn.metrics and a comparison of the ROC/AUC curve between all models. DataThe caravan data set used in this lab contains information on customers of an insurance company. It contains 86 features (variables). The data was collected to attempt to answer if it's possible to predict who would be interested in buying a carvan insurance policy with the target variable being CARAVAN. ###Code import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model import pandas as pd from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from sklearn.metrics import accuracy_score from sklearn.feature_selection import SelectFromModel %matplotlib inline # Load the caravan dataset url = 'https://raw.githubusercontent.com/WillKoehrsen/feature-selector/master/data/caravan-insurance-challenge.csv' df = pd.read_csv(url) df.head() all_vars = df.drop(['ORIGIN'], axis=1) #Group only the input variables x_vars = all_vars.drop(['CARAVAN'], axis=1) #Get the target variable y = df['CARAVAN'] print(y[0:5]) x_vars.head() ###Output 0 0 1 0 2 0 3 0 4 0 Name: CARAVAN, dtype: int64 ###Markdown Exploratory Data Analysis ###Code # Check for missing values missing = np.isnan(all_vars.values).any() if ( missing == False): print('No missing values') else: print('Oh uh. There are missing values!') # Summary of the input variables x_vars.describe() # Histogram of the target variable y.hist() # Set the title and labels plt.xlabel("Policy Status") plt.ylabel("Number of People") plt.title("Number of People with Caravan's Insured vs Not Insured") # show the plot plt.show() ###Output _____no_output_____ ###Markdown The histogram above shows imbalance in the dataset with respect to the target variable. Should the data be balanced before attempting to create any model? ###Code #Attempt to capture only the highly correlated features ( > 0.6) #https://stackoverflow.com/questions/26463714/pandas-get-combination-of-columns-where-correlation-is-high corr_matrix = x_vars.corr().abs() indices = np.where(corr_matrix > 0.6) indices = [(corr_matrix.index[x], corr_matrix.columns[y]) for x, y in zip(*indices) if x != y and x < y] len(indices) print(indices) ###Output [('MOSTYPE', 'MOSHOOFD'), ('MGEMOMV', 'MFALLEEN'), ('MGEMOMV', 'MFWEKIND'), ('MGODPR', 'MGODGE'), ('MRELGE', 'MRELOV'), ('MRELGE', 'MFALLEEN'), ('MRELOV', 'MFALLEEN'), ('MRELOV', 'MAUT0'), ('MFALLEEN', 'MFWEKIND'), ('MOPLHOOG', 'MOPLLAAG'), ('MOPLHOOG', 'MSKA'), ('MOPLMIDD', 'MOPLLAAG'), ('MOPLLAAG', 'MSKA'), ('MOPLLAAG', 'MSKC'), ('MBERHOOG', 'MSKA'), ('MBERHOOG', 'MZFONDS'), ('MBERHOOG', 'MZPART'), ('MBERARBG', 'MSKC'), ('MHHUUR', 'MHKOOP'), ('MAUT1', 'MAUT0'), ('MZFONDS', 'MZPART'), ('MINKM30', 'MINKGEM'), ('MINK7512', 'MINKGEM'), ('PWAPART', 'AWAPART'), ('PWABEDR', 'AWABEDR'), ('PWALAND', 'AWALAND'), ('PPERSAUT', 'APERSAUT'), ('PBESAUT', 'ABESAUT'), ('PMOTSCO', 'AMOTSCO'), ('PVRAAUT', 'AVRAAUT'), ('PAANHANG', 'AAANHANG'), ('PTRACTOR', 'ATRACTOR'), ('PWERKT', 'AWERKT'), ('PBROM', 'ABROM'), ('PLEVEN', 'ALEVEN'), ('PPERSONG', 'APERSONG'), ('PGEZONG', 'AGEZONG'), ('PWAOREG', 'AWAOREG'), ('PBRAND', 'ABRAND'), ('PZEILPL', 'AZEILPL'), ('PPLEZIER', 'APLEZIER'), ('PFIETS', 'AFIETS'), ('PINBOED', 'AINBOED'), ('PBYSTAND', 'ABYSTAND')] ###Markdown The code above shows that there are 44 pairs of features with a correlation greater than |0.6|. This is an indication of the presence of collinearity in the dataset. Models ###Code #Firt split the data 70% train and 30% test X_train, X_test, y_train, y_test = train_test_split(x_vars, y, test_size=0.3, random_state=0) ## BALANCED DATA SET using SMOTE (COMMENT this whole cell to used imbalanced data) from imblearn.over_sampling import SMOTE # smt = SMOTE() X_train, y_train = smt.fit_sample(X_train, y_train) ###Output /usr/local/lib/python3.6/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/). "(https://pypi.org/project/six/).", FutureWarning) /usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.neighbors.base module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API. warnings.warn(message, FutureWarning) /usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24. warnings.warn(msg, category=FutureWarning) ###Markdown Logistic regression using all features ###Code # Create logist regression object logreg = linear_model.LogisticRegression(max_iter=10000) # Train the model using the training sets logreg.fit(X_train, y_train) # Make predictions using the testing set y_pred = logreg.predict(X_test) #Print the accuracy score of the logist model print('Logistic Regression Accuracy: {:.2f}'.format(logreg.score(X_test, y_test))) # ROC Curve from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test)) fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() ###Output _____no_output_____ ###Markdown Logistic Regression with stepwise based on p-values ###Code #https://datascience.stackexchange.com/questions/24405/how-to-do-stepwise-regression-using-sklearn/24447#24447 import statsmodels.api as sm X = x_vars def stepwise_selection(X, y, initial_list=[], threshold_in=0.01, threshold_out = 0.05, verbose=True): """ Perform a forward-backward feature selection based on p-value from statsmodels.api.OLS Arguments: X - pandas.DataFrame with candidate features y - list-like with the target initial_list - list of features to start with (column names of X) threshold_in - include a feature if its p-value < threshold_in threshold_out - exclude a feature if its p-value > threshold_out verbose - whether to print the sequence of inclusions and exclusions Returns: list of selected features Always set threshold_in < threshold_out to avoid infinite looping. See https://en.wikipedia.org/wiki/Stepwise_regression for the details """ included = list(initial_list) while True: changed=False # forward step excluded = list(set(X.columns)-set(included)) new_pval = pd.Series(index=excluded) for new_column in excluded: model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included+[new_column]]))).fit() new_pval[new_column] = model.pvalues[new_column] best_pval = new_pval.min() if best_pval < threshold_in: # best_feature = new_pval.argmin() best_feature = new_pval.idxmin() included.append(best_feature) changed=True if verbose: print('Add {:30} with p-value {:.6}'.format(best_feature, best_pval)) # backward step model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit() # use all coefs except intercept pvalues = model.pvalues.iloc[1:] worst_pval = pvalues.max() # null if pvalues is empty if worst_pval > threshold_out: changed=True worst_feature = pvalues.argmax() included.remove(worst_feature) if verbose: print('Drop {:30} with p-value {:.6}'.format(worst_feature, worst_pval)) if not changed: break return included result = stepwise_selection(X, y) print('resulting features:') print(result) new_xvars = x_vars[['PPERSAUT', 'MKOOPKLA', 'PWAPART', 'APLEZIER', 'MOPLHOOG', 'PBRAND', 'MBERBOER', 'MRELGE', 'PWALAND', 'ABRAND', 'AZEILPL', 'MINK123M', 'PBYSTAND', 'PGEZONG', 'AGEZONG', 'MHHUUR']] new_xvars.head() # Split the data 70% train and 30% test #X_train, X_test, y_train, y_test = train_test_split(new_xvars, y, test_size=0.3, random_state=0) # Create logist regression object logreg_pval = linear_model.LogisticRegression(max_iter=10000) # Train the model using the training sets logreg_pval.fit(X_train, y_train) # Make predictions using the testing set y_pred = logreg_pval.predict(X_test) #Print the accuracy score of the logist model print('Logistic Regression Accuracy: {:.2f}'.format(logreg_pval.score(X_test, y_test))) # ROC Curve from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(y_test, logreg_pval.predict(X_test)) fpr, tpr, thresholds = roc_curve(y_test, logreg_pval.predict_proba(X_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (p-val based) (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() ###Output _____no_output_____ ###Markdown Random Forest based on Principal component analysis ###Code from sklearn.preprocessing import StandardScaler # standardize the data X_std = StandardScaler().fit_transform(x_vars) mean_vec = np.mean(X_std, axis=0) cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1) print('Covariance matrix \n%s' %cov_mat) #Perform eigendecomposition on covariance matrix cov_mat = np.cov(X_std.T) eig_vals, eig_vecs = np.linalg.eig(cov_mat) print('Eigenvectors \n%s' %eig_vecs) print('\nEigenvalues \n%s' %eig_vals) pca = PCA().fit(all_vars) plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance'); plt.plot(np.cumsum(pca.explained_variance_ratio_)) plt.xlabel('number of components') plt.ylabel('cumulative explained variance'); pca = PCA(0.90).fit(all_vars) pca.n_components_ ###Output _____no_output_____ ###Markdown From the results above, using PCA we were able to reduce the predicting variables from 85 to 13 and still be able to explain about 90% of the variance. ###Code #https://towardsdatascience.com/machine-learning-step-by-step-6fbde95c455a # Split the data 70% train and 30% test X_train_std, X_test_std, y_train, y_test = train_test_split(X_std, y, test_size=0.3, random_state=0) ## Balance Standardized data (COMMENT the next line to used imbalanced data) X_train_std, y_train = smt.fit_sample(X_train_std, y_train) # Reduce the number of features from 85 to 13 in the X_train_std and X_test_std data pca = PCA(n_components=13) pca.fit(X_train_std) X_train_pca = pca.transform(X_train_std) X_test_pca = pca.transform(X_test_std) # Fit train data to Random Forest Model from sklearn.ensemble import RandomForestClassifier rfc_pca = RandomForestClassifier(n_estimators=1000, random_state=0) rfc_pca.fit(X_train_pca, y_train) y_pred = rfc_pca.predict(X_test_pca) accuracy_score(y_test, y_pred) # ROC Curve from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve rfc_pca_roc_auc = roc_auc_score(y_test, rfc_pca.predict(X_test_pca)) fpr, tpr, thresholds = roc_curve(y_test, rfc_pca.predict_proba(X_test_pca)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Random Forest with PCA (area = %0.2f)' % rfc_pca_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() ###Output _____no_output_____ ###Markdown Random Forest based on feature importance feature selection ###Code #Firt split the data 70% train and 30% test X_train, X_test, y_train, y_test = train_test_split(x_vars, y, test_size=0.3, random_state=0) ## Balance data (COMMENT the next line to used imbalanced data) X_train, y_train = smt.fit_sample(X_train, y_train) # Create a list of feature names feat_labels = x_vars.columns # Create a random forest classifier clf = RandomForestClassifier(n_estimators=1000, random_state=0) # Train the classifier clf.fit(X_train, y_train) # Print the name and gini importance of each feature for feature in zip(feat_labels, clf.feature_importances_): print(feature) # Create a selector object that will use the random forest classifier to identify # features that have an importance of more than 0.02 sfm = SelectFromModel(clf, threshold=0.02) # Train the selector sfm.fit(X_train, y_train) # Print the names of the most important features for feature_list_index in sfm.get_support(indices=True): print(feat_labels[feature_list_index]) # Transform the data to create a new dataset containing only the most important features # Note: We have to apply the transform to both the training X and test X data. X_important_train = sfm.transform(X_train) X_important_test = sfm.transform(X_test) # Create a new random forest classifier for the most important features clf_important = RandomForestClassifier(random_state=0, n_jobs=-1) # Train the new classifier on the new dataset containing the most important features clf_important.fit(X_important_train, y_train) # Apply The Full Featured Classifier To The Test Data y_important_pred = clf_important.predict(X_important_test) # View The Accuracy Of Our Limited Feature (2 Features) Model accuracy_score(y_test, y_important_pred) # ROC Curve from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve rfc_feat_roc_auc = roc_auc_score(y_test, clf_important.predict(X_important_test)) fpr, tpr, thresholds = roc_curve(y_test, clf_important.predict_proba(X_important_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Random Forest with PCA (area = %0.2f)' % rfc_feat_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() ###Output _____no_output_____
notebooks/dlp07_working_with_keras.ipynb
###Markdown 준비된 `'difficulty'` 층을 출력층으로 추가하여 `priority`, `department`, `difficulty`세 개의 출력값을 생성하는 새로운 모델을 구성한다. ###Code new_model = keras.Model( inputs=[title, text_body, tags], outputs=[priority, department, difficulty]) ###Output _____no_output_____ ###Markdown 새로 생성된 모델은 기존에 훈련된 모델의 가중치,즉, 은닉층에 사용된 가중치는 그대로 사용되며,모델 구성 그래프는 다음과 같다.```python>>> keras.utils.plot_model(new_model, "updated_ticket_classifier.png", show_shapes=True)``` 요약 결과는 다음과 같다. ###Code new_model.summary() ###Output Model: "model_2" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== title (InputLayer) [(None, 10000)] 0 __________________________________________________________________________________________________ text_body (InputLayer) [(None, 10000)] 0 __________________________________________________________________________________________________ tags (InputLayer) [(None, 100)] 0 __________________________________________________________________________________________________ concatenate (Concatenate) (None, 20100) 0 title[0][0] text_body[0][0] tags[0][0] __________________________________________________________________________________________________ dense_8 (Dense) (None, 64) 1286464 concatenate[0][0] __________________________________________________________________________________________________ priority (Dense) (None, 1) 65 dense_8[0][0] __________________________________________________________________________________________________ department (Dense) (None, 4) 260 dense_8[0][0] __________________________________________________________________________________________________ difficulty (Dense) (None, 3) 195 dense_8[0][0] ================================================================================================== Total params: 1,286,984 Trainable params: 1,286,984 Non-trainable params: 0 __________________________________________________________________________________________________ ###Markdown 모델 구성법 3: 서브클래싱 케라스 모델과 호환되는 모델 클래스를 직접 선언하여 활용하려면 `keras.Model` 클래스를 상속해야 한다.이런 방식을 **서브클래싱**(subclassing)이라 부르며`keras.Model` 클래스를 상속하면서 기본적으로 아래 두 메서드를 목적에 맞추어 재정의(overriding)하면 된다.- `__init__()` 메서드(생성자): 은닉층과 출력층의 구성요소 지정- `call()` 메서드: 모델 구성 후 출력값 반환앞서 함수형 API로 구성한 티켓 모델을 서브클래싱을 기법을 이용하여 구현하면 다음과 같다.**참고**: `keras.layers.Layer`를 상속하여 사용자 정의 층을 선언하는 방식과 거의 유사하다([3장 6절](https://codingalzi.github.io/dlp/notebooks/dlp03_introduction_to_keras_and_tf.html) 참조). ###Code class CustomerTicketModel(keras.Model): def __init__(self, num_departments): super().__init__() self.concat_layer = layers.Concatenate() self.mixing_layer = layers.Dense(64, activation="relu") self.priority_scorer = layers.Dense(1, activation="sigmoid") self.department_classifier = layers.Dense( num_departments, activation="softmax") def call(self, inputs): # inputs: 사전 객체 입력값. 모양은 미정. title = inputs["title"] text_body = inputs["text_body"] tags = inputs["tags"] features = self.concat_layer([title, text_body, tags]) # 은닉층 features = self.mixing_layer(features) priority = self.priority_scorer(features) # 출력층 department = self.department_classifier(features) return priority, department # outputs ###Output _____no_output_____ ###Markdown 모델 구성은 해당 모델의 객체를 생성하면 된다.다만 `Layer`의 경우처럼 가중치는 실제 데이터와 함께 호출되지 전까지 생성되지 않는다. ###Code model = CustomerTicketModel(num_departments=4) model.weights ###Output _____no_output_____ ###Markdown 컴파일, 훈련, 평가, 예측은 이전과 완전히 동일한 방식으로 실행된다. ###Code model.compile(optimizer="adam", loss=["mean_squared_error", "categorical_crossentropy"], metrics=[["mean_absolute_error"], ["accuracy"]]) model.fit({"title": title_data, "text_body": text_body_data, "tags": tags_data}, [priority_data, department_data], epochs=1) model.evaluate({"title": title_data, "text_body": text_body_data, "tags": tags_data}, [priority_data, department_data]) priority_preds, department_preds = model.predict( {"title": title_data, "text_body": text_body_data, "tags": tags_data}) ###Output 40/40 [==============================] - 1s 6ms/step - loss: 8.1189 - output_1_loss: 0.3152 - output_2_loss: 7.8037 - output_1_mean_absolute_error: 0.4834 - output_2_accuracy: 0.2414 40/40 [==============================] - 0s 4ms/step - loss: 3.8896 - output_1_loss: 0.3274 - output_2_loss: 3.5622 - output_1_mean_absolute_error: 0.4954 - output_2_accuracy: 0.4742 ###Markdown **서브클래싱 기법의 장단점** - 장점 - `call()` 함수를 이용하여 층을 임의로 구성할 수 있다. - 파이썬 프로그래밍 관련 모든 기법을 적용할 수 있다.- 단점 - 모델 구성을 전적으로 책임져야 한다. - 모델 구성 정보가 `call()` 함수 외부로 노출되지 않아서 앞서 보았던 그래프 표현을 사용할 수 없다. 모델 구성법 혼합 소개된 세 가지 방식을 임의로 혼합하여 활용할 수 있다. **예제: 서브클래싱 모델을 함수형 모델에 활용하기** (강추!!!) ###Code class Classifier(keras.Model): def __init__(self, num_classes=2): super().__init__() if num_classes == 2: num_units = 1 activation = "sigmoid" else: num_units = num_classes activation = "softmax" self.dense = layers.Dense(num_units, activation=activation) def call(self, inputs): return self.dense(inputs) inputs = keras.Input(shape=(3,)) features = layers.Dense(64, activation="relu")(inputs) outputs = Classifier(num_classes=10)(features) model = keras.Model(inputs=inputs, outputs=outputs) ###Output _____no_output_____ ###Markdown **예제: 함수형 모델을 서브클래싱 모델에 활용하기** ###Code inputs = keras.Input(shape=(64,)) outputs = layers.Dense(1, activation="sigmoid")(inputs) binary_classifier = keras.Model(inputs=inputs, outputs=outputs) class MyModel(keras.Model): def __init__(self, num_classes=2): super().__init__() self.dense = layers.Dense(64, activation="relu") self.classifier = binary_classifier def call(self, inputs): features = self.dense(inputs) return self.classifier(features) model = MyModel() ###Output _____no_output_____ ###Markdown 7.3 훈련 모니터링 케라스 모델의 구성, 훈련, 평가, 예측은 정해진 방식으로 차례대로 이루어진다.아래 코드는 MNIST 데이터셋을 이용한 모델 훈련 전반 과정을 보여준다. ###Code from tensorflow.keras.datasets import mnist def get_mnist_model(): inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = keras.Model(inputs, outputs) return model (images, labels), (test_images, test_labels) = mnist.load_data() images = images.reshape((60000, 28 * 28)).astype("float32") / 255 test_images = test_images.reshape((10000, 28 * 28)).astype("float32") / 255 train_images, val_images = images[10000:], images[:10000] train_labels, val_labels = labels[10000:], labels[:10000] model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=3, validation_data=(val_images, val_labels)) test_metrics = model.evaluate(test_images, test_labels) predictions = model.predict(test_images) ###Output Epoch 1/3 1563/1563 [==============================] - 8s 5ms/step - loss: 0.2953 - accuracy: 0.9119 - val_loss: 0.1480 - val_accuracy: 0.9579 Epoch 2/3 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1671 - accuracy: 0.9527 - val_loss: 0.1220 - val_accuracy: 0.9684 Epoch 3/3 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1412 - accuracy: 0.9613 - val_loss: 0.1125 - val_accuracy: 0.9711 313/313 [==============================] - 0s 1ms/step - loss: 0.1069 - accuracy: 0.9717 ###Markdown 사용자 정의 평가지표(`metrics`) 활용 **`Metric` 클래스 상속**아래 세 개의 메서드를 재정의(overriding)해야 한다.- `update_state()`- `result()`- `reset_state()`아래 코드는 평균제곱근오차(RMSE)를 평가지표로 사용하는 클래스를 이용하는 모델 훈련을 소개한다. ###Code import tensorflow as tf class RootMeanSquaredError(keras.metrics.Metric): def __init__(self, name="rmse", **kwargs): super().__init__(name=name, **kwargs) self.mse_sum = self.add_weight(name="mse_sum", initializer="zeros") self.total_samples = self.add_weight( name="total_samples", initializer="zeros", dtype="int32") def update_state(self, y_true, y_pred, sample_weight=None): y_true = tf.one_hot(y_true, depth=tf.shape(y_pred)[1]) mse = tf.reduce_sum(tf.square(y_true - y_pred)) self.mse_sum.assign_add(mse) num_samples = tf.shape(y_pred)[0] self.total_samples.assign_add(num_samples) def result(self): return tf.sqrt(self.mse_sum / tf.cast(self.total_samples, tf.float32)) def reset_state(self): self.mse_sum.assign(0.) self.total_samples.assign(0) model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy", RootMeanSquaredError()]) model.fit(train_images, train_labels, epochs=3, validation_data=(val_images, val_labels)) test_metrics = model.evaluate(test_images, test_labels) ###Output Epoch 1/3 1563/1563 [==============================] - 9s 5ms/step - loss: 0.2935 - accuracy: 0.9141 - rmse: 7.1828 - val_loss: 0.1709 - val_accuracy: 0.9510 - val_rmse: 7.3536 Epoch 2/3 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1676 - accuracy: 0.9530 - rmse: 7.3561 - val_loss: 0.1227 - val_accuracy: 0.9657 - val_rmse: 7.4048 Epoch 3/3 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1410 - accuracy: 0.9623 - rmse: 7.3852 - val_loss: 0.1244 - val_accuracy: 0.9691 - val_rmse: 7.4222 313/313 [==============================] - 0s 1ms/step - loss: 0.1120 - accuracy: 0.9711 - rmse: 7.4363 ###Markdown 콜백(callback) 활용 **콜백**(callback)은 모델 훈련 도중에 부가적으로 호출되는 객체이며학습 과정을 모니터링 하면서 일부 제어기능을 수행하는 다양한 메서드를 제공한다.콜백이 활용되는 주요 기능은 다음과 같다.- 모델 체크포인팅: 훈련 중 모델 상태 수시로 저장- 훈련 조기 중단: 검증셋 손실이 더 이상 개선되지 않는 경우 훈련 중단- 하이퍼 파라미터 조정: 학습률의 동적 변경- 훈련 기록 작성: 훈련셋 및 검증셋의 손실값, 평가지표 등 기록 및 시각화```pythonkeras.callbacks.ModelCheckpointkeras.callbacks.EarlyStoppingkeras.callbacks.LearningRateSchedulerkeras.callbacks.ReduceLROnPlateaukeras.callbacks.CSVLogger```여기서는 `EarlyStopping`과 `ModelCheckpoint` 두 콜백의 기능을 살펴본다. **`fit()` 메서드에서 `callbacks` 인자 사용하기**아래 코드에 사용된 옵션은 다음과 같다.- `EarlyStopping`: 검증셋에 대한 정확도가 2 에포크(epoch) 연속 개선되지 않을 때 훈련 종료- `ModelCheckpoint`: 매 에포크마다 훈련된 모델 저장. `save_best_only=True`가 설정된 경우 검증셋에 대한 손실값이 가장 낮은 모델만 저장. ###Code callbacks_list = [ keras.callbacks.EarlyStopping( monitor="val_accuracy", patience=2, ), keras.callbacks.ModelCheckpoint( filepath="checkpoint_path.keras", monitor="val_loss", save_best_only=True, ) ] model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=10, callbacks=callbacks_list, validation_data=(val_images, val_labels)) ###Output Epoch 1/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.2962 - accuracy: 0.9114 - val_loss: 0.1489 - val_accuracy: 0.9575 Epoch 2/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1645 - accuracy: 0.9532 - val_loss: 0.1184 - val_accuracy: 0.9692 Epoch 3/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1412 - accuracy: 0.9617 - val_loss: 0.1192 - val_accuracy: 0.9692 Epoch 4/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1276 - accuracy: 0.9670 - val_loss: 0.1139 - val_accuracy: 0.9700 Epoch 5/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1212 - accuracy: 0.9694 - val_loss: 0.1102 - val_accuracy: 0.9747 Epoch 6/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1115 - accuracy: 0.9731 - val_loss: 0.1070 - val_accuracy: 0.9759 Epoch 7/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1033 - accuracy: 0.9747 - val_loss: 0.1043 - val_accuracy: 0.9764 Epoch 8/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1041 - accuracy: 0.9761 - val_loss: 0.1049 - val_accuracy: 0.9784 Epoch 9/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0994 - accuracy: 0.9774 - val_loss: 0.1070 - val_accuracy: 0.9785 Epoch 10/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0948 - accuracy: 0.9780 - val_loss: 0.1181 - val_accuracy: 0.9768 ###Markdown 조기종료 후 훈련과정에서 저장된 최고 성능의 모델을 불러오면 다음과 같다. ###Code model = keras.models.load_model("checkpoint_path.keras") ###Output _____no_output_____ ###Markdown 사용자 정의 콜백 활용 **`Callback` 클래스 상속**매 에포크와 매 배치 훈련 단계의 시작과 종료 지점에서수행해야 할 기능을 정의해야 하며 아래 메서드를 재정의하는 방식으로 이루어진다.```pythonon_epoch_begin(epoch, logs)on_epoch_end(epoch, logs)on_batch_begin(batch, logs)on_batch_end(batch, logs)on_train_begin(logs)on_train_end(logs)```각 메서드에 사용되는 인자는 훈련 과정 중에 자동으로 생성된 객체로부터 값을 받아온다.- `logs` 인자: 이전 배치와 에포크의 훈련셋과 검증셋에 대한 손실값, 평가지표 등을 포함한 사전 객체.- `batch`, `epoch`: 배치와 에포크 정보다음 `LossHistory` 콜백 클래스는 배치 훈련이 끝날 때마다 손실값을 저장하고에포크가 끝날 때마다 배치별 손실값을 그래프로 저장하여 훈련이 종료된 후 시각화하여 보여주도록 한다. ###Code from matplotlib import pyplot as plt class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs): self.per_batch_losses = [] def on_batch_end(self, batch, logs): self.per_batch_losses.append(logs.get("loss")) def on_epoch_end(self, epoch, logs): plt.clf() plt.plot(range(len(self.per_batch_losses)), self.per_batch_losses, label="Training loss for each batch") plt.xlabel(f"Batch (epoch {epoch})") plt.ylabel("Loss") plt.legend() plt.savefig(f"plot_at_epoch_{epoch}") self.per_batch_losses = [] model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=10, callbacks=[LossHistory()], validation_data=(val_images, val_labels)) ###Output Epoch 1/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.2943 - accuracy: 0.9124 - val_loss: 0.1439 - val_accuracy: 0.9585 Epoch 2/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1617 - accuracy: 0.9554 - val_loss: 0.1232 - val_accuracy: 0.9685 Epoch 3/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1413 - accuracy: 0.9618 - val_loss: 0.1168 - val_accuracy: 0.9719 Epoch 4/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1265 - accuracy: 0.9676 - val_loss: 0.1098 - val_accuracy: 0.9729 Epoch 5/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1142 - accuracy: 0.9715 - val_loss: 0.1086 - val_accuracy: 0.9755 Epoch 6/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1120 - accuracy: 0.9729 - val_loss: 0.1148 - val_accuracy: 0.9760 Epoch 7/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1064 - accuracy: 0.9743 - val_loss: 0.1161 - val_accuracy: 0.9763 Epoch 8/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1010 - accuracy: 0.9770 - val_loss: 0.1080 - val_accuracy: 0.9776 Epoch 9/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0980 - accuracy: 0.9774 - val_loss: 0.1118 - val_accuracy: 0.9786 Epoch 10/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0952 - accuracy: 0.9790 - val_loss: 0.1271 - val_accuracy: 0.9765 ###Markdown 텐서보드(TensorBoard) 활용 **텐서보드**(TensorBoard)는 모델 훈련과정을 모니터링하는 최고의 어플이며텐서플로우와 함께 기본적으로 설치된다.**주의사항**: 텐서보드 데이터의 저장경로를 ```python/full_path_to_your_log_dir```대신에 ```python./tensorboard_log_dir```등을 사용해야 리눅스, 맥 운영체제에서 오류가 발생하지 않는다. ###Code model = get_mnist_model() model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) tensorboard = keras.callbacks.TensorBoard( log_dir="./tensorboard_log_dir", ) model.fit(train_images, train_labels, epochs=10, validation_data=(val_images, val_labels), callbacks=[tensorboard]) ###Output Epoch 1/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.2950 - accuracy: 0.9128 - val_loss: 0.1475 - val_accuracy: 0.9591 Epoch 2/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1677 - accuracy: 0.9528 - val_loss: 0.1224 - val_accuracy: 0.9668 Epoch 3/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1395 - accuracy: 0.9621 - val_loss: 0.1158 - val_accuracy: 0.9697 Epoch 4/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1285 - accuracy: 0.9675 - val_loss: 0.1157 - val_accuracy: 0.9712 Epoch 5/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1192 - accuracy: 0.9708 - val_loss: 0.1141 - val_accuracy: 0.9722 Epoch 6/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1145 - accuracy: 0.9724 - val_loss: 0.1039 - val_accuracy: 0.9766 Epoch 7/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1059 - accuracy: 0.9740 - val_loss: 0.1045 - val_accuracy: 0.9790 Epoch 8/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.1050 - accuracy: 0.9754 - val_loss: 0.1107 - val_accuracy: 0.9770 Epoch 9/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0965 - accuracy: 0.9776 - val_loss: 0.1082 - val_accuracy: 0.9788 Epoch 10/10 1563/1563 [==============================] - 8s 5ms/step - loss: 0.0960 - accuracy: 0.9780 - val_loss: 0.1094 - val_accuracy: 0.9788 ###Markdown 텐서보드를 주피터 노트북에서 아래처럼 실행할 수 있다. ###Code %load_ext tensorboard %tensorboard --logdir ./tensorboard_log_dir ###Output _____no_output_____ ###Markdown 텐서보드를 독립적으로 실행하여 훈련과정을 실시간으로 모니터링 하려면아래 명령어를 터미널 창에서 실행하고 반환된 주소로 접속하면 된다.```pythontensorboard --logdir ./full_path_to_your_log_dir``` 7.4 사용자 정의 훈련 알고리즘: `fit()` 메서드 대체 Training versus inference Low-level usage of metrics ###Code metric = keras.metrics.SparseCategoricalAccuracy() targets = [0, 1, 2] predictions = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] metric.update_state(targets, predictions) current_result = metric.result() print(f"result: {current_result:.2f}") values = [0, 1, 2, 3, 4] mean_tracker = keras.metrics.Mean() for value in values: mean_tracker.update_state(value) print(f"Mean of values: {mean_tracker.result():.2f}") ###Output _____no_output_____ ###Markdown A complete training and evaluation loop **Writing a step-by-step training loop: the training step function** ###Code model = get_mnist_model() loss_fn = keras.losses.SparseCategoricalCrossentropy() optimizer = keras.optimizers.RMSprop() metrics = [keras.metrics.SparseCategoricalAccuracy()] loss_tracking_metric = keras.metrics.Mean() def train_step(inputs, targets): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs[metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["loss"] = loss_tracking_metric.result() return logs ###Output _____no_output_____ ###Markdown **Writing a step-by-step training loop: resetting the metrics** ###Code def reset_metrics(): for metric in metrics: metric.reset_state() loss_tracking_metric.reset_state() ###Output _____no_output_____ ###Markdown **Writing a step-by-step training loop: the loop itself** ###Code training_dataset = tf.data.Dataset.from_tensor_slices((train_images, train_labels)) training_dataset = training_dataset.batch(32) epochs = 3 for epoch in range(epochs): reset_metrics() for inputs_batch, targets_batch in training_dataset: logs = train_step(inputs_batch, targets_batch) print(f"Results at the end of epoch {epoch}") for key, value in logs.items(): print(f"...{key}: {value:.4f}") ###Output _____no_output_____ ###Markdown **Writing a step-by-step evaluation loop** ###Code def test_step(inputs, targets): predictions = model(inputs, training=False) loss = loss_fn(targets, predictions) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs["val_" + metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["val_loss"] = loss_tracking_metric.result() return logs val_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_labels)) val_dataset = val_dataset.batch(32) reset_metrics() for inputs_batch, targets_batch in val_dataset: logs = test_step(inputs_batch, targets_batch) print("Evaluation results:") for key, value in logs.items(): print(f"...{key}: {value:.4f}") ###Output _____no_output_____ ###Markdown Make it fast with `tf.function` **Adding a `tf.function` decorator to our evaluation step function** ###Code @tf.function def test_step(inputs, targets): predictions = model(inputs, training=False) loss = loss_fn(targets, predictions) logs = {} for metric in metrics: metric.update_state(targets, predictions) logs["val_" + metric.name] = metric.result() loss_tracking_metric.update_state(loss) logs["val_loss"] = loss_tracking_metric.result() return logs val_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_labels)) val_dataset = val_dataset.batch(32) reset_metrics() for inputs_batch, targets_batch in val_dataset: logs = test_step(inputs_batch, targets_batch) print("Evaluation results:") for key, value in logs.items(): print(f"...{key}: {value:.4f}") ###Output _____no_output_____ ###Markdown Leveraging `fit()` with a custom training loop **Implementing a custom training step to use with `fit()`** ###Code loss_fn = keras.losses.SparseCategoricalCrossentropy() loss_tracker = keras.metrics.Mean(name="loss") class CustomModel(keras.Model): def train_step(self, data): inputs, targets = data with tf.GradientTape() as tape: predictions = self(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) loss_tracker.update_state(loss) return {"loss": loss_tracker.result()} @property def metrics(self): return [loss_tracker] inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = CustomModel(inputs, outputs) model.compile(optimizer=keras.optimizers.RMSprop()) model.fit(train_images, train_labels, epochs=3) class CustomModel(keras.Model): def train_step(self, data): inputs, targets = data with tf.GradientTape() as tape: predictions = self(inputs, training=True) loss = self.compiled_loss(targets, predictions) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) self.compiled_metrics.update_state(targets, predictions) return {m.name: m.result() for m in self.metrics} inputs = keras.Input(shape=(28 * 28,)) features = layers.Dense(512, activation="relu")(inputs) features = layers.Dropout(0.5)(features) outputs = layers.Dense(10, activation="softmax")(features) model = CustomModel(inputs, outputs) model.compile(optimizer=keras.optimizers.RMSprop(), loss=keras.losses.SparseCategoricalCrossentropy(), metrics=[keras.metrics.SparseCategoricalAccuracy()]) model.fit(train_images, train_labels, epochs=3) ###Output _____no_output_____ ###Markdown 7장 케라스 모델 활용법 **감사말**: 프랑소와 숄레의 [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition?a_aid=keras&a_bid=76564dff) 7장에 사용된 코드에 대한 설명을 담고 있으며 텐서플로우 2.6 버전에서 작성되었습니다. 소스코드를 공개한 저자에게 감사드립니다.**tensorflow 버전과 GPU 확인**- 구글 코랩 설정: '런타임 -> 런타임 유형 변경' 메뉴에서 GPU 지정 후 아래 명령어 실행 결과 확인 ``` !nvidia-smi ```- 사용되는 tensorflow 버전 확인 ```python import tensorflow as tf tf.__version__ ```- tensorflow가 GPU를 사용하는지 여부 확인 ```python tf.config.list_physical_devices('GPU') ``` 주요 내용 - 모델 구성법- 모델 훈련 모니터링- 사용자 정의 모델 훈련 및 평가 7.1 케라스 활용성 케라스를 이용하여 매우 단순한 모델부터 매우 복잡한 모델까지 구성 및 훈련이 가능하다. 케라스의 모델과 층은 모두 각각 `Model` 클래스와 `Layer` 클래스를 상속하기에 다른 모델에서 사용된 요소들을 재활용하기에도 용이하다.여기서는 주어진 문제에 따른 케라스 모델 구성법과 훈련법의 다양한 방식을 살펴본다. 7.2 케라스 모델 구성법 케라스를 이용하여 모델을 세 가지 방식으로 구성할 수 있다.- `Sequential` 모델: 층으로 스택을 쌓아 만든 모델- 함수형 API 활용: 가장 많이 사용됨.- 모델 서브클래싱: 모든 것을 사용자가 지정.가장 간단한 모델부터 아주 복잡한 모델까지 모두 구성할 수 있으며사용자가 직접 정의한 모델과 레이어도 활용할 수 있다. 모델 구성법 1: `Sequential` 모델 층으로 스택을 쌓아 만든 모델이며 가장 단순하다.- 하나의 입력값과 하나의 출력값만 사용 가능- 층을 지정된 순서대로만 적용 가능 **`Sequential` 클래스** ###Code from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential([ layers.Dense(64, activation="relu"), layers.Dense(10, activation="softmax") ]) ###Output _____no_output_____ ###Markdown 층의 추가는 `add` 메서드를 이용할 수도 있다.더해진 순서대로 층이 쌓인다. ###Code model = keras.Sequential() model.add(layers.Dense(64, activation="relu")) model.add(layers.Dense(10, activation="softmax")) ###Output _____no_output_____ ###Markdown **`build()` 메서드** 모델 훈련에 사용되는 층별 가중치는 모델이 처음 활용될 때 호출되는`build()` 메서드에 의해 초기화된다.이유는 입력값이 들어와야 가중치 텐서의 모양(shape)을 정할 수 있기 때문이다. 아래 코드 샘플은 [3장](https://codingalzi.github.io/dlp/notebooks/dlp03_introduction_to_keras_and_tf.html)에서 `SimpleDense`를 선언할 때 사용된 `build()` 메서드를 보여주며,훈련이 시작되면서 첫 배치 데이터셋이 입력될 때 특성 수를 확인하여가중치와 편향 텐서를 생성과 동시에 초기화한다. ```pythondef build(self, input_shape): input_dim = input_shape[-1] 입력 샘플의 특성 수 self.W = self.add_weight(shape=(input_dim, self.units), initializer="random_normal") self.b = self.add_weight(shape=(self.units,), initializer="zeros")``` 따라서 지금 당장 가중치를 확인하려 하면 오류가 발생한다. ```python>>> model.weights...ValueError: Weights for model sequential_1 have not yet been created. Weights are created when the Model is first called on inputs or `build()` is called with an `input_shape`.``` 반면에 입력값 대신 `build()` 메서드를 특성 수 정보를 이용하여 직접 호출하면가중치 텐서가 무작위로 초기화된 형식으로 생성된다.즉, **모델 빌드**가 완성된다.- `input_shape` 키워드 인자: `(None, 특성수)`- `None`은 임의의 크기의 배치도 다룰 수 있다는 것을 의미함. ###Code model.build(input_shape=(None, 3)) ###Output _____no_output_____ ###Markdown 모델 빌드가 완성되면 `weights` 속성에 생성된 모델 훈련에 필요한 모든 가중치와 편향이 저장된다.위 모델에 대해서 층별로 가중치와 편향 텐서 하나씩 총 4 개의 텐서가 생성된다. ###Code len(model.weights) ###Output _____no_output_____ ###Markdown - 1층의 가중치와 편향 텐서 ###Code model.weights[0].shape model.weights[1].shape ###Output _____no_output_____ ###Markdown - 2층의 가중치와 편향 텐서 ###Code model.weights[2].shape model.weights[3].shape ###Output _____no_output_____ ###Markdown **`summary()` 메서드** 완성된 모델의 요악한 내용은 확인할 수 있다.- 모델과 층의 이름- 층별 파라미터 수- 파라미터 수 ###Code model.summary() ###Output Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_2 (Dense) (None, 64) 256 _________________________________________________________________ dense_3 (Dense) (None, 10) 650 ================================================================= Total params: 906 Trainable params: 906 Non-trainable params: 0 _________________________________________________________________ ###Markdown **`name` 인자**모델 또는 층을 지정할 때 생성자 메서등의 `name` 키워드 인자를 이용하여 이름을 지정할 수도 있다. ###Code model = keras.Sequential(name="my_example_model") model.add(layers.Dense(64, activation="relu", name="my_first_layer")) model.add(layers.Dense(10, activation="softmax", name="my_last_layer")) model.build((None, 3)) model.summary() ###Output Model: "my_example_model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= my_first_layer (Dense) (None, 64) 256 _________________________________________________________________ my_last_layer (Dense) (None, 10) 650 ================================================================= Total params: 906 Trainable params: 906 Non-trainable params: 0 _________________________________________________________________ ###Markdown **`Input()` 함수, `KerasTensor`, 모델 디버깅**모델 구성 중간에 구성 과정을 확인하려면 `Input()`함수를 이용하여**케라스텐서**(`KerasTensor`) 객체를가장 먼저 모델에 추가한다.그러면 층을 추가할 때마다 `summary()`를 실행할 수 있다.`Input()` 함수는 모델 훈련에 사용되는 데이터 샘플의 모양(shape) 정보를 제공하는 가상의 텐서인 `KerasTensor` 객체를 생성한다. **주의사항**: `shape` 키워드 인자에 사용되는 값은 각 샘플의 특성 수이며,앞서 `build()` 메서드의 인자와 다른 형식으로 사용된다. ###Code model = keras.Sequential() model.add(keras.Input(shape=(3,))) model.add(layers.Dense(64, activation="relu")) model.summary() model.add(layers.Dense(10, activation="softmax")) model.summary() ###Output Model: "sequential_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_4 (Dense) (None, 64) 256 _________________________________________________________________ dense_5 (Dense) (None, 10) 650 ================================================================= Total params: 906 Trainable params: 906 Non-trainable params: 0 _________________________________________________________________ ###Markdown 모델 구성법 2: 함수형 API 다중 입력과 다중 출력을 지원하려면 함수형 API를 활용하여 모델을 구성해야 하며,가장 많이 사용되는 모델 구성법이다. 사용법은 간단하다.```pythonModel(inputs, outputs)```- `Model`: 케라사의 기본 모델 클래스- `inputs` 인자: 한 개 이상의 케라스텐서(`KerasTensor`) 객체 이루어진 리스트- `outputs` 인자: 한 개 이사의 출력층으로 이루어진 리스트 기본 활용법 앞서 살펴 본 `Sequential` 모델을 함수형 API를 이용하여 구성하면 다음과 같다. ###Code inputs = keras.Input(shape=(3,), name="my_input") # 입력층 features = layers.Dense(64, activation="relu")(inputs) # 은닉층 outputs = layers.Dense(10, activation="softmax")(features) # 출력층 model = keras.Model(inputs=inputs, outputs=outputs) ###Output _____no_output_____ ###Markdown 사용된 단계들을 하나씩 살펴보자. - 입력층: `inputs = keras.Input(shape=(3,), name="my_input")` 생성된 값은 `KerasTensor`이다. ###Code type(inputs) ###Output _____no_output_____ ###Markdown 케라스텐서(`KerasTensor`)의 모양에서 `None`은 배치 사이즈, 즉 하나의 훈련 스텝에 사용되는 샘플의 수를 대상으로 하며, 임의의 크기의 배치를 처리할 수 있다는 의미로 사용된다. ###Code inputs.shape inputs.dtype ###Output _____no_output_____ ###Markdown - 은닉층: `features = layers.Dense(64, activation="relu")(inputs)` ###Code type(features) features.shape ###Output _____no_output_____ ###Markdown - 출력층: `outputs = layers.Dense(10, activation="softmax")(features)` ###Code type(outputs) ###Output _____no_output_____ ###Markdown - 모델 빌드 ```pythoh model = keras.Model(inputs=inputs, outputs=outputs) ``` ###Code model.summary() ###Output Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= my_input (InputLayer) [(None, 3)] 0 _________________________________________________________________ dense_6 (Dense) (None, 64) 256 _________________________________________________________________ dense_7 (Dense) (None, 10) 650 ================================================================= Total params: 906 Trainable params: 906 Non-trainable params: 0 _________________________________________________________________ ###Markdown `KerasTensor`의 역할 앞서 보았듯이 케라스텐서는 모델 훈련에 사용되는 텐서의 모양에 대한 정보를 제공하는 **가상의 텐서**이다.빌드되는 모델은 입력 케라스텐서부터 출력 케라스텐서까지 각 층에 저장된 텐서의 모양 정보를 이용하여 가중치 텐서와 편향 텐서를 생성하고 초기화한다. 다중 입력, 다중 출력 모델 구성법 고객의 요구사항이 적힌 티켓을 처리할 때 필요한 우선순위와 담당부서를 지정하는 시스템을 구현하려 한다.시스템에 사용될 모델은 세 개의 입력과 두 개의 출력을 사용한다. - 입력 - `title`: 요구사항 타이틀. 문자열 인코딩. `vocabulary_size` 활용(11장에서 다룸). - `text_body`: 요구사항 내용. 문자열 인코딩. `vocabulary_size` 활용(11장에서 다룸). - `tags`: 사용자에 의한 추가 선택 사항. 멀티-핫-인코딩 사용.- 출력 - `priority`: 요구사항 처리 우선순위. 0에서 1사이의 값. 시그모이드(sigmoid) 활용. - `department`: 요구사항 처리 담당 부서. 소프트맥스 활용. ###Code vocabulary_size = 10000 # 요구사항에 사용되는 단어 총 수 num_tags = 100 # 태그 수 num_departments = 4 # 부서 수 # 입력층: 세 개 title = keras.Input(shape=(vocabulary_size,), name="title") text_body = keras.Input(shape=(vocabulary_size,), name="text_body") tags = keras.Input(shape=(num_tags,), name="tags") # 은닉층 features = layers.Concatenate()([title, text_body, tags]) # shape=(None, 10000+10000+100) features = layers.Dense(64, activation="relu")(features) # 출력층: 두 개 priority = layers.Dense(1, activation="sigmoid", name="priority")(features) department = layers.Dense( num_departments, activation="softmax", name="department")(features) # 모델 빌드 model = keras.Model(inputs=[title, text_body, tags], outputs=[priority, department]) ###Output _____no_output_____ ###Markdown 모델 훈련을 위해 적절한 개수의 입력 텐서와 타깃 텐서를 지정해야 한다.여기서는 훈련 과정을 설명하기 위해 적절한 모양의 입력 텐서 3개와 타깃 텐서 2개를 무작위로 생성해서 사용한다. ###Code import numpy as np # 샘플 수 num_samples = 1280 # 입력 텐서 3 개 무작위 생성 title_data = np.random.randint(0, 2, size=(num_samples, vocabulary_size)) text_body_data = np.random.randint(0, 2, size=(num_samples, vocabulary_size)) tags_data = np.random.randint(0, 2, size=(num_samples, num_tags)) # 멀티-핫-인코딩 # 타깃 텐서 2 개 무작위 생성 priority_data = np.random.random(size=(num_samples, 1)) department_data = np.random.randint(0, 2, size=(num_samples, num_departments)) # 멀티-핫-인코딩 ###Output _____no_output_____ ###Markdown 모델 컴파일 과정에서 지정된 타깃 수만큼 손실함수와 측정 기준을 지정해야 한다.- 손실함수(loss) - `priority` 대상: `mean_squared_error` - `department` 대상: `categorical_crossentropy`- 평가지표(metrics): 평가지표는 여러 개를 사용할 수 있기에 대상 별로 리스트로 지정함. - `priority` 대상: `["mean_absolute_error"]` - `department` 대상: `["accuracy"]` ###Code model.compile(optimizer="adam", loss=["mean_squared_error", "categorical_crossentropy"], metrics=[["mean_absolute_error"], ["accuracy"]]) ###Output _____no_output_____ ###Markdown 모델 훈련은 `fit()` 함수에 세 개의 훈련 텐서로 이루어진 리스트와 두 개의 타깃 텐서로 이루어진 리스트를 지정한 후에 실행한다. 여기서는 시험삼아 한 번의 에포크만 사용한다.- `epochs=1`- `batch_size=None`: 배치 크기를 지정하지 않으면 32개로 자동 지정됨. 그래서 스텝수가 40(= 1280/30)이 된다. ###Code model.fit([title_data, text_body_data, tags_data], [priority_data, department_data], epochs=1) ###Output 40/40 [==============================] - 1s 6ms/step - loss: 7.9958 - priority_loss: 0.3332 - department_loss: 7.6626 - priority_mean_absolute_error: 0.5019 - department_accuracy: 0.2047 ###Markdown 평가도 훈련과 동일한 방식의 인자가 사용된다. ###Code model.evaluate([title_data, text_body_data, tags_data], [priority_data, department_data]) ###Output 40/40 [==============================] - 0s 3ms/step - loss: 14.5559 - priority_loss: 0.3365 - department_loss: 14.2194 - priority_mean_absolute_error: 0.5046 - department_accuracy: 0.2484 ###Markdown 예측은 입력값만 리스트로 지정하고 실행하면 두 개의 어레이 출력값으로 구성된 리스트가 반환된다. ###Code priority_preds, department_preds = model.predict([title_data, text_body_data, tags_data]) priority_preds department_preds ###Output _____no_output_____ ###Markdown **사전 객체 활용**입력층과 출력층의 이름을 이용하여 사전 형식으로 입력값과 출력값을 지정할 수 있다. ###Code model.compile(optimizer="adam", loss={"priority": "mean_squared_error", "department": "categorical_crossentropy"}, metrics={"priority": ["mean_absolute_error"], "department": ["accuracy"]}) model.fit({"title": title_data, "text_body": text_body_data, "tags": tags_data}, {"priority": priority_data, "department": department_data}, epochs=1) model.evaluate({"title": title_data, "text_body": text_body_data, "tags": tags_data}, {"priority": priority_data, "department": department_data}) priority_preds, department_preds = model.predict( {"title": title_data, "text_body": text_body_data, "tags": tags_data}) ###Output 40/40 [==============================] - 1s 6ms/step - loss: 7.8852 - priority_loss: 0.3365 - department_loss: 7.5487 - priority_mean_absolute_error: 0.5046 - department_accuracy: 0.2859 40/40 [==============================] - 0s 4ms/step - loss: 4.0846 - priority_loss: 0.3365 - department_loss: 3.7480 - priority_mean_absolute_error: 0.5046 - department_accuracy: 0.1852 ###Markdown 층 연결 구조 확인 `plot_model()`을 이용하여 층 연결 구조를 그래프로 나타낼 수 있다.```python>>> keras.utils.plot_model(model, "ticket_classifier.png")```**주의사항**: `pydot` 파이썬 모듈과 graphviz 라는 프로그램이 컴퓨터에 설치되어 있어야 한다.- `pydot` 모듈 설치: `pip install pydot`- graphviz 프로그램 설치: [https://graphviz.gitlab.io/download/](https://graphviz.gitlab.io/download/)- 구글 코랩에서 기본으로 지원됨. 입력 텐서와 출력 텐서의 모양을 함께 표기할 수도 있다.```python>>> keras.utils.plot_model(model, "ticket_classifier_with_shape_info.png", show_shapes=True)``` 모델 재활용 훈련된 모델의 특성을 이용하여 새로운 모델을 빌드할 수 있다.먼저 모델의 `layers` 속성을 이용하여 사용된 층에 대한 정보를 확인한다. `layers` 속성은 사용된 층들의 객체로 이루어진 리스트를 가리킨다. ###Code model.layers ###Output _____no_output_____ ###Markdown 예를 들어, 3번 인덱스에 해당하는 층의 입력값과 출력값에 대한 정보는 아래처럼 확인할 수 있다. ###Code model.layers[3].input model.layers[3].output ###Output _____no_output_____ ###Markdown 출력층을 제외한 나머지 층을 재활용해보자.출력층은 5번과 6번 인덱스에 위치하기에 4번 인덱스가가리키는 (은닉)층의 출력 정보를 따로 떼어낸다. ###Code features = model.layers[4].output ###Output _____no_output_____ ###Markdown 이제 출력층에 문제해결의 어려움 정도를 "quick", "medium", "difficult"로구분하는 어려움(difficulty) 정도를 판별하는 층을 추가해보자.먼저, `difficulty` 층을 준비한다. ###Code difficulty = layers.Dense(3, activation="softmax", name="difficulty")(features) ###Output _____no_output_____
community_detection/notebooks/meeting_level.ipynb
###Markdown Utility functions ###Code %matplotlib inline from nltk.cluster.kmeans import KMeansClusterer import nltk import pickle import torch from pytorch_pretrained_bert import BertTokenizer, BertConfig, BertModel from pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertPreTrainingHeads import numpy as np from scipy.spatial.distance import cosine import pickle import re import pandas as pd device = 'cpu' import sys import os import json class BertForPreTraining_custom(BertPreTrainedModel): def __init__(self, config): super(BertForPreTraining_custom, self).__init__(config) self.bert = BertModel(config) self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight) self.apply(self.init_bert_weights) def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None): output_all_encoded_layers=True sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=output_all_encoded_layers) if output_all_encoded_layers: sequence_output_pred = sequence_output[-1] prediction_scores, seq_relationship_score = self.cls(sequence_output_pred, pooled_output) return prediction_scores, seq_relationship_score, sequence_output, pooled_output tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') config = BertConfig.from_json_file('../data/bert_config.json') bert_model = 'bert-base-uncased' def getNSPScore(sample_text): m = torch.nn.Softmax() tokenized_text = tokenizer.tokenize(sample_text) indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text) segments_ids = [0]*tokenized_text.index('[SEP]')+[1]*(len(tokenized_text)-tokenized_text.index('[SEP]')) tokens_tensor = torch.tensor([indexed_tokens]) segments_tensors = torch.tensor([segments_ids]) pred_score, seq_rel, seq_out, pool_out = model1(tokens_tensor, segments_tensors) return m(seq_rel).detach().numpy()[0][0] #returns probability of being next sentence def getSentMatchScore(sent1, sent2, nsp_dampening_factor = 0.7): sent1_feats = getBERTFeatures(model1, sent1, attn_head_idx) sent2_feats = getBERTFeatures(model1, sent2, attn_head_idx) cosine_distance = 1- cosine(sent1_feats, sent2_feats) nsp_input1 = sent1+' [SEP] '+sent2 nsp_input2 = sent2+' [SEP] '+sent1 nsp_score_1 = getNSPScore(nsp_input1) nsp_score_2 = getNSPScore(nsp_input2) nsp_score = np.mean([nsp_score_1,nsp_score_2])*nsp_dampening_factor len_diff = abs(len(sent1.split(' '))-len(sent2.split(' '))) if len_diff>2*(min(len(sent1.split(' ')),len(sent2.split(' ')))): #give more weight to nsp if the sentences of largely varying lengths score = 0.4*cosine_distance+0.6*nsp_score else: score = np.mean([cosine_distance,nsp_score]) #print ("nsp score -> " + str(nsp_score)) #print ("cosine score -> " + str(cosine_distance)) return score def getSentMatchScore_wfeature(sent1, sent2, sent1_feats, sent2_feats, nsp_dampening_factor = 0.7): cosine_distance = 1-cosine(sent1_feats, sent2_feats) #return cosine_distance nsp_input1 = sent1+' [SEP] '+sent2 #nsp_input2 = sent2+' [SEP] '+sent1 nsp_score_1 = getNSPScore(nsp_input1) #nsp_score_2 = getNSPScore(nsp_input2) nsp_score = nsp_score_1 * nsp_dampening_factor #nsp_score = nsp_score_1*nsp_dampening_factor len_diff = abs(len(sent1.split(' '))-len(sent2.split(' '))) if len_diff>2*(min(len(sent1.split(' ')),len(sent2.split(' ')))): #give more weight to nsp if the sentences of largely varying lengths score = 0.4*cosine_distance+0.6*nsp_score else: score = np.mean([cosine_distance,nsp_score]) return score def getSentMatchScore_wfeature_cosine(sent1, sent2, sent1_feats, sent2_feats, nsp_dampening_factor = 0.7): cosine_distance = 1-cosine(sent1_feats, sent2_feats) return cosine_distance def getSentMatchScore_wfeature_test(sent1, sent2, sent1_feats, sent2_feats, nsp_dampening_factor = 0.7): cosine_distance = 1-cosine(sent1_feats, sent2_feats) nsp_input1 = sent1+' [SEP] '+sent2 nsp_input2 = sent2+' [SEP] '+sent1 nsp_score_1 = getNSPScore(nsp_input1) nsp_score_2 = getNSPScore(nsp_input2) nsp_score = np.mean([nsp_score_1,nsp_score_2])*nsp_dampening_factor #nsp_score = nsp_score_1*nsp_dampening_factor len_diff = abs(len(sent1.split(' '))-len(sent2.split(' '))) if len_diff>2*(min(len(sent1.split(' ')),len(sent2.split(' ')))): #give more weight to nsp if the sentences of largely varying lengths score = 0.4*cosine_distance+0.6*nsp_score else: score = np.mean([cosine_distance,nsp_score]) return score, cosine_distance, nsp_score def getBERTFeatures(model, text, attn_head_idx = -1): #attn_head_idx - index o[] tokenized_text = tokenizer.tokenize(text) if len(tokenized_text)>200: tokenized_text = tokenized_text[0:200] indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text) tokens_tensor = torch.tensor([indexed_tokens]) _, _, seq_out, pool_out = model(tokens_tensor) seq_out = list(getPooledFeatures(seq_out[attn_head_idx]).T) #pool_out = list(pool_out.detach().numpy().T) return seq_out def getPooledFeatures(np_array): np_array = np_array.reshape(np_array.shape[1],np_array.shape[2]).detach().numpy() np_array_mp = np.mean(np_array, axis=0).reshape(1, -1) return np_array_mp def replaceContractions(text): #text = text.lower() c_filt_text = '' for word in text.split(' '): if word in contractions: c_filt_text = c_filt_text+' '+contractions[word] else: c_filt_text = c_filt_text+' '+word return c_filt_text def cleanText(text): text = text.replace('\\n','') text = text.replace('\\','') #text = text.replace('\t', '') #text = re.sub('\[(.*?)\]','',text) #removes [this one] text = re.sub('(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\s', ' __url__ ',text) #remove urls #text = re.sub('\'','',text) #text = re.sub(r'\d+', ' __number__ ', text) #replaces numbers text = re.sub('\W', ' ', text) text = re.sub(' +', ' ', text) text = text.replace('\t', '') text = text.replace('\n', '') return text model1 = BertForPreTraining_custom(config) model1.to(device) #state_dict_1 = torch.load('/home/ether/domain_mind/ai/bert_10epc_ai_ds_1e-6_sl40.bin') state_dict_1 = torch.load('../data/bert_10epc_se_1e-6_sl40.bin') model1.load_state_dict(state_dict_1) model1.eval() def parsemeeting(text): with open(text, 'r') as f: parsed_text = json.load(f) return parsed_text text = parsemeeting('../data/meeting_transcript.txt') texts = '' for t in text['timeline']['transcriptSegments']: texts+= t['text'] texts ###Output _____no_output_____ ###Markdown get Communities from meetings. ###Code import sys, pickle sys.path.append('../') import text_preprocessing.preprocess as tp # with open('../data/Engineering_Mind_Test_Transcripts.txt','r') as fp: # texts = fp.read() mod_texts_unfiltered = tp.preprocess(texts, stop_words=False, remove_punct=True) mod_texts = [] for index, sent in enumerate(mod_texts_unfiltered): if len(sent.split(' '))>250: length = len(sent.split(' ')) split1 = ' '.join([i for i in sent.split(' ')[:round(length/2)]]) split2 = ' '.join([i for i in sent.split(' ')[round(length/2):]]) mod_texts.append(split1) mod_texts.append(split2) continue #mod_texts.pop(index) if len(sent.split(' '))<=6: continue mod_texts.append(sent) print(len(mod_texts)) fv = {} for index, sent in enumerate(mod_texts): fv[index] = getBERTFeatures(model1, sent, attn_head_idx=-1) print (index) import networkx as nx def build_graph(doc_list): eng_graph = nx.Graph() try: eng_graph.add_nodes_from(range(len(doc_list))) except Exception as e: print(e) return eng_graph tg = build_graph(mod_texts) attn_head_idx = -1 node_edge = [] for index1, sent1 in enumerate(mod_texts): print (index1) for index2, sent2 in enumerate(mod_texts): if index1!=index2: score = getSentMatchScore_wfeature(sent1, sent2,fv[index1],fv[index2]) # if score > 0.8: # #tg.add_edge(index1,index2,{'weight': score}) # tg.add_edge(index1,index2) tg.add_edge(index1,index2,weight=score) def build_community_graph(tg, mod_texts): com_graph = nx.Graph() for sent in list(tg.nodes()): com_graph.add_node(sent) for nodea in tg.nodes(): for nodeb in tg.nodes(): if nodea!=nodeb: if tg.edges[nodea,nodeb]['weight'] > 0.75: com_graph.add_edge(nodea,nodeb) return com_graph com_graph = build_community_graph(tg, mod_texts) # import community # import matplotlib.pyplot as plt # partition = community.best_partition(tg) # values = [partition.get(node) for node in tg.nodes()] # values=[partition.get(node) for node in tg.nodes()] # plt.rcParams['figure.figsize']= [16, 10] # measure_name = "Louviin Algorithm Community Structure" # pos = nx.spring_layout(tg, k=0.2, iterations=20) # nodes_plot=nx.draw_networkx_nodes(tg, pos, node_size=140, label=True, cmap=plt.get_cmap('magma', len(tg.nodes())/4),node_color=values, alpha=0.95) # edges_plot=nx.draw_networkx_edges(tg, pos, edge_color='r', alpha=0.1) # plt.title(measure_name, fontsize=22, fontname='Arial') # plt.colorbar(nodes_plot) # plt.axis('off') # plt.show() import community import matplotlib.pyplot as plt partition = community.best_partition(com_graph) values = [partition.get(node) for node in com_graph.nodes()] values=[partition.get(node) for node in com_graph.nodes()] plt.rcParams['figure.figsize']= [16, 10] measure_name = "Louviin Algorithm Community Structure" pos = nx.spring_layout(com_graph, k=0.2, iterations=20) nodes_plot=nx.draw_networkx_nodes(com_graph, pos, node_size=140, label=True, cmap=plt.get_cmap('magma', len(com_graph.nodes())/4),node_color=values, alpha=0.95) edges_plot=nx.draw_networkx_edges(com_graph, pos, edge_color='r', alpha=0.1) plt.title(measure_name, fontsize=22, fontname='Arial') plt.colorbar(nodes_plot) plt.axis('off') plt.show() community.modularity(partition, com_graph) partition = sorted(partition.items(), key=lambda kv: kv[1], reverse=False) current = 0 print ("--------------cluster " + str(0) + "------------ \n ") for word, cluster in partition: if cluster!=current: print ("--------------cluster " + str(cluster) + "------------ \n ") print (mod_texts[word]) current=cluster else: print (mod_texts[word]) com_graph.number_of_edges() tg.number_of_edges() clusters = [] temp = [] tot_com = 12 prev_com = 0 for word,cluster in partition: if prev_com!=cluster: clusters.append(temp) temp = [] prev_com+=1 else: temp.append(word) clusters new_text = [] temp = "" for com in clusters: new_text.append(' '.join(mod_texts[sent] for sent in com)) new_text[11] ###Output _____no_output_____ ###Markdown Using communities build word graph ###Code from graphrank.graphrank import GraphRank from graphrank.utils import GraphUtils, TextPreprocess gr = GraphRank() tp = TextPreprocess() utils = GraphUtils() keyphrases_list = [] for index, com in enumerate(new_text): if com!="": gr = GraphRank() tp = TextPreprocess() utils = GraphUtils() original_tokens, pos_tuple, filtered_pos_tuple = tp.preprocess_text(com, filter_by_pos=True, pos_filter=['NOUN', 'PROPN', 'ADJ', 'FW'], stop_words=False) word_graph = gr.build_word_graph(filtered_pos_tuple, original_tokens=original_tokens, window=4, reset_graph_context=True, preserve_common_words=False) keyphrases = gr.get_keyphrases(word_graph, normalize_nodes='degree', des) print (index, keyphrases[0]) keyphrases_list.append(keyphrases) for index, com in enumerate(keyphrases_list): print ("--------------Community----------- " + str(index)) for keyphrase in com: print (keyphrase[0]) ###Output --------------Community----------- 0 good shape highest priority ui changes request yesterday monday tasks timeline perspective ready nats performance shivam --------------Community----------- 1 best continuation orchestration basic slack install flow unique work space installation extra bucket private initial production level proper regression testing key phrase extraction customer provision method channel mind scheme corner cases manual peak ecxnumberx ebs peak kind hamburger menu context instance local storage installation process cdn distribution simple kind github pr custom url short time website front independent connectors api contract basic white cdn bucket service methods developer sign regression tests current database reply pattern regular key internal service channel list sxnumberx bucket admin table api contracts specific requirement current approaches customers table admin flow key phrase second pass current focus nats message current production customer service ready zoom place installs permissions minimum poke authenticates store header recording token scripts video cluster node document janus question authorization migrations login term poc support pim steps strategies desktop chapters fills priority transcript perspective thumbs localhost guys event confirm emit electron redirect environment closer dgraph pims implementation karthik create version parshwa free user tasks track shawshank staging today moment tomorrow entity server js work shivam changes ether tables api point key message service --------------Community----------- 2 cross domain cookie creations cross domain cookie creation hard gpl licenses default license specifications public hosted zones public hosted zone external dns godaddy account bad practice specific website ether bridge lgpl license good idea certificate creation manual experiments domain names manual tasks hosted zone etherlabs.io environments type organization example project policy servers apple kinds warning karthik bunch spl google agpl texts reason accounts repos mention chrome time lgpl meet call kind teraform middle creation --------------Community----------- 3 full text search gateway output handler official grav guideline config files users av capture edit action smaller sections root directory multisite setup lambda methods setup.phpfor subdirectory certificate issues model fields step fields validation errors form renders tasks nested fields task fields net today fossa changes menu scans scan naive database example build services tasksteps concerns guess lot controller problem yesterday steps path fieldsfor grav validation tasks form --------------Community----------- 4 overt racial tension frightening gang wars vermont sen. bernie sanders sum news release friday bidens campaign country south central los angeles texas rep. beto orourkes worlds oldest continuous monarchy news conference senator mitchell state senators holly mitchell california state bill sbxnumberx vice president joe biden mangy tawny shepherd dog democratic presidential candidates screen time app makers ubiquitous police helicopters big factor notorious police department american professional wrestler san francisco forgave insensitive police force president barack obama app data firm arms control note lucrative customers apple parental control apps saddling prisoners downloaded screen time iphone app store chrysanthemum throne crown prince ahmad fawad economic shackles eldest son adult content legged animals dangerous neighborhoods streets day day total unheated classroom administrative fees successful effort robert hertzberg thursday evening gentle figure childrens access york times childrens devices single day nonviolent teenagers misguided arrangement big stick sensor tower white house sadistic gangs unusual power advertising biden year festivities conventional weapons south central mr. singleton american culture san francisco head free mr. trump domestic laws apples business year apple apples tools john cena united nations tech titan cases apple united states latest companies app makers app store screen time countries matches fear handlers prosecution practice counties winner second policeman judge hours nowruz announcements change impossible shackling persian german reintegration communities crips autumn legislation society abdication boy land centuries fundraiser years philadelphia duty tuesday gun families akihito wave night stadium peace fight violence film blood foe place rival debt japan outskirts fortunes center county vibe email jaws tokyo moment august emperor corporations analysis frenzy individuals treaty money parents month letter decision captivating executives features procedures medium boyz lesser aggressive number experts options mercy control senate accord apple time --------------Community----------- 5 distributed scalable big data store random real time readwrite access fs hadoop distributed file system native library location tremendous struggle fault tolerant manner normal sequential programs store huge amounts data tofrom hbase better availability manner processing framework mapreduce distributed filesystem hdfs computation framework mapreduce random readwrite capability faster readwrite access sequential data access high throughput question hadoop lower risk nosql database hbase apis management bridge resource negotiator gigantic amounts hadoop cluster mapreduce jobs data loss sequential programs random read hadoop hbase parallel manner huge data fs hdfs downvotes suggestion day java google bigtable sense storage inefficient top redundant replication picture good hadoop huge access mapreduce --------------Community----------- 6 single binary distribution policy nested forms solution form pycharm interpreter settings multi nested form actual url automatic process vxnumberxsubsitefolderxnumberx works error message janus gateway formtasticcocoon gem future version lib folder vxnumberx folder folder structure deeper level vxnumberxsubsitefolderxnumberxlandingpage hxnumberx close original pypy quality speed project file landing answer numpy half links opencv issue encoding bearing tired ffmpeg files projects rails pip support python railscasts path folders level sites --------------Community----------- 7 opencv python webrtc apps genuine segmentation fault requirement opencv python efficient robust core dump directional communication matching distribution websocket connection media metadata place videoaudiodata performance cost intermediary server clues apis technology example version versions audio hand error network clients process service client server --------------Community----------- 8 pok sino indian ties kashmir issue hurriyat leaders protest letters china offering chinese investments jammu years pakistan residents visas islamabad projects troops beijing move china chinese ###Markdown testing topic modelling with LDA ###Code from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import string stop = set(stopwords.words('english')) exclude = set(string.punctuation) lemma = WordNetLemmatizer() def clean(doc): stop_free = " ".join([i for i in doc.lower().split() if i not in stop]) punc_free = ''.join(ch for ch in stop_free if ch not in exclude) normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split()) return normalized doc_clean = [clean(doc).split() for doc in new_text] #doc_clean = [clean(new_text[1]).split()] doc_clean import gensim from gensim import corpora dictionary = corpora.Dictionary(doc_clean) doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(doc_term_matrix, num_topics=3, id2word = dictionary, passes=50) print(ldamodel.print_topics()) ###Output [(0, '0.008*"zone" + 0.008*"hosted" + 0.008*"creation" + 0.008*"license" + 0.006*"one" + 0.006*"domain" + 0.005*"probably" + 0.005*"say" + 0.005*"thing" + 0.005*"never"'), (1, '0.018*"xnumberx" + 0.008*"data" + 0.007*"file" + 0.005*"task" + 0.005*"apple" + 0.005*"new" + 0.005*"time" + 0.005*"hbase" + 0.005*"hdfs" + 0.005*"hadoop"'), (2, '0.015*"like" + 0.015*"customer" + 0.011*"basically" + 0.008*"one" + 0.007*"service" + 0.007*"right" + 0.007*"know" + 0.007*"sign" + 0.007*"end" + 0.007*"thing"')]
VAE.ipynb
###Markdown Training ###Code # Setup encoder = Encoder(LATENT_DIM) decoder = Decoder(LATENT_DIM) model = VAE(encoder, decoder, N_SAMPLES, LATENT_DIM) model.to(device) optimizer = optim.Adam(vae.parameters(), lr=1e-4) kl_divergence_loss = KLDivergenceLoss() recon_loss = ReconstructionLoss() for epoch in range(1, EPOCHS + 1): # TRAIN model.train() train_loss = 0 for batch_idx, (x, _) in enumerate(train_loader): optimizer.zero_grad() x = Variable(x) x = x.to(device) xhat, mu, logvar = model.forward(x) rc_loss = recon_loss(xhat, x) kl_loss = kl_divergence_loss(mu, logvar) loss = rc_loss + kl_loss loss.backward() optimizer.step() train_loss += loss.item() if batch_idx % LOG_INTERVAL == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tRCLoss: {:.6f}, KLLoss: {:.6f}'.format( epoch, batch_idx * len(x), len(train_loader.dataset), 100. * batch_idx / len(train_loader), rc_loss.item(), kl_loss.item() )) print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(train_loader.dataset))) # TEST model.eval() test_loss = 0 for i, (data, _) in enumerate(test_loader): data = data.to(device) # we're only going to infer, so no autograd at all required: volatile=True data = Variable(data, volatile=True) xhat, mu, logvar = model.forward(data) rc_loss = recon_loss(xhat, x) kl_loss = kl_divergence_loss(mu, logvar) loss = rc_loss + kl_loss if i == 0: n = min(data.size(0), 8) # for the first 128 batch of the epoch, show the first 8 input digits # with right below them the reconstructed output digits comparison = torch.cat([data[:n], xhat.view(BATCH_SIZE, 1, 28, 28)[:n]]) save_image(comparison.data.cpu(), './mnist/reconstruction_' + str(epoch) + '.png', nrow=n) test_loss /= len(test_loader.dataset) print('====> Test set loss: {:.4f}'.format(loss)) xgen = vae.sample() xgen = xgen.detach().numpy()[0, 0, ...] plt.imshow(xgen) xgen.max(), xgen.min(), xgen.mean() ###Output _____no_output_____ ###Markdown Tests ###Code x, y = next(iter(train_loader)) print(x.shape) print(x.max()) plt.imshow(x[0][0]) mu, logvar = encoder.forward(x[0, ...]) mu, logvar.exp() xhat = decoder.forward(mu) plt.imshow(xhat.detach().numpy()[0][0]) xhat, mu, logvar = vae.forward(x) plt.imshow(xhat[0].detach().numpy()[0][0]) ###Output _____no_output_____ ###Markdown DatasetMNIST handwritten digits, reshaped to vectors in $\mathbb{R}^{784}$, and binarized. ###Code (x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape((x_train.shape[0], -1)) / 255 x_train = np.where(x_train < 0.5, 0, 1).astype('float32') x_test = x_test.reshape((x_test.shape[0], -1)) / 255 x_test = np.where(x_test < 0.5, 0, 1).astype('float32') ###Output _____no_output_____ ###Markdown Variational Autoencoder EncoderThe encoder takes an input $x$, and compresses it down to a lower dimensonal latent vector $z$. Actually, it is stochastic so it outputs parameters $\theta = \{\mu, \sigma\}$ to $q_{\theta}(z|x)$ which is an isotropic multivariate Gaussian distribution $\mathcal{N}(\mu, \sigma I)$. When we sample from this distribution we get noisy representations of $z$. DecoderThe decoder takes a latent vector $z$ and outputs parameters for the data distributions that we can sample from to generate a sample. In this case of binarized, flattened MNIST images, the output is 784 Bernoulli parameters $p_{\phi}(x|z) = \{ \mu_1, \dots, \mu_{784} \}$. Variational AutoencoderThe full variational autoencoder has an encoder and a decoder. It takes a batch of input images in and outputs a batch of parameters $\mu, \sigma, p$ to be used to calculate the loss. $z$ is sampled using the reparameterization trick by letting $z=\mu + \sigma \epsilon$, where $\epsilon \sim \mathcal{N}(0, 1)$, to make $z$ deterministic with respect to the parameters, allowing gradients to be computed. Since the KL-diveregence regularizer pushes the parameters of the encoder toward a unit gaussian, we can then hallucinate MNIST digits by sampling from a unit gaussian (of the hidden dimension) and feeding these vectors through the decoder! ###Code class Encoder(tf.keras.layers.Layer): """ Gaussian distribution q(z|x) of dimension hidden_dim """ def __init__(self, hidden_dim): super().__init__() self.h = hidden_dim self.dense1 = tf.keras.layers.Dense(2 * hidden_dim, activation='relu') self.dense2 = tf.keras.layers.Dense(2 * hidden_dim) def call(self, x): x = self.dense1(x) x = self.dense2(x) mean, std = x[:, :self.h], tf.nn.softplus(x[:, self.h:]) return mean, std class Decoder(tf.keras.layers.Layer): """ Bernoulli distribution p(x|z) of dimension output_dim """ def __init__(self, hidden_dim, output_dim=784): super().__init__() self.dense1 = tf.keras.layers.Dense(2 * hidden_dim, activation='relu') self.dense2 = tf.keras.layers.Dense(output_dim, activation='sigmoid') def call(self, z): z = self.dense1(z) p = self.dense2(z) return p class VAE(tf.keras.Model): def __init__(self, hidden_dim): super().__init__() self.hidden_dim = hidden_dim self.encoder = Encoder(hidden_dim) self.decoder = Decoder(hidden_dim) def call(self, x): mean, std = self.encoder(x) eps = tf.random.normal(shape=mean.shape) z = mean + std * eps # Reparametrization trick p = self.decoder(z) return mean, std, p def hallucinate(self, n): z = tf.random.normal(shape=(n, self.hidden_dim)) p = self.decoder(z) return p.numpy().reshape(n, 28, 28) ###Output _____no_output_____ ###Markdown Loss FunctionImplementing the loss functions, the reconstruction loss is a single sample Monte-Carlo estimate and the KL-divergence loss is the analytical solution between two Gaussians. One is the unit Gaussian, and the other is the distribution output by the encoder. ###Code def log(x): """ Dodging nans """ eps = 1e-8 return tf.math.log(x + eps) def reconstruction_loss(x, p): return -tf.einsum("ij, ij -> i", x, log(p)) - tf.einsum("ij, ij ->i", (1 - x), log(1 - p)) def kldiv_loss(mean, std): return tf.reduce_sum((tf.square(std) + tf.square(mean) - 1) / 2 - log(std), axis=-1) def compute_loss(model, x): mean, std, p = model(x) rec_loss = reconstruction_loss(x, p) kld_loss = kldiv_loss(mean, std) return tf.reduce_mean(rec_loss + kld_loss) ###Output _____no_output_____ ###Markdown Helper FunctionsJust some helper functions to make the training loop a bit more readable! ###Code train_loss = tf.keras.metrics.Mean(name='training loss') test_loss = tf.keras.metrics.Mean(name='test loss') def train_step(model, x): with tf.GradientTape() as tape: loss = compute_loss(model, x) grads = tape.gradient(loss, model.trainable_variables) opt.apply_gradients(zip(grads, model.trainable_variables)) train_loss(loss) def test_step(model, x): loss = compute_loss(model, x) test_loss(loss) def reset_metrics(): train_loss.reset_states() test_loss.reset_states() def write_to_tensorboard(epoch): tf.summary.scalar(name='training loss', data=train_loss.result(), step=epoch) tf.summary.scalar(name='test loss', data=test_loss.result(), step=epoch) def hallucinate_images(model, N=5, save=False): """ Show N * N hallucinated images in a grid """ fig = plt.figure(figsize=(10, 10)) grid = ImageGrid(fig, 111, nrows_ncols=(N, N), axes_pad=0.1) images = model.hallucinate(int(N * N)) for ax, im in zip(grid, images): ax.imshow(im) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.grid(False) plt.axis('off') if save: plt.savefig("hallucinated.png", dpi=500) plt.show() ###Output _____no_output_____ ###Markdown Training Loop ###Code EPOCHS = 25 LATENT = 50 bs = 128 test_ds = tf.data.Dataset.from_tensor_slices(x_test).batch(bs) train_ds = tf.data.Dataset.from_tensor_slices(x_train).shuffle(10000).batch(bs) current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") log_dir = 'logs/VAE/' + current_time writer = tf.summary.create_file_writer(log_dir) tmp_train = "[{:3d}, {:3d}] ---> Train loss: {:3.2f}" tmp_test = "Test loss : {:3.2f}\n" model = VAE(hidden_dim=LATENT) opt = tf.keras.optimizers.Adam(1e-4) reset_metrics() with writer.as_default(): for epoch in range(EPOCHS): for i, x_tr in enumerate(train_ds): train_step(model, x_tr) if i % 100 == 0: print(tmp_train.format(epoch, i, train_loss.result())) for x_te in test_ds: test_step(model, x_te) print(f"After epoch {epoch}:") print(tmp_test.format(test_loss.result())) # Visualize some hallucinated images every 10th epoch to see the progress! if epoch % 10 == 0: hallucinate_images(model, 5) write_to_tensorboard(epoch) reset_metrics() ###Output _____no_output_____ ###Markdown ###Code %tensorflow_version 1.x import tensorflow as tf import keras import numpy as np import matplotlib.pyplot as plt from keras.layers import Input, Dense, Lambda, InputLayer, concatenate, Dropout from keras.models import Model, Sequential from keras import backend as K from keras import metrics from keras.datasets import mnist from keras.utils import np_utils # Start tf session so we can run code. sess = tf.InteractiveSession() # Connect keras to the created session. K.set_session(sess) def vlb_binomial(x, x_decoded_mean, t_mean, t_log_var): """Returns the value of negative Variational Lower Bound The inputs are tf.Tensor x: (batch_size x number_of_pixels) matrix with one image per row with zeros and ones x_decoded_mean: (batch_size x number_of_pixels) mean of the distribution p(x | t), real numbers from 0 to 1 t_mean: (batch_size x latent_dim) mean vector of the (normal) distribution q(t | x) t_log_var: (batch_size x latent_dim) logarithm of the variance vector of the (normal) distribution q(t | x) Returns: A tf.Tensor with one element (averaged across the batch), VLB """ vlb = tf.reduce_mean(tf.reduce_sum(x * tf.log( x_decoded_mean+1e-19 ) + (1-x) * tf.log( 1-x_decoded_mean+1e-19 ), axis = 1 ) - 0.5 * tf.reduce_sum( -t_log_var + tf.exp( t_log_var ) + tf.square(t_mean) - 1 , axis = 1 )) return -vlb batch_size = 100 original_dim = 784 # Number of pixels in MNIST images. latent_dim = 3 # d, dimensionality of the latent code t. intermediate_dim = 128 # Size of the hidden layer. epochs = 20 x = Input(batch_shape=(batch_size, original_dim)) def create_encoder(input_dim): # Encoder network. # We instantiate these layers separately so as to reuse them later encoder = Sequential(name='encoder') encoder.add(InputLayer([input_dim])) encoder.add(Dense(intermediate_dim, activation='relu')) encoder.add(Dense(2 * latent_dim)) return encoder encoder = create_encoder(original_dim) get_t_mean = Lambda(lambda h: h[:, :latent_dim]) get_t_log_var = Lambda(lambda h: h[:, latent_dim:]) h = encoder(x) t_mean = get_t_mean(h) t_log_var = get_t_log_var(h) # Sampling from the distribution # q(t | x) = N(t_mean, exp(t_log_var)) # with reparametrization trick. def sampling(args): """Returns sample from a distribution N(args[0], diag(args[1])) The sample should be computed with reparametrization trick. The inputs are tf.Tensor args[0]: (batch_size x latent_dim) mean of the desired distribution args[1]: (batch_size x latent_dim) logarithm of the variance vector of the desired distribution Returns: A tf.Tensor of size (batch_size x latent_dim), the samples. """ t_mean, t_log_var = args # YOUR CODE HERE epsilon = K.random_normal(t_mean.shape) z = epsilon*K.exp(0.5*t_log_var) + t_mean return z t = Lambda(sampling)([t_mean, t_log_var]) def create_decoder(input_dim): # Decoder network # We instantiate these layers separately so as to reuse them later decoder = Sequential(name='decoder') decoder.add(InputLayer([input_dim])) decoder.add(Dense(intermediate_dim, activation='relu')) decoder.add(Dense(original_dim, activation='sigmoid')) return decoder decoder = create_decoder(latent_dim) x_decoded_mean = decoder(t) loss = vlb_binomial(x, x_decoded_mean, t_mean, t_log_var) vae = Model(x, x_decoded_mean) # Keras will provide input (x) and output (x_decoded_mean) to the function that # should construct loss, but since our function also depends on other # things (e.g. t_means), it is easier to build the loss in advance and pass # a function that always returns it. vae.compile(optimizer=keras.optimizers.RMSprop(lr=0.001), loss=lambda x, y: loss) # train the VAE on MNIST digits (x_train, y_train), (x_test, y_test) = mnist.load_data() # One hot encoding. y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) hist = vae.fit(x=x_train, y=x_train, shuffle=True, epochs=epochs, batch_size=batch_size, validation_data=(x_test, x_test), verbose=2) fig = plt.figure(figsize=(10, 10)) for fid_idx, (data, title) in enumerate( zip([x_train, x_test], ['Train', 'Validation'])): n = 10 # figure with 10 x 2 digits digit_size = 28 figure = np.zeros((digit_size * n, digit_size * 2)) decoded = sess.run(x_decoded_mean, feed_dict={x: data[:batch_size, :]}) for i in range(10): figure[i * digit_size: (i + 1) * digit_size, :digit_size] = data[i, :].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, digit_size:] = decoded[i, :].reshape(digit_size, digit_size) ax = fig.add_subplot(1, 2, fid_idx + 1) ax.imshow(figure, cmap='Greys_r') ax.set_title(title) ax.axis('off') plt.show() n_samples = 10 p_samples = tf.random_normal([n_samples, latent_dim], 0.0, 1.0) # sampled_im_mean is a tf.Tensor of size 10 x 784 with 10 random # images sampled from the vae model. sampled_im_mean = decoder(p_samples) sampled_im_mean_np = sess.run(sampled_im_mean) # Show the sampled images. plt.figure() for i in range(n_samples): ax = plt.subplot(n_samples // 5 + 1, 5, i + 1) plt.imshow(sampled_im_mean_np[i, :].reshape(28, 28), cmap='gray') ax.axis('off') plt.show() ###Output _____no_output_____ ###Markdown Auto Encoder ###Code import os import pickle from tensorflow.keras import Model from tensorflow.keras.layers import Input, Conv2D, ReLU, BatchNormalization, \ Flatten, Dense, Reshape, Conv2DTranspose, Activation, Lambda from tensorflow.keras import backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import MeanSquaredError import numpy as np import tensorflow as tf tf.compat.v1.disable_eager_execution() class VAE: """ VAE represents a Deep Convolutional variational autoencoder architecture with mirrored encoder and decoder components. """ def __init__(self, input_shape, conv_filters, conv_kernels, conv_strides, latent_space_dim): self.input_shape = input_shape # [28, 28, 1] self.conv_filters = conv_filters # [2, 4, 8] self.conv_kernels = conv_kernels # [3, 5, 3] self.conv_strides = conv_strides # [1, 2, 2] self.latent_space_dim = latent_space_dim # 2 self.reconstruction_loss_weight = 1000 self.encoder = None self.decoder = None self.model = None self._num_conv_layers = len(conv_filters) self._shape_before_bottleneck = None self._model_input = None self._build() def summary(self): self.encoder.summary() self.decoder.summary() self.model.summary() def compile(self, learning_rate=0.0001): optimizer = Adam(learning_rate=learning_rate) self.model.compile(optimizer=optimizer, loss=self._calculate_combined_loss) def train(self, x_train, batch_size, num_epochs): self.model.fit(x_train, x_train, batch_size=batch_size, epochs=num_epochs, shuffle=True) def save(self, save_folder="."): self._create_folder_if_it_doesnt_exist(save_folder) self._save_parameters(save_folder) self._save_weights(save_folder) def load_weights(self, weights_path): self.model.load_weights(weights_path) def reconstruct(self, images): latent_representations = self.encoder.predict(images) reconstructed_images = self.decoder.predict(latent_representations) return reconstructed_images, latent_representations @classmethod def load(cls, save_folder="."): parameters_path = os.path.join(save_folder, "parameters.pkl") with open(parameters_path, "rb") as f: parameters = pickle.load(f) autoencoder = VAE(*parameters) weights_path = os.path.join(save_folder, "weights.h5") autoencoder.load_weights(weights_path) return autoencoder def _calculate_combined_loss(self, y_target, y_predicted): reconstruction_loss = self._calculate_reconstruction_loss(y_target, y_predicted) kl_loss = self._calculate_kl_loss(y_target, y_predicted) combined_loss = self.reconstruction_loss_weight * reconstruction_loss\ + kl_loss return combined_loss def _calculate_reconstruction_loss(self, y_target, y_predicted): error = y_target - y_predicted reconstruction_loss = K.mean(K.square(error), axis=[1, 2, 3]) return reconstruction_loss def _calculate_kl_loss(self, y_target, y_predicted): kl_loss = -0.5 * K.sum(1 + self.log_variance - K.square(self.mu) - K.exp(self.log_variance), axis=1) return kl_loss def _create_folder_if_it_doesnt_exist(self, folder): if not os.path.exists(folder): os.makedirs(folder) def _save_parameters(self, save_folder): parameters = [ self.input_shape, self.conv_filters, self.conv_kernels, self.conv_strides, self.latent_space_dim ] save_path = os.path.join(save_folder, "parameters.pkl") with open(save_path, "wb") as f: pickle.dump(parameters, f) def _save_weights(self, save_folder): save_path = os.path.join(save_folder, "weights.h5") self.model.save_weights(save_path) def _build(self): self._build_encoder() self._build_decoder() self._build_autoencoder() def _build_autoencoder(self): model_input = self._model_input model_output = self.decoder(self.encoder(model_input)) self.model = Model(model_input, model_output, name="autoencoder") def _build_decoder(self): decoder_input = self._add_decoder_input() dense_layer = self._add_dense_layer(decoder_input) reshape_layer = self._add_reshape_layer(dense_layer) conv_transpose_layers = self._add_conv_transpose_layers(reshape_layer) decoder_output = self._add_decoder_output(conv_transpose_layers) self.decoder = Model(decoder_input, decoder_output, name="decoder") def _add_decoder_input(self): return Input(shape=self.latent_space_dim, name="decoder_input") def _add_dense_layer(self, decoder_input): num_neurons = np.prod(self._shape_before_bottleneck) # [1, 2, 4] -> 8 dense_layer = Dense(num_neurons, name="decoder_dense")(decoder_input) return dense_layer def _add_reshape_layer(self, dense_layer): return Reshape(self._shape_before_bottleneck)(dense_layer) def _add_conv_transpose_layers(self, x): """Add conv transpose blocks.""" # loop through all the conv layers in reverse order and stop at the # first layer for layer_index in reversed(range(1, self._num_conv_layers)): x = self._add_conv_transpose_layer(layer_index, x) return x def _add_conv_transpose_layer(self, layer_index, x): layer_num = self._num_conv_layers - layer_index conv_transpose_layer = Conv2DTranspose( filters=self.conv_filters[layer_index], kernel_size=self.conv_kernels[layer_index], strides=self.conv_strides[layer_index], padding="same", name=f"decoder_conv_transpose_layer_{layer_num}" ) x = conv_transpose_layer(x) x = ReLU(name=f"decoder_relu_{layer_num}")(x) x = BatchNormalization(name=f"decoder_bn_{layer_num}")(x) return x def _add_decoder_output(self, x): conv_transpose_layer = Conv2DTranspose( filters=1, kernel_size=self.conv_kernels[0], strides=self.conv_strides[0], padding="same", name=f"decoder_conv_transpose_layer_{self._num_conv_layers}" ) x = conv_transpose_layer(x) output_layer = Activation("sigmoid", name="sigmoid_layer")(x) return output_layer def _build_encoder(self): encoder_input = self._add_encoder_input() conv_layers = self._add_conv_layers(encoder_input) bottleneck = self._add_bottleneck(conv_layers) self._model_input = encoder_input self.encoder = Model(encoder_input, bottleneck, name="encoder") def _add_encoder_input(self): return Input(shape=self.input_shape, name="encoder_input") def _add_conv_layers(self, encoder_input): """Create all convolutional blocks in encoder.""" x = encoder_input for layer_index in range(self._num_conv_layers): x = self._add_conv_layer(layer_index, x) return x def _add_conv_layer(self, layer_index, x): """Add a convolutional block to a graph of layers, consisting of conv 2d + ReLU + batch normalization. """ layer_number = layer_index + 1 conv_layer = Conv2D( filters=self.conv_filters[layer_index], kernel_size=self.conv_kernels[layer_index], strides=self.conv_strides[layer_index], padding="same", name=f"encoder_conv_layer_{layer_number}" ) x = conv_layer(x) x = ReLU(name=f"encoder_relu_{layer_number}")(x) x = BatchNormalization(name=f"encoder_bn_{layer_number}")(x) return x def _add_bottleneck(self, x): """Flatten data and add bottleneck with Guassian sampling (Dense layer). """ self._shape_before_bottleneck = K.int_shape(x)[1:] x = Flatten()(x) self.mu = Dense(self.latent_space_dim, name="mu")(x) self.log_variance = Dense(self.latent_space_dim, name="log_variance")(x) def sample_point_from_normal_distribution(args): mu, log_variance = args epsilon = K.random_normal(shape=K.shape(self.mu), mean=0., stddev=1.) sampled_point = mu + K.exp(log_variance / 2) * epsilon return sampled_point x = Lambda(sample_point_from_normal_distribution, name="encoder_output")([self.mu, self.log_variance]) return x if __name__ == "__main__": autoencoder = VAE( input_shape=(28, 28, 1), conv_filters=(32, 64, 64, 64), conv_kernels=(3, 3, 3, 3), conv_strides=(1, 2, 2, 1), latent_space_dim=2 ) autoencoder.summary() ###Output WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/keras/layers/normalization/batch_normalization.py:532: _colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. Model: "encoder" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== encoder_input (InputLayer) [(None, 28, 28, 1)] 0 [] encoder_conv_layer_1 (Conv2D) (None, 28, 28, 32) 320 ['encoder_input[0][0]'] encoder_relu_1 (ReLU) (None, 28, 28, 32) 0 ['encoder_conv_layer_1[0][0]'] encoder_bn_1 (BatchNormalizati (None, 28, 28, 32) 128 ['encoder_relu_1[0][0]'] on) encoder_conv_layer_2 (Conv2D) (None, 14, 14, 64) 18496 ['encoder_bn_1[0][0]'] encoder_relu_2 (ReLU) (None, 14, 14, 64) 0 ['encoder_conv_layer_2[0][0]'] encoder_bn_2 (BatchNormalizati (None, 14, 14, 64) 256 ['encoder_relu_2[0][0]'] on) encoder_conv_layer_3 (Conv2D) (None, 7, 7, 64) 36928 ['encoder_bn_2[0][0]'] encoder_relu_3 (ReLU) (None, 7, 7, 64) 0 ['encoder_conv_layer_3[0][0]'] encoder_bn_3 (BatchNormalizati (None, 7, 7, 64) 256 ['encoder_relu_3[0][0]'] on) encoder_conv_layer_4 (Conv2D) (None, 7, 7, 64) 36928 ['encoder_bn_3[0][0]'] encoder_relu_4 (ReLU) (None, 7, 7, 64) 0 ['encoder_conv_layer_4[0][0]'] encoder_bn_4 (BatchNormalizati (None, 7, 7, 64) 256 ['encoder_relu_4[0][0]'] on) flatten (Flatten) (None, 3136) 0 ['encoder_bn_4[0][0]'] mu (Dense) (None, 2) 6274 ['flatten[0][0]'] log_variance (Dense) (None, 2) 6274 ['flatten[0][0]'] encoder_output (Lambda) (None, 2) 0 ['mu[0][0]', 'log_variance[0][0]'] ================================================================================================== Total params: 106,116 Trainable params: 105,668 Non-trainable params: 448 __________________________________________________________________________________________________ Model: "decoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= decoder_input (InputLayer) [(None, 2)] 0 decoder_dense (Dense) (None, 3136) 9408 reshape (Reshape) (None, 7, 7, 64) 0 decoder_conv_transpose_laye (None, 7, 7, 64) 36928 r_1 (Conv2DTranspose) decoder_relu_1 (ReLU) (None, 7, 7, 64) 0 decoder_bn_1 (BatchNormaliz (None, 7, 7, 64) 256 ation) decoder_conv_transpose_laye (None, 14, 14, 64) 36928 r_2 (Conv2DTranspose) decoder_relu_2 (ReLU) (None, 14, 14, 64) 0 decoder_bn_2 (BatchNormaliz (None, 14, 14, 64) 256 ation) decoder_conv_transpose_laye (None, 28, 28, 64) 36928 r_3 (Conv2DTranspose) decoder_relu_3 (ReLU) (None, 28, 28, 64) 0 decoder_bn_3 (BatchNormaliz (None, 28, 28, 64) 256 ation) decoder_conv_transpose_laye (None, 28, 28, 1) 577 r_4 (Conv2DTranspose) sigmoid_layer (Activation) (None, 28, 28, 1) 0 ================================================================= Total params: 121,537 Trainable params: 121,153 Non-trainable params: 384 _________________________________________________________________ Model: "autoencoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= encoder_input (InputLayer) [(None, 28, 28, 1)] 0 encoder (Functional) (None, 2) 106116 decoder (Functional) (None, 28, 28, 1) 121537 ================================================================= Total params: 227,653 Trainable params: 226,821 Non-trainable params: 832 _________________________________________________________________ ###Markdown Training ###Code from tensorflow.keras.datasets import mnist LEARNING_RATE = 0.0005 BATCH_SIZE = 32 EPOCHS = 100 def load_mnist(): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype("float32") / 255 x_train = x_train.reshape(x_train.shape + (1,)) x_test = x_test.astype("float32") / 255 x_test = x_test.reshape(x_test.shape + (1,)) return x_train, y_train, x_test, y_test def train(x_train, learning_rate, batch_size, epochs): autoencoder = VAE( input_shape=(28, 28, 1), conv_filters=(32, 64, 64, 64), conv_kernels=(3, 3, 3, 3), conv_strides=(1, 2, 2, 1), latent_space_dim=2 ) autoencoder.summary() autoencoder.compile(learning_rate) autoencoder.train(x_train, batch_size, epochs) return autoencoder if __name__ == "__main__": x_train, _, _, _ = load_mnist() autoencoder = train(x_train[:10000], LEARNING_RATE, BATCH_SIZE, EPOCHS) autoencoder.save("model") ###Output Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step 11501568/11490434 [==============================] - 0s 0us/step Model: "encoder" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== encoder_input (InputLayer) [(None, 28, 28, 1)] 0 [] encoder_conv_layer_1 (Conv2D) (None, 28, 28, 32) 320 ['encoder_input[0][0]'] encoder_relu_1 (ReLU) (None, 28, 28, 32) 0 ['encoder_conv_layer_1[0][0]'] encoder_bn_1 (BatchNormalizati (None, 28, 28, 32) 128 ['encoder_relu_1[0][0]'] on) encoder_conv_layer_2 (Conv2D) (None, 14, 14, 64) 18496 ['encoder_bn_1[0][0]'] encoder_relu_2 (ReLU) (None, 14, 14, 64) 0 ['encoder_conv_layer_2[0][0]'] encoder_bn_2 (BatchNormalizati (None, 14, 14, 64) 256 ['encoder_relu_2[0][0]'] on) encoder_conv_layer_3 (Conv2D) (None, 7, 7, 64) 36928 ['encoder_bn_2[0][0]'] encoder_relu_3 (ReLU) (None, 7, 7, 64) 0 ['encoder_conv_layer_3[0][0]'] encoder_bn_3 (BatchNormalizati (None, 7, 7, 64) 256 ['encoder_relu_3[0][0]'] on) encoder_conv_layer_4 (Conv2D) (None, 7, 7, 64) 36928 ['encoder_bn_3[0][0]'] encoder_relu_4 (ReLU) (None, 7, 7, 64) 0 ['encoder_conv_layer_4[0][0]'] encoder_bn_4 (BatchNormalizati (None, 7, 7, 64) 256 ['encoder_relu_4[0][0]'] on) flatten_1 (Flatten) (None, 3136) 0 ['encoder_bn_4[0][0]'] mu (Dense) (None, 2) 6274 ['flatten_1[0][0]'] log_variance (Dense) (None, 2) 6274 ['flatten_1[0][0]'] encoder_output (Lambda) (None, 2) 0 ['mu[0][0]', 'log_variance[0][0]'] ================================================================================================== Total params: 106,116 Trainable params: 105,668 Non-trainable params: 448 __________________________________________________________________________________________________ Model: "decoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= decoder_input (InputLayer) [(None, 2)] 0 decoder_dense (Dense) (None, 3136) 9408 reshape_1 (Reshape) (None, 7, 7, 64) 0 decoder_conv_transpose_laye (None, 7, 7, 64) 36928 r_1 (Conv2DTranspose) decoder_relu_1 (ReLU) (None, 7, 7, 64) 0 decoder_bn_1 (BatchNormaliz (None, 7, 7, 64) 256 ation) decoder_conv_transpose_laye (None, 14, 14, 64) 36928 r_2 (Conv2DTranspose) decoder_relu_2 (ReLU) (None, 14, 14, 64) 0 decoder_bn_2 (BatchNormaliz (None, 14, 14, 64) 256 ation) decoder_conv_transpose_laye (None, 28, 28, 64) 36928 r_3 (Conv2DTranspose) decoder_relu_3 (ReLU) (None, 28, 28, 64) 0 decoder_bn_3 (BatchNormaliz (None, 28, 28, 64) 256 ation) decoder_conv_transpose_laye (None, 28, 28, 1) 577 r_4 (Conv2DTranspose) sigmoid_layer (Activation) (None, 28, 28, 1) 0 ================================================================= Total params: 121,537 Trainable params: 121,153 Non-trainable params: 384 _________________________________________________________________ Model: "autoencoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= encoder_input (InputLayer) [(None, 28, 28, 1)] 0 encoder (Functional) (None, 2) 106116 decoder (Functional) (None, 28, 28, 1) 121537 ================================================================= Total params: 227,653 Trainable params: 226,821 Non-trainable params: 832 _________________________________________________________________ Train on 10000 samples Epoch 1/100 10000/10000 [==============================] - 18s 2ms/sample - loss: 89.6785 Epoch 2/100 10000/10000 [==============================] - 7s 747us/sample - loss: 63.4864 Epoch 3/100 10000/10000 [==============================] - 7s 742us/sample - loss: 62.2486 Epoch 4/100 10000/10000 [==============================] - 7s 748us/sample - loss: 61.8216 Epoch 5/100 10000/10000 [==============================] - 7s 738us/sample - loss: 56.3943 Epoch 6/100 10000/10000 [==============================] - 7s 742us/sample - loss: 55.3544 Epoch 7/100 10000/10000 [==============================] - 7s 748us/sample - loss: 54.7080 Epoch 8/100 10000/10000 [==============================] - 7s 744us/sample - loss: 53.8619 Epoch 9/100 10000/10000 [==============================] - 7s 747us/sample - loss: 53.8249 Epoch 10/100 10000/10000 [==============================] - 8s 763us/sample - loss: 53.7798 Epoch 11/100 10000/10000 [==============================] - 8s 752us/sample - loss: 52.8781 Epoch 12/100 10000/10000 [==============================] - 8s 750us/sample - loss: 52.9754 Epoch 13/100 10000/10000 [==============================] - 8s 751us/sample - loss: 52.8069 Epoch 14/100 10000/10000 [==============================] - 7s 742us/sample - loss: 52.3136 Epoch 15/100 10000/10000 [==============================] - 7s 734us/sample - loss: 52.1709 Epoch 16/100 10000/10000 [==============================] - 8s 762us/sample - loss: 52.7597 Epoch 17/100 10000/10000 [==============================] - 7s 749us/sample - loss: 51.7940 Epoch 18/100 10000/10000 [==============================] - 8s 759us/sample - loss: 51.3431 Epoch 19/100 10000/10000 [==============================] - 8s 757us/sample - loss: 51.4139 Epoch 20/100 10000/10000 [==============================] - 8s 751us/sample - loss: 51.0650 Epoch 21/100 10000/10000 [==============================] - 8s 754us/sample - loss: 50.9518 Epoch 22/100 10000/10000 [==============================] - 7s 744us/sample - loss: 50.5710 Epoch 23/100 10000/10000 [==============================] - 8s 751us/sample - loss: 50.2859 Epoch 24/100 10000/10000 [==============================] - 8s 755us/sample - loss: 50.1481 Epoch 25/100 10000/10000 [==============================] - 7s 743us/sample - loss: 49.8787 Epoch 26/100 10000/10000 [==============================] - 8s 762us/sample - loss: 49.8553 Epoch 27/100 10000/10000 [==============================] - 7s 743us/sample - loss: 49.5258 Epoch 28/100 10000/10000 [==============================] - 8s 763us/sample - loss: 49.5199 Epoch 29/100 10000/10000 [==============================] - 8s 757us/sample - loss: 49.1501 Epoch 30/100 10000/10000 [==============================] - 8s 765us/sample - loss: 49.2056 Epoch 31/100 10000/10000 [==============================] - 7s 745us/sample - loss: 48.6669 Epoch 32/100 10000/10000 [==============================] - 7s 743us/sample - loss: 48.5071 Epoch 33/100 10000/10000 [==============================] - 8s 767us/sample - loss: 48.5689 Epoch 34/100 10000/10000 [==============================] - 7s 749us/sample - loss: 48.2706 Epoch 35/100 10000/10000 [==============================] - 7s 748us/sample - loss: 48.5779 Epoch 36/100 10000/10000 [==============================] - 8s 758us/sample - loss: 47.9474 Epoch 37/100 10000/10000 [==============================] - 8s 760us/sample - loss: 48.0592 Epoch 38/100 10000/10000 [==============================] - 8s 751us/sample - loss: 47.6731 Epoch 39/100 10000/10000 [==============================] - 7s 748us/sample - loss: 47.4983 Epoch 40/100 10000/10000 [==============================] - 7s 746us/sample - loss: 47.6771 Epoch 41/100 10000/10000 [==============================] - 7s 749us/sample - loss: 47.4905 Epoch 42/100 10000/10000 [==============================] - 7s 748us/sample - loss: 47.0507 Epoch 43/100 10000/10000 [==============================] - 8s 751us/sample - loss: 47.1279 Epoch 44/100 10000/10000 [==============================] - 7s 750us/sample - loss: 47.1962 Epoch 45/100 960/10000 [=>............................] - ETA: 6s - loss: 46.4414 ###Markdown Analysis ###Code import numpy as np import matplotlib.pyplot as plt def select_images(images, labels, num_images=10): sample_images_index = np.random.choice(range(len(images)), num_images) sample_images = images[sample_images_index] sample_labels = labels[sample_images_index] return sample_images, sample_labels def plot_reconstructed_images(images, reconstructed_images): fig = plt.figure(figsize=(15, 3)) num_images = len(images) for i, (image, reconstructed_image) in enumerate(zip(images, reconstructed_images)): image = image.squeeze() ax = fig.add_subplot(2, num_images, i + 1) ax.axis("off") ax.imshow(image, cmap="gray_r") reconstructed_image = reconstructed_image.squeeze() ax = fig.add_subplot(2, num_images, i + num_images + 1) ax.axis("off") ax.imshow(reconstructed_image, cmap="gray_r") plt.show() def plot_images_encoded_in_latent_space(latent_representations, sample_labels): plt.figure(figsize=(10, 10)) plt.scatter(latent_representations[:, 0], latent_representations[:, 1], cmap="rainbow", c=sample_labels, alpha=0.5, s=2) plt.colorbar() plt.show() if __name__ == "__main__": autoencoder = Autoencoder.load("model") x_train, y_train, x_test, y_test = load_mnist() num_sample_images_to_show = 8 sample_images, _ = select_images(x_test, y_test, num_sample_images_to_show) reconstructed_images, _ = autoencoder.reconstruct(sample_images) plot_reconstructed_images(sample_images, reconstructed_images) num_images = 6000 sample_images, sample_labels = select_images(x_test, y_test, num_images) _, latent_representations = autoencoder.reconstruct(sample_images) plot_images_encoded_in_latent_space(latent_representations, sample_labels) ###Output _____no_output_____ ###Markdown ###Code import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import numpy as np import matplotlib.pyplot as plt np.random.seed(0) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) n_samples = mnist.train.num_examples def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=tf.float32) class VariationalAutoencoder(object): """ Variation Autoencoder (VAE) with an sklearn-like interface implemented using TensorFlow. This implementation uses probabilistic encoders and decoders using Gaussian distributions and realized by multi-layer perceptrons. The VAE can be learned end-to-end. See "Auto-Encoding Variational Bayes" by Kingma and Welling for more details. """ def __init__(self, network_architecture, transfer_fct=tf.nn.softplus, learning_rate=0.001, batch_size=100): self.network_architecture = network_architecture self.transfer_fct = transfer_fct self.learning_rate = learning_rate self.batch_size = batch_size # tf Graph input self.x = tf.placeholder(tf.float32, [None, network_architecture["n_input"]]) # Create autoencoder network self._create_network() # Define loss function based variational upper-bound and # corresponding optimizer self._create_loss_optimizer() # Initializing the tensor flow variables init = tf.global_variables_initializer() # Launch the session self.sess = tf.InteractiveSession() self.sess.run(init) def _create_network(self): # Initialize autoencode network weights and biases network_weights = self._initialize_weights(**self.network_architecture) # Use recognition network to determine mean and # (log) variance of Gaussian distribution in latent # space self.z_mean, self.z_log_sigma_sq = \ self._recognition_network(network_weights["weights_recog"], network_weights["biases_recog"]) # Draw one sample z from Gaussian distribution n_z = self.network_architecture["n_z"] eps = tf.random_normal((self.batch_size, n_z), 0, 1, dtype=tf.float32) # z = mu + sigma*epsilon self.z = tf.add(self.z_mean, tf.multiply(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps)) # Use generator to determine mean of # Bernoulli distribution of reconstructed input self.x_reconstr_mean = \ self._generator_network(network_weights["weights_gener"], network_weights["biases_gener"]) def _initialize_weights(self, n_hidden_recog_1, n_hidden_recog_2, n_hidden_gener_1, n_hidden_gener_2, n_input, n_z): all_weights = dict() all_weights['weights_recog'] = { 'h1': tf.Variable(xavier_init(n_input, n_hidden_recog_1)), 'h2': tf.Variable(xavier_init(n_hidden_recog_1, n_hidden_recog_2)), 'out_mean': tf.Variable(xavier_init(n_hidden_recog_2, n_z)), 'out_log_sigma': tf.Variable(xavier_init(n_hidden_recog_2, n_z))} all_weights['biases_recog'] = { 'b1': tf.Variable(tf.zeros([n_hidden_recog_1], dtype=tf.float32)), 'b2': tf.Variable(tf.zeros([n_hidden_recog_2], dtype=tf.float32)), 'out_mean': tf.Variable(tf.zeros([n_z], dtype=tf.float32)), 'out_log_sigma': tf.Variable(tf.zeros([n_z], dtype=tf.float32))} all_weights['weights_gener'] = { 'h1': tf.Variable(xavier_init(n_z, n_hidden_gener_1)), 'h2': tf.Variable(xavier_init(n_hidden_gener_1, n_hidden_gener_2)), 'out_mean': tf.Variable(xavier_init(n_hidden_gener_2, n_input)), 'out_log_sigma': tf.Variable(xavier_init(n_hidden_gener_2, n_input))} all_weights['biases_gener'] = { 'b1': tf.Variable(tf.zeros([n_hidden_gener_1], dtype=tf.float32)), 'b2': tf.Variable(tf.zeros([n_hidden_gener_2], dtype=tf.float32)), 'out_mean': tf.Variable(tf.zeros([n_input], dtype=tf.float32)), 'out_log_sigma': tf.Variable(tf.zeros([n_input], dtype=tf.float32))} return all_weights def _recognition_network(self, weights, biases): # Generate probabilistic encoder (recognition network), which # maps inputs onto a normal distribution in latent space. # The transformation is parametrized and can be learned. layer_1 = self.transfer_fct(tf.add(tf.matmul(self.x, weights['h1']), biases['b1'])) layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])) z_mean = tf.add(tf.matmul(layer_2, weights['out_mean']), biases['out_mean']) z_log_sigma_sq = \ tf.add(tf.matmul(layer_2, weights['out_log_sigma']), biases['out_log_sigma']) return (z_mean, z_log_sigma_sq) def _generator_network(self, weights, biases): # Generate probabilistic decoder (decoder network), which # maps points in latent space onto a Bernoulli distribution in data space. # The transformation is parametrized and can be learned. layer_1 = self.transfer_fct(tf.add(tf.matmul(self.z, weights['h1']), biases['b1'])) layer_2 = self.transfer_fct(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])) x_reconstr_mean = \ tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weights['out_mean']), biases['out_mean'])) return x_reconstr_mean def _create_loss_optimizer(self): # The loss is composed of two terms: # 1.) The reconstruction loss (the negative log probability # of the input under the reconstructed Bernoulli distribution # induced by the decoder in the data space). # This can be interpreted as the number of "nats" required # for reconstructing the input when the activation in latent # is given. # Adding 1e-10 to avoid evaluation of log(0.0) reconstr_loss = \ -tf.reduce_sum(self.x * tf.log(1e-10 + self.x_reconstr_mean) + (1-self.x) * tf.log(1e-10 + 1 - self.x_reconstr_mean), 1) # 2.) The latent loss, which is defined as the Kullback Leibler divergence ## between the distribution in latent space induced by the encoder on # the data and some prior. This acts as a kind of regularizer. # This can be interpreted as the number of "nats" required # for transmitting the the latent space distribution given # the prior. latent_loss = -0.5 * tf.reduce_sum(1 + self.z_log_sigma_sq - tf.square(self.z_mean) - tf.exp(self.z_log_sigma_sq), 1) self.cost = tf.reduce_mean(reconstr_loss + latent_loss) # average over batch # Use ADAM optimizer self.optimizer = \ tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost) def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost def transform(self, X): """Transform data by mapping it into the latent space.""" # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.z_mean, feed_dict={self.x: X}) def generate(self, z_mu=None): """ Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. """ if z_mu is None: z_mu = np.random.normal(size=self.network_architecture["n_z"]) # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.x_reconstr_mean, feed_dict={self.z: z_mu}) def reconstruct(self, X): """ Use VAE to reconstruct given data. """ return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X}) def train(network_architecture, learning_rate=0.001, batch_size=100, training_epochs=10, display_step=5): vae = VariationalAutoencoder(network_architecture, learning_rate=learning_rate, batch_size=batch_size) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(n_samples / batch_size) # Loop over all batches for i in range(total_batch): batch_xs, _ = mnist.train.next_batch(batch_size) # Fit training using batch data cost = vae.partial_fit(batch_xs) # Compute average loss avg_cost += cost / n_samples * batch_size # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) return vae network_architecture = \ dict(n_hidden_recog_1=500, # 1st layer encoder neurons n_hidden_recog_2=500, # 2nd layer encoder neurons n_hidden_gener_1=500, # 1st layer decoder neurons n_hidden_gener_2=500, # 2nd layer decoder neurons n_input=784, # MNIST data input (img shape: 28*28) n_z=20) # dimensionality of latent space vae = train(network_architecture, training_epochs=75) ###Output _____no_output_____ ###Markdown This script demonstrates how to build a variational autoencoder with Keras. Reference - Auto-Encoding Variational Bayes https://arxiv.org/abs/1312.6114 ###Code from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda from keras.models import Model from keras import backend as K from keras import metrics from keras.datasets import mnist batch_size = 100 original_dim = 784 latent_dim = 2 intermediate_dim = 256 epochs = 50 epsilon_std = 1.0 x = Input(shape=(original_dim,)) h = Dense(intermediate_dim, activation='relu')(x) z_mean = Dense(latent_dim)(h) z_log_var = Dense(latent_dim)(h) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0., stddev=epsilon_std) return z_mean + K.exp(z_log_var / 2) * epsilon ###Output _____no_output_____ ###Markdown note that "output_shape" isn't necessary with the TensorFlow backend ###Code z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var]) ###Output _____no_output_____ ###Markdown we instantiate these layers separately so as to reuse them later ###Code decoder_h = Dense(intermediate_dim, activation='relu') decoder_mean = Dense(original_dim, activation='sigmoid') h_decoded = decoder_h(z) x_decoded_mean = decoder_mean(h_decoded) ###Output _____no_output_____ ###Markdown instantiate VAE model ###Code vae = Model(x, x_decoded_mean) ###Output _____no_output_____ ###Markdown Compute VAE loss ###Code xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean) kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) vae_loss = K.mean(xent_loss + kl_loss) vae.add_loss(vae_loss) vae.compile(optimizer='rmsprop') vae.summary() ###Output _____no_output_____ ###Markdown train the VAE on MNIST digits ###Code (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) vae.fit(x_train, shuffle=True, epochs=epochs, batch_size=batch_size, validation_data=(x_test, None)) ###Output _____no_output_____ ###Markdown build a model to project inputs on the latent space ###Code encoder = Model(x, z_mean) ###Output _____no_output_____ ###Markdown display a 2D plot of the digit classes in the latent space ###Code x_test_encoded = encoder.predict(x_test, batch_size=batch_size) plt.figure(figsize=(6, 6)) plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown build a digit generator that can sample from the learned distribution ###Code decoder_input = Input(shape=(latent_dim,)) _h_decoded = decoder_h(decoder_input) _x_decoded_mean = decoder_mean(_h_decoded) generator = Model(decoder_input, _x_decoded_mean) ###Output _____no_output_____ ###Markdown display a 2D manifold of the digits ###Code n = 15 # figure with 15x15 digits digit_size = 28 figure = np.zeros((digit_size * n, digit_size * n)) # linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian # to produce values of the latent variables z, since the prior of the latent space is Gaussian grid_x = norm.ppf(np.linspace(0.05, 0.95, n)) grid_y = norm.ppf(np.linspace(0.05, 0.95, n)) for i, yi in enumerate(grid_x): for j, xi in enumerate(grid_y): z_sample = np.array([[xi, yi]]) x_decoded = generator.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digit plt.figure(figsize=(10, 10)) plt.imshow(figure, cmap='Greys_r') plt.show() ###Output _____no_output_____ ###Markdown Training- variational loss (KL divergence) annealed according to sigmoid schedule after 29 epochs, running for a total 120 epochs.- output GRU layer had one additional input, corresponding to the character sampled from the softmax output, trained using teacher forcingGetting output samples from softmax (depending on temperature):https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.htmlpreparing-for-trainingPytorch training loop over batches:loss.backward()opt.step()opt.zero_grad()Which reconstruction loss?CE loss? ###Code def one_hot_array(i, n): return map(int, [ix == i for ix in xrange(n)]) def one_hot_index(vec, charset): return map(charset.index, vec) def from_one_hot_array(vec): oh = np.where(vec == 1) if oh[0].shape == (0, ): return None return int(oh[0][0]) def decode_smiles_from_indexes(vec, charset): return "".join(map(lambda x: charset[x], vec)).strip() charset = ['n', '[', 'o', 'I', '3', 'H', '+', 'S', '@', '8', '4', '1', 's', 'N', 'F', 'P', '/', '=', 'O', 'B', 'C', '\\', '(', '-', ']', '6', ')', 'r', '5', '7', '2', '#', 'l', 'c', ' '] def sigmoid_schedule(time_step, slope=1., start=22): return float(1 / (1. + np.exp(slope * (start - float(time_step))))) sigmoid_schedule(30) ###Output _____no_output_____ ###Markdown Baseline: Mean prediction ###Code # logP = np.mean(np.abs(Y[:,0].mean()-Y[:,0])) print("logP baseline: ", logP) QED = np.mean(np.abs(Y[:,1].mean()-Y[:,1])) print("QED baseline: ", QED) (np.abs(Y.mean(axis=0)-Y)).mean(axis=0) # logP, QED, SAS ###Output _____no_output_____ ###Markdown Train ###Code # From other pytorch implementation def vae_loss(x_decoded_mean, x, z_mean, z_logvar): xent_loss = F.binary_cross_entropy(x_decoded_mean, x, size_average=False) kl_loss = -0.5 * torch.sum(1 + z_logvar - z_mean.pow(2) - z_logvar.exp()) return xent_loss + kl_loss def xent_loss(x_decoded_mean, x): return F.binary_cross_entropy(x_decoded_mean, x, size_average=False) def kl_loss(z_mean, z_logvar): return -0.5 * torch.sum(1 + z_logvar - z_mean.pow(2) - z_logvar.exp()) # prediction loss: mse def pred_loss(y_pred, y_true): return torch.mean((y_pred - y_true).pow(2)) def mae(y_pred, y_true): return torch.mean(torch.abs(y_pred - y_true)) device = 'cuda' if torch.cuda.is_available() else 'cpu' epochs = 5 iters = 100 model = ChemVAE().to(device) optimizer = optim.Adam(model.parameters()) # From other pytorch implementation TODO def train(epoch): model.train() train_loss = 0 for batch_idx, data in enumerate(train_loader): y_true = data[1] data = data[0].to(device) optimizer.zero_grad() output, mean, logvar, z = model(data) pred = model.prediction(z) # print("pred:", pred.shape, "y: ", y_true.shape) if batch_idx==0: inp = data.cpu().numpy() outp = output.cpu().detach().numpy() lab = data.cpu().numpy() print("Input:") print(decode_smiles_from_indexes(map(from_one_hot_array, inp[0]), charset)) print("Label:") print(decode_smiles_from_indexes(map(from_one_hot_array, lab[0]), charset)) sampled = outp[0].reshape(1, 120, len(charset)).argmax(axis=2)[0] print("Output:") print(decode_smiles_from_indexes(sampled, charset)) # print("pred loss: ", pred_loss(pred, y_true), "shape: ", pred_loss(pred, y_true).shape) loss = sigmoid_schedule(epoch)*kl_loss(mean, logvar) + xent_loss(output, data) + sigmoid_schedule(epoch)*pred_loss(pred, y_true) loss.backward() train_loss += loss optimizer.step() if batch_idx % 100 == 0: print(f'{epoch} / {batch_idx}\t{loss:.4f}') pred_mae = mae(pred, y_true) print(f'{epoch} / {batch_idx}\tPred loss: {pred_mae:.4f}') # print(f'epoch {epoch}: train loss:', (train_loss / len(train_loader.dataset))) return train_loss / len(train_loader.dataset) for epoch in range(1, epochs + 1): train_loss = train(epoch) ###Output Input: C[C@@H]1CCO[C@@H]1C(=O)N1CC[C@H](C(N)=O)c2ccccc21 Label: C[C@@H]1CCO[C@@H]1C(=O)N1CC[C@H](C(N)=O)c2ccccc21 Output: llSSSSSSSSSFFFFFFFFFFccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc 1 / 0 38952.7891 1 / 0 Pred loss: 2.0713 Input: O=C(NCc1ccc([N+]2=CCCC2)cc1)NC1(c2ccc(Cl)cc2)CC1 Label: O=C(NCc1ccc([N+]2=CCCC2)cc1)NC1(c2ccc(Cl)cc2)CC1 Output: C[@@(((((((ccc))))))))))))))))3333388888888888555555555 2 / 0 36592.6992 2 / 0 Pred loss: 2.0678 Input: CCc1nnc(-c2cc3ccccc3n2CC(=O)NC(C)(C)C)o1 Label: CCc1nnc(-c2cc3ccccc3n2CC(=O)NC(C)(C)C)o1 Output: CCC####//////N(((((]]]22))))))))))))))333344444666666666666 3 / 0 35045.2813 3 / 0 Pred loss: 2.0292 Input: CCCOc1ccc(Br)cc1C[NH+]1CCC([C@@H](C)O)CC1 Label: CCCOc1ccc(Br)cc1C[NH+]1CCC([C@@H](C)O)CC1 Output: C###////////////NN]]]]]]))33333333333333333333355555555555 4 / 0 34815.9922 4 / 0 Pred loss: 1.7854 Input: O=C(C1CCC1)N1CCC[C@H]1c1nc2cc(-c3ccccc3)ccc2o1 Label: O=C(C1CCC1)N1CCC[C@H]1c1nc2cc(-c3ccccc3)ccc2o1 Output: CC##////////////++-33333344444445555555 5 / 0 34439.9297 5 / 0 Pred loss: 0.9569 ###Markdown Manually push data through network ###Code example_input = x_train[0] x = example_input x = x.view(1, x.size(0), -1) print(x.size()) mu, logvar = model.encode(x) print(mu.shape, logvar.shape) z = model.reparameterize(mu, logvar) z.shape output = model.decode(z) print("decoded shape: ", output.shape) out, m, l = model.forward(x) vae_loss(out, x, m, l) model.prediction(z).shape # TODO should we still have batch here? ###Output prop1 shape: torch.Size([1, 1000]) prop 2 shape torch.Size([1, 1]) ###Markdown - Autoencoders are closely related to principal component analysis (PCA). - split the network into two segments, the encoder, and the decoder- $\phi : \mathcal X \rightarrow \mathcal F $- $\psi : \mathcal F \rightarrow \mathcal X $- $\phi , \psi = argmin_{\phi,\psi} ||X - (\psi o \phi) X||^2$Basically, trying to recreate the original image after some generalized non-linear compression. - Encoding Network - $z = \sigma (Wx+b) $- decoding Network - $x' = \sigma' (W'z+b') $- Loss : $\mathcal L(x,x') = || x-x'|| = ||x - \sigma '(W' (\sigma (Wx+b)) + b')||^2$ - This is self-supervised learning.- **aim** of the autoencoder is to select our encoder and decoder functions in such a way that we require the minimal information to encode the image such that it be can regenerated on the other side. Types of AutoEncoders :- Denoising Autoencoders : add some white noise to the data prior to training also compare the error to the original image when training. This forces the network to **not become overfit to arbitrary noise** present in images. - Sparse Autoencoders : has a larger latent dimension than the input or output dimensions. But only a small fraction of the neurons fires, meaning that the network is inherently ‘sparse’. It forms form regularization to reduce the propensity for the network to overfit.- Contractive Autoencoder: do not alter the architecture and simply add a regularizer to the loss function. This can be thought of as a neural form of ridge regression.- Variatioal Autoencoders : Implemented a form of variational inference taken from Bayesian statistics. It learn a data generating distribution, which allows us to take random samples from the latent space. These random samples can then be decoded using the decoder network to generate unique images that have similar characteristics to those that the network was trained on.Ref: https://jaan.io/what-is-variational-autoencoder-vae-tutorial/https://towardsdatascience.com/generating-images-with-autoencoders-77fd3a8dd368 ###Code ###Output _____no_output_____ ###Markdown Variational Autoencoders Abstract In this part, I use Variational Autoencoders to generate fake images. And I aslo adjust the size of the latent space and change the network architecture to figure out the best combination of them to generate most realistic images. ###Code import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from keras import backend as K class Sampling(layers.Layer): """Uses (z_mean, z_log_var) to sample z, the vector encoding a digit.""" def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon latent_dim = 2 # because of z_mean and z_log_variance encoder_inputs = keras.Input(shape=(28, 28, 1)) x = layers.Conv2D(32, 3, activation="relu", strides=2, padding="same")(encoder_inputs) x = layers.Conv2D(64, 3, activation="relu", strides=2, padding="same")(x) conv_shape = K.int_shape(x) #Shape of conv to be provided to decoder print(conv_shape) x = layers.Flatten()(x) x = layers.Dense(32, activation="relu")(x) z_mean = layers.Dense(latent_dim, name="z_mean")(x) z_log_var = layers.Dense(latent_dim, name="z_log_var")(x) z = Sampling()([z_mean, z_log_var]) encoder = keras.Model(encoder_inputs, [z_mean, z_log_var, z], name="encoder") encoder.summary() latent_inputs = keras.Input(shape=(latent_dim,)) x = layers.Dense(conv_shape[1] * conv_shape[2] * conv_shape[3], activation="relu")(latent_inputs) # 7x7x64 shape x = layers.Reshape((conv_shape[1],conv_shape[2], conv_shape[3]))(x) x = layers.Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x) x = layers.Conv2DTranspose(32, 3, activation="relu", strides=2, padding="same")(x) decoder_outputs = layers.Conv2DTranspose(1, 3, activation="sigmoid", padding="same")(x) decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder") decoder.summary() class VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder self.total_loss_tracker = keras.metrics.Mean(name="total_loss") self.reconstruction_loss_tracker = keras.metrics.Mean( name="reconstruction_loss" ) self.kl_loss_tracker = keras.metrics.Mean(name="kl_loss") @property def metrics(self): return [ self.total_loss_tracker, self.reconstruction_loss_tracker, self.kl_loss_tracker, ] def train_step(self, data): with tf.GradientTape() as tape: z_mean, z_log_var, z = self.encoder(data) reconstruction = self.decoder(z) reconstruction_loss = tf.reduce_mean( tf.reduce_sum( keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2) ) ) kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)) kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1)) total_loss = reconstruction_loss + kl_loss grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) self.total_loss_tracker.update_state(total_loss) self.reconstruction_loss_tracker.update_state(reconstruction_loss) self.kl_loss_tracker.update_state(kl_loss) return { "loss": self.total_loss_tracker.result(), "reconstruction_loss": self.reconstruction_loss_tracker.result(), "kl_loss": self.kl_loss_tracker.result(), } import pandas as pd df = pd.read_csv('./data/94_character_TMNIST.csv') print(df.shape) X = df.drop(columns={'names','labels'}) X_images = X.values.reshape(-1,28,28) X_images = np.expand_dims(X_images, -1).astype("float32") / 255 vae = VAE(encoder, decoder) vae.compile(optimizer=keras.optimizers.Adam()) vae.fit(X_images, epochs=10, batch_size=128) import matplotlib.pyplot as plt def plot_latent_space(vae, n=8, figsize=12): # display a n*n 2D manifold of digits digit_size = 28 scale_x_left = 1 # If we change the range, t generate different image. scale_x_right = 4 scale_y_bottom = 0 scale_y_top = 1 figure = np.zeros((digit_size * n, digit_size * n)) # If we want to see different x and y range we can change values in grid_x and gird_y. I trid x= [-3,-2] and y = [-3,-1] values and m labeled imaged are generated. grid_x = np.linspace(scale_x_left, scale_x_right, n) # -3, -2 grid_y = np.linspace(scale_y_bottom, scale_y_top, n)[::-1] # -3, -1 for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = vae.decoder.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[ i * digit_size : (i + 1) * digit_size, j * digit_size : (j + 1) * digit_size, ] = digit plt.figure(figsize=(figsize, figsize)) start_range = digit_size // 2 end_range = n * digit_size + start_range pixel_range = np.arange(start_range, end_range, digit_size) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.imshow(figure, cmap="Greys_r") plt.show() plot_latent_space(vae) ###Output _____no_output_____ ###Markdown Feature extractor Using a pre-tranined VGG-16 we insert an empty layer (after a relu) to capture the feature maps ###Code #create an empty layer that will simply record the feature map passed to it. class GetFeatures(nn.Module): def __init__(self): super(GetFeatures, self).__init__() self.features = None def forward(self, x): self.features = x return x #download the pre-trained weights of the VGG-19 and append them to an array of layers . #we insert a layers_deep layer after a relu layer. #layers_deep controls how deep we go into the network def get_feature_extractor(layers_deep = 7): C_net = models.vgg19(pretrained=True).to(device) C_net = C_net.eval() layers = [] for i in range(layers_deep): layers.append(C_net.features[i]) if isinstance(C_net.features[i], nn.ReLU): layers.append(GetFeatures()) return nn.Sequential(*layers) #this function calculates the L2 loss (MSE) on the feature maps copied by the layers_deep #between the reconstructed image and the origional def feature_loss(img, recon_data, feature_extractor): img_cat = torch.cat((img, torch.sigmoid(recon_data)), 0) out = feature_extractor(img_cat) loss = 0 for i in range(len(feature_extractor)): if isinstance(feature_extractor[i], GetFeatures): loss += (feature_extractor[i].features[:(img.shape[0])] - feature_extractor[i].features[(img.shape[0]):]).pow(2).mean() return loss/(i+1) #Linear scaling the learning rate down def lr_Linear(epoch_max, epoch, lr): lr_adj = ((epoch_max-epoch)/epoch_max)*lr set_lr(lr = lr_adj) def set_lr(lr): for param_group in optimizer.param_groups: param_group['lr'] = lr transform = T.Compose([T.Resize(imageSize), T.ToTensor()]) trainloader, testloader = get_data_STL10(transform, batchSize, download = False, root = dataset_root) #get a test image batch from the testloader to visualise the reconstruction quality dataiter = iter(testloader) test_images = dataiter.next()[0] test_images.shape plt.figure(figsize = (20,10)) out = vutils.make_grid(test_images[0:8]) plt.imshow(out.numpy().transpose((1, 2, 0))) #Create VAE network vae_net = VAE(channel_in = 3).to(device) #Create feature extractor network feature_extractor = get_feature_extractor() # setup optimizer optimizer = optim.Adam(vae_net.parameters(), lr=lr, betas=(0.5, 0.999)) #Loss function BCE_Loss = nn.BCEWithLogitsLoss() loss_log = [] #Create the save directory if it does note exist if not os.path.isdir(save_dir + "/Models"): os.makedirs(save_dir + "/Models") if not os.path.isdir(save_dir + "/Results"): os.makedirs(save_dir + "/Results") if load_checkpoint: checkpoint = torch.load(save_dir + "/Models/" + model_name + "_" + str(imageSize) + ".pt", map_location = "cpu") print("Checkpoint loaded") optimizer.load_state_dict(checkpoint['optimizer_state_dict']) vae_net.load_state_dict(checkpoint['model_state_dict']) start_epoch = checkpoint["epoch"] loss_log = checkpoint["loss_log"] else: #If checkpoint does exist raise an error to prevent accidental overwriting if os.path.isfile(save_dir + "/Models/" + model_name + "_" + str(imageSize) + ".pt"): raise ValueError("Warning Checkpoint exists") else: print("Starting from scratch") recon_data, mu, logvar = vae_net(test_images.to(device)) for epoch in range(start_epoch, nepoch): lr_Linear(nepoch, epoch, lr) for i, data in enumerate(trainloader, 0): recon_data, mu, logvar = vae_net(data[0].to(device)) #VAE loss loss = vae_loss(recon_data, data[0].to(device), mu, logvar) #Perception loss loss_feature = feature_loss(data[0].to(device), recon_data, feature_extractor) loss += loss_feature loss_log.append(loss.item()) vae_net.zero_grad() loss.backward() optimizer.step() clear_output(True) print('Epoch: [%d/%d], Itteration: [%d/%d] loss: %.4f' % (epoch, nepoch, i, len(trainloader), loss.item())) with torch.no_grad(): #For validation we set Train = False which will skip the sampling/reparameterization step #and just use mu to decode recon_data, _, _ = vae_net(test_images.to(device), Train = False) vutils.save_image(torch.cat((torch.sigmoid(recon_data.cpu()), test_images),2),"%s/%s/%s_%d.png" % (save_dir, "Results" , model_name, imageSize)) # #Save a checkpoint torch.save({ 'epoch' : epoch, 'loss_log' : loss_log, 'model_state_dict' : vae_net.state_dict(), 'optimizer_state_dict' : optimizer.state_dict() }, save_dir + "/Models/" + model_name + "_" + str(imageSize) + ".pt") ###Output _____no_output_____ ###Markdown ###Code import pickle import os import torch import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import median_absolute_deviation from torch import nn, optim from torchvision import datasets, transforms, models from torch.utils.data import DataLoader, Dataset from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.model_selection import KFold from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.linear_model import ElasticNet from sklearn.metrics import mean_squared_error, r2_score from scipy.stats import pearsonr import random from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV !nvidia-smi from google.colab import drive drive.mount('/content/gdrive') from torch.utils.data import Dataset, DataLoader class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) # VAE model class VAE(nn.Module): def __init__(self, input_size): super(VAE, self).__init__() self.fc1 = nn.Linear(input_size, 5000) self.fc2 = nn.Linear(5000, 2000) self.fc3 = nn.Linear(2000, 500) self.fc41 = nn.Linear(500, 100) self.fc42 = nn.Linear(500, 100) self.fc5 = nn.Linear(100, 500) self.fc6 = nn.Linear(500, 2000) self.fc7 = nn.Linear(2000, 5000) self.fc8 = nn.Linear(5000, input_size) # 编码 def encode(self, x): h = F.relu(self.fc1(x)) h = F.relu(self.fc2(h)) h = F.relu(self.fc3(h)) return self.fc41(h), self.fc42(h) # 随机生成隐含向量 def reparameterize(self, mu, log_var): std = torch.exp(log_var/2) eps = torch.randn_like(std) return mu + eps * std # 解码 def decode(self, z): h = F.relu(self.fc5(z)) h = F.relu(self.fc6(h)) h = F.relu(self.fc7(h)) return torch.sigmoid(self.fc8(h)) # 前向传播 def forward(self, x): mu, log_var = self.encode(x) z = self.reparameterize(mu, log_var) x_reconst = self.decode(z) return x_reconst, mu, log_var def loss_function(recon_x, x, mu, logvar): BCE = F.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum') # see Appendix B from VAE paper: # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 # https://arxiv.org/abs/1312.6114 # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return BCE + KLD # python读取 import pandas as pd import numpy as np bortezomib = pd.read_csv("gdrive/MyDrive/AE_results/Data/bortezomib_cells.txt", sep = "\t") # bortezomib.head(5) cisplatin = pd.read_csv("gdrive/MyDrive/AE_results/Data/cisplatin-occams_cells.txt", sep = "\t") paclitaxel = pd.read_csv("gdrive/MyDrive/AE_results/Data/paclitaxel_cells.txt", sep = "\t") parpi = pd.read_csv("gdrive/MyDrive/AE_results/Data/parpi_cells.txt", sep = "\t") data = parpi scaler = MinMaxScaler() new_data = scaler.fit_transform(data.iloc[:,1:]) all_data, all_labels = np.array(new_data), np.array(data.iloc[:,0]) all_dataset = RegressionDataset(torch.from_numpy(all_data).float(), torch.from_numpy(all_labels).float()) all_loader = DataLoader(dataset=all_dataset, batch_size=20) batch_size = 20 learning_rate = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) model = VAE(data.shape[1]-1).to(device) optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) all_loss = [] for epoch in range(200): train_loss = 0 for i, (x, _) in enumerate(all_loader): # 获取样本,并前向传播 x = x.to(device) x_reconst, mu, log_var = model(x) # 计算重构损失和KL散度(KL散度用于衡量两种分布的相似程度) reconst_loss = F.binary_cross_entropy(x_reconst, x, reduction='sum') kl_div = - 0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp()) loss = reconst_loss + kl_div # 反向传播和优化 optimizer.zero_grad() loss.backward() train_loss += loss.item() optimizer.step() all_loss.append(train_loss / len(all_loader)) if not epoch%50: print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(all_loader))) x_reconst, mu, log_var = model(torch.from_numpy(new_data).float().cuda()) x_encoder = VAE(data.shape[1]-1).reparameterize(mu, log_var) x_encoder.shape x_encoder.cpu().detach().numpy()[~np.isnan(all_labels)].shape encoder_nona = x_encoder.cpu().detach().numpy()[~np.isnan(all_labels)] labels_nona = all_labels[~np.isnan(all_labels)] from sklearn.model_selection import train_test_split train_encoder, test_encoder, y_train, y_test = train_test_split(x_encoder.cpu().detach().numpy()[~np.isnan(all_labels)], all_labels[~np.isnan(all_labels)], test_size=0.3) from sklearn.svm import SVR from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error rbf_svr = SVR(kernel='rbf', C=1.5) rbf_svr.fit(train_encoder, y_train) rbf_svr_predict = rbf_svr.predict(test_encoder) print(mean_squared_error(y_test, rbf_svr_predict)) print(r2_score(y_test, rbf_svr_predict)) from sklearn.model_selection import cross_val_score print(np.mean(cross_val_score(rbf_svr, encoder_nona, labels_nona, cv=5, scoring="neg_mean_squared_error"))) print(np.mean(cross_val_score(rbf_svr, encoder_nona, labels_nona, cv=5, scoring="r2"))) # PCA from sklearn.decomposition import PCA pca = PCA(n_components=100) pca.fit(all_data) # print(pca.explained_variance_ratio_) print(np.sum(pca.explained_variance_ratio_)) # print(pca.explained_variance_) X_new = pca.transform(all_data) X_new.shape X_new_nona = X_new[~np.isnan(all_labels)] labels_nona = all_labels[~np.isnan(all_labels)] print(np.mean(cross_val_score(rbf_svr, X_new_nona, labels_nona, cv=5, scoring="neg_mean_squared_error"))) print(np.mean(cross_val_score(rbf_svr, X_new_nona, labels_nona, cv=5, scoring="r2"))) # UMAP import umap reducer = umap.UMAP(n_components=100) X_new = reducer.fit_transform(all_data) X_new_nona = X_new[~np.isnan(all_labels)] labels_nona = all_labels[~np.isnan(all_labels)] print(np.mean(cross_val_score(rbf_svr, X_new_nona, labels_nona, cv=5, scoring="neg_mean_squared_error"))) print(np.mean(cross_val_score(rbf_svr, X_new_nona, labels_nona, cv=5, scoring="r2"))) import scipy.io as scio data_file = 'gdrive/MyDrive/AE_results/MC_PR_Data/CCLE_X.mat' data = scio.loadmat(data_file) gene_expr = data['X'] labels_file = 'gdrive/MyDrive/AE_results/MC_PR_Data/MMnormal.mat' labels_data = scio.loadmat(labels_file) labels = labels_data['MM'] # VAE model class VAE(nn.Module): def __init__(self, input_size): super(VAE, self).__init__() self.fc1 = nn.Linear(input_size, 3000) self.fc21 = nn.Linear(3000, 500) self.fc22 = nn.Linear(3000, 500) self.fc3 = nn.Linear(500, 3000) self.fc4 = nn.Linear(3000, input_size) # 编码 def encode(self, x): h = F.relu(self.fc1(x)) return self.fc21(h), self.fc22(h) # 随机生成隐含向量 def reparameterize(self, mu, log_var): std = torch.exp(log_var/2) eps = torch.randn_like(std) return mu + eps * std # 解码 def decode(self, z): h = F.relu(self.fc3(z)) h = self.fc4(h) return torch.sigmoid(h) # return h # 前向传播 def forward(self, x): mu, log_var = self.encode(x) z = self.reparameterize(mu, log_var) x_reconst = self.decode(z) return x_reconst, mu, log_var class customLoss(nn.Module): def __init__(self): super(customLoss, self).__init__() self.mse_loss = nn.MSELoss(reduction="sum") # x_recon ist der im forward im Model erstellte recon_batch, x ist der originale x Batch, mu ist mu und logvar ist logvar def forward(self, x_recon, x, mu, logvar): loss_MSE = self.mse_loss(x_recon, x) loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return loss_MSE + loss_KLD def loss_function(recon_x, x, mu, logvar): loss = nn.MSELoss(reduction="sum") loss_MSE = loss(recon_x, x) loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return loss_MSE + loss_KLD def scale_data(X_train, X_test): scaler = MinMaxScaler() new_X_train = scaler.fit_transform(X_train) new_X_test = scaler.transform(X_test) return new_X_train, new_X_test def top_mad(X_train, X_test, cut): index = np.argsort(-median_absolute_deviation(X_train)) new_index = index[:int(X_train.shape[1] * cut)] X_train = X_train[:,new_index] X_test = X_test[:,new_index] return X_train, X_test def classic_reg(X_train, y_train, X_test, method): if method == 'rf': rg = RandomForestRegressor() if method == 'svr': rg = SVR(kernel='rbf') if method == 'elasticnet': rg = ElasticNet() rg.fit(X_train, y_train) test_pred = rg.predict(X_test) return test_pred def evaluate(y_test, test_pred): r2 = r2_score(y_test, test_pred) mse = mean_squared_error(y_test, test_pred) pccs = pearsonr(y_test, test_pred) # print("Method = {}, r2_score = {}, MSE = {}, PCC = {}, PCC_p".format(method, r2, mse, pccs[0], pccs[1])) return r2, mse, pccs[0] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(gene_expr, labels[:,3], test_size=0.2, random_state=42) X_train, X_test = top_mad(X_train, X_test, cut=0.5) X_train, X_test = scale_data(X_train, X_test) train_loader = DataLoader(dataset=torch.from_numpy(X_train).float(), batch_size=30) test_loader = DataLoader(dataset=torch.from_numpy(X_test).float(), batch_size=30) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) input_size x.shape input_size = X_train.shape[1] model2 = VAE(input_size).to(device) optimizer = torch.optim.Adam(model2.parameters(), lr=1e-3) all_train_loss = [] all_test_loss = [] for epoch in range(200): train_loss = 0 model2.train() for x in train_loader: # model2.train() x = x.cuda() x_reconst, mu, log_var = model2(x) loss = loss_function(x_reconst, x, mu, log_var) # backprop optimizer.zero_grad() loss.backward() optimizer.step() train_loss += loss.item() with torch.no_grad(): model2.eval() test_loss = 0 for x in test_loader: # model2.eval() x = x.cuda() x_reconst, mu, log_var = model2(x) loss = loss_function(x_reconst, x, mu, log_var) test_loss += loss.item() all_train_loss.append(train_loss/len(train_loader)) all_test_loss.append(test_loss/len(test_loader)) if epoch % 20 == 0: print('epoch = {}, train loss = {}, test_loss = {};'.format(epoch,\ train_loss/len(train_loader), test_loss/len(test_loader))) plt.plot([x for x in range(200)], all_train_loss, label='Train Loss', linewidth=2) plt.plot([y for y in range(200)], all_test_loss, label='Val Loss', linewidth=2) plt.legend() plt.show() plt.plot([x for x in range(180)], all_train_loss[20:], label='Train Loss', linewidth=2) plt.plot([y for y in range(180)], all_test_loss[20:], label='Val Loss', linewidth=2) plt.legend() plt.show() torch.cuda.empty_cache() x_reconst, train_encoder, log_var = model2(torch.from_numpy(X_train).float().cuda()) x_reconst, test_encoder, log_var = model2(torch.from_numpy(X_test).float().cuda()) X_train = train_encoder.cpu().detach().numpy() X_test = test_encoder.cpu().detach().numpy() np.sum(np.all(np.equal(X_test, 0), axis=0)) methods = ['rf', 'svr'] all_r2 = [0, 0] all_mse = [0, 0] all_pcc = [0, 0] for j in range(2): test_pred = classic_reg(X_train, y_train, X_test, method=methods[j]) r2, mse, pcc = evaluate(y_test, test_pred) all_r2[j] += r2 all_mse[j] += mse all_pcc[j] += pcc print(all_r2) print(all_mse) print(all_pcc) ###Output [0.3872046592821007, 0.3566256168012716] [0.5644027933531994, 0.592567003893748] [0.6258431087467016, 0.628376624649286] ###Markdown ###Code import tensorflow.keras from tensorflow.keras import layers from tensorflow.keras import backend as K from tensorflow.keras.models import Model import numpy as np img_shape=(28, 28, 1) batch_size = 16 latent_dim= 2 input_img = tensorflow.keras.Input(shape = img_shape) x = layers.Conv2D(32,3,padding='same',activation='relu')(input_img) x = layers.Conv2D(64,3,padding='same',activation='relu',strides=(2,2))(x) x = layers.Conv2D(64,3,padding='same',activation='relu')(x) x = layers.Conv2D(64,3,padding='same',activation='relu')(x) shape_before_flattening = K.int_shape(x) x = layers.Flatten()(x) x = layers.Dense(32, activation='relu')(x) z_mean = layers.Dense(latent_dim)(x) z_log_var = layers.Dense(latent_dim)(x) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(K.shape(z_mean)[0],latent_dim),mean=0.,stddev=1.) return z_mean+K.exp(z_log_var)* epsilon z = layers.Lambda(sampling)([z_mean,z_log_var]) decoder_input = layers.Input(K.int_shape(z)[1:]) x = layers.Dense(np.prod(shape_before_flattening[1:]),activation='relu')(decoder_input) x = layers.Reshape(shape_before_flattening[1:])(x) x = layers.Conv2DTranspose(32, 3,padding='same',activation='relu',strides=(2,2))(x) x = layers.Conv2D(1, 3, padding='same',activation='sigmoid')(x) decoder = Model(decoder_input, x) z_decoded = decoder(z) class CustomVariationalLayer(tensorflow.keras.layers.Layer): def vae_loss(self, x, z_decoded): x = K.flatten(x) z_decoded = K.flatten(z_decoded) xent_loss = tensorflow.keras.metrics.binary_crossentropy(x, z_decoded) kl_loss = -5e-4 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) return K.mean(xent_loss + kl_loss) def call(self, inputs): x = inputs[0] z_decoded = inputs[1] loss = self.vae_loss(x, z_decoded) self.add_loss(loss, inputs = inputs) return x y = CustomVariationalLayer()([input_img, z_decoded]) from tensorflow.keras.datasets import mnist vae=Model(input_img, y) vae.compile(optimizer='rmsprop',loss=None) (x_train, _), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32')/255. ###Output W0820 13:06:38.966424 140294730282880 training_utils.py:1101] Output custom_variational_layer missing from loss dictionary. We assume this was done on purpose. The fit and evaluate APIs will not be expecting any data to be passed to custom_variational_layer. ###Markdown ###Code import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable from torchvision.utils import save_image import numpy as np import matplotlib.pyplot as plt batch_size =64 train_dataset = datasets.MNIST(root='./MNIST/',train=True,download=True, transform=transforms.ToTensor()) train = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) latent_dim=20 def generate_(batch_size): return torch.from_numpy(np.random.multivariate_normal(mean=np.zeros(latent_dim),cov =np.eye(latent_dim),size=batch_size)).type(torch.float) class VAE(nn.Module): def __init__(self): super(VAE,self).__init__() self.bottleneck=nn.Linear(784,400) self.mean=nn.Linear(400,latent_dim) self.variance=nn.Linear(400,latent_dim) self.dec1=nn.Linear(latent_dim,400) self.dec2=nn.Linear(400,784) def encoder(self,x): x=F.relu(self.bottleneck(x)) return self.mean(x),self.variance(x) def decoder(self,x): x=F.relu(self.dec1(x)) x=torch.sigmoid(self.dec2(x)) return x def sample(self,mu,sigma): sigma = torch.exp(0.5*sigma).to(device) # To make variance greater than zero normal = generate_(batch_size).to(device) return mu + sigma*normal def forward(self,x): mu,sigma = self.encoder(x) z = self.sample(mu,sigma).to(device) z = self.decoder(z) return mu,sigma,z def Loss(mu,sigma,recon_x,x,normal=False): loss = -0.5 * torch.sum(1 + sigma - mu.pow(2) - sigma.exp()) error =0 if(normal): error = F.mse_loss(recon_x,x) else: error = F.binary_cross_entropy(recon_x, x, reduction='sum') return loss+error # Check availabilty of device device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") model = VAE().to(device) optimizer = optim.Adam(model.parameters(), lr=1e-3) num_epochs = 50 loss_list = [] for epoch in range(num_epochs): loss=0 for i ,(images,target) in enumerate(train): batch_size = images.size(0) images = images.view(batch_size, -1).to(device) images = Variable(images,requires_grad =False) # set grad to zero optimizer.zero_grad() # Model training and Loss calculation mu,sigma,z = model(images) i_loss = Loss(mu,sigma,z,images) loss+=i_loss.item() i_loss.backward() optimizer.step() # accuracy if (i+1) % 200 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' .format(epoch, num_epochs, i+1, 938, i_loss.item())) loss_list.append(loss) z = generate_(100).to(device) generated_images = Variable(model.decoder(z),requires_grad =False) z= generated_images.reshape((100,28,28)) z=z.cpu().detach().numpy() fig=plt.figure(figsize=(12, 12)) columns = 10 rows = 10 for i in range(1, columns*rows +1): img = z[i-1] fig.add_subplot(rows, columns,i) show = plt.imshow(img) show.axes.get_xaxis().set_visible(False) show.axes.get_yaxis().set_visible(False) plt.savefig('result.jpg') plt.show() ###Output _____no_output_____ ###Markdown 构建VAE网络 ###Code import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatten, Reshape, Layer from keras.layers import Conv2D, Conv2DTranspose from keras.models import Model from keras import backend as K from keras import metrics from keras.datasets import mnist # input image dimensions gen_rows, gen_cols, gen_chns = 24, 24, 1 # number of convolutional filters to use filters = 64 # convolution kernel size num_conv = 3 batch_size = 100 if K.image_data_format() == 'channels_first': original_gen_size = (gen_chns, gen_rows, gen_cols) else: original_gen_size = (gen_rows, gen_cols, gen_chns) latent_dim = 5 intermediate_dim = 128 epsilon_std = 1.0 epochs = 5 x = Input(shape=original_gen_size) conv_1 = Conv2D(gen_chns, kernel_size=(2, 2), padding='same', activation='relu')(x) conv_2 = Conv2D(filters, kernel_size=(2, 2), padding='same', activation='relu', strides=(2, 2))(conv_1) conv_3 = Conv2D(filters, kernel_size=num_conv, padding='same', activation='relu', strides=1)(conv_2) conv_4 = Conv2D(filters, kernel_size=num_conv, padding='same', activation='relu', strides=1)(conv_3) flat = Flatten()(conv_4) hidden = Dense(intermediate_dim, activation='relu')(flat) z_mean = Dense(latent_dim)(hidden) z_log_var = Dense(latent_dim)(hidden) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0., stddev=epsilon_std) return z_mean + K.exp(z_log_var) * epsilon # note that "output_shape" isn't necessary with the TensorFlow backend # so you could write `Lambda(sampling)([z_mean, z_log_var])` z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var]) # we instantiate these layers separately so as to reuse them later decoder_hid = Dense(intermediate_dim, activation='relu') decoder_upsample = Dense(filters * 12 * 12, activation='relu') if K.image_data_format() == 'channels_first': output_shape = (batch_size, filters, 12, 12) else: output_shape = (batch_size, 12, 12, filters) decoder_reshape = Reshape(output_shape[1:]) decoder_deconv_1 = Conv2DTranspose(filters, kernel_size=num_conv, padding='same', strides=1, activation='relu') decoder_deconv_2 = Conv2DTranspose(filters, kernel_size=num_conv, padding='same', strides=1, activation='relu') if K.image_data_format() == 'channels_first': output_shape = (batch_size, filters, 25, 25) else: output_shape = (batch_size, 25, 25, filters) decoder_deconv_3_upsamp = Conv2DTranspose(filters, kernel_size=(3, 3), strides=(2, 2), padding='valid', activation='relu') decoder_mean_squash = Conv2D(gen_chns, kernel_size=2, padding='valid', activation='sigmoid') hid_decoded = decoder_hid(z) up_decoded = decoder_upsample(hid_decoded) reshape_decoded = decoder_reshape(up_decoded) deconv_1_decoded = decoder_deconv_1(reshape_decoded) deconv_2_decoded = decoder_deconv_2(deconv_1_decoded) x_decoded_relu = decoder_deconv_3_upsamp(deconv_2_decoded) x_decoded_mean_squash = decoder_mean_squash(x_decoded_relu) # Custom loss layer class CustomVariationalLayer(Layer): def __init__(self, **kwargs): self.is_placeholder = True super(CustomVariationalLayer, self).__init__(**kwargs) def vae_loss(self, x, x_decoded_mean_squash): x = K.flatten(x) x_decoded_mean_squash = K.flatten(x_decoded_mean_squash) xent_loss = gen_rows * gen_cols * metrics.binary_crossentropy(x, x_decoded_mean_squash) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) return K.mean(xent_loss + kl_loss) def call(self, inputs): x = inputs[0] x_decoded_mean_squash = inputs[1] loss = self.vae_loss(x, x_decoded_mean_squash) self.add_loss(loss, inputs=inputs) # We don't use this output. return x y = CustomVariationalLayer()([x, x_decoded_mean_squash]) vae = Model(x, y) vae.compile(optimizer='adam', loss=None) vae.summary() ###Output Using TensorFlow backend. ###Markdown 训练神经网络 ###Code vae.fit(x_train, shuffle=True, epochs=200, batch_size=128, validation_data=None) ###Output _____no_output_____ ###Markdown 提取解码器部分作为生成器 ###Code # build a model to project inputs on the latent space encoder = Model(x, z_mean) # build a digit generator that can sample from the learned distribution decoder_input = Input(shape=(latent_dim,)) _hid_decoded = decoder_hid(decoder_input) _up_decoded = decoder_upsample(_hid_decoded) _reshape_decoded = decoder_reshape(_up_decoded) _deconv_1_decoded = decoder_deconv_1(_reshape_decoded) _deconv_2_decoded = decoder_deconv_2(_deconv_1_decoded) _x_decoded_relu = decoder_deconv_3_upsamp(_deconv_2_decoded) _x_decoded_mean_squash = decoder_mean_squash(_x_decoded_relu) generator = Model(decoder_input, _x_decoded_mean_squash) ###Output _____no_output_____ ###Markdown 生成数据 ###Code generate_result = generator.predict(np.random.normal(size=(200000,5))) ###Output _____no_output_____ ###Markdown Teaching a Variational Autoencoder (VAE) to draw MNIST charactersAutoencoders are a type of neural network that can be used to learn efficient codings of input data. Given some inputs, the network firstly applies a series of transformations that map the input data into a lower dimensional space. This part of the network is called the _encoder_. Then, the network uses the encoded data to try and recreate the inputs. This part of the network is the _decoder_. Using the encoder, we can later compress data of the type that is understood by the network. However, autoencoders are rarely used for this purpose, as usually there exist hand-crafted algorithms (like _jpg_-compression) that are more efficient. Instead, autoencoders have repeatedly been applied to perform denoising tasks. Then, the encoder receives pictures that have been tampered with noise, and it learns how to reconstruct the original images. Variational Autoencoders put simplyBut there exists a much more interesting application for autoencoders. This application is called the _variational autoencoder_. Using variational autoencoders, it's not only possible to compress data -- it's also possible to generate new objects of the type the autoencoder has seen before.Using a general autoencoder, we don't know anything about the coding that's been generated by our network. We could take a look at and compare different encoded objects, but it's unlikely that we'll be able to understand what's going on. This means that we won't be able to use our decoder for creating new objects -- we simply don't know what the inputs should look like.Using a variational autoencoder, we take the opposite approach instead. We will not try to make guesses concerning the distribution that's being followed by the latent vectors. We simply tell our network what we want this distribution to look like. Usually, we will constrain the network to produce latent vectors having entries that follow the unit normal distribution. Then, when trying to generate data, we can simply sample some values from this distribution, feed them to the decoder, and the decoder will return us completely new objects that appear just like the objects our network has been trained with.Let's see how this can be done using python and tensorflow. We are going to teach our network how to draw MNIST characters. First steps -- Loading the training dataFirstly, we perform some basic imports. Tensorflow has a quite handy function that allows us to easily access the MNIST data set. ###Code import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') ###Output Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz ###Markdown Defining our input and output dataMNIST images have a dimension of 28 * 28 pixels with one color channel. Our inputs _X_in_ will be batches of MNIST characters, while our network will learn to reconstruct them and output them in a placeholder _Y_, which thus has the same dimensions. _Y_flat_ will be used later, when computing losses. _keep_prob_ will be used when applying dropouts as a means of regularization. During training, it will have a value of 0.8. When generating new data, we won't apply dropout, so the value will be 1. The function _lrelu_ is being defined as tensorflow unfortunately doesn't come up with a predefined leaky ReLU. ###Code tf.reset_default_graph() batch_size = 64 X_in = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28], name='X') Y = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28], name='Y') Y_flat = tf.reshape(Y, shape=[-1, 28 * 28]) keep_prob = tf.placeholder(dtype=tf.float32, shape=(), name='keep_prob') dec_in_channels = 1 n_latent = 8 reshaped_dim = [-1, 7, 7, dec_in_channels] inputs_decoder = 49 * dec_in_channels / 2 def lrelu(x, alpha=0.3): return tf.maximum(x, tf.multiply(x, alpha)) ###Output _____no_output_____ ###Markdown Defining the encoderAs our inputs are images, it's most reasonable to apply some convolutional transformations to them. What's most noteworthy is the fact that we are creating two vectors in our encoder, as the encoder is supposed to create objects following a Gaussian Distribution:* A vector of means* A vector of standard deviationsYou will see later how we "force" the encoder to make sure it really creates values following a Normal Distribution. The returned values that will be fed to the decoder are the _z_-values. We will need the mean and standard deviation of our distributions later, when computing losses. ###Code def encoder(X_in, keep_prob): activation = lrelu with tf.variable_scope("encoder", reuse=None): X = tf.reshape(X_in, shape=[-1, 28, 28, 1]) x = tf.layers.conv2d(X, filters=64, kernel_size=4, strides=2, padding='same', activation=activation) x = tf.nn.dropout(x, keep_prob) x = tf.layers.conv2d(x, filters=64, kernel_size=4, strides=2, padding='same', activation=activation) x = tf.nn.dropout(x, keep_prob) x = tf.layers.conv2d(x, filters=64, kernel_size=4, strides=1, padding='same', activation=activation) x = tf.nn.dropout(x, keep_prob) x = tf.contrib.layers.flatten(x) mn = tf.layers.dense(x, units=n_latent) sd = 0.5 * tf.layers.dense(x, units=n_latent) epsilon = tf.random_normal(tf.stack([tf.shape(x)[0], n_latent])) z = mn + tf.multiply(epsilon, tf.exp(sd)) return z, mn, sd ###Output _____no_output_____ ###Markdown Defining the decoderThe decoder does not care about whether the input values are sampled from some specific distribution that has been defined by us. It simply will try to reconstruct the input images. To this end, we use a series of transpose convolutions. ###Code def decoder(sampled_z, keep_prob): with tf.variable_scope("decoder", reuse=None): x = tf.layers.dense(sampled_z, units=inputs_decoder, activation=lrelu) x = tf.layers.dense(x, units=inputs_decoder * 2 + 1, activation=lrelu) x = tf.reshape(x, reshaped_dim) x = tf.layers.conv2d_transpose(x, filters=64, kernel_size=4, strides=2, padding='same', activation=tf.nn.relu) x = tf.nn.dropout(x, keep_prob) x = tf.layers.conv2d_transpose(x, filters=64, kernel_size=4, strides=1, padding='same', activation=tf.nn.relu) x = tf.nn.dropout(x, keep_prob) x = tf.layers.conv2d_transpose(x, filters=64, kernel_size=4, strides=1, padding='same', activation=tf.nn.relu) x = tf.contrib.layers.flatten(x) x = tf.layers.dense(x, units=28*28, activation=tf.nn.sigmoid) img = tf.reshape(x, shape=[-1, 28, 28]) return img ###Output _____no_output_____ ###Markdown Now, we'll wire together both parts: ###Code sampled, mn, sd = encoder(X_in, keep_prob) dec = decoder(sampled, keep_prob) ###Output _____no_output_____ ###Markdown Computing losses and enforcing a Gaussian latent distributionFor computing the image reconstruction loss, we simply use squared difference (which could lead to images sometimes looking a bit fuzzy). This loss is combined with the _Kullback-Leibler divergence_, which makes sure our latent values will be sampled from a normal distribution. For more on this topic, please take a look a Jaan Altosaar's great article on VAEs. ###Code unreshaped = tf.reshape(dec, [-1, 28*28]) img_loss = tf.reduce_sum(tf.squared_difference(unreshaped, Y_flat), 1) latent_loss = -0.5 * tf.reduce_sum(1.0 + 2.0 * sd - tf.square(mn) - tf.exp(2.0 * sd), 1) loss = tf.reduce_mean(img_loss + latent_loss) optimizer = tf.train.AdamOptimizer(0.0005).minimize(loss) sess = tf.Session() sess.run(tf.global_variables_initializer()) ###Output _____no_output_____ ###Markdown Training the networkNow, we can finally train our VAE! Every 200 steps, we'll take a look at what the current reconstructions look like. After having processed about 2000 batches, most reconstructions will look reasonable. ###Code for i in range(30000): batch = [np.reshape(b, [28, 28]) for b in mnist.train.next_batch(batch_size=batch_size)[0]] sess.run(optimizer, feed_dict = {X_in: batch, Y: batch, keep_prob: 0.8}) if not i % 200: ls, d, i_ls, d_ls, mu, sigm = sess.run([loss, dec, img_loss, latent_loss, mn, sd], feed_dict = {X_in: batch, Y: batch, keep_prob: 1.0}) plt.imshow(np.reshape(batch[0], [28, 28]), cmap='gray') plt.show() plt.imshow(d[0], cmap='gray') plt.show() print(i, ls, np.mean(i_ls), np.mean(d_ls)) ###Output _____no_output_____ ###Markdown Generating new dataThe most awesome part is that we are now able to create new characters. To this end, we simply sample values from a unit normal distribution and feed them to our decoder. Most of the created characters look just like they've been written by humans. ###Code randoms = [np.random.normal(0, 1, n_latent) for _ in range(10)] imgs = sess.run(dec, feed_dict = {sampled: randoms, keep_prob: 1.0}) imgs = [np.reshape(imgs[i], [28, 28]) for i in range(len(imgs))] for img in imgs: plt.figure(figsize=(1,1)) plt.axis('off') plt.imshow(img, cmap='gray') ###Output _____no_output_____ ###Markdown Variational AutoencoderImplementation based on the following papers:- [Auto Encoding Varational Bayes](https://arxiv.org/abs/1312.6114)- [Variational Autoencoder for Deep Learning of Images, Labels and Captions](https://papers.nips.cc/paper/6528-variational-autoencoder-for-deep-learning-of-images-labels-and-captions.pdf) 1. Import dependenciesImport the modules neccessary to run the project. If you get a ``` Error: Module not found```run the following code in a separate cell ``` !pip install -r requirements.txt ``` ###Code import torch from torch import nn, optim import torch.nn.functional as F from torch.utils.data import DataLoader import torchvision from torchvision import datasets, transforms import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import itertools ###Output _____no_output_____ ###Markdown Check if a CUDA GPU is available, and if yes use it. Else use the CPU for computations. ###Code device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("Using %s for computation" % device) project_dir = 'results/' dataset_dir = project_dir + 'datasets/' images_dir = project_dir + 'images/' model_dir = project_dir + 'model/' ###Output _____no_output_____ ###Markdown 2. Tune HyperparametersSet up the hyperparameters for the model. If you get any errors about running out of memeory, try reducing the batch size. The latent size is the size of the encoding vector that the Encoder finally produces. Increasing this value can improve performance, but there are diminishing returns once you cross a certain limit. ###Code batch_size = 32 # number of inputs in each batch epochs = 10 # times to run the model on complete data image_size = 64 hidden_size = 1024 # hidden dimension latent_size = 32 # latent vector dimension lr = 1e-3 # learning rate train_loss = [] # If you want to use the Vanilla VAE, uncomment the following block # image_size = 28 # input_size = image_size ** 2 # size of each input # hidden_size = 300 # hidden dimension # latent_size = 45 # latent vector dimension ###Output _____no_output_____ ###Markdown 3. Load Data and DataLoader ###Code from torchvision import transforms as tmf from torch.utils.data import Dataset, DataLoader import os from PIL import Image as IMG class CelebDataset(Dataset): def __init__(self, **kw): self.images_dir = kw.get('images_dir') self.images = os.listdir(self.images_dir) self.images = self.images[:kw.get('lim', len(self.images))] self.image_size = kw.get('image_size', 64) def __getitem__(self, index): file = self.images[index] img = self.transforms(IMG.open(self.images_dir + os.sep + file)) return {'input': img} def __len__(self): return len(self.images) @property def transforms(self): return tmf.Compose( [tmf.Resize(self.image_size), tmf.CenterCrop(self.image_size), tmf.ToTensor(), tmf.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) train_celebdataset = CelebDataset(images_dir='/data/akhanal1/img_align_celeba', lim=100) trainloader = DataLoader(dataset=train_celebdataset, batch_size=4, pin_memory=True, num_workers=8) test_celebdataset = CelebDataset(images_dir='/data/akhanal1/img_align_celeba', lim=300) testloader = DataLoader(dataset=test_celebdataset, batch_size=4, pin_memory=True, num_workers=8) ###Output _____no_output_____ ###Markdown Utility function to help * Display images from the tensor.* Flatten the image into a 1-D tensor.* Take a 1-D tensor and convert it back into a image. ###Code def show_images(images): images = torchvision.utils.make_grid(images) show_image(images) def show_image(img): plt.imshow(img.permute(1, 2, 0), cmap="gray") plt.show() ###Output _____no_output_____ ###Markdown Next we will have a look at the data we will be working with. ###Code trial = next(iter(trainloader.__iter__())) images, labels = trial['input'],1 print(labels) show_images(images) trial.keys() ###Output _____no_output_____ ###Markdown 4. Define the Model ArchitectureThe VAE consists of an encoder that takes the images outputs 2 vectors of length `latent_size`. Traditionally, one is the vector of `means`, μ, and another is the vector of `standard deviations`, σ.In this case however, to prevent the model from learning negative values of variance, we instead create a vector containing the `log(variance)`.This gives us a collection of random variables ***X***, from which we sample to provide inputs to the Fully Connected layer using the `sample` function. The next part is the decoder which tries to reconstruct the image from the vector. The Adam optimiser is used here. ###Code class VAE(nn.Module): def __init__(self): super(VAE, self).__init__() self.encodinglayer1 = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU() ) self.encodinglayer2_mean = nn.Sequential(nn.Linear(hidden_size, latent_size)) self.encodinglayer2_logvar = nn.Sequential(nn.Linear(hidden_size, latent_size)) self.decodinglayer = nn.Sequential( nn.Linear(latent_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, input_size), nn.Sigmoid(), ) def sample(self, log_var, mean): std = torch.exp(0.5 * log_var) eps = torch.randn_like(std) return eps.mul(std).add_(mean) def forward(self, x): x = x.view(-1, input_size) x = self.encodinglayer1(x) log_var = self.encodinglayer2_logvar(x) mean = self.encodinglayer2_mean(x) z = self.sample(log_var, mean) x = self.decodinglayer(z) return x, mean, log_var class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class UnFlatten(nn.Module): def forward(self, input, size=1024): return input.view(input.size(0), 1024, 1, 1) class DCVAE(nn.Module): def __init__(self, image_channels=3, image_dim=image_size, hidden_size=hidden_size, latent_size=latent_size): super(DCVAE, self).__init__() self.encoder = nn.Sequential( nn.Conv2d(image_channels, 32, 4, 2), nn.LeakyReLU(0.2), nn.Conv2d(32, 64, 4, 2), nn.LeakyReLU(0.2), nn.Conv2d(64, 128, 4, 2), nn.LeakyReLU(0.2), nn.Conv2d(128, 256, 4, 2), nn.LeakyReLU(0.2), Flatten(), ) self.encoder_mean = nn.Linear(hidden_size, latent_size) self.encoder_logvar = nn.Linear(hidden_size, latent_size) self.fc = nn.Linear(latent_size, hidden_size) self.decoder = nn.Sequential( UnFlatten(), nn.ConvTranspose2d(hidden_size, 128, 5, 2), nn.ReLU(), nn.ConvTranspose2d(128, 64, 5, 2), nn.ReLU(), nn.ConvTranspose2d(64, 32, 6, 2), nn.ReLU(), nn.ConvTranspose2d(32, image_channels, 6, 2), nn.Sigmoid() ) def sample(self, log_var, mean): std = torch.exp(0.5*log_var) eps = torch.randn_like(std) return eps.mul(std).add_(mean) def forward(self, x): x = self.encoder(x) log_var = self.encoder_logvar(x) mean = self.encoder_mean(x) z = self.sample(log_var, mean) x = self.fc(z) x = self.decoder(x) return x, mean, log_var vae = DCVAE().to('cuda') # vae = VAE().to(device) optimizer = optim.Adam(vae.parameters(), lr=lr) ###Output _____no_output_____ ###Markdown Load pretrained weightsComment this out if you want to train from scratch. ###Code vae.load_state_dict(torch.load(model_dir+"DCVAE.pt")) # vae.load_state_dict(torch.load(model_dir+"VAE.pt")) ###Output _____no_output_____ ###Markdown 5. Training the modelSet the model to the training mode first. Things to note, two types of loss are used here. The first one is just the reconstruction loss that compares the recontructed images to the original one using Binary Cross Entropy. The second one is called the [Kullback–Leibler divergence](https://www.countbayesie.com/blog/2017/5/9/kullback-leibler-divergence-explained) which gives a measure of how much a distibution diverges from another. We use this to force the encodings to distribute themselves around the centre of the latent space. ###Code vae.train() for epoch in range(100): for i, (images) in enumerate(trainloader): images = images['input'].to(device) optimizer.zero_grad() reconstructed_image, mean, log_var = vae(images) CE = F.binary_cross_entropy(reconstructed_image, images, reduction='sum') # for VAE # CE = F.binary_cross_entropy( # reconstructed_image, images.view(-1, input_size), reduction="sum" # ) KLD = -0.5 * torch.sum(1 + log_var - mean.pow(2) - log_var.exp()) loss = CE + KLD loss.backward() train_loss.append(loss.item()) optimizer.step() if(i % 100 == 0): print("Loss:") print(loss.item() / len(images)) plt.plot(train_loss) plt.show() ###Output _____no_output_____ ###Markdown 6. Evaluate performance on the test setSet the model to the evaluation mode. This is important otherwise you will get inconsistent results.We save the mean vectors and the labels in a separate list to visualise them later.As we can see, the model has learnt to reconstruct the images pretty well. We can improve performance by training for longer or by increasing the latent vector size to encode more information. ###Code vae.eval() vectors = [] with torch.no_grad(): for i, (images) in enumerate(testloader): images = images['input'].to(device) reconstructed_image, mean, log_var = vae(images) reconstructed_image = reconstructed_image.view(-1, 1, image_size, image_size) labels=[1,1,1,1] temp = list(zip(labels, mean.tolist())) for x in temp: vectors.append(x) if(i%100 == 0): show_images(reconstructed_image.cpu()) img_name = images_dir + "evaluation/DCVAE/" + str(i).zfill(3) # img_name = images_dir + "evaluation/VAE/" + str(i).zfill(3) #plt.savefig(img_name) plt.show() ###Output _____no_output_____ ###Markdown 7. Generate images from latent vectorsHere I have taken three vectors and I'll interpolate between them to show how the continuos latent space in a VAE allows you to smoothly tranistion between different types of images.This code is for the DCVAE. ###Code vae.eval() start = np.array([-1.8611, 0.3629, -0.1625, 0.6801, 1.2033, 1.0312, 0.5436, 1.3066, 0.2905, 0.1377, 0.5122, -0.1663, 2.3431, -0.0896, -0.5873, -1.4804, 0.8141, -1.2197, 0.0484, 0.6414, -0.8172, -0.9543, -0.8818, -1.1465, 0.2720, 1.1792, 1.8410, -0.4715, 1.4380, 0.5139, 1.2099, -0.5012]) middle = np.array([-0.4763, -0.4644, -0.3850, 0.6598, 0.9110, 0.4451, 0.4617, -0.0526, 0.2808, 0.6080, 0.5532, -1.5506, -0.5199, 0.1359, 0.0373, 0.4284, -0.4134, -1.7078, -0.0309, -1.0195, -0.3151, -0.5569, 0.2832, -0.9132, -1.1339, -1.3196, 2.1297, 0.8122, 0.6849, -0.6710, -0.3507, -0.9001]) end = np.array([-1.6239, 0.2496, -1.0690, -0.8745, 0.4133, 2.2452, -0.2385, -0.6532, 0.3818, -0.9425, 0.9404, 1.3901, -0.3327, -0.3719, -0.0365, 0.3240, 0.4928, -0.4988, -1.2228, -0.1638, 0.6093, -0.5264, -1.6963, -0.3718, 2.1971, 0.2166, -0.0821, -0.1722, -0.1896, -1.6610, -0.1497, 1.0655]) points = 50 linfit = interpolate.interp1d([1, points/2, points], np.vstack([start, middle, end]), axis=0) with torch.no_grad(): for i in range(2, points-1): z = linfit(i) z = torch.FloatTensor(z) print(z.shape) z = z.reshape((-1, 32)) z = z.to(device) z = vae.fc(z) generated_images = vae.decoder(z) generated_images = generated_images.view(-1, 64, 64) img = generated_images[0].cpu() plt.imshow(img) img_name = images_dir + 'interpolate/' + str(i).zfill(3) plt.savefig(img_name) plt.show() ###Output _____no_output_____ ###Markdown 8. Visualise the latent representations of the imagesUsing Singular Value Decomposition, we perform Principal Component Analysis to visualise the two largest eigenvalues. Then we add the labels for each element and create a dataframe. ###Code labels, z_vectors = list(zip(*vectors)) z_vectors = torch.tensor(z_vectors) U, S, V = torch.svd(torch.t(z_vectors)) C = torch.mm(z_vectors, U[:, :2]).tolist() C = [x + [labels[i]] for i, x in enumerate(C)] df = pd.DataFrame(C, columns=['x', 'y', 'label']) df.head() sns.lmplot( x="x", y="y", data=df, fit_reg=False, hue='label') ###Output _____no_output_____ ###Markdown 9. Saving the modelSave the model incase we need to load it again. ###Code torch.save(vae.state_dict(), model_dir+"DCVAE.pt") # Use this for saving the VAE model # torch.save(vae.state_dict(), model_dir + "VAE.pt") ###Output _____no_output_____ ###Markdown VAE ###Code input_img = Input(shape=(n, n, 1)) x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) encoded = MaxPooling2D((2, 2), padding='same')(x) # at this point the representation is (4, 4, 8) i.e. 128-dimensional x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation='relu')(x) x = UpSampling2D((2, 2))(x) decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x) model = Model(input_img, decoded) model.compile(optimizer='adadelta', loss='binary_crossentropy', metrics=['accuracy']) model.summary() model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1000, batch_size=10, workers = 4) z_mean def sampling(args): """Reparameterization trick by sampling from an isotropic unit Gaussian. # Arguments args (tensor): mean and log of variance of Q(z|X) # Returns z (tensor): sampled latent vector """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_mean)[1] # by default, random_normal has mean = 0 and std = 1.0 epsilon = K.random_normal(shape=(batch, dim)) return z_mean + K.exp(0.5 * z_log_var) * epsilon np.reshape(X_train, [-1, n*n]).shape X_train = X_train.reshape((-1, n*n)) y_train = y_train.reshape((-1, n*n)) X_test = X_test.reshape((-1, n*n)) y_test = y_test.reshape((-1, n*n)) image_size = n original_dim = n * n # network parameters input_shape = (original_dim, ) intermediate_dim = 512 batch_size = 128 latent_dim = 2 epochs = 50 # VAE model = encoder + decoder # build encoder model inputs = Input(shape=input_shape, name='encoder_input') x = Dense(intermediate_dim, activation='relu')(inputs) z_mean = Dense(latent_dim, name='z_mean')(x) z_log_var = Dense(latent_dim, name='z_log_var')(x) # use reparameterization trick to push the sampling out as input # note that "output_shape" isn't necessary with the TensorFlow backend z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var]) # instantiate encoder model encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder') encoder.summary() plot_model(encoder, to_file='vae_mlp_encoder.png', show_shapes=True) # build decoder model latent_inputs = Input(shape=(latent_dim,), name='z_sampling') x = Dense(intermediate_dim, activation='relu')(latent_inputs) outputs = Dense(original_dim, activation='sigmoid')(x) # instantiate decoder model decoder = Model(latent_inputs, outputs, name='decoder') decoder.summary() plot_model(decoder, to_file='vae_mlp_decoder.png', show_shapes=True) # instantiate VAE model outputs = decoder(encoder(inputs)[2]) vae = Model(inputs, outputs, name='vae_mlp') models = (encoder, decoder) data = (X_test, y_test) reconstruction_loss = keras.losses.binary_crossentropy(inputs, outputs) reconstruction_loss *= original_dim kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var) kl_loss = K.sum(kl_loss, axis=-1) kl_loss *= -0.5 vae_loss = K.mean(reconstruction_loss + kl_loss) vae.add_loss(vae_loss) vae.compile(optimizer='adam', metrics = ['accuracy']) vae.summary() plot_model(vae, to_file='vae_mlp.png', show_shapes=True) vae.fit(X_train, epochs=epochs, batch_size=batch_size, validation_data=(X_test, None)) def plot_results(models, data, batch_size=128, model_name="vae_mnist"): """Plots labels and MNIST digits as a function of the 2D latent vector # Arguments models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ encoder, decoder = models X_test, y_test = data os.makedirs(model_name, exist_ok=True) filename = os.path.join(model_name, "vae_mean.png") # display a 2D plot of the digit classes in the latent space z_mean, _, _ = encoder.predict(X_test, batch_size=batch_size) plt.figure(figsize=(12, 10)) plt.scatter(z_mean[:, 0], z_mean[:, 1], )#c=y_test) plt.colorbar() plt.xlabel("z[0]") plt.ylabel("z[1]") plt.savefig(filename) plt.show() filename = os.path.join(model_name, "partitions_over_latent.png") # display a 30x30 2D manifold of digits n = 10 digit_size = 28 figure = np.zeros((digit_size * n, digit_size * n)) # linearly spaced coordinates corresponding to the 2D plot # of digit classes in the latent space grid_x = np.linspace(-4, 4, n) grid_y = np.linspace(-4, 4, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = decoder.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digit plt.figure(figsize=(n * 10, n * 10)) start_range = digit_size // 2 end_range = (n - 1) * digit_size + start_range + 1 pixel_range = np.arange(start_range, end_range, digit_size) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.imshow(figure, cmap='Greys_r') plt.savefig(filename) plt.show() plot_results(models, data, batch_size=batch_size, model_name="vae_mlp") ###Output _____no_output_____ ###Markdown Variational Autoencoder ###Code # Setup on Colab !pip install gradio &> /dev/null !pip install pytorch_lightning &> /dev/null !curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash !sudo apt-get install git-lfs !git lfs install !if [ ! -e ki_wir ]; then git clone https://github.com/fhswf/ki-wir.git ki_wir; else cd ki_wir; git pull; fi !cd ki_wir; git lfs fetch !cd ki_wir; git lfs checkout import gradio as gr import torch import numpy as np import ki_wir.models.vanilla_vae as vanilla_vae import ki_wir.models.logcosh_vae as logcosh_vae import ki_wir.models.dfcvae as dfc_vae import ki_wir.models.experiment as experiment from PIL import Image from torchvision import transforms import torchvision.utils as vutils %env CUDA_VISIBLE_DEVICES=1 device = torch.device("cuda:0") params={"in_channels": 3, "latent_dim": 128, "img_size": 64} config = { "DFC": [ dfc_vae.DFCVAE, "ki_wir/pretrained/dfc.ckpt" ], \ "LogCosh": [ logcosh_vae.LogCoshVAE, "ki_wir/pretrained/logcosh.ckpt" ], \ "Vanilla": [ vanilla_vae.VanillaVAE, "ki_wir/pretrained/vanilla.ckpt" ] } models = {} for m, c in config.items(): model = c[0](**params) exp = experiment.VAEXperiment(model, params) exp.load_from_checkpoint(c[1], vae_model=model, params=params).to(device) models[m] = exp models def reconstruct(name, image1, image2, alpha): SetRange = transforms.Lambda(lambda X: 2 * X - 1.) img1 = Image.fromarray(image1) img2 = Image.fromarray(image2) img1 = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), ])(img1) img2 = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), ])(img2) img = alpha*img2 + (1-alpha)*img1 orig = transforms.ToPILImage(mode='RGB')(img) img = SetRange(img) #img = torch.moveaxis(img, 0, -1) img = torch.unsqueeze(img.cuda(), 0) dec = models[name].model.generate(img, latent_dim=128) dec = torch.squeeze(dec[0], 0) dec = transforms.Lambda(lambda X: 0.5 * (X + 1.))(dec) return transforms.ToPILImage(mode='RGB')(dec) test_label = "" for name in models.keys(): exp = models[name] exp.curr_device = device samples = exp.model.sample(144, device) vutils.save_image(samples.cpu().data, f"sample_{name}.png", normalize=True, nrow=12) model = gr.inputs.Dropdown(list(models.keys()), type="value", default=None, label="Model") alpha = gr.inputs.Slider(minimum=0, maximum=1.0, step=0.1, default=0, label=None) out1 = gr.outputs.Image(type="auto", label="original") out2 = gr.outputs.Image(type="auto", label="reconstructed") iface = gr.Interface(fn=reconstruct, layout="vertical", inputs=[model, "image", "image", alpha], outputs=out1).launch(debug=True, share=True) ###Output This share link will expire in 72 hours. To get longer links, send an email to: [email protected]
Feature Engineering/Feature Scaling/Feature Scaling.ipynb
###Markdown Author : Sanjoy Biswas Topic : Feature Scaling : Min-Max Scaler | Standardization Email : [email protected] Feature ScalingFeature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data pre-processing to handle highly varying magnitudes or values or units. If feature scaling is not done, then a machine learning algorithm tends to weigh greater values, higher and consider smaller values as the lower values, regardless of the unit of the values.Example: If an algorithm is not using feature scaling method then it can consider the value 3000 meter to be greater than 5 km but that’s actually not true and in this case, the algorithm will give wrong predictions. So, we use Feature Scaling to bring all values to same magnitudes and thus, tackle this issue. Example of Algorithm where Feature Scaling Matters :1. K-Means 2. K-Nearest Neighbors3. Principle Component Analysis4. Gradient DesentMainly Distance Base algorithms are affected by Feature ScalingNote: Naive Bayes, Linear Discriminant Analysis,Tree based algorithm are not affected by feature scaling Techniques to perform Feature ScalingConsider the two most important ones:Min-Max Normalization: This technique re-scales a feature or observation value with distribution value between 0 and 1.![min-max-normalisation.jpg](attachment:min-max-normalisation.jpg)Standardization: It is a very effective technique which re-scales a feature value so that it has distribution with 0 mean value and variance equals to 1.![standardisation.jpg](attachment:standardisation.jpg) The Big Question – Normalize or Standardize?Normalization vs. standardization is an eternal question among machine learning newcomers. Let me elaborate on the answer in this section.Normalization is good to use when you know that the distribution of your data does not follow a Gaussian distribution. This can be useful in algorithms that do not assume any distribution of the data like K-Nearest Neighbors and Neural Networks.Standardization, on the other hand, can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Also, unlike normalization, standardization does not have a bounding range. So, even if you have outliers in your data, they will not be affected by standardization. Import Libraries ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Import Dataset ###Code data_set = pd.read_csv(r'F:\Feature Engineering\Feature Scaling\feature_scaling.csv') data_set x = data_set.iloc[:,1:3] x ###Output _____no_output_____ ###Markdown MIN MAX SCALER ###Code from sklearn.preprocessing import MinMaxScaler mns = MinMaxScaler(feature_range = (0,1)) x_after_min_max_scaler = mns.fit_transform(x) x_after_min_max_scaler ###Output _____no_output_____ ###Markdown Standardisation ###Code from sklearn.preprocessing import StandardScaler Standardisation = StandardScaler() x_after_standardisation = Standardisation.fit_transform(x) x_after_standardisation ###Output _____no_output_____ ###Markdown Loading the dataset ###Code import pandas as pd import numpy as np bigmart = pd.read_csv('train_bm.csv') data = bigmart[['Item_Visibility', 'Item_MRP']] data.head() ###Output _____no_output_____ ###Markdown Min Max Scaler ###Code from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_data = scaler.fit_transform(data) scaled_data = pd.DataFrame(scaled_data, columns=['Item_Visibility', 'Item_MRP']) scaled_data.head() scaled_data.describe() ###Output _____no_output_____ ###Markdown Standard Scaler ###Code from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaled_data = scaler.fit_transform(data) scaled_data = pd.DataFrame(scaled_data, columns=['Item_Visibility', 'Item_MRP']) scaled_data.head() scaled_data.describe() ###Output _____no_output_____
Jupyter Notebooks/Bode_plot_example.ipynb
###Markdown Bode Plots (Example 8.3)For the first order system in the example:$$G(i\omega)=\frac{1}{i\omega\tau+1}$$Plot the Bode magnitude and phase angle plots ###Code import numpy as np import control import matplotlib.pyplot as plt # plotting library # Assign arbitrary value for tau tau = 1 num=[1] den=[tau, 1] sys = control.tf(num,den) _ = control.bode_plot(sys, dB=False, omega=None, plot=True, omega_limits=None, omega_num=None) # The underscore means we don't care about assigning the output of `control.bode_plot` to a variable ###Output _____no_output_____ ###Markdown Let's look at some time responses to see what's really going on.According to the bode plots, at really low forcing frequencies, the amplitude of the system response will be almost equal to the amplitude of the sinusoidal input, but there will be a small lag indicated by the phase angle. ###Code time = np.arange(0,60,0.1) freq = 0.1 sin_input = np.sin(freq*time) T, output = control.forced_response(sys, T=time, U=sin_input, X0=0.0, transpose=False, interpolate=False, return_x=None, squeeze=None) ############################################################# fig = plt.figure(figsize=(6,4)) ax = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax.get_ymajorticklabels(),fontsize=18) plt.setp(ax.get_xmajorticklabels(),fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Turn on the plot grid and set appropriate linestyle and color ax.grid(True,linestyle=':', color='0.75') ax.set_axisbelow(True) # Define the X and Y axis labels plt.xlabel('Time (s)', fontsize=22, weight='bold', labelpad=5) plt.ylabel('Displacement', fontsize=22, weight='bold', labelpad=10) plt.plot(T, output, linewidth=2, linestyle='-', label=r'Response') plt.plot(time, sin_input, linewidth=2, linestyle='--', label=r'Input') # uncomment below and set limits if needed # plt.xlim(0,5) plt.ylim(-1.1,1.75) # Create the legend, then fix the fontsize leg = plt.legend(loc='upper right', ncol = 1, fancybox=True, ) ltext = leg.get_texts() plt.setp(ltext,fontsize=16) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) # save the figure as a high-res pdf in the current folder # plt.savefig('plot_filename.pdf') ###Output _____no_output_____ ###Markdown As the input frequency increases, the response amplitude will start to be less than the input amplitude and the phase lag increases. ###Code time = np.arange(0,10,0.01) freq = 1 sin_input = np.sin(freq*time) T, output = control.forced_response(sys, T=time, U=sin_input, X0=0.0, transpose=False, interpolate=False, return_x=None, squeeze=None) ############################################################# fig = plt.figure(figsize=(6,4)) ax = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax.get_ymajorticklabels(),fontsize=18) plt.setp(ax.get_xmajorticklabels(),fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Turn on the plot grid and set appropriate linestyle and color ax.grid(True,linestyle=':', color='0.75') ax.set_axisbelow(True) # Define the X and Y axis labels plt.xlabel('Time (s)', fontsize=22, weight='bold', labelpad=5) plt.ylabel('Displacement', fontsize=22, weight='bold', labelpad=10) plt.plot(T, output, linewidth=2, linestyle='-', label=r'Response') plt.plot(time, sin_input, linewidth=2, linestyle='--', label=r'Input') # uncomment below and set limits if needed # plt.xlim(0,5) plt.ylim(-1.1,1.75) # Create the legend, then fix the fontsize leg = plt.legend(loc='upper right', ncol = 1, fancybox=True, ) ltext = leg.get_texts() plt.setp(ltext,fontsize=16) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) # save the figure as a high-res pdf in the current folder # plt.savefig('plot_filename.pdf') time = np.arange(0,5,0.01) freq = 10 sin_input = np.sin(freq*time) T, output = control.forced_response(sys, T=time, U=sin_input, X0=0.0, transpose=False, interpolate=False, return_x=None, squeeze=None) ############################################################# fig = plt.figure(figsize=(6,4)) ax = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax.get_ymajorticklabels(),fontsize=18) plt.setp(ax.get_xmajorticklabels(),fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Turn on the plot grid and set appropriate linestyle and color ax.grid(True,linestyle=':', color='0.75') ax.set_axisbelow(True) # Define the X and Y axis labels plt.xlabel('Time (s)', fontsize=22, weight='bold', labelpad=5) plt.ylabel('Displacement', fontsize=22, weight='bold', labelpad=10) plt.plot(T, output, linewidth=2, linestyle='-', label=r'Response') plt.plot(time, sin_input, linewidth=2, linestyle='--', label=r'Input') # uncomment below and set limits if needed # plt.xlim(0,5) plt.ylim(-1.1,1.75) # Create the legend, then fix the fontsize leg = plt.legend(loc='upper right', ncol = 1, fancybox=True, ) ltext = leg.get_texts() plt.setp(ltext,fontsize=16) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) # save the figure as a high-res pdf in the current folder # plt.savefig('plot_filename.pdf') ###Output _____no_output_____ ###Markdown For very high input frequencies, the system's response amplitude starts to become insignificant compared to the amplitude of the sinusoidal input. Bode plot of Second-order systemsSecond-order system transfer function:$$G(s)=\frac{\omega_n^2}{s^2 + 2\zeta\omega_n s + \omega_n^2}$$ ###Code # Assign arbitrary value for wn wn = 10 # natural frequency # make bode plots for several values of zeta zeta1 = 0 # damping ratio num2nd=[wn**2] den2nd=[1, 2*zeta1*wn, wn**2] sys2nd = control.tf(num2nd,den2nd) mag1, phase1, omega1 = control.bode_plot(sys2nd, dB=True, omega=None, plot=False, omega_limits=None, omega_num=None) zeta2 = 0.1 # damping ratio num2nd=[wn**2] den2nd=[1, 2*zeta2*wn, wn**2] sys2nd = control.tf(num2nd,den2nd) mag2, phase2, omega2 = control.bode_plot(sys2nd, dB=True, omega=None, plot=False, omega_limits=None, omega_num=None) zeta3 = 0.5 # damping ratio num2nd=[wn**2] den2nd=[1, 2*zeta3*wn, wn**2] sys2nd = control.tf(num2nd,den2nd) mag3, phase3, omega3 = control.bode_plot(sys2nd, dB=True, omega=None, plot=False, omega_limits=None, omega_num=None) zeta4 = 1 # damping ratio num2nd=[wn**2] den2nd=[1, 2*zeta4*wn, wn**2] sys2nd = control.tf(num2nd,den2nd) mag4, phase4, omega4 = control.bode_plot(sys2nd, dB=True, omega=None, plot=False, omega_limits=None, omega_num=None) ############################################################# fig = plt.figure(figsize=(6,4)) ax = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax.get_ymajorticklabels(),fontsize=18) plt.setp(ax.get_xmajorticklabels(),fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Turn on the plot grid and set appropriate linestyle and color ax.grid(True,linestyle=':', color='0.75') ax.set_axisbelow(True) # Define the X and Y axis labels plt.xlabel('Frequency (rad/s)', fontsize=22, weight='bold', labelpad=5) plt.ylabel('Magnitude', fontsize=22, weight='bold', labelpad=10) plt.plot(omega1, mag1, linewidth=2, linestyle='-', label=r'$\zeta=0$') plt.plot(omega2, mag2, linewidth=2, linestyle='--', label=r'$\zeta=0.1$') plt.plot(omega3, mag3, linewidth=2, linestyle='-.', label=r'$\zeta=0.5$') plt.plot(omega4, mag4, linewidth=2, linestyle=':', label=r'$\zeta=1$') ax.set_yscale('log') ax.set_xscale('log') # plt.plot(time, sin_input, linewidth=2, linestyle='--', label=r'Input') # uncomment below and set limits if needed # plt.xlim(0,5) # plt.ylim(-1.1,1.75) # Create the legend, then fix the fontsize leg = plt.legend(loc='upper right', ncol = 1, fancybox=True, ) ltext = leg.get_texts() plt.setp(ltext,fontsize=16) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) # save the figure as a high-res pdf in the current folder # plt.savefig('plot_filename.pdf') ###Output _____no_output_____ ###Markdown The peak response amplitude occurs when the input frequency is near the natural frequency of the system (in this case 10 rad/s). For $\zeta=0$, the response magnitude at the natural frequency equal to input frequency is infinite (it doesn't look infinite here because of the sampling rate used to generate the plot). As damping ratio increases, the peak magnitude reduces and moves to a ***slightly*** lower frequency. This is known as the damped frequency, $\omega_d=\omega_n \sqrt{1-\zeta^2}$. ###Code ############################################################# fig = plt.figure(figsize=(6,4)) ax = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax.get_ymajorticklabels(),fontsize=18) plt.setp(ax.get_xmajorticklabels(),fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Turn on the plot grid and set appropriate linestyle and color ax.grid(True,linestyle=':', color='0.75') ax.set_axisbelow(True) # Define the X and Y axis labels plt.xlabel('Frequency (rad/s)', fontsize=22, weight='bold', labelpad=5) plt.ylabel('Phase (deg)', fontsize=22, weight='bold', labelpad=10) plt.plot(omega1, phase1*180/np.pi, linewidth=2, linestyle='-', label=r'$\zeta=0$') plt.plot(omega2, phase2*180/np.pi, linewidth=2, linestyle='--', label=r'$\zeta=0.1$') plt.plot(omega3, phase3*180/np.pi, linewidth=2, linestyle='-.', label=r'$\zeta=0.5$') plt.plot(omega4, phase4*180/np.pi, linewidth=2, linestyle=':', label=r'$\zeta=1$') # ax.set_yscale('log') ax.set_xscale('log') ax.set_yticks(np.arange(-180,1,30)) # plt.plot(time, sin_input, linewidth=2, linestyle='--', label=r'Input') # uncomment below and set limits if needed # plt.xlim(0,5) # plt.ylim(-1.1,1.75) # Create the legend, then fix the fontsize leg = plt.legend(loc='upper right', ncol = 1, fancybox=True, ) ltext = leg.get_texts() plt.setp(ltext,fontsize=16) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) # save the figure as a high-res pdf in the current folder # plt.savefig('plot_filename.pdf') ###Output _____no_output_____ ###Markdown For undamped second-order systems, the phase angle or lag in the system's vibration is zero until the input frequency reaches the natural frequency. There is then a sudden shift from being completely in-phase to being directly out of phase at 180 degrees. The transition is more gradual for $0<\zeta\leq 1$. No matter the value of the damping ratio, the phase angle plot always passes through 90 degrees at the natural frequency for second-order systems. Transient response from frequency responseAlthough the Bode plots show magnitude and phase of the steady-state response to a sinusoidal input, we can use it to get some information about the system's transient behavior. Looking back at the magnitude of the second-order frequency response, the peak of the response occurs at the resonant frequency $\omega_r$ and has a maximum value of the magnitude $M_{p\omega}$. The resonant frequency is found by taking the derivative of the magnitude with respect to $\omega$ and setting it equal to zero:$$\omega_r=\omega_n\sqrt{1-2\zeta^2} \quad \zeta<0.707$$The peak magnitude at this resonant frequency is:$$M_{p\omega}=|G(i\omega_r)|=\left(2\zeta\sqrt{1-\zeta^2}\right)^{-1} \quad \zeta<0.707$$The relationship between damping ratio, resonant frequency, and resonant magnitude are shown below. ###Code zeta_range = np.arange(0.01,0.707,0.01) wr_normalized = np.sqrt(1-2*zeta_range**2) Mpw = (2*zeta_range*np.sqrt(1-zeta_range**2))**-1 # Mpw=20*np.log10(Mpw) fig = plt.figure(figsize=(6,4)) ax1 = plt.gca() plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) # Change the axis units font plt.setp(ax1.get_ymajorticklabels(),fontsize=18) plt.setp(ax1.get_xmajorticklabels(),fontsize=18) # Remove the top and right border, they are not needed ax1.spines['right'].set_color('k') ax1.spines['top'].set_color('none') # Define the positions of the axes tick marks ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') # Manually set the x-axis limits, if necessary plt.xlim(0.0,0.7) # Turn on the plot grid and set appropriate linestyle and color ax1.grid(True, linestyle=':', color='0.75') ax1.set_axisbelow(True) # Define the X and Y1 axis labels ax1.set_xlabel(r'$\zeta$', fontsize=22, weight='bold', labelpad=5) ax1.set_ylabel(r'Magnitude', fontsize=22, weight='bold', labelpad=10) # Plots gain used on input to tracking of Surge ax1.plot(zeta_range, Mpw, linewidth=2, linestyle='-', label=r'$M_{p\omega}$',) # Manually set the y1-axes limits, if necessary ax1.set_ylim(0, 4.85) # Set up the 2nd Y-axis, using the same x-axis as the first ax2 = ax1.twinx() # Remove the top border, it's not needed ax2.spines['top'].set_color('none') # Turn on the plot grid and set appropriate linestyle and color ax2.grid(True, linestyle=':', color='0.75') ax2.set_axisbelow(True) # Change the y2 axis units font plt.setp(ax2.get_ymajorticklabels(), fontsize=18) # Define the Y2 axis labels ax2.set_ylabel(r'$\omega_r/\omega_n$', fontsize=22, weight='bold', labelpad=10) ax2.plot(zeta_range, wr_normalized, linewidth=2, linestyle='--', color = '#377eb8', label=r'$\omega_r/\omega_n$') # Manually set the y2-axes limits, if necessary # ax2.set_ylim(0, 8) # Create the legend, then fix the fontsize # ask matplotlib for the plotted objects and their labels lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() leg = ax2.legend(lines1 + lines2, labels1 + labels2, loc='upper right', ncol = 1, fancybox=True) ltext = leg.get_texts() plt.setp(ltext,fontsize=18) # Adjust the page layout filling the page using the new tight_layout command plt.tight_layout(pad=0.5) ###Output _____no_output_____
notebooks/exercises/4 - Functions and exceptions.ipynb
###Markdown Functions and exceptions FunctionsWrite a function that converts from Celsius to Kelvin.To convert from Celsius to Kelvin you add 273.15 from the value.Try your solution for a few values. ###Code def celsius_to_kelvin(c): # implementation here pass celsius_to_kelvin(0) ###Output _____no_output_____ ###Markdown Now write another function to convert from Fahrenheit to Celsius.The formula for doing so is C = 5/9*(F-32)Again, verify that your function does what is expected. ###Code def fahrenheit_to_celsius(f): pass fahrenheit_to_celsius(0) ###Output _____no_output_____ ###Markdown Now make a function to convert from Fahrenheit to Kelvin.Before you start coding, stop to think for a second. You can actually re-use the two other functions you have made. Fahrenheit to Kelvin can be represented as Fahrenheit to Celsius followed by Celsius to Kelvin. ###Code def fahrenheit_to_kelvin(f): pass fahrenheit_to_kelvin(0) ###Output _____no_output_____ ###Markdown Finally, implement a more general conversion function that takes as arguments also the input and output scales, e.g. **from_scale** and **to_scale**. Provide default values for **from_scale** and **to_scale**, and call the function with different number of arguments. Try to call the function using both positional and keyword arguments. Which approach is more readable for you? ExceptionsOk, here's some code that fails. Find out at least 2 errors it raises by giving different inputs.Then construct a ``try-except`` clause around the lines of code. ###Code var = float(input("give a number: ")) divided = 1/var ###Output _____no_output_____ ###Markdown The `open` function is used to open files for reading or writing. We'll get to that but first let's try to open a file that doesn't exist.Filesystem related errors are very common. A file might not exist or for some reason the user might not have the rights to open the file. Go ahead and make a try-except clause to catch this error. ###Code file_handle = open("i_dont_exist", "r") ###Output _____no_output_____ ###Markdown Compound Implement the three remaining functions so you can convert freely between Fahrenheit and Kelvin.Now look at the temperature_converter function. Try to figure out what errors malformed user input can cause. You can either wrap the function call in a ``try-except`` or you can wrap parts of the function.If you have time you can increase the complexity of the function to cover centigrade conversions as well but this is not required. Hint: if you always convert the value to centigrade if it is not and to the desired output if desired output is not you can simplify the code. ###Code def celsius_to_fahrenheit(c): pass def kelvin_to_celsius(k): pass def kelvin_to_fahrenheit(k): pass def temperature_converter(): from_scale = input("Give scale to convert from: ") to_scale = input("Give scale to convert to: ") value = float(input("Give temperature: ")) if from_scale == "K" and to_scale == "F": return kelvin_to_fahrenheit(value) elif from_scale == "F" and to_scale == "K": return fahrenheit_to_kelvin elif from_scale == "C" or to_scale == "C": raise NotImplementedError("Conversion to Celsius not implemented!") return temperature_converter() ###Output _____no_output_____
content/_build/jupyter_execute/notebooks/Appendix-NLLS-Python.ipynb
###Markdown Model fitting in Python Introduction Python offers a wide range of tools for fitting mathematical models to data. Here we will look at using Python to fit non-linear models to data using Least Squares (NLLS). You may want to have a look at [this Chapter](./20-ModelFitting.ipynb), and in particular, it NLLS section, and the lectures on [Model fitting](https://github.com/mhasoba/TheMulQuaBio/tree/master/content/lectures/ModelFitting) and [NLLS](https://github.com/mhasoba/TheMulQuaBio/blob/master/content/lectures/NLLS) before proceeding. WE will use the `Lmfit` package, which provides a high-level interface to non-linear optimization and curve fitting problems for Python.There are three main things that one needs in order to perform NLLS fitting succesfully in Python.1. Data2. Model specification3. Initial values for parameters in the modelThe image below summarizes how NLLS fitting works with these 3 entities.![image](./graphics/lmfit_workflow.jpg) We will use population growth rates as an example, as we did the [model fitting chapter](Model-Fitting-R-Population-Growth) (where we used R).First let's import the necessary packages (you may need to install `lmfit` first). ###Code from lmfit import Minimizer, Parameters, report_fit import numpy as np import matplotlib.pylab as plt ###Output _____no_output_____ ###Markdown Now, create some artificial data: ###Code t = np.arange(0, 24, 2) N = np.array([32500, 33000, 38000, 105000, 445000, 1430000, 3020000, 4720000, 5670000, 5870000, 5930000, 5940000]) np.random.seed(1234) #Set random seed for reproducibility N_rand = N*(1 + np.random.normal(scale = 0.1, size = len(N))) #Add some error to data ###Output _____no_output_____ ###Markdown Here's what the data look like: ###Code plt.plot(t, N_rand, 'r+', markersize = 15, markeredgewidth = 2, label = 'Data') plt.xlabel('t', fontsize = 20) plt.ylabel(r'$N$', fontsize = 20) plt.ticklabel_format(style='scientific', scilimits=[0,3]) plt.yscale('log') ###Output _____no_output_____ ###Markdown Fitting a Linear model to the data Lets start with the simplest case; a linear model. \begin{equation*}\label{eq:linear_model} N_t = at^3 + bt^2 + ct + d\end{equation*} where $a$, $b$, $c$ and $d$, are phenomenological parameters. Using NLLS ###Code #Create object for storing parameters params_linear = Parameters() #Add parameters and initial values to it params_linear.add('a', value = 1) params_linear.add('b', value = 1) params_linear.add('c', value = 1) params_linear.add('d', value = 1) #Write down the objective function that we want to minimize, i.e., the residuals def residuals_linear(params, t, data): """Calculate cubic growth and subtract data""" #Get an ordered dictionary of parameter values v = params.valuesdict() #Cubic model model = v['a']*t**3 + v['b']*t**2 + v['c']*t + v['d'] return model - data #Return residuals #Create a Minimizer object minner = Minimizer(residuals_linear, params_linear, fcn_args=(t, np.log(N_rand))) #Perform the minimization fit_linear_NLLS = minner.minimize() ###Output _____no_output_____ ###Markdown The variable `fit_linear` belongs to a class called [`MinimizerResult`](https://lmfit.github.io/lmfit-py/fitting.htmllmfit.minimizer.MinimizerResult), which include data such as status and error messages, fit statistics, and the updated (i.e., best-fit) parameters themselves in the params attribute. Now get the summary of the fit: ###Code report_fit(fit_linear_NLLS) ###Output [[Fit Statistics]] # fitting method = leastsq # function evals = 10 # data points = 12 # variables = 4 chi-square = 1.68617886 reduced chi-square = 0.21077236 Akaike info crit = -15.5493005 Bayesian info crit = -13.6096739 [[Variables]] a: -0.00147820 +/- 5.3322e-04 (36.07%) (init = 1) b: 0.03687009 +/- 0.01787451 (48.48%) (init = 1) c: 0.14339899 +/- 0.16467922 (114.84%) (init = 1) d: 10.0545124 +/- 0.39977042 (3.98%) (init = 1) [[Correlations]] (unreported correlations are < 0.100) C(a, b) = -0.984 C(b, c) = -0.960 C(a, c) = 0.900 C(c, d) = -0.779 C(b, d) = 0.621 C(a, d) = -0.528 ###Markdown Using OLS`lmfit`'s purpose is not to fit linear models, although it is general enough to do so. Recall that a 3rd degree polynomial is a Lienar model, and it can be fitted using *Ordinary Least Squares*. You can easily do this with the function `polyfit`. Let's try this for the same data. ###Code fit_linear_OLS = np.polyfit(t, np.log(N_rand), 3) # degree = 3 as this is a cubic ###Output _____no_output_____ ###Markdown Now check the fitted coefficients: ###Code print(fit_linear_OLS) ###Output [-1.47819938e-03 3.68700893e-02 1.43398989e-01 1.00545124e+01] ###Markdown Comparing the NLLS and OLS fitsLet's compare the the coefficients obtained using NLLS (using `lmfit`) vs using OLS (with `polyfit`) above. First have a another look at the NLLS result: ###Code fit_linear_NLLS.params ###Output _____no_output_____ ###Markdown Now extract the just the estimated parameter values obtained with `lmfit` (it takes some effort as these are saved in a Python dictionary within the fitted model object): ###Code par_dict = fit_linear_NLLS.params.valuesdict().values() #Transform these into an array par = np.array(list(par_dict)) #Check the difefrences in the the parameter values obtained with lmfit and polyfit print(fit_linear_OLS - par) ###Output [ 2.18245647e-12 2.18892265e-12 7.72548692e-13 -1.61293201e-11] ###Markdown There are differences because NLLS is not an exact method. But these differences are *tiny*, showing that NLLS converges on pretty much the same solution as the (exact) OLS method.Next, you can calculate the residuals of the fit: Calculating the residuals, etc. Once you have done the model fitting you can calculate the residuals: ###Code #Construct the fitted polynomial equation my_poly = np.poly1d(fit_linear_OLS) #Compute predicted values ypred = my_poly(t) #Calculate residuals residuals = ypred - np.log(N_rand) ###Output _____no_output_____ ###Markdown The residuals can be then used to calculate BIC, AIC, etc, as you [learned previously](Model-Fitting-R-Comparing-Models). Exercise* We calculated the residuals above using the OLS fit of the cubic model to the data. Calculate the residuals for the NLLS fit of the same model to the data (i.e., using the `fit_linear_NLLS` object). * *Hint*: To do this, you will need to first extract the coefficients, and then use the `residuals_linear` function that we created above. Fitting Non-linear models to the dataNow let's use `lmfit` to do what it was actually designed for: fitting non-linear mathematical models to data. We will fit the same two models that we fitted in the [Model Fitting Chapter](Model-Fitting-R-Population-Growth) (where we used R). Logistic model fit A classical, somewhat mechanistic model is the logistic growth equation:\begin{equation*} N_t = \frac{N_0 N_{max} e^{r t}}{N_{max} + N_0 (e^{r t} - 1)}\end{equation*}Here $N_t$ is population size at time $t$, $N_0$ is initial population size, $r$ is maximum growth rate (AKA $r_{max}$), and $N_{max}$ is carrying capacity (commonly denoted by $K$ in the ecological literature). ###Code #Create object for parameter storing params_logistic = Parameters() params_logistic.add('N_0', value = N_rand[0]) params_logistic.add('N_max', value = N_rand[-1]) #Recall the value for growth rate obtained from a linear fit params_logistic.add('r', value = 0.62) #Write down the objective function that we want to minimize, i.e., the residuals def residuals_logistic(params, t, data): '''Model a logistic growth and subtract data''' #Get an ordered dictionary of parameter values v = params.valuesdict() #Logistic model model = np.log(v['N_0'] * v['N_max'] * np.exp(v['r']*t) / \ (v['N_max'] + v['N_0'] * ( np.exp(v['r']*t) - 1 ))) #Return residuals return model - data #Create a Minimizer object minner = Minimizer(residuals_logistic, params_logistic, fcn_args=(t, np.log(N_rand)))#Plug in the logged data. #Perform the minimization fit_logistic = minner.minimize(method = 'leastsq') ###Output _____no_output_____ ###Markdown Note that I am choosing the least squares as the optimization method. A table with alternative fitting algorithms offered by lmfit can be found [here](https://lmfit.github.io/lmfit-py/fitting.htmlchoosing-different-fitting-methods). ###Code #Get summary of the fit report_fit(fit_logistic) ###Output [[Fit Statistics]] # fitting method = leastsq # function evals = 34 # data points = 12 # variables = 3 chi-square = 2.19693074 reduced chi-square = 0.24410342 Akaike info crit = -14.3741446 Bayesian info crit = -12.9194246 [[Variables]] N_0: 13998.5739 +/- 4769.60185 (34.07%) (init = 34032.16) N_max: 7108406.32 +/- 2165947.53 (30.47%) (init = 6529216) r: 0.44848151 +/- 0.05161938 (11.51%) (init = 0.62) [[Correlations]] (unreported correlations are < 0.100) C(N_0, r) = -0.807 C(N_max, r) = -0.448 C(N_0, N_max) = 0.239 ###Markdown Where function evals, is the number of iterations needed to reach the minimum. The `report_fit` function also offers estimations of goodness of fit such as $\chi^2$, BIC and AIC. These are calculated as specified [here](https://lmfit.github.io/lmfit-py/fitting.htmlakaike-and-bayesian-information-criteria). Finally, uncertainties of each parameter estimate, correlation levels between them are also calculated. Details and caveats about these values can be found [here](https://lmfit.github.io/lmfit-py/fitting.htmluncertainties-in-variable-parameters-and-their-correlations). Gompertz model Another alternative is the Gompertz model, which has been used frequently in the literature to model bacterial growth\begin{equation*}\label{eq:Gompertzlog} \log(N_t) = N_0 + (N_{max} - N_0) e^{-e^{r_{max} \exp(1) \frac{t_{lag} - t}{(N_{max} - N_0) \log(10)} + 1}}\end{equation*}Here maximum growth rate ($r_{max}$) is the tangent to the inflection point, $t_{lag}$ is the x-axis intercept to this tangent (duration of the delay before the population starts growing exponentially) and $\log\left(\frac{N_{max}}{N_0}\right)$ is the asymptote of the log-transformed population growth trajectory, i.e., the log ratio of maximum population density $N_{max}$ (aka “carrying capacity”) and initial cell (Population) $N_0$ density. ###Code #Create object for parameter storing params_gompertz = Parameters() # add with tuples: (NAME VALUE VARY MIN MAX EXPR BRUTE_STEP) params_gompertz.add_many(('N_0', np.log(N_rand)[0] , True, 0, None, None, None), ('N_max', np.log(N_rand)[-1], True, 0, None, None, None), ('r_max', 0.62, True, None, None, None, None), ('t_lag', 5, True, 0, None, None, None))#I see it in the graph #Write down the objective function that we want to minimize, i.e., the residuals def residuals_gompertz(params, t, data): '''Model a logistic growth and subtract data''' #Get an ordered dictionary of parameter values v = params.valuesdict() #Logistic model model = v['N_0'] + (v['N_max'] - v['N_0']) * \ np.exp(-np.exp(v['r_max'] * np.exp(1) * (v['t_lag'] - t) / \ ((v['N_max'] - v['N_0']) * np.log(10)) + 1)) #Return residuals return model - data #Create a Minimizer object minner = Minimizer(residuals_gompertz, params_gompertz, fcn_args=(t, np.log(N_rand))) #Perform the minimization fit_gompertz = minner.minimize() #Sumarize results report_fit(fit_gompertz) ###Output [[Fit Statistics]] # fitting method = leastsq # function evals = 37 # data points = 12 # variables = 4 chi-square = 0.11350314 reduced chi-square = 0.01418789 Akaike info crit = -47.9299775 Bayesian info crit = -45.9903509 [[Variables]] N_0: 10.3910132 +/- 0.07901002 (0.76%) (init = 10.43506) N_max: 15.6520240 +/- 0.06730933 (0.43%) (init = 15.6918) r_max: 1.74097660 +/- 0.09837840 (5.65%) (init = 0.62) t_lag: 4.52049075 +/- 0.24729695 (5.47%) (init = 5) [[Correlations]] (unreported correlations are < 0.100) C(r_max, t_lag) = 0.757 C(N_0, t_lag) = 0.581 C(N_max, r_max) = -0.465 C(N_max, t_lag) = -0.318 C(N_0, N_max) = -0.132 C(N_0, r_max) = 0.115 ###Markdown Plot the results ###Code plt.rcParams['figure.figsize'] = [20, 15] #Linear result_linear = np.log(N_rand) + fit_linear_NLLS.residual # These points lay on top of the theoretical fitted curve plt.plot(t, result_linear, 'y.', markersize = 15, label = 'Linear') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec))#Create a vector of ones. residual_smooth_linear = residuals_linear(fit_linear_NLLS.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_linear + log_N_vec, 'orange', linestyle = '--', linewidth = 1) #Logistic result_logistic = np.log(N_rand) + fit_logistic.residual plt.plot(t, result_logistic, 'b.', markersize = 15, label = 'Logistic') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_logistic = residuals_logistic(fit_logistic.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_logistic + log_N_vec, 'blue', linestyle = '--', linewidth = 1) #Gompertz result_gompertz = np.log(N_rand) + fit_gompertz.residual plt.plot(t, result_gompertz, 'g.', markersize = 15, label = 'Gompertz') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_gompertz = residuals_gompertz(fit_gompertz.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_gompertz + log_N_vec, 'green', linestyle = '--', linewidth = 1) #Plot data points plt.plot(t, np.log(N_rand), 'r+', markersize = 15,markeredgewidth = 2, label = 'Data') #Plot legend plt.legend(fontsize = 20) plt.xlabel('t', fontsize = 20) plt.ylabel(r'$\log(N_t)$', fontsize = 20) plt.ticklabel_format(style='scientific', scilimits=[0,3]) ###Output _____no_output_____ ###Markdown ExerciseThe generalized Logistic model (also known as Richards' curve) is an extension of the logistic or sigmoid functions, allowing for more flexible S-shaped curves:\begin{equation*}\label{eq:Hill} \log(N_t) = A + \frac{K - A}{1 + Q(e^{-Bt})^{1/\mu}}\end{equation*}Where $A$ is the lower asymptote, $K$ is the higher asymptote. If $A=0$ then $K$ is the carrying capacity. $B$ is the growth rate, $\mu >0$ affects near which asymptote maximum growth occurs. $Q$ is related to the value $N(0)$Fit this model to the data using as initial values for the parameters: $A = 10$, $K = 16$, $Q = 0.5$, $B = 1$, $\mu = 0.1$, $T = 7.5$ ###Code #Define the parameter object params_genlogistic = Parameters() #Add parameters and initial values params_genlogistic.add('A', value = 10, min = 0) params_genlogistic.add('K', value = 16, min = 0) params_genlogistic.add('Q', value = 0.5, min = 0) params_genlogistic.add('B', value = 1, min = 0) params_genlogistic.add('mu', value = 0.1, min = 0) params_genlogistic.add('T', value = 7.5, min = 0) #Define the model def residuals_genlogistic(params, t, data): '''Model a logistic growth and subtract data''' #Get an ordered dictionary of parameter values v = params.valuesdict() #Logistic model model = v['A'] + (v['K'] - v['A']) / \ (1 + v['Q'] * np.exp(-v['B']*(t-v['T'])))**(1/v['mu']) #Return residuals return model - data #Perform the fit #Create a Minimizer object minner = Minimizer(residuals_genlogistic, params_genlogistic, fcn_args=(t, np.log(N_rand))) #Perform the minimization fit_genlogistic = minner.minimize() #Overlay the fit with the others plt.rcParams['figure.figsize'] = [20, 15] #Linear result_linear = np.log(N_rand) + fit_linear_NLLS.residual plt.plot(t, result_linear, 'y.', markersize = 15, label = 'Linear') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_linear = residuals_linear(fit_linear_NLLS.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_linear + log_N_vec, 'orange', linestyle = '--', linewidth = 1) #Logistic result_logistic = np.log(N_rand) + fit_logistic.residual plt.plot(t, result_logistic, 'b.', markersize = 15, label = 'Logistic') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_logistic = residuals_logistic(fit_logistic.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_logistic + log_N_vec, 'blue', linestyle = '--', linewidth = 1) #Gompertz result_gompertz = np.log(N_rand) + fit_gompertz.residual plt.plot(t, result_gompertz, 'g.', markersize = 15, label = 'Gompertz') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_gompertz = residuals_gompertz(fit_gompertz.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_gompertz + log_N_vec, 'green', linestyle = '--', linewidth = 1) #Generalized logistic result_genlogistic = np.log(N_rand) + fit_genlogistic.residual plt.plot(t, result_genlogistic, '.', markerfacecolor = 'magenta', markeredgecolor = 'magenta', markersize = 15, label = 'Generalized Logistic') #Get a smooth curve by plugging a time vector to the fitted logistic model t_vec = np.linspace(0,24,1000) log_N_vec = np.ones(len(t_vec)) residual_smooth_genlogistic = residuals_genlogistic(fit_genlogistic.params, t_vec, log_N_vec) plt.plot(t_vec, residual_smooth_genlogistic + log_N_vec, 'magenta', linestyle = '--', linewidth = 1) #Plot data points plt.plot(t, np.log(N_rand), 'r+', markersize = 15,markeredgewidth = 2, label = 'Data') #Plot legend plt.legend(fontsize = 20) plt.xlabel('t', fontsize = 20) plt.ylabel(r'$\log(N_t)$', fontsize = 20) plt.ticklabel_format(style='scientific', scilimits=[0,3]) ###Output _____no_output_____
Archive/sandbox.ipynb
###Markdown Read it in ###Code import pandas as pd import numpy as np df = pd.read_csv('StrongSignal_Continuous.tsv.gz',sep='\t',index_col=0) ###Output _____no_output_____ ###Markdown Get subset as numpy arrays ###Code X = df.iloc[:,:-1].values.astype(np.float32) X_columns = df.iloc[:,:-1].columns y = df.iloc[:,-1:].values.astype(np.int32).ravel() y_columns = df.iloc[:,-1:].columns print y ###Output [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3] ###Markdown X and y get change in a function, then we write them ###Code X = X[0:4] y = y[0:4] X_final = pd.DataFrame(data=X,columns=X_columns) y_final = pd.DataFrame(data=y,columns=y_columns) print X_final X_final.to_csv('output_X.tsv',sep='\t') y_final.to_csv('output_y.tsv',sep='\t') cp ../Dropbox/ML-Flex-Lite/Validation/StrongSignal_Continuous.tsv.gz StrongSignal_Continuous.tsv.gz import pandas as pd import numpy as np import sys #DataFilePath = sys.argv[1] #Prefix = sys.argv[2] #OutFilePath = sys.argv[3] #add checks to make sure command line data is valid df = pd.read_csv('StrongSignal_Continuous.tsv.gz', sep = '\t', index_col = 0) #change to DataFilePath X = df.iloc[:,:-1].values.astype(np.float32) X_columns = df.iloc[:,-1:].columns y = df.iloc[:,-1:].values.astype(np.int32).ravel() y_columns = df.iloc[:,-1:].columns from imblearn.under_sampling import NearMiss #from imblearn.under_sampling import ClusterCentroids #from imblearn.over_sampling import RandomOverSampler #from imblearn.over_sampling import ADYSN sampler = NearMiss(version=2) #sampler = ClusterCentroids() #sampler = RandomOverSampler() #sampler ADYSN() X_resampled, y_resampled = sampler.fit_sample(X, y) X_columns = df.iloc[:,:].columns a = np.array(X_resampled) b = np.array(y_resampled) np.column_stack((a,b)) X_y_Final = np.column_stack((a,b)) X_y_Final = pd.DataFrame(data=X_y_Final,columns=X_columns) np.savetxt("output_X.tsv", X_y_Final, delimiter ='\t') print X_y_Final print X_y_Final ###Output _____no_output_____
jupyter/Chapter02/apparent_range.ipynb
###Markdown ***Introduction to Radar Using Python and MATLAB*** Andy Harrison - Copyright (C) 2019 Artech House Apparent Range*** Since a wave transmitted through the atmosphere experiences a refractive index that is a function of altitude, the path length from the transmitter to the target exceeds the geometrical path length, as shown in Figure 2.9. This difference in range is described by the integral$$\Delta R = \int \limits_{A}^{B} (n - 1) \, dl,$$where $l$ is the length along the path, and $(A, B)$ is the starting and ending points of the path. This expression is used when the variation of the constitutive parameters along the integration path are known. A semiempirical method was developed in order to calculate the apparent range when the temperature, atmospheric pressure, and relative humidity are known at ground level. This method was derived in 1979 using atmospheric radio profiles at 500 meteorological stations over the course of one year. The expression for the difference in range for this method is$$\Delta R = \frac{\Delta R_V}{\sin \theta \sqrt{(1 + k \cot^2\theta)}} + \delta(\theta, \Delta R_V),$$*** Begin by getting the library path ###Code import lib_path ###Output _____no_output_____ ###Markdown Set the radar and target location (latitude (deg), longitude (deg), altitude (m)) ###Code from numpy import array radar_lla = array([34.0, 84.0, 120.0]) target_lla = array([34.0, 80.0, 12000.0]) ###Output _____no_output_____ ###Markdown Set up the keyword args ###Code kwargs = {'radar_lla': radar_lla, 'target_lla': target_lla} ###Output _____no_output_____ ###Markdown Calculate the true and apparent ranges using the `apparent_range` routine ###Code from Libs.wave_propagation import refraction true_range, apparent_range = refraction.apparent_range(**kwargs) ###Output _____no_output_____ ###Markdown Display the true and apparent ranges ###Code print('{:.4f}'.format(true_range/1.e3)) print('{:.4f}'.format(apparent_range/1.e3)) ###Output 370.0054 370.0776
notebooks/5.0_comparing_magnifications/3.1_20x_dw.export_matching.field_thr.ipynb
###Markdown Read shift data ###Code shifts = pd.read_csv(f"shift_correction/{selected_magnification}_{selected_image_type}.shifts.csv") shifts.index = shifts["sid"].values shifts.drop("sid", 1, inplace=True) ###Output _____no_output_____ ###Markdown Matching 20x_raw and reference dots ###Code dots_data = pd.read_csv("/mnt/data/Imaging/202105-Deconwolf/data_210726/dots_data.clean.tsv.gz", sep="\t") dots_data = dots_data[selected_magnification == dots_data["magnification"]] dots_data = dots_data[selected_image_type == dots_data["image_type"]] thresholds_table = pd.read_csv("../../data/magnifications_matching/intensity_thresholds.by_field.tsv", sep="\t") matched_dots = pd.read_csv( os.path.join("../../data/magnifications_matching", f"{selected_magnification}_{selected_image_type}.matched_dots.field_thr.tsv" ), sep="\t") reference = pd.read_csv("../../data/60x_reference/ref__dw.field_thr.tsv", sep="\t") all_20x_dots: List[pd.DataFrame] = [] selected_20x_dots: List[pd.DataFrame] = [] for current_field_id in tqdm(np.unique(dots_data["sid"])): thresholds = thresholds_table.loc[current_field_id == thresholds_table["sid"], :] intensity_thr = thresholds.loc[selected_image_type == thresholds["image_type"], "thr"].values[0] dot_max_z_proj = tifffile.imread(os.path.join(dot_image_folder_path, f"a647_{current_field_id:03d}.tif")).max(0) ref_max_z_proj = tifffile.imread(os.path.join(ref_image_folder_path, f"a647_{current_field_id:03d}.tif")).max(0) dot_labels = tifffile.imread(os.path.join(dot_mask_folder_path, f"a647_{current_field_id:03d}.dilated_labels.from_60x.tiff") ).reshape(dot_max_z_proj.shape) ref_labels = tifffile.imread(os.path.join(ref_mask_folder_path, f"a647_{current_field_id:03d}.dilated_labels.tiff") ).reshape(ref_max_z_proj.shape) dots = dots_data.loc[current_field_id == dots_data["sid"], :].copy( ).sort_values("Value2", ascending=False).reset_index(drop=True) dot_coords = dots.loc[intensity_thr <= dots["Value2"], ("x", "y")].copy().reset_index(drop=True) dot_coords2 = dot_coords.copy() / aspect dot_coords2["x"] += (shifts.loc[current_field_id, "x"] * 9) dot_coords2["y"] += (shifts.loc[current_field_id, "y"] * 9) ref_coords = reference.loc[reference["sid"] == current_field_id, ("x", "y")].copy().reset_index(drop=True) matched_20x_dots = matched_dots.loc[matched_dots["series"] == current_field_id, "id_20x"].values matched_60x_dots = matched_dots.loc[matched_dots["series"] == current_field_id, "id_60x"].values max_match_dist = matched_dots.loc[matched_dots["series"] == current_field_id, "eudist"].max() all_20x_dots.append(dots.loc[intensity_thr <= dots["Value2"], :]) selected_20x_dots.append(dots.loc[matched_20x_dots, :]) pd.concat(all_20x_dots).reset_index( drop=True).to_csv(os.path.join("../../data/magnifications_matching", f"{selected_magnification}_{selected_image_type}.field_thr.all.tsv"), sep="\t", index=False) pd.concat(selected_20x_dots).reset_index( drop=True).to_csv(os.path.join("../../data/magnifications_matching", f"{selected_magnification}_{selected_image_type}.field_thr.selected.tsv"), sep="\t", index=False) ###Output _____no_output_____
{{ cookiecutter.repo_name }}/notebooks/scratch_pad.ipynb
###Markdown {{cookiecutter.project_name}}{{cookiecutter.description}} Data Sources- file1 : Link to SF Report- file2: Link to SF Report (As Needed)- file3: Link to SF Report (As Needed) Changes- {% now 'utc', '%m-%d-%Y' %} : Started project ###Code # ALWAYS RUN # General Setup %load_ext dotenv %dotenv %load_ext nb_black from salesforce_reporting import Connection, ReportParser import pandas as pd from pathlib import Path from datetime import datetime import helpers import os import numpy as np from reportforce import Reportforce SF_PASS = os.environ.get("SF_PASS") SF_TOKEN = os.environ.get("SF_TOKEN") SF_USERNAME = os.environ.get("SF_USERNAME") sf = Reportforce(username=SF_USERNAME, password=SF_PASS, security_token=SF_TOKEN) ###Output _____no_output_____ ###Markdown File Locations ###Code # ALWAYS RUN today = datetime.today() in_file1 = Path.cwd() / "data" / "raw" / "sf_output_file1.csv" summary_file = Path.cwd() / "data" / "processed" / "processed_data.pkl" in_file2 = Path.cwd() / "data" / "raw" / "sf_output_file2.csv" summary_file2 = Path.cwd() / "data" / "processed" / "processed_data_file2.pkl" in_file3 = Path.cwd() / "data" / "raw" / "sf_output_file3.csv" summary_file3 = Path.cwd() / "data" / "processed" / "processed_data_file3.pkl" in_file4 = Path.cwd() / "data" / "raw" / "sf_output_file4.csv" summary_file4 = Path.cwd() / "data" / "processed" / "processed_data_file4.pkl" ###Output _____no_output_____ ###Markdown Load Report From Salesforce ###Code # Run if downloading report from salesforce # File 1 report_id_file1 = "SF_REPORT_ID" file_1_id_column = '18 Digit ID' # adjust as needed sf_df = sf.get_report(report_id_file1, id_column=file_1_id_column) # File 2 (As needed) # report_id_file2 = "SF_REPORT_ID" # file_2_id_column = '18 Digit ID' # adjust as needed # sf_df_file2 = sf.get_report(report_id_file2, id_column=file_2_id_column) # File 3 (As needed) # report_id_file3 = "SF_REPORT_ID" # file_3_id_column = '18 Digit ID' # adjust as needed # sf_df_file3 = sf.get_report(report_id_file3, id_column=file_3_id_column) ###Output _____no_output_____ ###Markdown Save report as CSV ###Code # Only run if ran above cell # File 1 sf_df.to_csv(in_file1, index=False) # File 2 and 3 (As needed) # sf_df_file2.to_csv(in_file2, index=False) # sf_df_file3.to_csv(in_file3, index=False) ###Output _____no_output_____ ###Markdown Load DF from saved CSV* Start here if CSV already exist ###Code # ALWAYS RUN # Data Frame for File 1 - if using more than one file, rename df to df_file1 df = pd.read_csv(in_file1) # Data Frames for File 1 and 2 (As needed) # df_file2 = pd.read_csv(in_file2) # df_file3 = pd.read_csv(in_file3) ###Output _____no_output_____ ###Markdown Data Manipulation ###Code # File 1 df = helpers.shorten_site_names(df) df = helpers.clean_column_names(df) # File 2 # df_file2 = helpers.shorten_site_names(df_file2) # df_file2 = helpers.clean_column_names(df_file2) ###Output _____no_output_____ ###Markdown Save output file into processed directorySave a file in the processed directory that is cleaned properly. It will be read in and used later for further analysis. ###Code # Save File 1 Data Frame (Or master df) df.to_pickle(summary_file) ###Output _____no_output_____
courses/machine_learning/deepdive2/computer_vision_fun/labs/classifying_images_with_pre-built_tf_container_on_vertex_ai.ipynb
###Markdown Classifying Images with pre-built TF Container on Vertex AIThis notebook demonstrates how to implement different image models on MNIST using the [tf.keras API](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras). Learning Objectives1. Understand how to build a Dense Neural Network (DNN) for image classification.2. Understand how to use dropout (DNN) for image classification.3. Understand how to use Convolutional Neural Networks (CNN).4. Know how to deploy and use an image classifcation model using Google Cloud's [Vertex AI](https://cloud.google.com/vertex-ai/).Each learning objective will correspond to a __TODO__ in the notebook, where you will complete the notebook cell's code before running the cell. Refer to the [solution notebook](../solutions/classifying_images_with_pre-built_tf_container_on_vertex_ai.ipynb) for reference.First things first. Configure the parameters below to match your own Google Cloud project details. If you don’t want to change the region, leave all settings as they are. Otherwise, update the region as you want, leave other settings as they are and run the cell. ###Code from datetime import datetime import os REGION = 'us-central1' PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] BUCKET = PROJECT MODEL_TYPE = "cnn" # "linear", "dnn", "dnn_dropout", or "cnn" # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.environ["REGION"] = REGION os.environ["MODEL_TYPE"] = MODEL_TYPE ###Output _____no_output_____ ###Markdown Building a dynamic modelThis notebook demonstrates how to implement DNN and CNN models on [MNIST](http://yann.lecun.com/exdb/mnist/) using the [tf.keras API](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras). In the previous notebook, “[Classifying_Images_with_DNN_Model.ipynb](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/computer_vision_fun/labs/7_Classifying_Images_with_DNN_Model.ipynb)”, you ran our code directly from the notebook. In order to run it on Vertex AI, you can also package your notebook as a python module.The boilerplate structure for this module has already been set up in the folder `mnist_models`. The module lives in the sub-folder, `trainer`, and is designated as a python package with the empty `__init__.py` (`mnist_models/trainer/__init__.py`) file. It still needs the model and a trainer to run it, so let's make them.Let's start with the trainer file first. This file parses command line arguments to feed into the model. ###Code %%writefile mnist_models/trainer/task.py import argparse import json import os import sys from . import model def _parse_arguments(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--model_type', help='Which model type to use', type=str, default='linear') parser.add_argument( '--epochs', help='The number of epochs to train', type=int, default=10) parser.add_argument( '--steps_per_epoch', help='The number of steps per epoch to train', type=int, default=100) parser.add_argument( '--job-dir', help='Directory where to save the given model', type=str, default='mnist_models/') return parser.parse_known_args(argv) def main(): """Parses command line arguments and kicks off model training.""" args = _parse_arguments(sys.argv[1:])[0] # Configure path for hyperparameter tuning. trial_id = json.loads( os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', '') output_path = args.job_dir if not trial_id else args.job_dir + '/' model_layers = model.get_layers(args.model_type) image_model = model.build_model(model_layers, args.job_dir) model_history = model.train_and_evaluate( image_model, args.epochs, args.steps_per_epoch, args.job_dir) if __name__ == '__main__': main() ###Output Writing mnist_models/trainer/task.py ###Markdown Next, let's group non-model functions into a util file to keep the model file simple. You'll copy over the `scale` and `load_dataset` functions from the previous lab. ###Code %%writefile mnist_models/trainer/util.py import tensorflow as tf def scale(image, label): """Scales images from a 0-255 int range to a 0-1 float range""" image = tf.cast(image, tf.float32) image /= 255 image = tf.expand_dims(image, -1) return image, label def load_dataset( data, training=True, buffer_size=5000, batch_size=100, nclasses=10): """Loads MNIST dataset into a tf.data.Dataset""" (x_train, y_train), (x_test, y_test) = data x = x_train if training else x_test y = y_train if training else y_test # One-hot encode the classes y = tf.keras.utils.to_categorical(y, nclasses) dataset = tf.data.Dataset.from_tensor_slices((x, y)) dataset = dataset.map(scale).batch(batch_size) if training: dataset = dataset.shuffle(buffer_size).repeat() return dataset ###Output Writing mnist_models/trainer/util.py ###Markdown Finally, let's code the models! The tf.keras API accepts an array of layers into a model object, so you can create a dictionary of layers based on the different model types you want to use. mnist_models/trainer/model.py file has three functions: get_layers, build_model and train_and_evaluate. In get_layers function: You will build the structure of our model in get_layers with four different layers:* First, you define a linear model.* Second, you define the Keras layers for a DNN model.* Third, you define the Keras layers for a dropout model.* Lastly, you define the Keras layers for a CNN model.In the build_model function: You compile the model, specifying an optimizer to use, the loss to minimize, and metrics to report. Finally in the train_and_evaluate function, you compile your keras model by loading data into it for training.Note that these models progressively build on each other. Look at the imported tensorflow.keras.layers modules and the default values for the variables defined in get_layers for guidance. ###Code %%writefile mnist_models/trainer/model.py import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import ( Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Softmax) from . import util # Image Variables WIDTH = 28 HEIGHT = 28 def get_layers( model_type, nclasses=10, hidden_layer_1_neurons=400, hidden_layer_2_neurons=100, dropout_rate=0.25, num_filters_1=64, kernel_size_1=3, pooling_size_1=2, num_filters_2=32, kernel_size_2=3, pooling_size_2=2): """Constructs layers for a keras model based on a dict of model types.""" model_layers = { 'linear': [ Flatten(), Dense(nclasses), Softmax() ], 'dnn': [ # TODO 1: Your code here ], 'dnn_dropout': [ # TODO 2: Your code here ], 'cnn': [ # TODO 3: Your code here ] } return model_layers[model_type] def build_model(layers, output_dir): """Compiles keras model for image classification.""" model = Sequential(layers) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model def train_and_evaluate(model, num_epochs, steps_per_epoch, output_dir): """Compiles keras model and loads data into it for training.""" mnist = tf.keras.datasets.mnist.load_data() train_data = util.load_dataset(mnist) validation_data = util.load_dataset(mnist, training=False) callbacks = [] if output_dir: tensorboard_callback = TensorBoard(log_dir=output_dir) callbacks = [tensorboard_callback] history = model.fit( train_data, validation_data=validation_data, epochs=num_epochs, steps_per_epoch=steps_per_epoch, verbose=2, callbacks=callbacks) if output_dir: export_path = os.path.join(output_dir, 'keras_export') model.save(export_path, save_format='tf') return history ###Output Writing mnist_models/trainer/model.py ###Markdown Local TrainingWith everything set up, let's run locally to test the code. Some of the previous tests have been copied over into a testing script `mnist_models/trainer/test.py` to make sure the model still passes our previous checks. On `line 13`, you can specify which model types you would like to check. `line 14` and `line 15` has the number of epochs and steps per epoch respectively.Moment of truth! Run the code below to check your models against the unit tests. If you see "OK" at the end when it's finished running, congrats! You've passed the tests! ###Code !python3 -m mnist_models.trainer.test ###Output 2022-01-10 11:10:26.956391: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance. 2022-01-10 11:10:27.032398: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2) .. *** Building model for linear *** Epoch 1/10 100/100 - 6s - loss: 1.3205 - accuracy: 0.6661 - val_loss: 0.7883 - val_accuracy: 0.8210 Epoch 2/10 100/100 - 1s - loss: 0.6711 - accuracy: 0.8396 - val_loss: 0.5605 - val_accuracy: 0.8658 Epoch 3/10 100/100 - 1s - loss: 0.5260 - accuracy: 0.8742 - val_loss: 0.4689 - val_accuracy: 0.8826 Epoch 4/10 100/100 - 2s - loss: 0.4703 - accuracy: 0.8773 - val_loss: 0.4196 - val_accuracy: 0.8934 Epoch 5/10 100/100 - 1s - loss: 0.4305 - accuracy: 0.8874 - val_loss: 0.3920 - val_accuracy: 0.8960 Epoch 6/10 100/100 - 2s - loss: 0.3896 - accuracy: 0.8963 - val_loss: 0.3653 - val_accuracy: 0.9042 Epoch 7/10 100/100 - 1s - loss: 0.3758 - accuracy: 0.8976 - val_loss: 0.3520 - val_accuracy: 0.9058 Epoch 8/10 100/100 - 1s - loss: 0.3714 - accuracy: 0.8994 - val_loss: 0.3408 - val_accuracy: 0.9079 Epoch 9/10 100/100 - 1s - loss: 0.3443 - accuracy: 0.9077 - val_loss: 0.3315 - val_accuracy: 0.9095 Epoch 10/10 100/100 - 1s - loss: 0.3574 - accuracy: 0.9003 - val_loss: 0.3239 - val_accuracy: 0.9098 *** Building model for dnn *** Epoch 1/10 100/100 - 5s - loss: 0.5966 - accuracy: 0.8317 - val_loss: 0.2996 - val_accuracy: 0.9136 Epoch 2/10 100/100 - 2s - loss: 0.2474 - accuracy: 0.9297 - val_loss: 0.2354 - val_accuracy: 0.9350 Epoch 3/10 100/100 - 1s - loss: 0.2067 - accuracy: 0.9414 - val_loss: 0.1759 - val_accuracy: 0.9458 Epoch 4/10 100/100 - 2s - loss: 0.1874 - accuracy: 0.9459 - val_loss: 0.1452 - val_accuracy: 0.9570 Epoch 5/10 100/100 - 1s - loss: 0.1526 - accuracy: 0.9572 - val_loss: 0.1289 - val_accuracy: 0.9593 Epoch 6/10 100/100 - 1s - loss: 0.1382 - accuracy: 0.9630 - val_loss: 0.1239 - val_accuracy: 0.9606 Epoch 7/10 100/100 - 1s - loss: 0.1153 - accuracy: 0.9652 - val_loss: 0.1106 - val_accuracy: 0.9654 Epoch 8/10 100/100 - 1s - loss: 0.1049 - accuracy: 0.9679 - val_loss: 0.1072 - val_accuracy: 0.9673 Epoch 9/10 100/100 - 2s - loss: 0.0929 - accuracy: 0.9735 - val_loss: 0.0902 - val_accuracy: 0.9715 Epoch 10/10 100/100 - 1s - loss: 0.0893 - accuracy: 0.9726 - val_loss: 0.1087 - val_accuracy: 0.9655 *** Building model for dnn_dropout *** Epoch 1/10 100/100 - 5s - loss: 0.6451 - accuracy: 0.8088 - val_loss: 0.2746 - val_accuracy: 0.9172 Epoch 2/10 100/100 - 1s - loss: 0.3084 - accuracy: 0.9087 - val_loss: 0.1987 - val_accuracy: 0.9400 Epoch 3/10 100/100 - 1s - loss: 0.2309 - accuracy: 0.9341 - val_loss: 0.1780 - val_accuracy: 0.9460 Epoch 4/10 100/100 - 1s - loss: 0.2006 - accuracy: 0.9424 - val_loss: 0.1478 - val_accuracy: 0.9536 Epoch 5/10 100/100 - 1s - loss: 0.1570 - accuracy: 0.9551 - val_loss: 0.1440 - val_accuracy: 0.9547 Epoch 6/10 100/100 - 2s - loss: 0.1646 - accuracy: 0.9543 - val_loss: 0.1186 - val_accuracy: 0.9627 Epoch 7/10 100/100 - 2s - loss: 0.1321 - accuracy: 0.9601 - val_loss: 0.1231 - val_accuracy: 0.9601 Epoch 8/10 100/100 - 1s - loss: 0.1169 - accuracy: 0.9649 - val_loss: 0.1037 - val_accuracy: 0.9680 Epoch 9/10 100/100 - 1s - loss: 0.1121 - accuracy: 0.9676 - val_loss: 0.0924 - val_accuracy: 0.9699 Epoch 10/10 100/100 - 2s - loss: 0.1023 - accuracy: 0.9678 - val_loss: 0.0996 - val_accuracy: 0.9689 *** Building model for cnn *** Epoch 1/10 100/100 - 10s - loss: 0.6706 - accuracy: 0.7978 - val_loss: 0.2021 - val_accuracy: 0.9384 Epoch 2/10 100/100 - 8s - loss: 0.2099 - accuracy: 0.9420 - val_loss: 0.1285 - val_accuracy: 0.9602 Epoch 3/10 100/100 - 7s - loss: 0.1380 - accuracy: 0.9606 - val_loss: 0.0908 - val_accuracy: 0.9729 Epoch 4/10 100/100 - 8s - loss: 0.1041 - accuracy: 0.9683 - val_loss: 0.0600 - val_accuracy: 0.9795 Epoch 5/10 100/100 - 8s - loss: 0.0973 - accuracy: 0.9696 - val_loss: 0.0646 - val_accuracy: 0.9797 Epoch 6/10 100/100 - 8s - loss: 0.0826 - accuracy: 0.9762 - val_loss: 0.0518 - val_accuracy: 0.9834 Epoch 7/10 100/100 - 8s - loss: 0.0606 - accuracy: 0.9815 - val_loss: 0.0402 - val_accuracy: 0.9866 Epoch 8/10 100/100 - 8s - loss: 0.0622 - accuracy: 0.9821 - val_loss: 0.0387 - val_accuracy: 0.9873 Epoch 9/10 100/100 - 7s - loss: 0.0516 - accuracy: 0.9854 - val_loss: 0.0487 - val_accuracy: 0.9840 Epoch 10/10 100/100 - 8s - loss: 0.0592 - accuracy: 0.9827 - val_loss: 0.0379 - val_accuracy: 0.9874 ... ---------------------------------------------------------------------- Ran 5 tests in 138.340s OK ###Markdown Now you know that your models are working as expected, let's run it on Google Cloud within Vertex AI. You can run it as a python module locally first using the command line.The below cell transfers some of your variables to the command line as well as create a job directory including a timestamp. ###Code current_time = datetime.now().strftime("%Y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "mnist_models/models/{}_{}/".format( model_type, current_time) ###Output _____no_output_____ ###Markdown The cell below runs the local version of the code. The epochs and steps_per_epoch flag can be changed to run for longer or shorther, as defined in your `mnist_models/trainer/task.py` file. ###Code %%bash python3 -m mnist_models.trainer.task \ --job-dir=$JOB_DIR \ --epochs=5 \ --steps_per_epoch=50 \ --model_type=$MODEL_TYPE ###Output Epoch 1/5 50/50 - 9s - loss: 1.0487 - accuracy: 0.6644 - val_loss: 0.3334 - val_accuracy: 0.8990 Epoch 2/5 50/50 - 5s - loss: 0.3760 - accuracy: 0.8886 - val_loss: 0.2216 - val_accuracy: 0.9332 Epoch 3/5 50/50 - 4s - loss: 0.2188 - accuracy: 0.9376 - val_loss: 0.1374 - val_accuracy: 0.9590 Epoch 4/5 50/50 - 5s - loss: 0.1550 - accuracy: 0.9534 - val_loss: 0.1135 - val_accuracy: 0.9678 Epoch 5/5 50/50 - 5s - loss: 0.1457 - accuracy: 0.9554 - val_loss: 0.0957 - val_accuracy: 0.9680 ###Markdown Training on the cloudFor this model, you will be able to use a Tensorflow pre-built container on Vertex AI, as you do not have any particular additional prerequisites. You use setuptools for this, and store the created source distribution on Cloud Storage by using “**gsutil cp**”. ###Code %%writefile mnist_models/setup.py from setuptools import find_packages from setuptools import setup setup( name='mnist_trainer', version='0.1', packages=find_packages(), include_package_data=True, description='MNIST model training application.' ) %%bash cd mnist_models python ./setup.py sdist --formats=gztar cd .. gsutil cp mnist_models/dist/mnist_trainer-0.1.tar.gz gs://${BUCKET}/mnist/ ###Output running sdist running egg_info creating mnist_trainer.egg-info writing mnist_trainer.egg-info/PKG-INFO writing dependency_links to mnist_trainer.egg-info/dependency_links.txt writing top-level names to mnist_trainer.egg-info/top_level.txt writing manifest file 'mnist_trainer.egg-info/SOURCES.txt' reading manifest file 'mnist_trainer.egg-info/SOURCES.txt' writing manifest file 'mnist_trainer.egg-info/SOURCES.txt' running check creating mnist_trainer-0.1 creating mnist_trainer-0.1/mnist_trainer.egg-info creating mnist_trainer-0.1/trainer copying files to mnist_trainer-0.1... copying setup.py -> mnist_trainer-0.1 copying mnist_trainer.egg-info/PKG-INFO -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/SOURCES.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/dependency_links.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/top_level.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying trainer/__init__.py -> mnist_trainer-0.1/trainer copying trainer/model.py -> mnist_trainer-0.1/trainer copying trainer/task.py -> mnist_trainer-0.1/trainer copying trainer/test.py -> mnist_trainer-0.1/trainer copying trainer/util.py -> mnist_trainer-0.1/trainer Writing mnist_trainer-0.1/setup.cfg creating dist Creating tar archive removing 'mnist_trainer-0.1' (and everything under it) ###Markdown Then, you can start the Vertex AI Custom Job using the pre-built container. You can pass your source distribution URI using the `--python-package-uris` flag. ###Code current_time = datetime.now().strftime("%Y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "gs://{}/mnist_{}_{}/".format( BUCKET, model_type, current_time) os.environ["JOB_NAME"] = "mnist_{}_{}".format( model_type, current_time) ###Output _____no_output_____ ###Markdown After submitting the following job, view the status in __Vertex AI__ > __Training__ and select __Custom Jobs__ tab. Wait for the job to finish. ###Code %%bash echo $JOB_DIR $REGION $JOB_NAME PYTHON_PACKAGE_URIS=gs://${BUCKET}/mnist/mnist_trainer-0.1.tar.gz MACHINE_TYPE=n1-standard-4 REPLICA_COUNT=1 PYTHON_PACKAGE_EXECUTOR_IMAGE_URI="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-3:latest" PYTHON_MODULE=trainer.task WORKER_POOL_SPEC="machine-type=$MACHINE_TYPE,\ replica-count=$REPLICA_COUNT,\ executor-image-uri=$PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,\ python-module=$PYTHON_MODULE" gcloud ai custom-jobs create \ --region=${REGION} \ --display-name=$JOB_NAME \ --python-package-uris=$PYTHON_PACKAGE_URIS \ --worker-pool-spec=$WORKER_POOL_SPEC \ --args="--job-dir=$JOB_DIR,--model_type=$MODEL_TYPE" %%bash SAVEDMODEL_DIR=${JOB_DIR}keras_export echo $SAVEDMODEL_DIR gsutil ls $SAVEDMODEL_DIR ###Output gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/ gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/saved_model.pb gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/assets/ gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/variables/ ###Markdown Deploying and predicting with modelOnce you have a model you're proud of, let's deploy it! All you need to do is to upload the created model artifact from Cloud Storage to Vertex AI as a model, create a new endpoint, and deploy the model to the endpoint. It can take 15-20 minutes to complete. Make a note of __ENDPOINT_RESOURCENAME__ for further use. ###Code %%bash TIMESTAMP=$(date -u +%Y%m%d_%H%M%S) MODEL_DISPLAYNAME=mnist_$TIMESTAMP ENDPOINT_DISPLAYNAME=mnist_endpoint_$TIMESTAMP IMAGE_URI="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-3:latest" SAVEDMODEL_DIR=${JOB_DIR}keras_export echo $SAVEDMODEL_DIR # Model MODEL_RESOURCENAME=$(gcloud ai models upload \ --region=$REGION \ --display-name=$MODEL_DISPLAYNAME \ --container-image-uri=$IMAGE_URI \ --artifact-uri=$SAVEDMODEL_DIR \ --format="value(model)") echo "MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}" echo "MODEL_RESOURCENAME=${MODEL_RESOURCENAME}" # Endpoint ENDPOINT_RESOURCENAME=$(gcloud ai endpoints create \ --region=$REGION \ --display-name=$ENDPOINT_DISPLAYNAME \ --format="value(name)") echo "ENDPOINT_DISPLAYNAME=${ENDPOINT_DISPLAYNAME}" echo "ENDPOINT_RESOURCENAME=${ENDPOINT_RESOURCENAME}" # Deployment DEPLOYED_MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}_deployment MACHINE_TYPE=n1-standard-2 gcloud ai endpoints deploy-model $ENDPOINT_RESOURCENAME \ --region=$REGION \ --model=$MODEL_RESOURCENAME \ --display-name=$DEPLOYED_MODEL_DISPLAYNAME \ --machine-type=$MACHINE_TYPE \ --min-replica-count=1 \ --max-replica-count=1 \ --traffic-split=0=100 ###Output gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export MODEL_DISPLAYNAME=mnist_20220110_113117 MODEL_RESOURCENAME=projects/867925218804/locations/us-central1/models/5397040785868718080 ENDPOINT_DISPLAYNAME=mnist_endpoint_20220110_113117 ENDPOINT_RESOURCENAME=projects/867925218804/locations/us-central1/endpoints/2075394168124866560 ###Markdown To predict with the model, let's take one of the example images.Write a .json file with image data to send to a Vertex AI deployed model. ###Code import json, codecs import tensorflow as tf import matplotlib.pyplot as plt HEIGHT = 28 WIDTH = 28 IMGNO = 12 mnist = tf.keras.datasets.mnist.load_data() (x_train, y_train), (x_test, y_test) = mnist test_image = x_test[IMGNO] jsondata = # TODO 4: Your code here json.dump(jsondata, codecs.open("test.json", "w", encoding = "utf-8")) plt.imshow(test_image.reshape(HEIGHT, WIDTH)); !cat test.json ###Output {"instances": [[[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [49], [180], [253], [255], [253], [169], [36], [11], [76], [9], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [5], [68], [228], [252], [252], [253], [252], [252], [160], [189], [253], [92], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [55], [252], [252], [227], [79], [69], [69], [100], [90], [236], [247], [67], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [43], [233], [252], [185], [50], [0], [0], [0], [26], [203], [252], [135], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [168], [253], [178], [37], [0], [0], [0], [0], [70], [252], [252], [63], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [155], [253], [242], [42], [0], [0], [0], [0], [5], [191], [253], [190], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [230], [0], [0], [0], [0], [5], [136], [252], [252], [64], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [230], [0], [0], [0], [32], [138], [252], [252], [227], [16], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [165], [252], [249], [207], [207], [207], [228], [253], [252], [252], [160], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [9], [179], [253], [252], [252], [252], [252], [75], [169], [252], [56], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [64], [116], [116], [74], [0], [149], [253], [215], [21], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [253], [252], [162], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [32], [253], [240], [50], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [157], [253], [164], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [43], [240], [253], [92], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [93], [253], [252], [84], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [114], [252], [209], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [116], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [165], [252], [116], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [93], [200], [63], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]]]} ###Markdown Finally, you can send it to the prediction service. The output will have a 1 in the index of the corresponding digit it is predicting. Congrats! You've completed the lab! ###Code %%bash ENDPOINT_RESOURCENAME=#Insert ENDPOINT_RESOURCENAME from above gcloud ai endpoints predict $ENDPOINT_RESOURCENAME \ --region=$REGION \ --json-request=test.json ###Output [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] ###Markdown Classifying Images with pre-built TF Container on Vertex AI IntroductionIn this notebook, you learn how to implement different image models on MNIST using the [tf.keras API](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras). Learning objectives1. Understand how to build a Dense Neural Network (DNN) for image classification.2. Understand how to use dropout (DNN) for image classification.3. Understand how to use Convolutional Neural Networks (CNN).4. Know how to deploy and use an image classifcation model using Google Cloud's [Vertex AI](https://cloud.google.com/vertex-ai/).Each learning objective will correspond to a __TODO__ in the student lab notebook -- try to complete this notebook first and then review the [solution notebook](../solutions/classifying_images_with_pre-built_tf_container_on_vertex_ai.ipynb) Configuring the parametersFirst, configure the parameters below to match your own Google Cloud project details.If you don’t want to change the region, leave all settings as they are. Otherwise, update the region as you want, leave other settings as they are and run the cell. ###Code from datetime import datetime import os REGION = 'us-central1' PROJECT = !(gcloud config get-value core/project) PROJECT = PROJECT[0] BUCKET = PROJECT MODEL_TYPE = "cnn" # "linear", "dnn", "dnn_dropout", or "cnn" # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.environ["REGION"] = REGION os.environ["MODEL_TYPE"] = MODEL_TYPE ###Output _____no_output_____ ###Markdown Building a dynamic modelThis part of notebook demonstrates how to implement DNN and CNN models on [MNIST](http://yann.lecun.com/exdb/mnist/) using the [tf.keras API](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras). In the previous notebook, “[classifying_images_with_a_nn_and_dnn_model.ipynb](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/computer_vision_fun/solutions/classifying_images_with_a_nn_and_dnn_model.ipynb)”, you run the code directly from the notebook. In this notebook, you see that you can also package your notebook as a python module on Vertex AI.The boilerplate structure for this module has already been set up in the folder mnist_models. The module lives in the sub-folder, trainer, and is designated as a python package with the empty __init__.py (mnist_models/trainer/__init__.py) file. It still needs the model and a trainer to run it, so let's make them.Start with the trainer file first. This file parses command line arguments to feed into the model. ###Code %%writefile mnist_models/trainer/task.py import argparse import json import os import sys from . import model def _parse_arguments(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--model_type', help='Which model type to use', type=str, default='linear') parser.add_argument( '--epochs', help='The number of epochs to train', type=int, default=10) parser.add_argument( '--steps_per_epoch', help='The number of steps per epoch to train', type=int, default=100) parser.add_argument( '--job-dir', help='Directory where to save the given model', type=str, default='mnist_models/') return parser.parse_known_args(argv) def main(): """Parses command line arguments and kicks off model training.""" args = _parse_arguments(sys.argv[1:])[0] # Configure path for hyperparameter tuning. trial_id = json.loads( os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', '') output_path = args.job_dir if not trial_id else args.job_dir + '/' model_layers = model.get_layers(args.model_type) image_model = model.build_model(model_layers, args.job_dir) model_history = model.train_and_evaluate( image_model, args.epochs, args.steps_per_epoch, args.job_dir) if __name__ == '__main__': main() ###Output Writing mnist_models/trainer/task.py ###Markdown Next, group non-model functions into a util file to keep the model file simple. Use the scale and load_dataset functions to scale images from a 0-255 int range to a 0-1 float range and load MNIST dataset into a tf.data.Dataset. ###Code %%writefile mnist_models/trainer/util.py import tensorflow as tf def scale(image, label): """Scales images from a 0-255 int range to a 0-1 float range""" image = tf.cast(image, tf.float32) image /= 255 image = tf.expand_dims(image, -1) return image, label def load_dataset( data, training=True, buffer_size=5000, batch_size=100, nclasses=10): """Loads MNIST dataset into a tf.data.Dataset""" (x_train, y_train), (x_test, y_test) = data x = x_train if training else x_test y = y_train if training else y_test # One-hot encode the classes y = tf.keras.utils.to_categorical(y, nclasses) dataset = tf.data.Dataset.from_tensor_slices((x, y)) dataset = dataset.map(scale).batch(batch_size) if training: dataset = dataset.shuffle(buffer_size).repeat() return dataset ###Output Writing mnist_models/trainer/util.py ###Markdown Now you can code the models. The tf.keras API accepts an array of layers into a model object, so you can create a dictionary of layers based on the different model types you want to use. mnist_models/trainer/model.py file has three functions: get_layers, build_model and train_and_evaluate. In get_layers function: Youl build the structure of our model in get_layers with four different layers:* First, you define a linear model.* Second, you define the Keras layers for a DNN model.* Third, you define the Keras layers for a dropout model.* Lastly, you define the Keras layers for a CNN model.In the build_model function: You compile the model, specifying an optimizer to use, the loss to minimize, and metrics to report. Finally in the train_and_evaluate function, you compile your Keras model by loading data into it for training.Note that these models progressively build on each other. Look at the imported tensorflow.keras.layers modules and the default values for the variables defined in get_layers for guidance. ###Code %%writefile mnist_models/trainer/model.py import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import ( Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Softmax) from . import util # Image Variables WIDTH = 28 HEIGHT = 28 def get_layers( model_type, nclasses=10, hidden_layer_1_neurons=400, hidden_layer_2_neurons=100, dropout_rate=0.25, num_filters_1=64, kernel_size_1=3, pooling_size_1=2, num_filters_2=32, kernel_size_2=3, pooling_size_2=2): """Constructs layers for a keras model based on a dict of model types.""" model_layers = { 'linear': [ Flatten(), Dense(nclasses), Softmax() ], 'dnn': [ # TODO 1: Your code here ], 'dnn_dropout': [ # TODO 2: Your code here ], 'cnn': [ # TODO 3: Your code here ] } return model_layers[model_type] def build_model(layers, output_dir): """Compiles keras model for image classification.""" model = Sequential(layers) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model def train_and_evaluate(model, num_epochs, steps_per_epoch, output_dir): """Compiles keras model and loads data into it for training.""" mnist = tf.keras.datasets.mnist.load_data() train_data = util.load_dataset(mnist) validation_data = util.load_dataset(mnist, training=False) callbacks = [] if output_dir: tensorboard_callback = TensorBoard(log_dir=output_dir) callbacks = [tensorboard_callback] history = model.fit( train_data, validation_data=validation_data, epochs=num_epochs, steps_per_epoch=steps_per_epoch, verbose=2, callbacks=callbacks) if output_dir: export_path = os.path.join(output_dir, 'keras_export') model.save(export_path, save_format='tf') return history ###Output Writing mnist_models/trainer/model.py ###Markdown Local TrainingAfter completing the set up, you can run locally to test the code. Some of the previous tests have been copied over into a testing script mnist_models/trainer/test.py to make sure the model still passes our previous checks. On line 13, you can specify which model types you would like to check. line 14 and line 15 have the number of epochs and steps per epoch respectively.Run the code below to check your models against the unit tests. If you see "OK" at the end when it's finished running, congrats! You've passed the tests! ###Code !python3 -m mnist_models.trainer.test ###Output 2022-01-10 11:10:26.956391: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance. 2022-01-10 11:10:27.032398: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2) .. *** Building model for linear *** Epoch 1/10 100/100 - 6s - loss: 1.3205 - accuracy: 0.6661 - val_loss: 0.7883 - val_accuracy: 0.8210 Epoch 2/10 100/100 - 1s - loss: 0.6711 - accuracy: 0.8396 - val_loss: 0.5605 - val_accuracy: 0.8658 Epoch 3/10 100/100 - 1s - loss: 0.5260 - accuracy: 0.8742 - val_loss: 0.4689 - val_accuracy: 0.8826 Epoch 4/10 100/100 - 2s - loss: 0.4703 - accuracy: 0.8773 - val_loss: 0.4196 - val_accuracy: 0.8934 Epoch 5/10 100/100 - 1s - loss: 0.4305 - accuracy: 0.8874 - val_loss: 0.3920 - val_accuracy: 0.8960 Epoch 6/10 100/100 - 2s - loss: 0.3896 - accuracy: 0.8963 - val_loss: 0.3653 - val_accuracy: 0.9042 Epoch 7/10 100/100 - 1s - loss: 0.3758 - accuracy: 0.8976 - val_loss: 0.3520 - val_accuracy: 0.9058 Epoch 8/10 100/100 - 1s - loss: 0.3714 - accuracy: 0.8994 - val_loss: 0.3408 - val_accuracy: 0.9079 Epoch 9/10 100/100 - 1s - loss: 0.3443 - accuracy: 0.9077 - val_loss: 0.3315 - val_accuracy: 0.9095 Epoch 10/10 100/100 - 1s - loss: 0.3574 - accuracy: 0.9003 - val_loss: 0.3239 - val_accuracy: 0.9098 *** Building model for dnn *** Epoch 1/10 100/100 - 5s - loss: 0.5966 - accuracy: 0.8317 - val_loss: 0.2996 - val_accuracy: 0.9136 Epoch 2/10 100/100 - 2s - loss: 0.2474 - accuracy: 0.9297 - val_loss: 0.2354 - val_accuracy: 0.9350 Epoch 3/10 100/100 - 1s - loss: 0.2067 - accuracy: 0.9414 - val_loss: 0.1759 - val_accuracy: 0.9458 Epoch 4/10 100/100 - 2s - loss: 0.1874 - accuracy: 0.9459 - val_loss: 0.1452 - val_accuracy: 0.9570 Epoch 5/10 100/100 - 1s - loss: 0.1526 - accuracy: 0.9572 - val_loss: 0.1289 - val_accuracy: 0.9593 Epoch 6/10 100/100 - 1s - loss: 0.1382 - accuracy: 0.9630 - val_loss: 0.1239 - val_accuracy: 0.9606 Epoch 7/10 100/100 - 1s - loss: 0.1153 - accuracy: 0.9652 - val_loss: 0.1106 - val_accuracy: 0.9654 Epoch 8/10 100/100 - 1s - loss: 0.1049 - accuracy: 0.9679 - val_loss: 0.1072 - val_accuracy: 0.9673 Epoch 9/10 100/100 - 2s - loss: 0.0929 - accuracy: 0.9735 - val_loss: 0.0902 - val_accuracy: 0.9715 Epoch 10/10 100/100 - 1s - loss: 0.0893 - accuracy: 0.9726 - val_loss: 0.1087 - val_accuracy: 0.9655 *** Building model for dnn_dropout *** Epoch 1/10 100/100 - 5s - loss: 0.6451 - accuracy: 0.8088 - val_loss: 0.2746 - val_accuracy: 0.9172 Epoch 2/10 100/100 - 1s - loss: 0.3084 - accuracy: 0.9087 - val_loss: 0.1987 - val_accuracy: 0.9400 Epoch 3/10 100/100 - 1s - loss: 0.2309 - accuracy: 0.9341 - val_loss: 0.1780 - val_accuracy: 0.9460 Epoch 4/10 100/100 - 1s - loss: 0.2006 - accuracy: 0.9424 - val_loss: 0.1478 - val_accuracy: 0.9536 Epoch 5/10 100/100 - 1s - loss: 0.1570 - accuracy: 0.9551 - val_loss: 0.1440 - val_accuracy: 0.9547 Epoch 6/10 100/100 - 2s - loss: 0.1646 - accuracy: 0.9543 - val_loss: 0.1186 - val_accuracy: 0.9627 Epoch 7/10 100/100 - 2s - loss: 0.1321 - accuracy: 0.9601 - val_loss: 0.1231 - val_accuracy: 0.9601 Epoch 8/10 100/100 - 1s - loss: 0.1169 - accuracy: 0.9649 - val_loss: 0.1037 - val_accuracy: 0.9680 Epoch 9/10 100/100 - 1s - loss: 0.1121 - accuracy: 0.9676 - val_loss: 0.0924 - val_accuracy: 0.9699 Epoch 10/10 100/100 - 2s - loss: 0.1023 - accuracy: 0.9678 - val_loss: 0.0996 - val_accuracy: 0.9689 *** Building model for cnn *** Epoch 1/10 100/100 - 10s - loss: 0.6706 - accuracy: 0.7978 - val_loss: 0.2021 - val_accuracy: 0.9384 Epoch 2/10 100/100 - 8s - loss: 0.2099 - accuracy: 0.9420 - val_loss: 0.1285 - val_accuracy: 0.9602 Epoch 3/10 100/100 - 7s - loss: 0.1380 - accuracy: 0.9606 - val_loss: 0.0908 - val_accuracy: 0.9729 Epoch 4/10 100/100 - 8s - loss: 0.1041 - accuracy: 0.9683 - val_loss: 0.0600 - val_accuracy: 0.9795 Epoch 5/10 100/100 - 8s - loss: 0.0973 - accuracy: 0.9696 - val_loss: 0.0646 - val_accuracy: 0.9797 Epoch 6/10 100/100 - 8s - loss: 0.0826 - accuracy: 0.9762 - val_loss: 0.0518 - val_accuracy: 0.9834 Epoch 7/10 100/100 - 8s - loss: 0.0606 - accuracy: 0.9815 - val_loss: 0.0402 - val_accuracy: 0.9866 Epoch 8/10 100/100 - 8s - loss: 0.0622 - accuracy: 0.9821 - val_loss: 0.0387 - val_accuracy: 0.9873 Epoch 9/10 100/100 - 7s - loss: 0.0516 - accuracy: 0.9854 - val_loss: 0.0487 - val_accuracy: 0.9840 Epoch 10/10 100/100 - 8s - loss: 0.0592 - accuracy: 0.9827 - val_loss: 0.0379 - val_accuracy: 0.9874 ... ---------------------------------------------------------------------- Ran 5 tests in 138.340s OK ###Markdown Now you know that your models are working as expected. Now ,you can run it on Google Cloud within Vertex AI. You can run it as a python module locally first using the command line.The below cell transfers some of your variables to the command line and creates a job directory including a timestamp. ###Code current_time = datetime.now().strftime("%Y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "mnist_models/models/{}_{}/".format( model_type, current_time) ###Output _____no_output_____ ###Markdown The cell below runs the local version of the code. The epochs and steps_per_epoch flag can be changed to run for longer or shorter, as defined in your mnist_models/trainer/task.py file. ###Code %%bash python3 -m mnist_models.trainer.task \ --job-dir=$JOB_DIR \ --epochs=5 \ --steps_per_epoch=50 \ --model_type=$MODEL_TYPE ###Output Epoch 1/5 50/50 - 9s - loss: 1.0487 - accuracy: 0.6644 - val_loss: 0.3334 - val_accuracy: 0.8990 Epoch 2/5 50/50 - 5s - loss: 0.3760 - accuracy: 0.8886 - val_loss: 0.2216 - val_accuracy: 0.9332 Epoch 3/5 50/50 - 4s - loss: 0.2188 - accuracy: 0.9376 - val_loss: 0.1374 - val_accuracy: 0.9590 Epoch 4/5 50/50 - 5s - loss: 0.1550 - accuracy: 0.9534 - val_loss: 0.1135 - val_accuracy: 0.9678 Epoch 5/5 50/50 - 5s - loss: 0.1457 - accuracy: 0.9554 - val_loss: 0.0957 - val_accuracy: 0.9680 ###Markdown Training on the cloudFor this model, you use a Tensorflow pre-built container on Vertex AI, as you do not have any particular additional prerequisites. You use setuptools for this, and store the created source distribution on Cloud Storage by using “**gsutil cp**”. ###Code %%writefile mnist_models/setup.py from setuptools import find_packages from setuptools import setup setup( name='mnist_trainer', version='0.1', packages=find_packages(), include_package_data=True, description='MNIST model training application.' ) %%bash cd mnist_models python ./setup.py sdist --formats=gztar cd .. gsutil cp mnist_models/dist/mnist_trainer-0.1.tar.gz gs://${BUCKET}/mnist/ ###Output running sdist running egg_info creating mnist_trainer.egg-info writing mnist_trainer.egg-info/PKG-INFO writing dependency_links to mnist_trainer.egg-info/dependency_links.txt writing top-level names to mnist_trainer.egg-info/top_level.txt writing manifest file 'mnist_trainer.egg-info/SOURCES.txt' reading manifest file 'mnist_trainer.egg-info/SOURCES.txt' writing manifest file 'mnist_trainer.egg-info/SOURCES.txt' running check creating mnist_trainer-0.1 creating mnist_trainer-0.1/mnist_trainer.egg-info creating mnist_trainer-0.1/trainer copying files to mnist_trainer-0.1... copying setup.py -> mnist_trainer-0.1 copying mnist_trainer.egg-info/PKG-INFO -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/SOURCES.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/dependency_links.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying mnist_trainer.egg-info/top_level.txt -> mnist_trainer-0.1/mnist_trainer.egg-info copying trainer/__init__.py -> mnist_trainer-0.1/trainer copying trainer/model.py -> mnist_trainer-0.1/trainer copying trainer/task.py -> mnist_trainer-0.1/trainer copying trainer/test.py -> mnist_trainer-0.1/trainer copying trainer/util.py -> mnist_trainer-0.1/trainer Writing mnist_trainer-0.1/setup.cfg creating dist Creating tar archive removing 'mnist_trainer-0.1' (and everything under it) ###Markdown Then, you can start the Vertex AI Custom Job using the pre-built container. You can pass your source distribution URI using the --python-package-uris flag. ###Code current_time = datetime.now().strftime("%Y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "gs://{}/mnist_{}_{}/".format( BUCKET, model_type, current_time) os.environ["JOB_NAME"] = "mnist_{}_{}".format( model_type, current_time) ###Output _____no_output_____ ###Markdown After submitting the following job, view the status in __Vertex AI__ > __Training__ and select __Custom Jobs__ tab. Wait for the job to finish. ###Code %%bash echo $JOB_DIR $REGION $JOB_NAME PYTHON_PACKAGE_URIS=gs://${BUCKET}/mnist/mnist_trainer-0.1.tar.gz MACHINE_TYPE=n1-standard-4 REPLICA_COUNT=1 PYTHON_PACKAGE_EXECUTOR_IMAGE_URI="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-3:latest" PYTHON_MODULE=trainer.task WORKER_POOL_SPEC="machine-type=$MACHINE_TYPE,\ replica-count=$REPLICA_COUNT,\ executor-image-uri=$PYTHON_PACKAGE_EXECUTOR_IMAGE_URI,\ python-module=$PYTHON_MODULE" gcloud ai custom-jobs create \ --region=${REGION} \ --display-name=$JOB_NAME \ --python-package-uris=$PYTHON_PACKAGE_URIS \ --worker-pool-spec=$WORKER_POOL_SPEC \ --args="--job-dir=$JOB_DIR,--model_type=$MODEL_TYPE" %%bash SAVEDMODEL_DIR=${JOB_DIR}keras_export echo $SAVEDMODEL_DIR gsutil ls $SAVEDMODEL_DIR ###Output gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/ gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/saved_model.pb gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/assets/ gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export/variables/ ###Markdown Deploying and predicting with modelOnce you have a model you're proud of, let's deploy it! All you need to do is to upload the created model artifact from Cloud Storage to Vertex AI as a model, create a new endpoint, and deploy the model to the endpoint. It can take 15-20 minutes to complete. Make a note of **ENDPOINT_RESOURCENAME** for further use. ###Code %%bash TIMESTAMP=$(date -u +%Y%m%d_%H%M%S) MODEL_DISPLAYNAME=mnist_$TIMESTAMP ENDPOINT_DISPLAYNAME=mnist_endpoint_$TIMESTAMP IMAGE_URI="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-3:latest" SAVEDMODEL_DIR=${JOB_DIR}keras_export echo $SAVEDMODEL_DIR # Model MODEL_RESOURCENAME=$(gcloud ai models upload \ --region=$REGION \ --display-name=$MODEL_DISPLAYNAME \ --container-image-uri=$IMAGE_URI \ --artifact-uri=$SAVEDMODEL_DIR \ --format="value(model)") echo "MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}" echo "MODEL_RESOURCENAME=${MODEL_RESOURCENAME}" # Endpoint ENDPOINT_RESOURCENAME=$(gcloud ai endpoints create \ --region=$REGION \ --display-name=$ENDPOINT_DISPLAYNAME \ --format="value(name)") echo "ENDPOINT_DISPLAYNAME=${ENDPOINT_DISPLAYNAME}" echo "ENDPOINT_RESOURCENAME=${ENDPOINT_RESOURCENAME}" # Deployment DEPLOYED_MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}_deployment MACHINE_TYPE=n1-standard-2 gcloud ai endpoints deploy-model $ENDPOINT_RESOURCENAME \ --region=$REGION \ --model=$MODEL_RESOURCENAME \ --display-name=$DEPLOYED_MODEL_DISPLAYNAME \ --machine-type=$MACHINE_TYPE \ --min-replica-count=1 \ --max-replica-count=1 \ --traffic-split=0=100 ###Output gs://qwiklabs-gcp-04-25783cd152f3/mnist_cnn_20220110_112058/keras_export MODEL_DISPLAYNAME=mnist_20220110_113117 MODEL_RESOURCENAME=projects/867925218804/locations/us-central1/models/5397040785868718080 ENDPOINT_DISPLAYNAME=mnist_endpoint_20220110_113117 ENDPOINT_RESOURCENAME=projects/867925218804/locations/us-central1/endpoints/2075394168124866560 ###Markdown To predict with the model, take one of the example images.Write a .json file with image data to send to a Vertex AI deployed model. ###Code import json, codecs import tensorflow as tf import matplotlib.pyplot as plt HEIGHT = 28 WIDTH = 28 IMGNO = 12 mnist = tf.keras.datasets.mnist.load_data() (x_train, y_train), (x_test, y_test) = mnist test_image = x_test[IMGNO] jsondata = # TODO 4: Your code here json.dump(jsondata, codecs.open("test.json", "w", encoding = "utf-8")) plt.imshow(test_image.reshape(HEIGHT, WIDTH)); !cat test.json ###Output {"instances": [[[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [49], [180], [253], [255], [253], [169], [36], [11], [76], [9], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [5], [68], [228], [252], [252], [253], [252], [252], [160], [189], [253], [92], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [55], [252], [252], [227], [79], [69], [69], [100], [90], [236], [247], [67], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [43], [233], [252], [185], [50], [0], [0], [0], [26], [203], [252], [135], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [168], [253], [178], [37], [0], [0], [0], [0], [70], [252], [252], [63], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [155], [253], [242], [42], [0], [0], [0], [0], [5], [191], [253], [190], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [230], [0], [0], [0], [0], [5], [136], [252], [252], [64], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [230], [0], [0], [0], [32], [138], [252], [252], [227], [16], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [165], [252], [249], [207], [207], [207], [228], [253], [252], [252], [160], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [9], [179], [253], [252], [252], [252], [252], [75], [169], [252], [56], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [64], [116], [116], [74], [0], [149], [253], [215], [21], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [253], [252], [162], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [32], [253], [240], [50], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [157], [253], [164], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [43], [240], [253], [92], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [93], [253], [252], [84], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [114], [252], [209], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [207], [252], [116], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [165], [252], [116], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [93], [200], [63], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]]]} ###Markdown Finally, you can send it to the prediction service. The output will have a 1 in the index of the corresponding digit it is predicting. Congrats! You've completed the lab! ###Code %%bash ENDPOINT_RESOURCENAME=#Insert ENDPOINT_RESOURCENAME from above gcloud ai endpoints predict $ENDPOINT_RESOURCENAME \ --region=$REGION \ --json-request=test.json ###Output [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]
sigprocMXC_wavelets/sigprocMXC_wavelet.ipynb
###Markdown --- VIDEO: What are wavelets?--- ###Code ## general simulation parameters fs = 1024 npnts = fs*5 + 1 # 5 seconds # has to be odd for 0 to be included # centered time vector timevec = np.arange(0,npnts)/fs timevec = timevec - np.mean(timevec) # mean center on x axis # for power spectrum hz = np.linspace(0,fs/2,int(np.floor(npnts/2)+1)) ## Morlet wavelet # parameters freq = 4 # peak frequency csw = np.cos(2*np.pi*freq*timevec) # cosine wave fwhm = .5 # full-width at half-maximum in seconds gaussian = np.exp( -(4*np.log(2)*timevec**2) / fwhm**2 ) # Gaussian # Morlet wavelet MorletWavelet = csw * gaussian # amplitude spectrum MorletWaveletPow = np.abs(scipy.fftpack.fft(MorletWavelet)/npnts) # time-domain plotting plt.subplot(211) plt.plot(timevec,MorletWavelet,'k') plt.xlabel('Time (sec.)') plt.title('Morlet wavelet in time domain') # frequency-domain plotting plt.subplot(212) plt.plot(hz,MorletWaveletPow[:len(hz)],'k') plt.xlim([0,freq*3]) plt.xlabel('Frequency (Hz)') plt.title('Morlet wavelet in frequency domain') plt.show() ## Haar wavelet # create Haar wavelet HaarWavelet = np.zeros(npnts) HaarWavelet[np.argmin(timevec**2) : np.argmin((timevec-.5)**2) ] = 1 HaarWavelet[np.argmin((timevec-.5)**2) : np.argmin((timevec-1-1/fs)**2)] = -1 # amplitude spectrum HaarWaveletPow = np.abs(scipy.fftpack.fft(HaarWavelet)/npnts) # time-domain plotting plt.subplot(211) plt.plot(timevec,HaarWavelet,'k') plt.xlabel('Time (sec.)') plt.title('Haar wavelet in time domain') # frequency-domain plotting plt.subplot(212) plt.plot(hz,HaarWaveletPow[:len(hz)],'k') plt.xlim([0,freq*3]) plt.xlabel('Frequency (Hz)') plt.title('Haar wavelet in frequency domain') plt.show() ## Mexican hat wavelet # the wavelet s = .4 MexicanWavelet = (2/(np.sqrt(3*s)*np.pi**.25)) * (1- (timevec**2)/(s**2) ) * np.exp( (-timevec**2)/(2*s**2) ) # amplitude spectrum MexicanPow = np.abs(scipy.fftpack.fft(MexicanWavelet)/npnts) # time-domain plotting plt.subplot(211) plt.plot(timevec,MexicanWavelet,'k') plt.xlabel('Time (sec.)') plt.title('Mexican wavelet in time domain') # frequency-domain plotting plt.subplot(212) plt.plot(hz,MexicanPow[:len(hz)],'k') plt.xlim([0,freq*3]) plt.xlabel('Frequency (Hz)') plt.title('Mexican wavelet in frequency domain') plt.show() ## Difference of Gaussians (DoG) # (approximation of Laplacian of Gaussian) # define sigmas sPos = .1 sNeg = .5 # create the two GAussians gaus1 = np.exp( (-timevec**2) / (2*sPos**2) ) / (sPos*np.sqrt(2*np.pi)) gaus2 = np.exp( (-timevec**2) / (2*sNeg**2) ) / (sNeg*np.sqrt(2*np.pi)) # their difference is the DoG DoG = gaus1 - gaus2 # amplitude spectrum DoGPow = np.abs(scipy.fftpack.fft(DoG)/npnts) # time-domain plotting plt.subplot(211) plt.plot(timevec,DoG,'k') plt.xlabel('Time (sec.)') plt.title('DoG wavelet in time domain') # frequency-domain plotting plt.subplot(212) plt.plot(hz,DoGPow[:len(hz)],'k') plt.xlim([0,freq*3]) plt.xlabel('Frequency (Hz)') plt.title('DoG wavelet in frequency domain') plt.show() ###Output _____no_output_____ ###Markdown --- VIDEO: Convolution with wavelets--- ###Code ## general simulation parameters fs = 1024 npnts = fs*5 # 5 seconds # centered time vector timevec = np.arange(0,npnts)/fs timevec = timevec - np.mean(timevec) # for power spectrum hz = np.linspace(0,fs/2,int(np.floor(npnts/2)+1)) ### create wavelets # parameters freq = 4 # peak frequency csw = np.cos(2*np.pi*freq*timevec) # cosine wave fwhm = .5 # full-width at half-maximum in seconds gaussian = np.exp( -(4*np.log(2)*timevec**2) / fwhm**2 ) # Gaussian ## Morlet wavelet MorletWavelet = csw * gaussian ## Haar wavelet HaarWavelet = np.zeros(npnts) HaarWavelet[np.argmin(timevec**2) : np.argmin( (timevec-.5)**2 )] = 1 HaarWavelet[np.argmin((timevec-.5)**2) : np.argmin( (timevec-1-1/fs)**2 )] = -1 ## Mexican hat wavelet s = .4 MexicanWavelet = (2/(np.sqrt(3*s)*np.pi**.25)) * (1- (timevec**2)/(s**2) ) * np.exp( (-timevec**2)/(2*s**2) ) ## convolve with random signal # signal signal1 = scipy.signal.detrend(np.cumsum(np.random.randn(npnts))) # convolve signal with different wavelets morewav = np.convolve(signal1,MorletWavelet,'same') haarwav = np.convolve(signal1,HaarWavelet,'same') mexiwav = np.convolve(signal1,MexicanWavelet,'same') # amplitude spectra morewaveAmp = np.abs(scipy.fftpack.fft(morewav)/npnts) haarwaveAmp = np.abs(scipy.fftpack.fft(haarwav)/npnts) mexiwaveAmp = np.abs(scipy.fftpack.fft(mexiwav)/npnts) ### plotting # the signal plt.plot(timevec,signal1,'k') plt.title('Signal') plt.xlabel('Time (s)') plt.show() # the convolved signals plt.subplot(211) plt.plot(timevec,morewav,label='Morlet') plt.plot(timevec,haarwav,label='Haar') plt.plot(timevec,mexiwav,label='Mexican') plt.title('Time domain') plt.legend() # spectra of convolved signals plt.subplot(212) plt.plot(hz,morewaveAmp[:len(hz)],label='Morlet') plt.plot(hz,haarwaveAmp[:len(hz)],label='Haar') plt.plot(hz,mexiwaveAmp[:len(hz)],label='Mexican') plt.yscale('log') plt.xlim([0,40]) plt.legend() plt.xlabel('Frequency (Hz.)') plt.show() ###Output _____no_output_____ ###Markdown --- VIDEO: Wavelet convolution for narrowband filtering--- ###Code # simulation parameters srate = 4352 # hz npnts = 8425 time = np.arange(0,npnts)/srate hz = np.linspace(0,srate/2,int(np.floor(npnts/2)+1)) # pure noise signal signal1 = np.exp( .5*np.random.randn(npnts) ) # let's see what it looks like plt.subplot(211) plt.plot(time,signal1,'k') plt.xlabel('Time (s)') # in the frequency domain signalX = 2*np.abs(scipy.fftpack.fft(signal1)) plt.subplot(212) plt.plot(hz,signalX[:len(hz)],'k') plt.xlim([1,srate/6]) plt.ylim([0,300]) plt.xlabel('Frequency (Hz)') plt.show() ## create and inspect the Morlet wavelet # wavelet parameters ffreq = 34 # filter frequency in Hz fwhm = .12 # full-width at half-maximum in seconds wavtime = np.arange(-3,3,1/srate) # wavelet time vector (same sampling rate as signal!) # create the wavelet morwav = np.cos(2*np.pi*ffreq*wavtime) * np.exp( -(4*np.log(2)*wavtime**2) / fwhm**2 ) # amplitude spectrum of wavelet # (note that the wavelet needs its own hz because different length) wavehz = np.linspace(0,srate/2,int(np.floor(len(wavtime)/2)+1)) morwavX = 2*np.abs(scipy.fftpack.fft(morwav)) # plot it! plt.subplot(211) plt.plot(wavtime,morwav,'k') plt.xlim([-.5,.5]) plt.xlabel('Time (sec.)') plt.subplot(212) plt.plot(wavehz,morwavX[:len(wavehz)],'k') plt.xlim([0,ffreq*2]) plt.xlabel('Frequency (Hz)') plt.show() ## now for convolution convres = scipy.signal.convolve(signal1,morwav,'same') # show in the time domain plt.subplot(211) plt.plot(time,convres,'r') # and in the frequency domain plt.subplot(212) convresX = 2*np.abs(scipy.fftpack.fft(convres)) plt.plot(hz,convresX[:len(hz)],'r') plt.show() ### Time-domain wavelet normalization is... annoying and difficult. ### Let's do it in the frequency domain ### "manual" convolution nConv = npnts + len(wavtime) - 1 halfw = int( np.floor(len(wavtime)/2) ) # spectrum of wavelet morwavX = scipy.fftpack.fft(morwav,nConv) # now normalize in the frequency domain morwavX = morwavX / np.max(morwavX) # also equivalent: morwavX = (np.abs(morwavX)/max(np.abs(morwavX))) * np.exp(1j*np.angle(morwavX)) # now for the rest of convolution convres = scipy.fftpack.ifft( morwavX * scipy.fftpack.fft(signal1,nConv) ) convres = np.real( convres[halfw:-halfw+1] ) # time domain plt.plot(time,signal1,'k',label='original') plt.plot(time,convres,'b',label='filtered, norm.') plt.legend() plt.xlabel('Time') plt.show() # frequency domain convresX = 2*np.abs(scipy.fftpack.fft(convres)) plt.plot(hz,signalX[:len(hz)],'k',label='original') plt.plot(hz,convresX[:len(hz)],'b',label='filtered, norm.') plt.ylim([0,300]) plt.xlim([0,90]) plt.show() ## to preserve DC offset, compute and add back convres = convres + np.mean(signal1) plt.plot(time,signal1,'k',label='original') plt.plot(time,convres,'m',label='filtered, norm.') plt.legend() plt.xlabel('Time') plt.show() ###Output _____no_output_____ ###Markdown --- Time-frequency analysis with complex wavelets--- ###Code # data from http://www.vibrationdata.com/Solomon_Time_History.zip equake = np.loadtxt('Solomon_Time_History.txt') # more convenient times = equake[:,0] equake = equake[:,1] srate = np.round( 1/np.mean(np.diff(times)) ) ## plot the signal # time domain plt.subplot(211) plt.plot(times/60/60,equake) plt.xlim([times[0]/60/60,times[-1]/60/60]) plt.xlabel('Time (hours)') # frequency domain using pwelch plt.subplot(212) winsize = srate*60*10 # window size of 10 minutes f, welchpow = scipy.signal.welch(equake,fs=srate,window=np.hanning(winsize),nperseg=winsize,noverlap=winsize/4) plt.semilogy(f,welchpow) plt.xlabel('frequency [Hz]') plt.ylabel('Power') plt.ylim([10e-11,10e-6]) plt.show() ## setup time-frequency analysis # parameters (in Hz) numFrex = 40 minFreq = 2 maxFreq = srate/2 npntsTF = 1000 # this one's in points # frequencies in Hz frex = np.linspace(minFreq,maxFreq,numFrex) # wavelet widths (FWHM in seconds) fwhms = np.linspace(5,15,numFrex) # time points to save for plotting tidx = np.arange(1,len(times),npntsTF) # setup wavelet and convolution parameters wavet = np.arange(-10,10,1/srate) halfw = int(np.floor(len(wavet)/2)) nConv = len(times) + len(wavet) - 1 # create family of Morlet wavelets cmw = np.zeros((len(wavet),numFrex),dtype=complex) # loop over frequencies and create wavelets for fi in range(0,numFrex): cmw[:,fi] = np.exp(2*1j*np.pi*frex[fi]*wavet)*np.exp(-(4*np.log(2)*wavet**2)/fwhms[fi]**2) # plot them plt.pcolormesh(wavet,frex,np.abs(cmw).T,vmin=0,vmax=1) plt.xlabel('Time (s)'), plt.ylabel('Frequency (Hz)') plt.show() ## run convolution # initialize time-frequency matrix tf = np.zeros((len(frex),len(tidx))) tfN = np.zeros((len(frex),len(tidx))) # baseline time window for normalization basetidx = [0,0] basetidx[0] = np.argmin( (times--1000)**2 ) basetidx[1] = np.argmin( times**2 ) basepow = np.zeros(numFrex) # spectrum of data dataX = scipy.fftpack.fft(equake,nConv) # loop over frequencies for convolution for fi in range(0,numFrex): # create wavelet waveX = scipy.fftpack.fft( cmw[:,fi],nConv ) waveX = waveX/np.max(waveX) # normalize # convolve as1 = scipy.fftpack.ifft( waveX*dataX ) # trim as1 = as1[halfw:-halfw] # power time course at this frequency powts = np.abs(as1)**2 # baseline (pre-quake) basepow[fi] = np.mean(powts[range(basetidx[0],basetidx[1])]) tf[fi,:] = 10*np.log10( powts[tidx] ) tfN[fi,:] = 10*np.log10( powts[tidx]/basepow[fi] ) ## show time-frequency maps # "raw" power plt.subplot(211) plt.pcolormesh(times[tidx],frex,tf,vmin=-150,vmax=-70) plt.xlabel('Time'), plt.ylabel('Frequency (Hz)') plt.title('"Raw" time-frequency power') # pre-quake normalized power plt.subplot(212) plt.pcolormesh(times[tidx],frex,tfN,vmin=-15,vmax=15) plt.xlabel('Time'), plt.ylabel('Frequency (Hz)') plt.title('"Raw" time-frequency power') plt.show() ## normalized and non-normalized power plt.subplot(211) plt.plot(frex,np.mean(tf,axis=1),'ks-') plt.xlabel('Frequency (Hz)'), plt.ylabel('Power (10log_{10})') plt.title('Raw power') plt.subplot(212) plt.plot(frex,np.mean(tfN,axis=1),'ks-') plt.xlabel('Frequency (Hz)'), plt.ylabel('Power (norm.)') plt.title('Pre-quake normalized power') plt.show() ###Output _____no_output_____ ###Markdown --- VIDEO: Time-frequency analysis of brain signals--- ###Code # load in data braindat = sio.loadmat('data4TF.mat') timevec = braindat['timevec'][0] srate = braindat['srate'][0] data = braindat['data'][0] # plot the signal plt.plot(timevec,data) plt.xlabel('Time (s)'), plt.ylabel('Voltage (\muV)') plt.title('Time-domain signal') plt.show() ## create complex Morlet wavelets # wavelet parameters nfrex = 50 # 50 frequencies frex = np.linspace(8,70,nfrex) fwhm = .2 # full-width at half-maximum in seconds # time vector for wavelets wavetime = np.arange(-2,2,1/srate) # initialize matrices for wavelets wavelets = np.zeros( (nfrex,len(wavetime)) ,dtype=complex) # create complex Morlet wavelet family for wi in range(0,nfrex): # Gaussian gaussian = np.exp( -(4*np.log(2)*wavetime**2) / fwhm**2 ) # complex Morlet wavelet wavelets[wi,:] = np.exp(1j*2*np.pi*frex[wi]*wavetime) * gaussian # show the wavelets plt.plot(wavetime,np.real(wavelets[10,:]),label='Real part') plt.plot(wavetime,np.imag(wavelets[10,:]),label='Imag part') plt.xlabel('Time') plt.xlim([-.5, .5]) plt.legend() plt.show() plt.pcolormesh(wavetime,frex,np.real(wavelets)) plt.xlabel('Time (s)'), plt.ylabel('Frequency (Hz)') plt.title('Real part of wavelets') plt.xlim([-.5,.5]) plt.show() ## run convolution using spectral multiplication # convolution parameters nconv = len(timevec) + len(wavetime) - 1 # M+N-1 halfk = int( np.floor(len(wavetime)/2) ) # Fourier spectrum of the signal dataX = scipy.fftpack.fft(data,nconv) # initialize time-frequency matrix tf = np.zeros( (nfrex,len(timevec)) ) # convolution per frequency for fi in range(0,nfrex): # FFT of the wavelet waveX = scipy.fftpack.fft(wavelets[fi,:],nconv) # amplitude-normalize the wavelet waveX = waveX/np.max(waveX) # convolution convres = scipy.fftpack.ifft( waveX*dataX ) # trim the "wings" convres = convres[halfk-1:-halfk] # extract power from complex signal tf[fi,:] = np.abs(convres)**2 ## plot the results plt.pcolormesh(timevec,frex,tf,vmin=0,vmax=1e3) plt.xlabel('Time (s)'), plt.ylabel('Frequency (Hz)') plt.title('Time-frequency power') plt.show() ###Output _____no_output_____
snippets/Untitled.ipynb
###Markdown https://www.kaggle.com/arthurtok/titanic/introduction-to-ensembling-stacking-in-python/run/1294782 ###Code # Load in our libraries import pandas as pd import numpy as np import re import sklearn import xgboost as xgb import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import plotly.offline as py py.init_notebook_mode(connected=True) import plotly.graph_objs as go import plotly.tools as tls import warnings warnings.filterwarnings('ignore') # Going to use these 5 base models for the stacking from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier, ExtraTreesClassifier from sklearn.svm import SVC from sklearn.cross_validation import KFold; # Load in the train and test datasets train = pd.read_csv('./titanic_data/train.csv') test = pd.read_csv('./titanic_data/test.csv') # Store our passenger ID for easy access PassengerId = test['PassengerId'] train.head(13) ###Output _____no_output_____
Python/ml/White_Wine_Quality_Prediction.ipynb
###Markdown WHITE WINE QUALITY PREDICTION Link to the Dataset: [White Wine Quality](https://www.kaggle.com/piyushagni5/white-wine-quality) Importing Libraries ###Code import pandas as pd import numpy as np from sklearn import preprocessing from sklearn import metrics import seaborn as sns from scipy import stats from sklearn.model_selection import train_test_split # making predictions using different classifiers from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from statsmodels.stats.outliers_influence import variance_inflation_factor import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report ###Output _____no_output_____ ###Markdown Getting our Data ###Code df = pd.read_csv(r'C:\Users\DELL\Desktop\Kaggle+HE\Github GSSoC21\NeoAlgo\whitewinequality.csv', sep=";") df ###Output _____no_output_____ ###Markdown Data Preprocessing ###Code # checking for null values df.isnull().any() df.columns # checking variance variables = df[['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol']] vif = pd.DataFrame() vif['VIF'] = [variance_inflation_factor(variables.values, i) for i in range(variables.shape[1])] vif['Features'] = variables.columns vif # dropping all columns having vif>10 df = df.drop(['fixed acidity','citric acid','total sulfur dioxide','density','pH','sulphates','alcohol'], axis = 1) df # removing all outliners df = df[(np.abs(stats.zscore(df)) < 3).all(axis=1)] df ###Output _____no_output_____ ###Markdown Data Visualization ###Code # checking the distribution of outcomes sns.countplot(x = 'quality', data = df) # so there are 5 classes under which the quality of white wine is classified ###Output _____no_output_____ ###Markdown Splitting Data for Training and Testing ###Code data = df.values X, y = data[:,:-1], data[:,-1] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0) # splitting in the ratio 80:20 ###Output _____no_output_____ ###Markdown Making Predictions using KNN ###Code classifier1 = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2) classifier1.fit(X_train, y_train) y_pred1 = classifier1.predict(X_test) # Accuracy print('Accuracy:', classifier1.score(X_test, y_test)) ###Output Accuracy: 0.4683815648445874 ###Markdown Making Predictions using Support Vector Machines ###Code classifier2 = SVC(kernel='linear', random_state=0) classifier2.fit(X_train, y_train) y_pred2 = classifier2.predict(X_test) # Accuracy print('Accuracy:', classifier2.score(X_test, y_test)) ###Output Accuracy: 0.45444801714898175 ###Markdown Making Predictions using Decision Trees ###Code classifier3 = DecisionTreeClassifier(random_state=0) classifier3.fit(X_train, y_train) y_pred3 = classifier3.predict(X_test) # Accuracy print('Accuracy:', classifier3.score(X_test, y_test)) ###Output Accuracy: 0.5830653804930332 ###Markdown Making Predictions using Random Forest Classifier ###Code classifier4 = RandomForestClassifier(random_state=0) classifier4.fit(X_train, y_train) y_pred4 = classifier4.predict(X_test) # Accuracy print('Accuracy:', classifier4.score(X_test, y_test)) ###Output Accuracy: 0.639871382636656 ###Markdown Making Predictions using Naive Bayes ###Code classifier5 = GaussianNB() classifier5.fit(X_train, y_train) y_pred5 = classifier5.predict(X_test) # Accuracy print('Accuracy:', classifier5.score(X_test, y_test)) ###Output Accuracy: 0.4833869239013934 ###Markdown Random Forest Classifier is the most accurate model. Predictions are 63.98% accurate. Cross Validation for boosting Accuracy ###Code # performing k-fold cross validation from sklearn.model_selection import StratifiedKFold skf = StratifiedKFold(n_splits=5, random_state=None) # X is the feature set and y is the target for train_index, test_index in skf.split(X,y): print("Train:", train_index, "Validation:", test_index) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] y_pred_f = classifier4.predict(X_test) # Accuracy print('New Accuracy:', classifier4.score(X_test, y_test)) ###Output New Accuracy: 0.9356223175965666 ###Markdown Final predictions are 93.56% accurate. Results' Visualization ###Code cm = confusion_matrix(y_test, y_pred_f) cm plt.figure(figsize=(6,6)) sns.heatmap(cm, annot=True, fmt=".0f", linewidths=0.5, square = True, cmap = 'Pastel1') plt.ylabel('Actual label') plt.xlabel('Predicted label') plt.show() ###Output _____no_output_____ ###Markdown Classification Report ###Code class_names = ['4','5','6','7','8'] print(classification_report(y_test, y_pred_f, target_names=class_names)) ###Output precision recall f1-score support 4 1.00 0.93 0.96 27 5 0.93 0.93 0.93 274 6 0.93 0.95 0.94 423 7 0.94 0.94 0.94 175 8 0.93 0.82 0.87 33 accuracy 0.94 932 macro avg 0.95 0.91 0.93 932 weighted avg 0.94 0.94 0.94 932
05_Fashion_MNIST_Training_Dropout_Momentum/.ipynb_checkpoints/FashionMNIST_dropout_momentum_Training-checkpoint.ipynb
###Markdown FashionMNISTLoad images from the [Fashion-MNIST data](https://github.com/zalandoresearch/fashion-mnist)The dataset comprised of 60,000 small square 28x28 pixel grayscale images of items of 10 types of clothing with 0-9 class labels.class labels:* 0: T-shirt/top* 1: Trouser* 2: Pullover* 3: Dress* 4: Coat* 5: Sandal* 6: Shirt* 7: Sneaker* 8: Bag* 9: Ankle boot Load the Fashion-MNIST data* Use ``torch.utils.data.dataset``* Data path: data* Apply transformations to the data (turning all images into Tensor's for training a NN Train and CNN to classify images* Load in both training and test datasets from the FashionMNIST class Import the Necessary Packages ###Code # basic torch libraries import torch import torchvision # data loading and transforming from torchvision.datasets import FashionMNIST from torch.utils.data import DataLoader from torchvision import transforms # basic libraries import numpy as np import matplotlib.pyplot as plt %matplotlib inline ###Output _____no_output_____ ###Markdown The output of ``torchvision`` are PILImage images of range [0, 1]* Transform them to Tensor for input into a CNN ###Code # Defin a transform to read the data in as a Tensor data_transform = transforms.ToTensor() # Choose the training and test datasets path = './data' # Training datasets train_data = FashionMNIST(root=path, train=True, download=False, transform=data_transform) # Test datasets test_data = FashionMNIST(root=path, train=False, download=False, transform=data_transform) # Print out some stats about the training data print('Train data, number of images', len(train_data)) # Print out some stats about the training data print('Test data, number of images', len(test_data)) ###Output Train data, number of images 60000 Test data, number of images 10000 ###Markdown Data iteration and batching``torch.utils.data.DataLoader`` is an iterator that allows to batch and shuffle the data ###Code # shuffle the data and load in image/label data in batches of size 20 # Depends on large or small size of batch size will affect the loss batch_size = 20 # load train train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True) # load test test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True) # specify the image classes classes = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] ###Output _____no_output_____ ###Markdown Using ``dataiter.next()`` for cell iterates over the training dataset of loaded a random batch image/label data.Plots the batch of images and labels in a ``2*batch_size/2`` grid. ###Code # obtain one batch of training images # iter dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # convert to numpy # plot the images in the batch with labels fig = plt.figure(figsize=(25, 4)) # fig size for idx in np.arange(batch_size): ax = fig.add_subplot(2, batch_size/2, idx+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[idx]), cmap='gray') ax.set_title(classes[labels[idx]]) ###Output /home/eightun/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:10: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later. # Remove the CWD from sys.path while we load stuff. ###Markdown View an image* Normalize* grayscale image NormalizationNormalization ensures that, as we go through a feedforward and then backpropagation step in training our CNN, that each image feature will fall within a similar range of values and not overly activate any particular layer in our network. During the feedfoward step, a network takes in an input image and multiplies each input pixel by some convolutional filter weights (and adds biases!), then it applies some activation and pooling functions. Without normalization, it's much more likely that the calculated gradients in the backpropagaton step will be quite large and cause our loss to increase instead of converge ###Code # select an image by index idx = 2 img = np.squeeze(images[idx]) # display the pixel values in the image fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(img, cmap='gray') width, height = img.shape thresh = img.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if img[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), horizontalalignment='center', verticalalignment='center', color='white' if img[x][y]<thresh else 'black') ###Output _____no_output_____ ###Markdown NN Architecture* Architecture for simple ConvNet [INPUT-CONV-RELU-POOL-FC]* [NN Layers](http://pytorch.org/docs/master/nn.html)* Flattening used for the output of conv/pooling layer to a linear layer. In Keras used ``Flatten()``. In Pytorch used an input x with ``x = x.view(x.size(0), -1)``* Keep tract output dimension for case ``output_dim = (W-F+2P)/S + 1`` * Input volume size(W) * Receptive field size of the Conv Layer neurons(F) * The sride with which applied(S) * The amount of zero padding used(P)* Dropout randomly turns off perceptrons(nodes). It gives a way to balance network so that every node works equally towards the same goal, and if one makes a mistake, it won't dominate the behavior of our model. ``nn.Dropout()``We set dropout p = 0.9 which means each epoch, each nodes get turned off with a probabilit 90percent. Necessary Packages for NN Module ###Code import torch.nn as nn import torch.nn.functional as F # Define Layers of a model # Will use [INPUT-CONV-RELU-POOL-CONV-RELU-POOL-FC] class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel(grayscale), 10 output channels/features maps # Applies a 2D convolution over an input signal composed of several input planes. # 3x3 square convolution kernel # output_dim = (28-3)/1 + 1 = 26 # output Tensor for one image will have the dimensions: (10, 26, 26) self.conv1 = nn.Conv2d(1, 10, 3) # maxpool layer with kernel_size=2, stride=2 # Output_dim = 26/2 = 13 # output Tensor for one image will have the dimensions: (10, 13, 13) self.pool = nn.MaxPool2d(2,2) # Apply Second conv layer: 10 inputs, 20 outputs # 3x3 square convolution kernel # output_dim = (13-3)/1 + 1 = 11 # output Tensor for one image will have the dimensions: (20, 11, 11) self.conv2 = nn.Conv2d(10, 20, 3) # Outpu_dim for pooling after secon conv (20, 5, 5); 5.5 is rounded down ###### # FC # # 20 outputs * the 5*5 filtered/poled map size # # 10 output channels (for the 10 classes) # self.fc1 = nn.Linear(20*5*5, 10) # pool 10 -> 50 self.fc1 = nn.Linear(20*5*5, 50) ###### # dropout with p=0.4 self.fc1_drop = nn.Dropout(p=0.4) # finally, create 10 output channels (for the 10 classes) self.fc2 = nn.Linear(50, 10) ###### # feedforward behavior def forward(self, x): # Apply [CONV-RELU-POOL-CONV-RELU-POOL] x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) # Flattening used for the output of conv/pooling layer to a linear laye # Flatten the inputs into a vector x = x.view(x.size(0), -1) # One linear layer x = F.relu(self.fc1(x)) # # Apply softmax layer to convert the 10 outputs (0-9) into a distribution prob of class scores # x = F.log_softmax(x, dim=1) #### # two linear layers with dropout in between x = self.fc1_drop(x) x = self.fc2(x) #### return x # Instantiate and print Net net = Net() print(net) ###Output Net( (conv1): Conv2d(1, 10, kernel_size=(3, 3), stride=(1, 1)) (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv2d(10, 20, kernel_size=(3, 3), stride=(1, 1)) (fc1): Linear(in_features=500, out_features=50, bias=True) (fc1_drop): Dropout(p=0.4, inplace=False) (fc2): Linear(in_features=50, out_features=10, bias=True) ) ###Markdown Loss function and Optimizer* Loss function typically uses cross entropy loss ``criterion = nn.CrossEntropyLoss()``; Cross entropy loss combines softmax and NLL loss (``nn.NLLLoss()``).* NLL Loss being uesd for the output of Net is a distribution of class scores which this condtion fit to the model.* Some standard stochastic optimizers are stochastic gradient descent and Adam.* Apply momentum. It helps to find and then move on from local minimums and find the global minimum ###Code # additional necessary package for optimizer import torch.optim as optim # # Apply NLL Loss for distribution of class scores # criterion = nn.NLLLoss() #### # using cross entropy which combines sftmax and NLL loss criterion = nn.CrossEntropyLoss() # Optimizer used SGD with small learning rate 0.001 optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) #### ###Output _____no_output_____ ###Markdown Accuracy before training* The accuracy of before and after training hepls to see the differnce whether netwrok has learned something. ###Code # Calculate accuracy before training correct = 0 total = 0 # Iterate through test dataset for images, labels in test_loader: # forward pass to get outputs # the outputs are a series of class scores outputs = net(images) # get the predicted class from the maximum value in the output-list of class scores _, predicted = torch.max(outputs.data, 1) # count up total number of correct labels for which the predicted and true labels are equal total += labels.size(0) correct += (predicted == labels).sum() # calculate the accuracy to convert correct from a Tensor into a scalar, use .item() accuracy = 100.0 * correct.item() / total print('Accuracy before training: ', accuracy) ###Output Accuracy before training: 11.76 ###Markdown Train the Network* n_epochs: The number of epochs how many times a netwrok will cycle through the entire training dataset* Loop over the training dataset in batches and record the loss every 1000 batches* Steps: * Zero's the gradients to prepare for a forward pass * Passes the input through the network(forward pass * Computes the loss * Propagates gradients back into the netorks' parameter(backward pass) * Updates the weight(parameter update * print calculated loss ###Code def train(n_epochs): # collect loss as the network trains loss_over_time = [] # loop over the dataset for epoch in range(n_epochs): running_loss = 0.0 for batch_i, data in enumerate(train_loader): # get the input images and their corresponding labels inputs, labels = data # Zero the parameter(weight) gradients optimizer.zero_grad() # Forward pass to get outputs outputs = net(inputs) # Calculate the loss loss = criterion(outputs, labels) # backward pass o calculate the parameter gradients loss.backward() # Update the parameters optimizer.step() #Print loss stat to convert loss into a scalar and add it to running_loss, here used .item() running_loss += loss.item() # show stat at every 1000 batches if batch_i % 1000 == 999: avg_loss = running_loss/1000 # record and print the avg loss over the 1000 batches loss_over_time.append(avg_loss) print('Epoch: {}, Batch: {}, Avg. Loss: {}'.format(epoch+1, batch_i+1, avg_loss)) running_loss = 0.0 print('Finished Training') return loss_over_time # define the number of epochs to train for # start with small epochs to see if model works initially n_epochs = 30 # call train and record the loss over time training_loss = train(n_epochs) ###Output /home/eightun/anaconda3/lib/python3.7/site-packages/torch/autograd/__init__.py:147: UserWarning: CUDA initialization: CUDA unknown error - this may be due to an incorrectly set up environment, e.g. changing env variable CUDA_VISIBLE_DEVICES after program start. Setting the available devices to be zero. (Triggered internally at /pytorch/c10/cuda/CUDAFunctions.cpp:109.) allow_unreachable=True, accumulate_grad=True) # allow_unreachable flag ###Markdown Visualize the Lossprint recorded avg loss for each 1000 batches and for each epoch ###Code # Visualize the Loss plt.plot(training_loss) plt.xlabel('1000\'s of batches') plt.ylabel('Loss') plt.ylim(0, 2.5) plt.show() ###Output _____no_output_____ ###Markdown As shown above plot shows the loss decreases over time.It takes a little bot for big initial loss decrease, and the loss is flattening out over time Test the Trained Network* Test trained model on a previously unseen dataset* Use training images (good modle should reach greater than 85% accuracy on this test dataset) ###Code # Initialize tensor and lists to monitor test loss and accuracy test_loss = torch.zeros(1) class_correct = [0. for i in range(10)] class_total = [0. for i in range(10)] # set the module to evaluation mode net.eval() for batch_i, data in enumerate(test_loader): # get the input images and their corresponding labels inputs, labels = data # forward pass to get outputs outputs = net(inputs) # calcuate the loss loss = criterion(outputs, labels) # update avg test loss test_loss += ((torch.ones(1) / (batch_i + 1)) * (loss.data - test_loss)) # get the predicted class from the maximum valuein the output list of class scores _, predicted = torch.max(outputs.data, 1) # compare prediction to true label # this creates a correct Tensor that holds the number of correctly classified images in a batch correct = np.squeeze(predicted.eq(labels.data.view_as(predicted))) # calculate test accuracy for each object class for i in range(batch_size): label = labels.data[i] # get the scalar value of correct items for a class, by calling 'correct[i].item()' class_correct[label] += correct[i].item() class_total[label] += 1 print('Test Loss: {:.6f}\n'.format(test_loss.numpy()[0])) for i in range(10): if class_total[i] > 0: print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (classes[i], 100 * class_correct[i] / class_total[i], np.sum(class_correct[i]), np.sum(class_total[i]))) else: print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i])) print('\nTest Accuracy (Overall): %2d%% (%2d/%2d)' %(100. * np.sum(class_correct) / np.sum(class_total), np.sum(class_correct), np.sum(class_total))) ###Output Test Loss: 0.309656 Test Accuracy of T-shirt/top: 79% (797/1000) Test Accuracy of Trouser: 96% (965/1000) Test Accuracy of Pullover: 76% (764/1000) Test Accuracy of Dress: 90% (907/1000) Test Accuracy of Coat: 85% (851/1000) Test Accuracy of Sandal: 96% (964/1000) Test Accuracy of Shirt: 71% (717/1000) Test Accuracy of Sneaker: 96% (966/1000) Test Accuracy of Bag: 97% (972/1000) Test Accuracy of Ankle boot: 95% (957/1000) Test Accuracy (Overall): 88% (8860/10000) ###Markdown Visualize sample test resultsShows predicted class(true class) ###Code # obtan one batch of test images dataiter = iter(test_loader) images, labels = dataiter.next() # get predictions preds = np.squeeze(net(images).data.max(1, keepdim=True)[1].numpy()) images = images.numpy() # plot the images in the batch, along with predicted and true labels fig = plt.figure(figsize=(25, 4)) for idx in np.arange(batch_size): ax = fig.add_subplot(2, batch_size/2, idx+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[idx]), cmap='gray') ax.set_title("{} ({})".format(classes[preds[idx]], classes[labels[idx]]), color=('green' if preds[idx]==labels[idx] else 'red')) ###Output /home/eightun/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:12: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later. if sys.path[0] == '': ###Markdown After add dropout and momentum The [Previous model](https://github.com/bmaxdk/NN-PyTorch/blob/main/04_Fashion_MNIST_Training/FashionMNIST_Training.ipynb) has Weaknesses:Test Accuracy of Dress: 0% ( 0/1000)As a result this two have 0% accuracy. Due o incorrectly classifies most of other which has a similar overall shape. We can add regularization.Dropout layers to avoid overfitting certain classes at the cost of generalization. Dropou layers and adding momentum help to improve the [Previous model](https://github.com/bmaxdk/NN-PyTorch/blob/main/04_Fashion_MNIST_Training/FashionMNIST_Training.ipynb) Save the model ###Code # path and model name model_dir = 'saved_models/' model_name = 'fashion_net_simple.pt' # after training, save your model parameters in the directoy 'saved_models' torch.save(net.state_dict(), model_dir+model_name) ###Output _____no_output_____
module2-scala-for-spark/tony_scala4.ipynb
###Markdown ###Code println("Hello World") println(10) print("Hello world!") print(10) val x = 10 x=20 var y = 10 y =20 val z: Int=10 val a: Double=1.0 val b: Double=10 ###Output _____no_output_____ ###Markdown truefalse ###Code !true !false true == false 10 > 5 1+1 2 - 1 5 * 3 6/2 6/4 6.0/4 6/4.0 1+7 "a" 'a' "hello world".length "hello world".substring(2,6) "hello world".replace("o","3") "hello world".take(5) "hello world".drop(5) val n=45 s"We have $n apples" s"Power of 2: ${math.pow(2,2)}" "They stood outside the \"Rose and Crown\"" def sumofSquares(x: Int, y: Int): Int = { val x2 = x * x val y2 = y * y x2 + y2 } def sumofSquares(x: Int, y: Int): Int = x*x + y*y sumofSquares(3,4) def substract(x: Int, y:Int):Int = x-y substract(10,3) substract(y=10,x=3) def sq(x: Int) = x*x def addWithDefault(x:Int, y:Int=5) = x+y addWithDefault(1,2) addWithDefault(1) (x:Int)=> x*x val sq: Int=>Int=x=>x*x sq(10) val addOne: Int => Int=_+1 val weirdSum: (Int, Int)=> Int=(_ * 2 + _ * 3) addOne(5) weirdSum(2,4) 1 to 5 val r = 1 to 5 r.foreach(println) r foreach println (5 to 1 by -1) foreach(println) def showNumbersInRange(a:Int, b:Int): Unit={ print(a) if (a<b) showNumbersInRange(a+1,b) } showNumbersInRange(1,14) val x=10 if (x==1) println("yeah") if (x==10) println("yeah") else println("nay") println(if (x==10) "yeah" else "nope") val text = if (x==10) "yeah" else "nope" val a = Array(1,2,3,5,8,13) a(0) a(3) a(21) val s= Set(1,3,7) s(0) s(1) (1,2) (4,3,2) (1,2,"three") (a,2,"three") val divideInts = (x:Int, y:Int)=>(x/y, x%y) divideInts(10,3) val d = divideInts(10,3) d._1 d._2 val(div, mod)= divideInts(10,3) div mod val add10:Int => Int=_+10 List(1,2,3) map add10 List(1,2,3) map (x=> x+10) List(1,2,3) map(_+10) List("Dom","Bob","Natalia") foreach println val s=Set(1,3,7) s.map(sq) val sSquared = s. map(sq) sSquared.filter(_ < 10) sSquared.reduce(_+_) List(1,2,3) filter(_ > 2) case class Person(name:String, age:Int) List( Person(name = "Dom", age=23), Person(name = "Bob", age=30) ).filter(_.age > 25) val aListOfNumbers = List(1,2,3,4,10,20,100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println import scala.collection.immutable.List import scala.collection.immutable._ import scala.collection.immutable.{List, Map} import scala.collection.immutable.{List => ImmutableList} ###Output _____no_output_____
tutorials/2 - Static Connectivity.ipynb
###Markdown 2 - Static ConnectivityIn this short tutorial, we will compute the static connectivity of the EEG singals. - - - Load data ###Code import numpy as np import scipy from scipy import io eeg = np.load("data/eyes_opened.npy") num_trials, num_channels, num_samples = np.shape(eeg) eeg1 = np.squeeze(eeg[0, :, :]) ###Output _____no_output_____ ###Markdown Static connectivityAs a first example, we are going to compute the static connectivity of the EEG signals using the IPLV estimator. ###Code import warnings warnings.simplefilter(action='ignore', category=FutureWarning) from dyconnmap.fc import iplv ###Output _____no_output_____ ###Markdown Define the frequency band we are interested to examine, in Hz ###Code band = [1.0, 4.0] ###Output _____no_output_____ ###Markdown Define the sampling frequency, in Hz ###Code sampling_frequency = 160.0 ###Output _____no_output_____ ###Markdown We will invoke the estimator using the full by-name arguments. The last arguement, `pairs` is `None` by default, which means all "full connectivity", otherwise you check the documentation about the structure of the value. ###Code ts, avg = iplv(eeg1, fb=band, fs=sampling_frequency, pairs=None) print("""Time series array shape: {0} Average time series array shape: {1}""".format(np.shape(ts), np.shape(avg))) ###Output Time series array shape: (64, 64, 9600) Average time series array shape: (64, 64) ###Markdown Make the connectivity matrix symmetric ###Code avg_symm = avg + avg.T np.fill_diagonal(avg_symm, 1.0) ###Output _____no_output_____ ###Markdown PlotPlot the matrix using the standard Matplotlib functions ###Code import matplotlib.pyplot as plt mtx_min = 0.0 # we know it's 0.0 because of the estimator's properties mtx_max = np.max(avg) plt.figure(figsize=(6, 6)) cax = plt.imshow(avg_symm, vmin=mtx_min, vmax=mtx_max, cmap=plt.cm.Spectral) cb = plt.colorbar(fraction=0.046, pad=0.04) cb.ax.set_ylabel('Imaginary PLV', fontdict={'fontsize': 20}) plt.title('Connectivity Matrix', fontdict={'fontsize': 20}) plt.xlabel('Sensor', fontdict={'fontsize': 20}) plt.ylabel('Sensor', fontdict={'fontsize': 20}) plt.show() ###Output _____no_output_____
topics/4a_functies.ipynb
###Markdown FunctiesFun met Python functies! Computing*Berekeningen*, handelingen op data Een computer *rekent*, en daarmee voert het handelingen op data uit. Met data heb je kennisgemaakt en hoe dit door de computer wordt opgeslagen (denk aan de "dozen" in het geheugen en bits als fundamentele informatie-eenheid). Maar hoe worden *bewerkingen* op deze data uitgevoerd? We gaan kennismaken met een andere bouwsteen om te kunnen handelen: functies! HandelenInput en output ###Code len("huiswerk") ###Output _____no_output_____ ###Markdown Je hebt inmiddels al functies gebruikt, bijvoorbeeld de functie `len(x)`. Deze functie accepteert een *parameter* (een waarde, de *input*) en geeft een resultaat terug (*output*). We weten of zien niet welke handelingen `len(x)` verricht, we weten alleen dat het een waarde terugggeeft. Laten we Python functies eens vergelijken met wat je al kent van andere disciplines, bijvoorbeeld wiskunde. ![Google googol](images/4/google_googol.png) [Googol](https://nl.wikipedia.org/wiki/Googol) is de wiskundige aanduiding van een getal met de waarde $10^{100}$ (uitgeschreven een 1 gevolgd door 100 nullen). Dit is meer dan het aantal deeltjes in het waarneembaar heelal, maar minder dan het geschat [mogelijk aantal zetten in een schaakspel](https://en.wikipedia.org/wiki/Shannon_number) ($10^{120}$)!En als iemand in het verleden niet een [spelfout](https://graphics.stanford.edu/~dk/google_name_origin.html) had gemaakt dan zocht je nu met Googol in plaats van [Google](https://google.com) ... Laten we onze eigen "googoler" functie maken die *elk* getal tot de macht 100 kan verheffen. Structuur versus procedure $$g(x) = x^{100}$$Definieert een **structuur**: wat het *is* (en wat logischerwijs volgt) Functies ken je uit de wiskunde en je zou een "googolige" machtsverheffing kunnen *beschrijven* als een functie. We beschrijven hier dat voor elke parameter $x$ je deze als $x^{100}$ terugkrijgt. Dit is de syntax die wiskudigen hebben bedacht om een *structuur* te beschrijven en wat daar logischerwijs uit zou moeten volgen. ```pythondef g(x): return x**100```Defineert een **procedure**: wat het *doet* (en wat gedragsmatig volgt) Python heeft ook functies. Het heeft de speciale syntax `def` (wat *define* betekent) om te zeggen "Ik definieer een functie", in dit geval een functie met de naam `g` die een enkele parameter `x` accepteert.De combinatie van naam en welke parameters worden geaccepteerd wordt ook de *signatuur* van een functie genoemd, want dit is wat het uniek maakt en onderscheidt van andere functies die we gaan schrijven. Let ook op dat een functie definitie wordt afgesloten met de dubbele punt `:`!Dit is al een stuk concreter, want anders dan de wiskundige beschrijving definiëren we hier een procedure (één of meerdere handelingen die uitgevoerd moeten worden op basis van een mogelijke input) en een resultaat dat mogelijk met het `return` *statement* wordt teruggegeven (output). Let ook op dat alles wat na de dubbele punt volgt moet worden ingesprongen om aan te geven dat het een codeblok is dat onderdeel van de functie is.Syntax check! De dubbele punt geeft aan dat een nieuwe context volgt, je hebt dit bijvoorbeeld ook gezien bij conditionele statements als `if:`. De vuistregel is *altijd inspringen* na een dubbele punt! Binnen een functie ###Code def flipside(s): """ flipside(s): spiegel s! input s: een string """ x = len(s) // 2 return s[x:] + s[:x] flipside("automaat") ###Output _____no_output_____ ###Markdown Laten we gaan kijken naar de binnenkant van functies. We hebben hier een functie `flipside` gedefinieerd die een *string* spiegelt. Je ziet dat functie `len(x)`, *floor division* `//` en string *slicing* wordt gebruikt. Maar je ziet ook andere dingen, bijvoorbeeld binnen de functie een nieuwe variabele `x` en tekst tussen driedubbele aanhalingstekens `"""`. Docstrings```pythondef flipside(s): """ flipside(s): spiegel s! input s: een string """``` ###Code help(flipside) ###Output Help on function flipside in module __main__: flipside(s) flipside(s): spiegel s! input s: een string ###Markdown Met een string met driedubbele aanhalingstekens direct na de dubbele punt documenteer je de functie (voor jezelf en voor anderen). Je beschrijft in deze *docstring* op de eerste regel kort wat de functie doet en verder andere informatie die nodig is, bijvoorbeeld de typen van parameters. Deze documentatie kan je altijd opvragen met `help(x)`. Probeer dit ook een voor (ingebouwde) Python functies als (`len(x)` of `print()`). Gebruik variabelen```pythondef flipside(s): x = len(s) // 2 return s[x:] + s[:x]``` De lengte van de string is nodig om vervolgens met een floor division het aantal karakters tot het middelpunt van de string te bepalen. Dit aantal wordt aan de nieuwe variabele `x` toegekend en deze `x` wordt vervolgens 2 keer gebruikt voor het slicen van de string (de start- en stop waarden). We breken met het zetten van deze variabele `x` ook het probleem in stukjes op, en het scheelt ons typewerk! ```pythondef flipside(s): return s[len(s) // 2:] + s[:len(s) // 2]``` Je had de stap van het zetten van een variabele ook kunnnen overslaan en de start- en stop waarde voor het slicen van de string ook als resultaat van `len(s) // 2` kunnen schrijven, maar je merkt al dat het minder goed leesbaar is. Het gebruik van variabelen helpt de leesbaarheid en zelfs de computer vind het prettiger omdat het efficiënter is: er hoeft maar één keer het aantal karakters tot het midden te worden berekend! Variabelen opnieuw definieren```pythondef convert_from_seconds(s): """Een getal naar dagen, uren, minuten en seconden Zet een getal om naar naar een lijst van [days, hours, minutes, seconds] input s: een int """ days = s // (24 * 60 * 60) aantal dagen s = s % (24 * 60 * 60) restant s hours = s // (60 * 60) aantal uren s = s % (60 * 60) restant s minutes = s // 60 aantal minuten s = s % 60 restant s return [days, hours, minutes, s]``` Gebruik variabelen en definiereer ze opnieuw als het nodig is! In dit voorbeeld wordt `s` steeds opnieuw gedefineerd op basis van het resultaat van een vorige handeling. Een floor division (`//`) wordt eerst gebruikt om bijvoorbeeld het aantal dagen te vinden en met het restant (`%`) wordt op dezlfde manier het aantal uren weer gevonden. Hetzelfde proces wordt herhaald voor het aantal minuten tot een restant aan aantal seconden overblijft.Naast de *docstring* zie je ook commentaren: alles wat na een `` volgt slaat Python over, het doet daar niets mee. Het is vooral voor mensen een manier om opmerkingen tussendoor te plaatsen. Let verder ook op het return statement waar de waarden als *list* wordt teruggegeven. Return versus printWat is het verschil? Je hebt eerder kennisgemaakt met `print(x)` en deze functie geeft iets terug, althans zo lijkt het! `return` geeft een resultaat van een functie terug, wat is nu het verschil met `print(x)`? ###Code def dbl(x): """verdubbelt x? """ return 2 * x a_dbl = dbl(20) + 20 ###Output _____no_output_____ ###Markdown Dit is een eenvoudige functie die een waarde verdubbelt en het resultaat teruggeeft met `return`. Nu een variant met `print(x)` in plaats van `return`: ###Code def dbl_pr(x): """verdubbelt x? """ print(2 * x) ###Output _____no_output_____ ###Markdown ```pythona_dbl_pr = dbl_pr(20) + 20``` ```text---------------------------------------------------------------------------TypeError Traceback (most recent call last) in 4 print(2 * x) 5 ----> 6 a_dbl_pr = dbl_pr(20) + 20TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'``` Dit geeft een fout op regel 6, waar we bij het resultaat van de functie 20 willen optellen. Waarom deze fout terwijl we wél een resultaat op scherm zien (40)? De verklaring is dat een functie zonder `return` niets teruggeeft en dat "niets" (verassend genoeg!) wél een waarde heeft, een waarde `None` (met type `NoneType`). `None` ("geen") representeert het niets en Python zegt ons hier dat we 20 *niet* bij niets kunnen optellen!Het *niets* is voor Python blijkbaar wel "iets" (`None`)!Als je er bij stilstaat is dit niet zo gek. Wij mensen maken ook een onderscheid tussen iets en niets (en hebben daar woorden voor, *iets* of *niets*) en voor Python is in dit niet(s) anders: het heeft een manier nodig om niets te kunnen representeren en uit te drukken. Het verschil**print** wijzigt pixels op het scherm**return** geeft resultaat van de functie-aanroep terug `return` is de manier hoe software informatie aan functies doorgeeft, waar het resultaat (output) van de een de input kan zijn voor de ander. Testen ###Code # 1: functie definitie def flipside(s): """ flipside(s): spiegel s! input s: een string """ x = len(s) // 2 return s[x:] + s[:x] # 2: Tests assert flipside('huiswerk') == 'werkhuis' assert flipside('popster') == 'sterpop' print(" toplap ~", flipside('laptop')) # print het resultaat naar het scherm ###Output toplap ~ toplap ###Markdown Voeg `assert` statements toe, waar *assert* een aanname betekent. Bijvoorbeeld, lees```pythonassert flipside('huiswerk') == 'werkhuis'```als "neem aan dat het resultaat van de aanroep `flipside('huiswerk')` gelijk is aan de string `'werkhuis'`". Verder kan je natuurlijk altijd print statements gebruiken om waarden naar het scherm te printen! None?`None` is iets dat *niets* representeert, kan je dit ook testen? ###Code assert dbl_pr(20) == None ###Output 40
Week 6 PA 1/Deep+Features+for+Image+Classification.ipynb
###Markdown Using deep features to build an image classifier Fire up GraphLab Create ###Code import graphlab ###Output _____no_output_____ ###Markdown Load a common image analysis datasetWe will use a popular benchmark dataset in computer vision called CIFAR-10. (We've reduced the data to just 4 categories = {'cat','bird','automobile','dog'}.)This dataset is already split into a training set and test set. ###Code image_train = graphlab.SFrame('image_train_data/') image_test = graphlab.SFrame('image_test_data/') ###Output [INFO] This commercial license of GraphLab Create is assigned to [email protected]. [INFO] Start server at: ipc:///tmp/graphlab_server-123075 - Server binary: /home/ubuntu/anaconda/lib/python2.7/site-packages/graphlab/unity_server - Server log: /tmp/graphlab_server_1440701433.log [INFO] GraphLab Server Version: 1.5.2 ###Markdown Exploring the image data ###Code graphlab.canvas.set_target('ipynb') image_train['image'].show() ###Output _____no_output_____ ###Markdown Train a classifier on the raw image pixelsWe first start by training a classifier on just the raw pixels of the image. ###Code raw_pixel_model = graphlab.logistic_classifier.create(image_train,target='label', features=['image_array']) ###Output PROGRESS: Creating a validation set from 5 percent of training data. This may take a while. You can set ``validation_set=None`` to disable validation tracking. PROGRESS: Logistic regression: PROGRESS: -------------------------------------------------------- PROGRESS: Number of examples : 1900 PROGRESS: Number of classes : 4 PROGRESS: Number of feature columns : 1 PROGRESS: Number of unpacked features : 3072 PROGRESS: Number of coefficients : 9219 PROGRESS: Starting L-BFGS PROGRESS: -------------------------------------------------------- PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ PROGRESS: | Iteration | Passes | Step size | Elapsed Time | Training-accuracy | Validation-accuracy | PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ PROGRESS: | 1 | 6 | 0.000013 | 1.298911 | 0.280526 | 0.276190 | PROGRESS: | 2 | 8 | 1.000000 | 1.426180 | 0.364211 | 0.314286 | PROGRESS: | 3 | 9 | 1.000000 | 1.499995 | 0.411579 | 0.409524 | PROGRESS: | 4 | 10 | 1.000000 | 1.577665 | 0.435263 | 0.514286 | PROGRESS: | 5 | 11 | 1.000000 | 1.653563 | 0.464211 | 0.533333 | PROGRESS: | 6 | 12 | 1.000000 | 1.727710 | 0.467368 | 0.523810 | PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ ###Markdown Make a prediction with the simple model based on raw pixels ###Code image_test[0:3]['image'].show() image_test[0:3]['label'] raw_pixel_model.predict(image_test[0:3]) ###Output _____no_output_____ ###Markdown The model makes wrong predictions for all three images. Evaluating raw pixel model on test data ###Code raw_pixel_model.evaluate(image_test) ###Output _____no_output_____ ###Markdown The accuracy of this model is poor, getting only about 46% accuracy. Can we improve the model using deep featuresWe only have 2005 data points, so it is not possible to train a deep neural network effectively with so little data. Instead, we will use transfer learning: using deep features trained on the full ImageNet dataset, we will train a simple model on this small dataset. ###Code len(image_train) ###Output _____no_output_____ ###Markdown Computing deep features for our imagesThe two lines below allow us to compute deep features. This computation takes a little while, so we have already computed them and saved the results as a column in the data you loaded. (Note that if you would like to compute such deep features and have a GPU on your machine, you should use the GPU enabled GraphLab Create, which will be significantly faster for this task.) ###Code #deep_learning_model = graphlab.load_model('http://s3.amazonaws.com/GraphLab-Datasets/deeplearning/imagenet_model_iter45') #image_train['deep_features'] = deep_learning_model.extract_features(image_train) ###Output _____no_output_____ ###Markdown As we can see, the column deep_features already contains the pre-computed deep features for this data. ###Code image_train.head() ###Output _____no_output_____ ###Markdown Given the deep features, let's train a classifier ###Code deep_features_model = graphlab.logistic_classifier.create(image_train, features=['deep_features'], target='label') ###Output PROGRESS: Creating a validation set from 5 percent of training data. This may take a while. You can set ``validation_set=None`` to disable validation tracking. PROGRESS: WARNING: Detected extremely low variance for feature(s) 'deep_features' because all entries are nearly the same. Proceeding with model training using all features. If the model does not provide results of adequate quality, exclude the above mentioned feature(s) from the input dataset. PROGRESS: Logistic regression: PROGRESS: -------------------------------------------------------- PROGRESS: Number of examples : 1919 PROGRESS: Number of classes : 4 PROGRESS: Number of feature columns : 1 PROGRESS: Number of unpacked features : 4096 PROGRESS: Number of coefficients : 12291 PROGRESS: Starting L-BFGS PROGRESS: -------------------------------------------------------- PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ PROGRESS: | Iteration | Passes | Step size | Elapsed Time | Training-accuracy | Validation-accuracy | PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ PROGRESS: | 1 | 5 | 0.000130 | 0.376212 | 0.720688 | 0.732558 | PROGRESS: | 2 | 9 | 0.250000 | 0.717980 | 0.766024 | 0.790698 | PROGRESS: | 3 | 10 | 0.250000 | 0.892061 | 0.769151 | 0.802326 | PROGRESS: | 4 | 11 | 0.250000 | 1.022422 | 0.774883 | 0.802326 | PROGRESS: | 5 | 12 | 0.250000 | 1.152027 | 0.788431 | 0.802326 | PROGRESS: | 6 | 13 | 0.250000 | 1.287902 | 0.797290 | 0.790698 | PROGRESS: | 10 | 17 | 0.250000 | 1.812273 | 0.875456 | 0.767442 | PROGRESS: +-----------+----------+-----------+--------------+-------------------+---------------------+ ###Markdown Apply the deep features model to first few images of test set ###Code image_test[0:3]['image'].show() deep_features_model.predict(image_test[0:3]) ###Output _____no_output_____ ###Markdown The classifier with deep features gets all of these images right! Compute test_data accuracy of deep_features_modelAs we can see, deep features provide us with significantly better accuracy (about 78%) ###Code deep_features_model.evaluate(image_test) ###Output _____no_output_____
notebooks/VAE_training_hydraulic_faults.ipynb
###Markdown Imports ###Code %reload_ext autoreload %autoreload 2 %matplotlib inline from VAE1D import * from IPython.core.debugger import set_trace ###Output _____no_output_____ ###Markdown Define train function in notebook due to import namespace difficulties. ###Code def train_VAE1D(dl): """ Execute the training loop """ loss_tracker = AvgTracker() kl_tracker = AvgTracker() logp_tracker = AvgTracker() timer = StopWatch() freq = min(log_freq, len(dl)) for i, (X, _) in enumerate(tqdm(dl)): X = X.to(device) timer.lap() # load time # Generate transient and compute loss X_hat, mu, logvar = model(X) loss, loss_desc = criterion(X_hat, X, mu, logvar) timer.lap() # gen time loss_tracker.update(loss.item()) kl_tracker.update(loss_desc['KL'].item()) logp_tracker.update(loss_desc['logp'].item()) if model.training: # Update weights optimizer.zero_grad() loss.backward() optimizer.step() timer.lap() # backprop time if ((i + 1) % freq == 0) and ((epoch + 1) % ep_freq == 0): # Print progress if model.training: print('TRAINING') else: print('VALIDATION') print(f'Epoch: {epoch + 1} ({i + 1}/{len(dl)})') print(f'\tData load time: {timer.elapsed[0]:.3f} sec') print(f'\tGeneration time: {timer.elapsed[1]:.3f} sec') if model.training: print(f'\tBackprop time: {timer.elapsed[2]:.3f} sec') print(f'\tLog probability: {logp_tracker.val:.4f} ' f'(avg {logp_tracker.avg:.4f})') print(f'\tKL: {kl_tracker.val:.4f} (avg {kl_tracker.avg:.4f})') print(f'\tLoss: {loss_tracker.val:.4f} (avg {loss_tracker.avg:.4f})') return loss_tracker.avg, kl_tracker.avg, logp_tracker.avg ###Output _____no_output_____ ###Markdown Accumulator Build model and loss function Initially designed for 2D input images, modified for 1D time-series data.Based on this paper: https://arxiv.org/abs/1807.01349 ###Code # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) model beta = 1 # KL term relative weight criterion = VAE1DLoss(beta) ###Output _____no_output_____ ###Markdown Load hydraulic test dataFrom this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems ###Code desc = 'accumulator' data_path = Path(f'data/hydraulic/{desc}/') batch_size = 32 train_dl, val_dl, test_dl = load_datasets(data_path, batch_size=batch_size) print(len(train_dl), len(val_dl), len(test_dl)) ###Output 27 7 1157 ###Markdown Prepare for training ###Code # Display settings - TODO add Visdom logging log_freq = 15 # batches ep_freq = 10 # epochs # Training parameters epochs = 300 lr = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ###Output _____no_output_____ ###Markdown Train the model ###Code # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}-{beta}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ###Output 100%|██████████| 27/27 [00:01<00:00, 21.96it/s] 100%|██████████| 7/7 [00:00<00:00, 25.75it/s] 0%| | 0/27 [00:00<?, ?it/s] ###Markdown Cooler Build model and loss function Initially designed for 2D input images, modified for 1D time-series data.Based on this paper: https://arxiv.org/abs/1807.01349 ###Code # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) beta = 1 # KL term relative weight criterion = VAE1DLoss(beta) ###Output _____no_output_____ ###Markdown Load hydraulic test dataFrom this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems ###Code desc = 'cooler' data_path = Path(f'data/hydraulic/{desc}/') batch_size = 32 train_dl, val_dl, test_dl = load_datasets(data_path, batch_size=batch_size) print(len(train_dl), len(val_dl), len(test_dl)) ###Output 28 7 1100 ###Markdown Prepare for training ###Code # Display settings - TODO add Visdom logging log_freq = 15 # batches ep_freq = 10 # epochs # Training parameters epochs = 300 lr = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ###Output _____no_output_____ ###Markdown Train the model ###Code # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}-{beta}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ###Output 100%|██████████| 28/28 [00:01<00:00, 22.75it/s] 100%|██████████| 7/7 [00:00<00:00, 24.74it/s] 0%| | 0/28 [00:00<?, ?it/s] ###Markdown Pump Build model and loss function Initially designed for 2D input images, modified for 1D time-series data.Based on this paper: https://arxiv.org/abs/1807.01349 ###Code # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) beta = 1 # KL term relative weight criterion = VAE1DLoss(beta) ###Output _____no_output_____ ###Markdown Load hydraulic test dataFrom this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems ###Code desc = 'pump' data_path = Path(f'data/hydraulic/{desc}/') batch_size = 32 train_dl, val_dl, test_dl = load_datasets(data_path, batch_size=batch_size) print(len(train_dl), len(val_dl), len(test_dl)) ###Output 33 9 920 ###Markdown Prepare for training ###Code # Display settings - TODO add Visdom logging log_freq = 15 # batches ep_freq = 10 # epochs # Training parameters epochs = 300 lr = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ###Output _____no_output_____ ###Markdown Train the model ###Code # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}-{beta}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ###Output 100%|██████████| 33/33 [00:01<00:00, 23.03it/s] 100%|██████████| 9/9 [00:00<00:00, 27.72it/s] 0%| | 0/33 [00:00<?, ?it/s] ###Markdown Valve Build model and loss function Initially designed for 2D input images, modified for 1D time-series data.Based on this paper: https://arxiv.org/abs/1807.01349 ###Code # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) beta = 1 # KL term relative weight criterion = VAE1DLoss(beta) ###Output _____no_output_____ ###Markdown Load hydraulic test dataFrom this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems ###Code desc = 'valve' data_path = Path(f'data/hydraulic/{desc}/') batch_size = 32 train_dl, val_dl, test_dl = load_datasets(data_path, batch_size=batch_size) print(len(train_dl), len(val_dl), len(test_dl)) ###Output 38 10 720 ###Markdown Prepare for training ###Code # Display settings - TODO add Visdom logging log_freq = 15 # batches ep_freq = 10 # epochs # Training parameters epochs = 300 lr = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ###Output _____no_output_____ ###Markdown Train the model ###Code # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}-{beta}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ###Output 100%|██████████| 38/38 [00:01<00:00, 23.20it/s] 100%|██████████| 10/10 [00:00<00:00, 30.02it/s] 0%| | 0/38 [00:00<?, ?it/s] ###Markdown Any Fault Limited data for this, only 20% of total dataset Build model and loss function Initially designed for 2D input images, modified for 1D time-series data.Based on this paper: https://arxiv.org/abs/1807.01349 ###Code # The hydraulic system has 14 sensors from which to pull data n_channels = 14 # The data has been resized to 512, although it represents 1 min for each cycle size = 512 # Latent space is restricted to be about 1/170th of the input dims, similar to 2D case n_latent = 50 model = VAE1D(size, n_channels, n_latent) beta = 1 # KL term relative weight criterion = VAE1DLoss(beta) ###Output _____no_output_____ ###Markdown Load hydraulic test dataFrom this dataset: https://archive.ics.uci.edu/ml/datasets/Condition+monitoring+of+hydraulic+systems ###Code desc = 'any' data_path = Path(f'data/hydraulic/{desc}/') batch_size = 32 train_dl, val_dl, test_dl = load_datasets(data_path, batch_size=batch_size) print(len(train_dl), len(val_dl), len(test_dl)) ###Output 9 2 1881 ###Markdown Prepare for training ###Code # Display settings - TODO add Visdom logging log_freq = 15 # batches ep_freq = 10 # epochs # Training parameters epochs = 300 lr = 1e-3 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Checkpoint to resume from (default None) load_path = None # Checkpoint save location save_path = Path(f"models/{date.today().strftime('%y%m%d')}-{desc}/") if save_path.is_dir(): print(f"Folder {save_path} already exists") else: os.mkdir(save_path) save_path # Load checkpoint if any if load_path is not None: checkpoint = torch.load(load_path, map_location=device) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("Checkpoint loaded") print(f"Validation loss: {checkpoint['val_loss']}") print(f"Epoch: {checkpoint['epoch']}") # Load optimizer and scheduler optimizer = torch.optim.Adam(params=model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10) # Move to GPU model = model.to(device) criterion = criterion.to(device) ###Output _____no_output_____ ###Markdown Train the model ###Code # Main loop best_loss = np.inf for epoch in range(epochs): model.train() scheduler.step() train_loss, train_kl, train_logp = train_VAE1D(train_dl) model.eval() with torch.no_grad(): val_loss, val_kl, val_logp = train_VAE1D(val_dl) # Report training progress to user if val_loss < best_loss: print('Saving checkpoint..') best_loss = val_loss save_dict = {'epoch': epoch + 1, 'state_dict': model.state_dict(), 'val_loss': val_loss, 'optimizer': optimizer.state_dict()} path = save_path / f'best_model-{n_latent}-{beta}.pt' torch.save(save_dict, path) print(f'Lowest validation loss: {best_loss:.4f}') ###Output 100%|██████████| 9/9 [00:00<00:00, 14.72it/s] 100%|██████████| 2/2 [00:00<00:00, 10.04it/s] 0%| | 0/9 [00:00<?, ?it/s]
fit_generator-Velocity-data_from_internet-Validate.ipynb
###Markdown Change the variable **filenames** to data path. ###Code filenames = "GAN_flownet/data/train.tfrecords" dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.map(parser) dataset = dataset.batch(BATCH_SIZE) def generate_images(boundary_np,sflow_true, model= None): if(model != None): sflow_generated = model(boundary_np, training=True) else: sflow_generated = sflow_true sflow_plot_true =(sflow_true.numpy()).reshape([pix_dimX,pix_dimY,pix_output]) sflow_plot_generated =(sflow_generated.numpy()).reshape([pix_dimX,pix_dimY,pix_output]) # sflow_plot = np.concatenate([sflow_true, sflow_generated, sflow_true - sflow_generated], axis=1) boundary_np_plot = (boundary_np.numpy()).reshape(pix_dimX,pix_dimY) boundary_concat = np.concatenate([boundary_np_plot.reshape(1,128,256,1)], axis=2) sflow_plot_true = np.sqrt(np.square(sflow_plot_true[:,:,0]) + np.square(sflow_plot_true[:,:,1]))#- 0.5*boundary_concat[0,:,:,0] sflow_plot_generated = np.sqrt(np.square(sflow_plot_generated[:,:,0]) + np.square(sflow_plot_generated[:,:,1]))#- 0.5*boundary_concat[0,:,:,0] display_list = [boundary_np_plot, sflow_plot_true,sflow_plot_generated] title = ['Input Image', 'Ground Truth', 'Predicted Image'] # display it plt.figure(figsize=(15,15)) for i in range(3): plt.subplot(1, 3, i+1) plt.title(title[i]) # getting the pixel values between [0, 1] to plot it. plt.imshow(display_list[i], cmap = 'gray') # plt.axis('off') plt.show() #Note here ground and predicted are same beause model is not initiated and is an hack to avoid runtime failure. for i,o in dataset.take(10): generate_images(i,o) ###Output _____no_output_____ ###Markdown Architecture of GAN model ###Code #refer pix2pix tutorial def downsample(filters, size, apply_batchnorm=True): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) if apply_batchnorm: result.add(tf.keras.layers.BatchNormalization()) result.add(tf.keras.layers.LeakyReLU()) return result def upsample(filters, size, apply_dropout=False): initializer = tf.random_normal_initializer(0., 0.02) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False)) result.add(tf.keras.layers.BatchNormalization()) if apply_dropout: result.add(tf.keras.layers.Dropout(0.5)) result.add(tf.keras.layers.ReLU()) return result def Generator(): inputs = tf.keras.layers.Input(shape=[pix_dimX,pix_dimY,pix_input], name = 'adityab') down_stack = [ downsample(64, 4, apply_batchnorm=False), downsample(128, 4), downsample(256, 4), downsample(512, 4), downsample(512, 4), downsample(512, 4), # downsample(512, 4), downsample(512, 4), ] up_stack = [ # upsample(512, 4, apply_dropout=True), upsample(512, 4, apply_dropout=True), upsample(512, 4, apply_dropout=True), upsample(512, 4), # (bs, 16, 16, 1024) upsample(256, 4), # (bs, 32, 32, 512) upsample(128, 4), # (bs, 64, 64, 256) upsample(64, 4), # (bs, 128, 128, 128) ] initializer = tf.random_normal_initializer(0., 0.02) last = tf.keras.layers.Conv2DTranspose(pix_output, 4, strides=2, padding='same', kernel_initializer=initializer, activation='tanh') x = inputs # Downsampling through the model skips = [] for down in down_stack: x = down(x) skips.append(x) skips = reversed(skips[:-1]) # Upsampling and establishing the skip connections for up, skip in zip(up_stack, skips): x = up(x) x = tf.keras.layers.Concatenate()([x, skip]) x = last(x) return tf.keras.Model(inputs=inputs, outputs=x) generator = Generator() generator.summary() tf.keras.utils.plot_model(generator, show_shapes=True, dpi=64) ###Output _____no_output_____ ###Markdown Optimizers ###Code generator_optimizer = tf.keras.optimizers.Adam()# tf.keras.optimizers.Adam(2e-4, beta_1=0.5) ###Output _____no_output_____ ###Markdown Loss function and train ###Code # loss function is tested using total_gen_loss= tf.constant(0.) and tf.constant(1.) #from tensorflow.keras import backend def loss_function_generator(y_pred, y_true): total_gen_loss = tf.reduce_mean(tf.abs(y_true - y_pred)) return total_gen_loss ###Output _____no_output_____ ###Markdown Load old weights (if aplicable) ###Code #generator.load_weights('checkpoints\GAN_without_discriminator\gan_without_discrminator_car_weghits') ###Output _____no_output_____ ###Markdown Compile and fit ###Code generator.compile(optimizer= generator_optimizer, loss =loss_function_generator) Epochs =100 def train(): setEpochs = int(Epochs/10) for i in range(0,setEpochs): generator.fit(dataset, epochs = setEpochs) generator.save_weights('checkpoints\VanGogh_Fit_generator_Velocity\VanGogh_weghits') for inputI,outputI in dataset.take(5): generate_images(inputI,outputI,generator) train() for inputI,outputI in dataset.take(5): generate_images(inputI,outputI,generator) generator.save('checkpoints/VanGogh_Fit_generator_Velocity/complete_Model/Vangogh_generator_car.h5') generator.save_weights('checkpoints\VanGogh_Fit_generator_Velocity\gan_without_discrminator_car_weghits') ###Output _____no_output_____
notebooks/geo_visualisation.ipynb
###Markdown Interactive geographical visualisation of MONROE data FeaturesThis notebook enables on-demand visualisation of data collected with MONROE platform on a geographical map. It provides the following features:* Fast visualisation of multiple parameters of data collected on MONROE nodes along the geographical dimensions.* Adaptive granularity, where the data resolution is adjusted by the user.* Selection and on-disk storage of visualised data for further analysis in Orange data mining toolbox. Prerequisites Database accessCassandra DB used for the central MONROE data repository is a no-SQL database inappropriate for time-series data mining. Instead, this notebook requires that the data is stored in an Influx DB accessible from the machine where this script is run. Influx DB is a database that __[performs up to 168 times faster for certain queries than Cassandra DB](https://www.influxdata.com/blog/influxdb-vs-cassandra-time-series/)__. To create a replica of MONROE data on your local Influx DB: > 1) Create recipes for loading and naming MONROE data tables and their attributes that you plan to have in your local database. __[Example recipes](https://github.com/ivek1312/ricercando/tree/master/scripts/recipes)__.> 2) Download __[MONROE daily dump CSV files](https://www.monroe-system.eu/user/dailyDumps/)__ of tables for which the recepies are present and for dates for which you would like to have data in your local database.> 3) Run cassandra_dump_to_line_protocol.sh as __[per instructions](https://github.com/ivek1312/ricercando/tree/master/scripts)__. Python packagesThe notebook requires the following Python packages:* **ricercando** - this package is bundled in __[RICERCANDO repository](https://github.com/ivek1312/ricercando)__ and can be installed with ```pip install -e ."``` ran in the repository's root directory. Known issues* Plotting measurements sampled at one second intervalcan be very slow or can crash you browser. Analysis flowPlease run the following cells one after another, starting with the pre-initialisation cells. Pre-initialisation ###Code # Set to database IP. This must be reachable from the machine where this script is ran. DB_IP='192.168.27.75' # DB_IP='localhost' #load with this parameters #jupyter notebook --NotebookApp.iopub_data_rate_limit=10000000000 #problem with zoom https://github.com/ioam/geoviews/issues/111 #pip install --user --pre -i https://pypi.anaconda.org/bokeh/channel/dev/simple bokeh==0.12.14dev6 --extra-index-url https://pypi.python.org/simple/ import holoviews as hv import param, paramnb import pandas as pd from colorcet import cm #pip install colorcet import numpy as np from bokeh.models import HoverTool from bokeh.models import WMTSTileSource from operator import itemgetter from cartopy import crs as ccrs #https://stackoverflow.com/questions/41675041/bokeh-time-series-plot-annotation-is-off-by-1-hour/41698735 #https://github.com/bokeh/bokeh/issues/5499 #https://github.com/bokeh/bokeh/issues/1135 #https://github.com/bokeh/bokeh/issues/729 #https://github.com/bokeh/bokeh/issues/1103 hv.notebook_extension('bokeh', width=100) from ricercando import set_connection_params, all_tables, all_nodes, getdf, tables_for_node, nodes_for_table from ricercando.db import _CATEGORICAL_COLUMNS set_connection_params(host=DB_IP) #set_connection_params(host='localhost') rtt_opts= {'Points':{'style':dict(cmap='Set3', size=2), 'plot':dict( color_index='Message', width=400, height=400, colorbar=True, tools=['hover', 'lasso_select', 'box_select']) }} #data type, if df doesnt coontain these valuse, fill them with appropriate NA values => 'None' if categorical, zero if continous values = {} categorical = list(_CATEGORICAL_COLUMNS) continous = ['Altitude', 'SatelliteCount', 'Speed', 'RTT', 'BootCounter', 'CPU_Apps', 'CPU_User', 'CumUptime', 'Swap', 'Uptime', 'RSCP','RSRP','RSRQ','RSSI', 'Temperature', 'IOWait', 'TCPCbytesAll','TCPSbytesAll','TCPDuration','TCPCRTTAVG','TCPCRTTSTD','TCPCPktsRetx','TCPCPktsOOO','TCPSPktsRetx','TCPSPktsOOO', 'Download','Upload','RTTClient','RTTServer','Status' 'UDPCbytesAll','UDPSbytesAll','UDPCDurat','UDPSDurat', 'TCPGoodPutUpload', 'TCPGoodPutDownload', 'UDPGoodPutUpload', 'UDPGoodPutDownload'] for val in categorical: values[val]='None' for val in continous: values[val]=0 values['RTT']=-50 #nans not plotted, lets visualize that with -50 kdims=['Longitude','Latitude'] #all tables from dataframe tables = 'ping gps modem event sensor nettest tcpcomplete udpcomplete' import geoviews as gv from bokeh.tile_providers import STAMEN_TONER tiles = {'OpenMap': WMTSTileSource(url='http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png'), 'ESRI': WMTSTileSource(url='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'), 'Wikipedia': WMTSTileSource(url='https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png'), 'StamenToner': STAMEN_TONER} tile_options = dict(width=600,height=600, xaxis=None,yaxis=None,bgcolor='white',show_grid=True) #changes the html object when another column is selected, it si not possible to draw to same graph with different axes def render(obj): renderer = hv.renderer('bokeh') plot = renderer.get_plot(obj) size = renderer.get_size(plot) #return renderer.figure_data(plot), size #bokeh older than 0.12.10 and holoview older than 1.9.0 return renderer._figure_data(plot), size def fixVals(df): tmp = df.copy() for val in categorical: #categorical data have nan and can't be shown if nan is not set to some new categirical value=>'None' if val in tmp.columns: tmp[val] = tmp[val].cat.add_categories("None") else: tmp[val] = np.nan for val in continous: if val not in tmp.columns: tmp[val] = np.nan return tmp.fillna(value=values) # Classes for data exploration class DateExplorer(hv.streams.Stream): output = paramnb.view.HTML(renderer=render) Node = param.ObjectSelector(default='582', objects=nodes_for_table()['gps'], precedence=5) Day = param.ObjectSelector(default='01', objects=["%.2d" % i for i in range(1,32)], precedence=1) Month = param.ObjectSelector(default='01', objects=["%.2d" % i for i in range(1,13)],precedence=2) Year = param.Integer(default=2018, bounds=(2016, 2018),precedence=3) Coloring = param.ObjectSelector(default='RTT', objects=continous+categorical, precedence=4) Colormap = param.ObjectSelector(default=cm['linear_bmy_10_95_c71'], objects=cm.values()) Sampling = param.ObjectSelector(default='1m', objects=['30m','1m','1s']) MapTile = param.ObjectSelector(default="OpenMap", objects=['OpenMap','ESRI','Wikipedia','StamenToner']) data = [] callbacks = [] def retData(self): return pd.concat([d[1].iloc[c.index] for d,c in zip(self.data,self.callbacks)]) class CallbackClass(object): def __init__(self): self.index=None def callback(self, index): self.index = index return hv.Overlay([]) def event(self, **kwargs): if self.output is None or 'Day' in kwargs or 'Month' in kwargs or 'Year' in kwargs or 'Node' in kwargs or 'Coloring' in kwargs or 'Colormap' in kwargs or 'MapTile' in kwargs or 'Sampling' in kwargs: df = getdf(tables, nodeid=self.Node, start_time='{0}-{1}-{2} 00:00:00'.format(self.Year, self.Month, self.Day), end_time='{0}-{1}-{2} 23:59:59'.format(self.Year, self.Month, self.Day), freq=self.Sampling) if df.empty or 'Iccid' not in df.columns: self.output = hv.Points(pd.DataFrame([[0,0]], columns=kdims), kdims=kdims,vdims=[], label='Empty dataframe').opts(rtt_opts); return iccidGroups = [(iccid,group.reset_index()) for iccid,group in df.groupby('Iccid') if all(x in group.columns for x in ['Latitude', 'Longitude', self.Coloring ]) and group.Latitude.notnull().any() and group.Longitude.notnull().any() and group[self.Coloring].notnull().any() ] if not iccidGroups: self.output = hv.Points(pd.DataFrame([[0,0]], columns=kdims), kdims=kdims,vdims=[],label='GPS or '+self.Coloring+' missing.').opts(rtt_opts); return iccidGroups = sorted(iccidGroups, key=itemgetter(0)) iccidGroups4plot = [ (iccid,fixVals(group)) for iccid,group in iccidGroups] self.data = iccidGroups rtt_opts['Points']['plot']['color_index']=self.Coloring rtt_opts['Points']['style']['cmap']=self.Colormap HVpoints = [ gv.Points(group, kdims=kdims, vdims=categorical+continous, label=iccid).opts(rtt_opts ) for iccid,group in iccidGroups4plot] streams4points = [hv.streams.Selection1D(source=points) for points in HVpoints] self.callbacks = [self.CallbackClass() for point in HVpoints] dmaps = [hv.DynamicMap(callback.callback ,kdims=[], streams=[selection]) for callback,selection in zip(self.callbacks,streams4points)] self.output = hv.Layout([point*dmap*gv.WMTS(tiles[self.MapTile]) for point,dmap in zip(HVpoints,dmaps)]).cols(2) else: super(DateExplorer, self).event( **kwargs) class GPSPlot(object): def __init__(self): self.explorer = DateExplorer() paramnb.Widgets(self.explorer, continuous_update=True, callback=self.explorer.event, on_init=True) def retData(self): return self.explorer.retData() ###Output _____no_output_____ ###Markdown Visualisation initalisation and interactionRunning the cell below should produce a node/date/parameter selector and geographical plots of these -- one plot for each of the node's interfaces.If you want to visualise data from multiple nodes simultaneously, simply copy the cell, rename the variable (say to ```plot2```) and run it, as shown in the example below. Interactive visualisationThe visualisation widget allows the user to:* Select the date (day, month, year) for which the data will be shown. * Select the node whose data will be visualised.* Select the parameter that will correspond to the coloring of the plotted points. * Select the colormap.The data is initially always shown on a 24-hour plot and for all interfaces on the selected node (plot title corresponds to the interface ICCID). However, the user can zoom in to a particular region on the plot, in which case all plots are zoomed in simultaneously. ###Code plot1 = GPSPlot() # plot2 = GPSPlot() ###Output _____no_output_____ ###Markdown Data selection and storageData can be selected with Lasso select or Box select on a plot. Calling ```retData()``` function of the ```GPSPlot``` object returns a data frame that corresponds to the selected data as in the example below. ###Code df_selected = plot1.retData()[['Iccid', 'Latitude','Longitude','RSSI']] ###Output _____no_output_____ ###Markdown The selected data can now be stored on a local disk and loaded in Orange using the iPython connector widget from the MONROE toolbox. ###Code # Stores the df_selected dataframe to a local disk. %store df_selected ###Output _____no_output_____
samples/contrib/mnist/00_Kubeflow_Cluster_Setup.ipynb
###Markdown Deploying a Kubeflow Cluster on Google Cloud Platform (GCP)This notebook provides instructions for setting up a Kubeflow cluster on GCP using the command-line interface (CLI). For additional help, see the guide to [deploying Kubeflow using the CLI](https://www.kubeflow.org/docs/gke/deploy/deploy-cli/).There are two possible alternatives:- The first alternative is to deploy Kubeflow cluster using the [Kubeflow deployment web app](https://deploy.kubeflow.cloud/), and the instruction can be found [here](https://www.kubeflow.org/docs/gke/deploy/deploy-ui/).- Another alternative is to use recently launched [AI Platform Pipeline](https://cloud.google.com/ai-platform/pipelines/docs/introduction). But, it is important to note that the AI Platform Pipeline is a standalone [Kubeflow Pipeline](https://www.kubeflow.org/docs/pipelines/overview/pipelines-overview/) deployment, where a lot of the components in full Kubeflow deployment won't be pre-installed. The instruction can be found [here](https://cloud.google.com/ai-platform/pipelines/docs/setting-up).The CLI deployment gives you more control over the deployment process and configuration than you get if you use the deployment UI. Prerequisites- You have a [GCP project setup](https://www.kubeflow.org/docs/gke/deploy/project-setup/) for your Kubeflow Deployment with you having the [owner role](https://cloud.google.com/iam/docs/understanding-rolesprimitive_role_definitions) for the project and with the following APIs enabled: - [Compute Engine API](https://pantheon.corp.google.com/apis/library/compute.googleapis.com) - [Kubernetes Engine API](https://pantheon.corp.google.com/apis/library/container.googleapis.com) - [Identity and Access Management(IAM) API](https://pantheon.corp.google.com/apis/library/iam.googleapis.com) - [Deployment Manager API](https://pantheon.corp.google.com/apis/library/deploymentmanager.googleapis.com) - [Cloud Resource Manager API](https://pantheon.corp.google.com/apis/library/cloudresourcemanager.googleapis.com) - [AI Platform Training & Prediction API](https://pantheon.corp.google.com/apis/library/ml.googleapis.com)- You have set up [OAuth for Cloud IAP](https://www.kubeflow.org/docs/gke/deploy/oauth-setup/)- You have installed and setup [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)- You have installed [gcloud-sdk](https://cloud.google.com/sdk/) Running Environment**This notebook helps in creating the Kubeflow cluster on GCP. You must run this notebook in an environment with Cloud SDK installed, such as Cloud Shell. Learn more about [installing Cloud SDK](https://cloud.google.com/sdk/docs/).** Setting up a Kubeflow cluster1. Download kfctl2. Setup environment variables3. Create dedicated service account for deployment4. Deploy Kubefow5. Install Kubeflow Pipelines SDK6. Sanity check Create a working directoryCreate a new working directory in your current directory. The default name is **kubeflow**, but you can change the name. ###Code work_directory_name = 'kubeflow' ! mkdir -p $work_directory_name %cd $work_directory_name ###Output _____no_output_____ ###Markdown Download kfctlDownload kfctl to your working directory. The default version used is v0.7.0, but you can find the latest release [here](https://github.com/kubeflow/kubeflow/releases). ###Code ## Download kfctl v0.7.0 ! curl -LO https://github.com/kubeflow/kubeflow/releases/download/v0.7.0/kfctl_v0.7.0_linux.tar.gz ## Unpack the tar ball ! tar -xvf kfctl_v0.7.0_linux.tar.gz ###Output _____no_output_____ ###Markdown **If you are using AI Platform Notebooks**, your environment is already authenticated. Skip the following cell. ###Code ## Create user credentials ! gcloud auth application-default login ###Output _____no_output_____ ###Markdown Set up environment variablesSet up environment variables to use while installing Kubeflow. Replace variable placeholders (for example, ``) with the correct values for your environment. ###Code # Set your GCP project ID and the zone where you want to create the Kubeflow deployment %env PROJECT=<ADD GCP PROJECT HERE> %env ZONE=<ADD GCP ZONE TO LAUNCH KUBEFLOW CLUSTER HERE> # google cloud storage bucket %env GCP_BUCKET=gs://<ADD STORAGE LOCATION HERE> # Use the following kfctl configuration file for authentication with # Cloud IAP (recommended): uri = "https://raw.githubusercontent.com/kubeflow/manifests/v0.7-branch/kfdef/kfctl_gcp_iap.0.7.0.yaml" uri = uri.strip() %env CONFIG_URI=$uri # For using Cloud IAP for authentication, create environment variables # from the OAuth client ID and secret that you obtained earlier: %env CLIENT_ID=<ADD OAuth CLIENT ID HERE> %env CLIENT_SECRET=<ADD OAuth CLIENT SECRET HERE> # Set KF_NAME to the name of your Kubeflow deployment. You also use this # value as directory name when creating your configuration directory. # For example, your deployment name can be 'my-kubeflow' or 'kf-test'. %env KF_NAME=<ADD KUBEFLOW DEPLOYMENT NAME HERE> # Set up name of the service account that should be created and used # while creating the Kubeflow cluster %env SA_NAME=<ADD SERVICE ACCOUNT NAME TO BE CREATED HERE> ###Output _____no_output_____ ###Markdown Configure gcloud and add kfctl to your path. ###Code ! gcloud config set project ${PROJECT} ! gcloud config set compute/zone ${ZONE} # Set the path to the base directory where you want to store one or more # Kubeflow deployments. For example, /opt/. # Here we use the current working directory as the base directory # Then set the Kubeflow application directory for this deployment. import os base = os.getcwd() %env BASE_DIR=$base kf_dir = os.getenv('BASE_DIR') + "/" + os.getenv('KF_NAME') %env KF_DIR=$kf_dir # The following command is optional. It adds the kfctl binary to your path. # If you don't add kfctl to your path, you must use the full path # each time you run kfctl. In this example, the kfctl file is present in # the current directory new_path = os.getenv('PATH') + ":" + os.getenv('BASE_DIR') %env PATH=$new_path ###Output _____no_output_____ ###Markdown Create service account ###Code ! gcloud iam service-accounts create ${SA_NAME} ! gcloud projects add-iam-policy-binding ${PROJECT} \ --member serviceAccount:${SA_NAME}@${PROJECT}.iam.gserviceaccount.com \ --role 'roles/owner' ! gcloud iam service-accounts keys create key.json \ --iam-account ${SA_NAME}@${PROJECT}.iam.gserviceaccount.com ###Output _____no_output_____ ###Markdown Set GOOGLE_APPLICATION_CREDENTIALS ###Code key_path = os.getenv('BASE_DIR') + "/" + 'key.json' %env GOOGLE_APPLICATION_CREDENTIALS=$key_path ###Output _____no_output_____ ###Markdown Setup and deploy Kubeflow ###Code ! mkdir -p ${KF_DIR} %cd $kf_dir ! kfctl apply -V -f ${CONFIG_URI} ###Output _____no_output_____ ###Markdown Install Kubeflow Pipelines SDK ###Code %%capture # Install the SDK (Uncomment the code if the SDK is not installed before) ! pip3 install 'kfp>=0.1.36' --quiet --user ###Output _____no_output_____ ###Markdown Sanity Check: Check the ingress created ###Code ! kubectl -n istio-system describe ingress ###Output _____no_output_____
notebooks/5.0_comparing_magnifications/0.1_20x.field_thr.ipynb
###Markdown Find tentative intensity threshold for 20x datasets After filtering for FWHM in [0.5; 5] and selecting only dots in (selected) nuclei ###Code nuclear_features = fread("../../data/selected_nuclei.tsv", key=c("sid", "nid")) ddata = dots_data2[FWHM >= .5 & FWHM <= 5 & nid > 0] setkeyv(ddata, c("series_id", "nid")) ddata2 = nuclear_features[ddata][!is.na(size)] ddata3 = ddata2["20x" == magnification] ###Output _____no_output_____ ###Markdown Checking intensity and SNR density and scatter plots ###Code plist_density = pblapply(split(ddata3, list(ddata3$magnification, ddata3$image_type)), function(pdata) { p1 = ggplot(pdata, aes(x=Value2)) + geom_density() + facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + scale_x_log10() + scale_y_log10() + labs(x="Intensity") }, cl=4 ) options(repr.plot.width=21, repr.plot.height=8) plot_grid(plotlist=plist_density, nrow=2) plist_density = pblapply(split(ddata3, list(ddata3$magnification, ddata3$image_type)), function(pdata) { p1 = ggplot(pdata, aes(x=SNR2)) + geom_density() + facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + scale_x_log10() + scale_y_log10() + labs(x="SNR") }, cl=4 ) options(repr.plot.width=21, repr.plot.height=8) plot_grid(plotlist=plist_density, nrow=2) plist = pblapply(split(ddata3, list(ddata3$magnification, ddata3$image_type)), function(pdata) { p1 = ggplot(pdata, aes(x=SNR2, y=Value2)) + geom_scattermore() + facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + scale_x_log10() + scale_y_log10() + labs(x="SNR", y="Intensity") }, cl=4 ) options(repr.plot.width=21, repr.plot.height=8) plot_grid(plotlist=plist, nrow=2) ###Output |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=06s ###Markdown Field-based thresholds ###Code thr_table = rbindlist(list( data.table( image_type="dw", magnification="20x", sid=1:7, thr=c(11, 12, 11, 11, 10.5, 11, 12) ), data.table( image_type="raw", magnification="20x", sid=1:7, thr=c(.095, .095, .085, .085, .092, .092, .096) ) )) #threshold = .096 #selected_sid = 7 #pdata = ddata3["20x"==magnification&"raw"==image_type&selected_sid==sid] #p1 = ggplot(pdata, aes(x=Value2)) + geom_density() + # geom_vline(xintercept=threshold, color="red") + # facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + # scale_x_log10() + scale_y_log10() + labs(x="Intensity") #p2 = ggplot(pdata, aes(x=SNR2, y=Value2)) + geom_scattermore() + # geom_hline(yintercept=threshold, color="red") + # facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + # scale_x_log10() + scale_y_log10() + labs(x="SNR", y="Intensity") #options(repr.plot.width=12, repr.plot.height=6) #plot_grid(p1, p2, nrow=1) plist_density = pblapply(split(ddata3, list(ddata3$magnification, ddata3$image_type)), function(pdata) { selected_magnification = pdata[1, magnification] selected_image_type = pdata[1, image_type] selected_thresholds = thr_table[magnification == selected_magnification & image_type == selected_image_type,] p1 = ggplot(pdata, aes(x=Value2)) + geom_density() + geom_vline(data=selected_thresholds, aes(xintercept=thr), color="red") + facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + scale_x_log10() + scale_y_log10() + labs(x="Intensity") }, cl=4 ) options(repr.plot.width=21, repr.plot.height=8) plot_grid(plotlist=plist_density, nrow=2) plist = pblapply(split(ddata3, list(ddata3$magnification, ddata3$image_type)), function(pdata) { selected_magnification = pdata[1, magnification] selected_image_type = pdata[1, image_type] selected_thresholds = thr_table[magnification == selected_magnification & image_type == selected_image_type,] p1 = ggplot(pdata, aes(x=SNR2, y=Value2)) + geom_scattermore() + geom_hline(data=selected_thresholds, aes(yintercept=thr), color="red") + facet_wrap(~image_type~magnification~sid, nrow=1, scales="free") + theme_bw() + scale_x_log10() + scale_y_log10() + labs(x="SNR", y="Intensity") }, cl=4 ) options(repr.plot.width=21, repr.plot.height=8) plot_grid(plotlist=plist, nrow=2) fwrite(thr_table, "../../data/magnifications_matching/intensity_thresholds.by_field.tsv", sep="\t") ###Output _____no_output_____
ML_27.ipynb
###Markdown Data Science and Machine learning in PythonInstructor: Atish Adhikari Auto Encoders ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Input from tensorflow.keras.datasets import mnist (X_train, _ ), (X_test, _) = mnist.load_data() X_train = X_train.reshape(60000, 28*28) / 255 input_layer = Input(shape=(784, )) encoder_layer = Dense(units=400, activation="relu") (input_layer) encoder_layer = Dense(units=200, activation="relu") (encoder_layer) encoder_layer = Dense(units=100, activation="relu") (encoder_layer) middle = Dense(units=50, activation="sigmoid") (encoder_layer) decoder_layer = Dense(units=150, activation="relu") (middle) decoder_layer = Dense(units=450, activation="relu") (decoder_layer) output_layer = Dense(units=784, activation="sigmoid") (decoder_layer) auto_encoder = Model(inputs=input_layer, outputs=output_layer) auto_encoder.compile(loss="mse", optimizer="adam") auto_encoder.fit(X_train, X_train, epochs=5) encoder = Model(inputs=input_layer, outputs=middle) encoder.compile(loss="mse", optimizer="adam") X_compressed = encoder.predict(X_train) X_compressed.shape plt.imshow(X_compressed[0].reshape(5, 10), cmap="binary_r") plt.show() auto_encoder.layers decoder_input = Input(shape=(50,)) decoder_1 = auto_encoder.layers[-3] (decoder_input) decoder_2 = auto_encoder.layers[-2] (decoder_1) decoder_output = auto_encoder.layers[-1] (decoder_2) decoder = Model(decoder_input, decoder_output) decoder.compile(loss="mse", optimizer="adam") X_reconstructed = decoder.predict(X_compressed) X_reconstructed.shape plt.figure(figsize=(8, 10)) plt.subplot(1,3,1) plt.imshow(X_train[1].reshape(28,28), cmap="binary_r") plt.subplot(1,3,2) plt.imshow(X_compressed[1].reshape(5,10), cmap="binary_r") plt.subplot(1,3,3) plt.imshow(X_reconstructed[1].reshape(28,28), cmap="binary_r") plt.show() ###Output _____no_output_____
Examples/Cats/Cats.ipynb
###Markdown Benchmarking ###Code @btime neural_network_dense($train_data_x, $train_data_y_orig, $layer_dims, 100, 0.0075) @btime initialize_parameters($layer_dims, $train_data_y_orig) parameters = initialize_parameters(layer_dims, train_data_y_orig) activations = (relu, sigmoid) y, caches = forward_prop(train_data_x, parameters, activations) print() @btime forward_prop($train_data_x, $parameters, $activations) y_orig = Array{Float32, 2}(train_data_y_orig) cost = cost_binary(y_orig, y) @btime cost_binary($y_orig, $y) activations_back = (relu_back, sigmoid_back) grads = backward_prop(y_orig, y, parameters, caches, layer_dims, activations_back) @btime backward_prop($y_orig, $y, $parameters, $caches, $layer_dims, $activations_back) learning_rate = 0.000001 parameters = update_parameters(parameters, grads, layer_dims, learning_rate) @btime update_parameters($parameters, $grads, $layer_dims, $learning_rate) @btime neural_network_dense($train_data_x, $train_data_y_orig, $layer_dims, 1, 0.0075) ###Output 5.981 ms (350 allocations: 14.45 MiB)
homework_1-ANN/[HW1-1] Polynomial Approximation.ipynb
###Markdown AI502/KSE527, Homework 01 This file is made by Jaehoon Oh, which is modified based on https://github.com/floydhub/regression ###Code import torch import torch.nn as nn import torch.utils.data # plotting libraries import numpy as np import matplotlib.pyplot as plt POLY_DEGREE = 4 torch.manual_seed(2020) W_target = torch.randn(POLY_DEGREE, 1) * 5 b_target = torch.randn(1) * 5 def poly_desc(W, b): """Creates a string description of a polynomial.""" result = 'y = ' for i, w in enumerate(W): result += '{:+.2f} x^{} '.format(w, len(W) - i) result += '{:+.2f}'.format(b[0]) return result print('==> The real function you should approximate:\t' + poly_desc(W_target.view(-1), b_target)) ###Output ==> The real function you should approximate: y = +6.19 x^4 -4.80 x^3 +7.71 x^2 -2.04 x^1 +4.40 ###Markdown --- ###Code def make_features(x): """Builds features i.e. a matrix with columns [x^4, x^3, x^2, x^1].""" x = x.unsqueeze(1) return torch.cat([x ** (POLY_DEGREE+1-i) for i in range(1, POLY_DEGREE+1)], 1) def f(x): """Approximated function.""" return x.mm(W_target) + b_target[0] def get_dataset(dataset_size): """Builds a batch i.e. (x, f(x)) pair.""" random = torch.randn(dataset_size) x = make_features(random) y = f(x) dataset = list(zip(x, y)) return dataset dataset = get_dataset(200) # you can make as many as dataset as you want # # debug # print("W_target: \n") print(W_target) print("\n") print("b_target: \n") print(b_target) print("\n") print("dataset: \n") print(dataset) def compute_results(x, w, bias): x = make_features(x) return torch.squeeze(x.mm(w) + bias[0]) print(W_target) compute_results(torch.linspace(-10, 10, steps=1000), W_target, b_target) def plot_graphs(W_target, b_target, W_learned, b_learned, epoch_num): x = torch.linspace(-10, 10, steps=1000) fig = plt.figure(figsize=(10, 5)) #plt.subplot(1, 2, 1) #plt.ylim(ymax = 100, ymin = -10) #plt.xlim(xmax = 10, xmin = -10) plt.title("Function plot - epoch number: {}".format(epoch_num)) plt.xlabel("x-axis") plt.ylabel("y-axis") plt.grid() plt.plot(x.numpy(), compute_results(torch.linspace(-10, 10, steps=1000), W_target, b_target).numpy(), label="Actual function") plt.plot(x.numpy(), compute_results(x, torch.unsqueeze(torch.squeeze(W_learned), 1), b_learned), label="Learned function") plt.legend() plt.show() #plot_graphs(W_target, b_target, net.fc.weight.data, net.fc.bias.data) #print(net.fc.weight.data) ###Output _____no_output_____ ###Markdown --- ###Code num_epochs = 500 batch_size = 50 learning_rate = 0.001 criterion = nn.SmoothL1Loss() dataset_loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True) ###Output _____no_output_____ ###Markdown --- ###Code class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc = nn.Linear(W_target.size(0), 1) # For fixing the initial weights and bias self.fc.weight.data.fill_(0.) self.fc.bias.data.fill_(0.) def forward(self, x): output = self.fc(x) return output ###Output _____no_output_____ ###Markdown --- ###Code def fit(model,loader,criterion,learning_rate,num_epochs, graphs=False): model.train() optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) loss_list = [] for epoch in range(num_epochs): accum_loss = 0 num_batch = 0 for i, data in enumerate(loader): if torch.cuda.is_available(): x = data[0].type(torch.FloatTensor).cuda() y = data[1].type(torch.FloatTensor).cuda() else: x = data[0].type(torch.FloatTensor) y = data[1].type(torch.FloatTensor) y_hat = model(x) loss = criterion(y_hat, y) accum_loss += loss.item() num_batch += 1 optimizer.zero_grad() loss.backward() optimizer.step() loss_list.append(accum_loss/num_batch) if graphs==True and (epoch+1) in [5,10,20,100,200, 500]: plot_graphs(W_target, b_target, model.fc.weight.data, model.fc.bias.data, epoch+1) print('==> Learned function:\t' + poly_desc(model.fc.weight.data.view(-1), model.fc.bias.data)) print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target)) return loss_list ###Output _____no_output_____ ###Markdown --- ###Code net = Net().cuda() if torch.cuda.is_available() else Net() print('==> Initial function:\t' + poly_desc(net.fc.weight.data.view(-1), net.fc.bias.data)) print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target)) # train loss_list = fit(net,dataset_loader,criterion,learning_rate,num_epochs, graphs=True) print('==> Learned function:\t' + poly_desc(net.fc.weight.data.view(-1), net.fc.bias.data)) print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target)) fig = plt.figure(figsize=(10, 5)) plt.title("Loss function - Learning rate: {}".format(learning_rate)) plt.xlabel("epoch") plt.ylabel("loss") plt.grid() plt.plot(list(range(num_epochs)), loss_list) plt.show() ###Output _____no_output_____
doc/_build/html/_downloads/plot_skope_rules.ipynb
###Markdown SkopeRules exampleAn example using SkopeRules for imbalanced classification.SkopeRules find logical rules with high precision and fuse them. Finding goodrules is done by fitting classification and regression trees to sub-samples.A fitted tree defines a set of rules (each tree node defines a rule); rulesare then tested out of the bag, and the ones with higher precision are selectedand merged. This produces a real-valued decision function, reflecting foreach new sample how many rules (each weighted by respective precision) havefound it abnormal. ###Code import numpy as np import matplotlib.pyplot as plt from skrules import SkopeRules print(__doc__) rng = np.random.RandomState(42) n_inliers = 1000 n_outliers = 50 # Generate train data I = 0.5 * rng.randn(int(n_inliers / 2), 2) X_inliers = np.r_[I + 2, I - 2] O = 0.5 * rng.randn(n_outliers, 2) X_outliers = O # np.r_[O, O + [2, -2]] X_train = np.r_[X_inliers, X_outliers] y_train = [0] * n_inliers + [1] * n_outliers ###Output _____no_output_____ ###Markdown Training the SkopeRules classifier.................................. ###Code # fit the model clf = SkopeRules(random_state=rng, n_estimators=10) clf.fit(X_train, y_train) # plot the line, the samples, and the nearest vectors to the plane xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50)) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Skope Rules, value of the decision_function method") plt.contourf(xx, yy, Z, cmap=plt.cm.Blues) a = plt.scatter(X_inliers[:, 0], X_inliers[:, 1], c='white', s=20, edgecolor='k') b = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red', s=20, edgecolor='k') plt.axis('tight') plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend([a, b], ["inliers", "outliers"], loc="upper left") plt.show() ###Output _____no_output_____ ###Markdown Extracting top rules....................On the 4 following figures, the predict_top_rules method is used withseveral values of n_rules. n_rules = 2 means that the prediction isdone using only the 2 best rules. ###Code print('The 4 most precise rules are the following:') for rule in clf.rules_[:4]: print(rule[0]) fig, axes = plt.subplots(2, 2, figsize=(12, 5), sharex=True, sharey=True) for i_ax, ax in enumerate(np.ravel(axes)): Z = clf.predict_top_rules(np.c_[xx.ravel(), yy.ravel()], i_ax+1) Z = Z.reshape(xx.shape) ax.set_title("Prediction with predict_top_rules, n_rules="+str(i_ax+1)) ax.contourf(xx, yy, Z, cmap=plt.cm.Blues) a = ax.scatter(X_inliers[:, 0], X_inliers[:, 1], c='white', s=20, edgecolor='k') b = ax.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red', s=20, edgecolor='k') ax.axis('tight') plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend([a, b], ["inliers", "outliers"], loc="upper left") plt.show() ###Output _____no_output_____
ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb
###Markdown Germany: LK Gifhorn (Niedersachsen)* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb) ###Code import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview(country="Germany", subregion="LK Gifhorn", weeks=5); overview(country="Germany", subregion="LK Gifhorn"); compare_plot(country="Germany", subregion="LK Gifhorn", dates="2020-03-15:"); # load the data cases, deaths = germany_get_region(landkreis="LK Gifhorn") # get population of the region for future normalisation: inhabitants = population(country="Germany", subregion="LK Gifhorn") print(f'Population of country="Germany", subregion="LK Gifhorn": {inhabitants} people') # compose into one table table = compose_dataframe_summary(cases, deaths) # show tables with up to 1000 rows pd.set_option("max_rows", 1000) # display the table table ###Output _____no_output_____ ###Markdown Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on how to use Jupyter Notebook Acknowledgements:- Johns Hopkins University provides data for countries- Robert Koch Institute provides data for within Germany- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)- Open source and scientific computing community for the data tools- Github for hosting repository and html files- Project Jupyter for the Notebook and binder service- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))-------------------- ###Code print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}") ###Output _____no_output_____ ###Markdown Germany: LK Gifhorn (Niedersachsen)* Homepage of project: https://oscovida.github.io* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb) ###Code import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview(country="Germany", subregion="LK Gifhorn"); # load the data cases, deaths, region_label = germany_get_region(landkreis="LK Gifhorn") # compose into one table table = compose_dataframe_summary(cases, deaths) # show tables with up to 500 rows pd.set_option("max_rows", 500) # display the table table ###Output _____no_output_____ ###Markdown Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on how to use Jupyter Notebook Acknowledgements:- Johns Hopkins University provides data for countries- Robert Koch Institute provides data for within Germany- Open source and scientific computing community for the data tools- Github for hosting repository and html files- Project Jupyter for the Notebook and binder service- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))-------------------- ###Code print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}") ###Output _____no_output_____ ###Markdown Germany: LK Gifhorn (Niedersachsen)* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb) ###Code import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview(country="Germany", subregion="LK Gifhorn", weeks=5); overview(country="Germany", subregion="LK Gifhorn"); compare_plot(country="Germany", subregion="LK Gifhorn", dates="2020-03-15:"); # load the data cases, deaths = germany_get_region(landkreis="LK Gifhorn") # compose into one table table = compose_dataframe_summary(cases, deaths) # show tables with up to 500 rows pd.set_option("max_rows", 500) # display the table table ###Output _____no_output_____ ###Markdown Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Gifhorn.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on how to use Jupyter Notebook Acknowledgements:- Johns Hopkins University provides data for countries- Robert Koch Institute provides data for within Germany- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)- Open source and scientific computing community for the data tools- Github for hosting repository and html files- Project Jupyter for the Notebook and binder service- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))-------------------- ###Code print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}") ###Output _____no_output_____
8 Selecting the Right Model/2. Visualizing overfitting and underfitting using knn/Underfit_Overfit_using_KNN_1.ipynb
###Markdown Importing the data ###Code data = pd.read_csv('data_cleaned.csv') data.head() data.isnull().sum() ###Output _____no_output_____ ###Markdown Segregating variables - Dependent & Independent ###Code #seperating independent and dependent variables x = data.drop(['Survived'], axis=1) y = data['Survived'] ###Output _____no_output_____ ###Markdown Scaling the data ###Code from sklearn.preprocessing import StandardScaler ss = StandardScaler() x = ss.fit_transform(x) from sklearn.model_selection import train_test_split train_x,test_x,train_y,test_y = train_test_split(x,y, random_state = 96, stratify=y) ###Output _____no_output_____ ###Markdown Implementing KNN ###Code #importing KNN classifier and metric F1score from sklearn.neighbors import KNeighborsClassifier as KNN from sklearn.metrics import f1_score # Creating instance of KNN clf = KNN(n_neighbors = 3) # Fitting the model clf.fit(train_x, train_y) # Predicting over the Train Set and calculating F1 train_predict = clf.predict(train_x) k = f1_score(train_predict, train_y) print('Training F1 Score', k ) # Predicting over the Train Set and calculating F1 test_predict = clf.predict(test_x) k = f1_score(test_predict, test_y) print('Test F1 Score ', k ) ###Output Training F1 Score 0.82092555332 Test F1 Score 0.708074534161 ###Markdown Checking the Training F1 and Test F1curve ###Code def F1score(K): ''' Takes an input K consisting of a range of K values for KNN Input: K = list Returns: lists containing F1 corresponding to every value of K train_f1 = list of train f1 score corresponding K test_f1 = list of test f1 score corresponding to K ''' # initiating empty list train_f1 = [] test_f1 = [] # training model for evey value of K for i in K: # Instance oh KNN clf = KNN(n_neighbors = i) clf.fit(train_x, train_y) # Appending F1 scores to empty list claculated using the predictions tmp = clf.predict(train_x) tmp = f1_score(tmp,train_y) train_f1.append(tmp) tmp = clf.predict(test_x) tmp = f1_score(tmp,test_y) test_f1.append(tmp) return train_f1, test_f1 #Defining K range k = range(1,150) # calling above defined function train_f1, test_f1 = F1score(k) score = pd.DataFrame({'train score': train_f1, 'test score': test_f1}, index = k) score ###Output _____no_output_____ ###Markdown Visualizing ###Code from pylab import rcParams rcParams['figure.figsize'] = 8, 6 # plotting the Curvesg plt.figure(figsize=(4,2), dpi=150) plt.plot(k[0:60], test_f1[0:60], color = 'red' , label = 'test') plt.plot(k[0:60], train_f1[0:60], color = 'green', label = 'train') plt.xlabel('K Neighbors') plt.ylabel('F1 Score') plt.title('F1 Curve') plt.ylim(0.4,1) plt.legend() ###Output _____no_output_____ ###Markdown Question Pop and Video Break Challenges with Test set ###Code from sklearn.model_selection import train_test_split train_x,test_x,train_y,test_y = train_test_split(x,y, random_state = 96, stratify = y) # calling above defined function k = range(1,50) train, test = F1score(k) # plotting the Curves plt.plot(k, test, color = 'red' , label = 'test') plt.plot(k, train, color = 'green', label = 'train') plt.xlabel('K Neighbors') plt.ylabel('F1 Score') plt.title('F1 Curve') plt.ylim(0.4,1) plt.legend() ###Output _____no_output_____
Tensorflow_linear_regression_hello_world.ipynb
###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown The Hello World of Deep Learning with Neural Networks Like every first app you should start with something super simple that shows the overall scaffolding for how your code works. In the case of creating neural networks, the sample I like to use is one where it learns the relationship between two numbers. So, for example, if you were writing code for a function like this, you already know the 'rules' — ```float hw_function(float x){ float y = (2 * x) - 1; return y;}```So how would you train a neural network to do the equivalent task? Using data! By feeding it with a set of Xs, and a set of Ys, it should be able to figure out the relationship between them. This is obviously a very different paradigm than what you might be used to, so let's step through it piece by piece. ImportsLet's start with our imports. Here we are importing TensorFlow and calling it tf for ease of use.We then import a library called numpy, which helps us to represent our data as lists easily and quickly.The framework for defining a neural network as a set of Sequential layers is called keras, so we import that too. ###Code import tensorflow as tf import numpy as np from tensorflow import keras ###Output _____no_output_____ ###Markdown Define and Compile the Neural NetworkNext we will create the simplest possible neural network. It has 1 layer, and that layer has 1 neuron, and the input shape to it is just 1 value. ###Code model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) ###Output _____no_output_____ ###Markdown Now we compile our Neural Network. When we do so, we have to specify 2 functions, a loss and an optimizer.If you've seen lots of math for machine learning, here's where it's usually used, but in this case it's nicely encapsulated in functions for you. But what happens here — let's explain...We know that in our function, the relationship between the numbers is y=2x-1. When the computer is trying to 'learn' that, it makes a guess...maybe y=10x+10. The LOSS function measures the guessed answers against the known correct answers and measures how well or how badly it did.It then uses the OPTIMIZER function to make another guess. Based on how the loss function went, it will try to minimize the loss. At that point maybe it will come up with somehting like y=5x+5, which, while still pretty bad, is closer to the correct result (i.e. the loss is lower)It will repeat this for the number of EPOCHS which you will see shortly. But first, here's how we tell it to use 'MEAN SQUARED ERROR' for the loss and 'STOCHASTIC GRADIENT DESCENT' for the optimizer. You don't need to understand the math for these yet, but you can see that they work! :)Over time you will learn the different and appropriate loss and optimizer functions for different scenarios. ###Code model.compile(optimizer='sgd', loss='mean_squared_error') ###Output _____no_output_____ ###Markdown Providing the DataNext up we'll feed in some data. In this case we are taking 6 xs and 6ys. You can see that the relationship between these is that y=2x-1, so where x = -1, y=-3 etc. etc. A python library called 'Numpy' provides lots of array type data structures that are a defacto standard way of doing it. We declare that we want to use these by specifying the values as an np.array[] ###Code xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) ###Output _____no_output_____ ###Markdown Training the Neural Network The process of training the neural network, where it 'learns' the relationship between the Xs and Ys is in the **model.fit** call. This is where it will go through the loop we spoke about above, making a guess, measuring how good or bad it is (aka the loss), using the opimizer to make another guess etc. It will do it for the number of epochs you specify. When you run this code, you'll see the loss on the right hand side. ###Code model.fit(xs, ys, epochs=500) ###Output Epoch 1/500 1/1 [==============================] - 0s 426ms/step - loss: 42.2953 Epoch 2/500 1/1 [==============================] - 0s 7ms/step - loss: 33.6400 Epoch 3/500 1/1 [==============================] - 0s 8ms/step - loss: 26.8230 Epoch 4/500 1/1 [==============================] - 0s 7ms/step - loss: 21.4524 Epoch 5/500 1/1 [==============================] - 0s 10ms/step - loss: 17.2198 Epoch 6/500 1/1 [==============================] - 0s 7ms/step - loss: 13.8828 Epoch 7/500 1/1 [==============================] - 0s 5ms/step - loss: 11.2506 Epoch 8/500 1/1 [==============================] - 0s 5ms/step - loss: 9.1729 Epoch 9/500 1/1 [==============================] - 0s 3ms/step - loss: 7.5317 Epoch 10/500 1/1 [==============================] - 0s 4ms/step - loss: 6.2340 Epoch 11/500 1/1 [==============================] - 0s 3ms/step - loss: 5.2067 Epoch 12/500 1/1 [==============================] - 0s 3ms/step - loss: 4.3922 Epoch 13/500 1/1 [==============================] - 0s 5ms/step - loss: 3.7454 Epoch 14/500 1/1 [==============================] - 0s 4ms/step - loss: 3.2305 Epoch 15/500 1/1 [==============================] - 0s 5ms/step - loss: 2.8197 Epoch 16/500 1/1 [==============================] - 0s 3ms/step - loss: 2.4907 Epoch 17/500 1/1 [==============================] - 0s 4ms/step - loss: 2.2263 Epoch 18/500 1/1 [==============================] - 0s 4ms/step - loss: 2.0127 Epoch 19/500 1/1 [==============================] - 0s 5ms/step - loss: 1.8394 Epoch 20/500 1/1 [==============================] - 0s 4ms/step - loss: 1.6978 Epoch 21/500 1/1 [==============================] - 0s 5ms/step - loss: 1.5812 Epoch 22/500 1/1 [==============================] - 0s 4ms/step - loss: 1.4844 Epoch 23/500 1/1 [==============================] - 0s 4ms/step - loss: 1.4034 Epoch 24/500 1/1 [==============================] - 0s 7ms/step - loss: 1.3347 Epoch 25/500 1/1 [==============================] - 0s 5ms/step - loss: 1.2760 Epoch 26/500 1/1 [==============================] - 0s 4ms/step - loss: 1.2252 Epoch 27/500 1/1 [==============================] - 0s 7ms/step - loss: 1.1806 Epoch 28/500 1/1 [==============================] - 0s 4ms/step - loss: 1.1411 Epoch 29/500 1/1 [==============================] - 0s 5ms/step - loss: 1.1057 Epoch 30/500 1/1 [==============================] - 0s 6ms/step - loss: 1.0736 Epoch 31/500 1/1 [==============================] - 0s 7ms/step - loss: 1.0441 Epoch 32/500 1/1 [==============================] - 0s 4ms/step - loss: 1.0168 Epoch 33/500 1/1 [==============================] - 0s 4ms/step - loss: 0.9913 Epoch 34/500 1/1 [==============================] - 0s 5ms/step - loss: 0.9673 Epoch 35/500 1/1 [==============================] - 0s 4ms/step - loss: 0.9446 Epoch 36/500 1/1 [==============================] - 0s 4ms/step - loss: 0.9230 Epoch 37/500 1/1 [==============================] - 0s 5ms/step - loss: 0.9023 Epoch 38/500 1/1 [==============================] - 0s 5ms/step - loss: 0.8823 Epoch 39/500 1/1 [==============================] - 0s 4ms/step - loss: 0.8631 Epoch 40/500 1/1 [==============================] - 0s 3ms/step - loss: 0.8445 Epoch 41/500 1/1 [==============================] - 0s 4ms/step - loss: 0.8265 Epoch 42/500 1/1 [==============================] - 0s 5ms/step - loss: 0.8090 Epoch 43/500 1/1 [==============================] - 0s 3ms/step - loss: 0.7920 Epoch 44/500 1/1 [==============================] - 0s 4ms/step - loss: 0.7754 Epoch 45/500 1/1 [==============================] - 0s 4ms/step - loss: 0.7592 Epoch 46/500 1/1 [==============================] - 0s 4ms/step - loss: 0.7434 Epoch 47/500 1/1 [==============================] - 0s 4ms/step - loss: 0.7280 Epoch 48/500 1/1 [==============================] - 0s 4ms/step - loss: 0.7129 Epoch 49/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6981 Epoch 50/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6837 Epoch 51/500 1/1 [==============================] - 0s 5ms/step - loss: 0.6696 Epoch 52/500 1/1 [==============================] - 0s 5ms/step - loss: 0.6558 Epoch 53/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6423 Epoch 54/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6291 Epoch 55/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6161 Epoch 56/500 1/1 [==============================] - 0s 4ms/step - loss: 0.6035 Epoch 57/500 1/1 [==============================] - 0s 5ms/step - loss: 0.5911 Epoch 58/500 1/1 [==============================] - 0s 13ms/step - loss: 0.5789 Epoch 59/500 1/1 [==============================] - 0s 7ms/step - loss: 0.5670 Epoch 60/500 1/1 [==============================] - 0s 8ms/step - loss: 0.5554 Epoch 61/500 1/1 [==============================] - 0s 4ms/step - loss: 0.5439 Epoch 62/500 1/1 [==============================] - 0s 4ms/step - loss: 0.5328 Epoch 63/500 1/1 [==============================] - 0s 4ms/step - loss: 0.5218 Epoch 64/500 1/1 [==============================] - 0s 4ms/step - loss: 0.5111 Epoch 65/500 1/1 [==============================] - 0s 4ms/step - loss: 0.5006 Epoch 66/500 1/1 [==============================] - 0s 9ms/step - loss: 0.4903 Epoch 67/500 1/1 [==============================] - 0s 7ms/step - loss: 0.4802 Epoch 68/500 1/1 [==============================] - 0s 4ms/step - loss: 0.4704 Epoch 69/500 1/1 [==============================] - 0s 4ms/step - loss: 0.4607 Epoch 70/500 1/1 [==============================] - 0s 10ms/step - loss: 0.4512 Epoch 71/500 1/1 [==============================] - 0s 5ms/step - loss: 0.4420 Epoch 72/500 1/1 [==============================] - 0s 5ms/step - loss: 0.4329 Epoch 73/500 1/1 [==============================] - 0s 4ms/step - loss: 0.4240 Epoch 74/500 1/1 [==============================] - 0s 4ms/step - loss: 0.4153 Epoch 75/500 1/1 [==============================] - 0s 4ms/step - loss: 0.4068 Epoch 76/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3984 Epoch 77/500 1/1 [==============================] - 0s 5ms/step - loss: 0.3902 Epoch 78/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3822 Epoch 79/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3744 Epoch 80/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3667 Epoch 81/500 1/1 [==============================] - 0s 3ms/step - loss: 0.3591 Epoch 82/500 1/1 [==============================] - 0s 3ms/step - loss: 0.3518 Epoch 83/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3445 Epoch 84/500 1/1 [==============================] - 0s 6ms/step - loss: 0.3375 Epoch 85/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3305 Epoch 86/500 1/1 [==============================] - 0s 6ms/step - loss: 0.3237 Epoch 87/500 1/1 [==============================] - 0s 7ms/step - loss: 0.3171 Epoch 88/500 1/1 [==============================] - 0s 4ms/step - loss: 0.3106 Epoch 89/500 1/1 [==============================] - 0s 5ms/step - loss: 0.3042 Epoch 90/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2979 Epoch 91/500 1/1 [==============================] - 0s 6ms/step - loss: 0.2918 Epoch 92/500 1/1 [==============================] - 0s 6ms/step - loss: 0.2858 Epoch 93/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2800 Epoch 94/500 1/1 [==============================] - 0s 5ms/step - loss: 0.2742 Epoch 95/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2686 Epoch 96/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2631 Epoch 97/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2577 Epoch 98/500 1/1 [==============================] - 0s 4ms/step - loss: 0.2524 Epoch 99/500 1/1 [==============================] - 0s 10ms/step - loss: 0.2472 Epoch 100/500 1/1 [==============================] - 0s 11ms/step - loss: 0.2421 Epoch 101/500 1/1 [==============================] - 0s 10ms/step - loss: 0.2371 Epoch 102/500 1/1 [==============================] - 0s 12ms/step - loss: 0.2323 Epoch 103/500 1/1 [==============================] - 0s 17ms/step - loss: 0.2275 Epoch 104/500 1/1 [==============================] - 0s 10ms/step - loss: 0.2228 Epoch 105/500 1/1 [==============================] - 0s 16ms/step - loss: 0.2182 Epoch 106/500 1/1 [==============================] - 0s 11ms/step - loss: 0.2138 Epoch 107/500 1/1 [==============================] - 0s 7ms/step - loss: 0.2094 Epoch 108/500 1/1 [==============================] - 0s 8ms/step - loss: 0.2051 Epoch 109/500 1/1 [==============================] - 0s 3ms/step - loss: 0.2009 Epoch 110/500 1/1 [==============================] - 0s 5ms/step - loss: 0.1967 Epoch 111/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1927 Epoch 112/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1887 Epoch 113/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1849 Epoch 114/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1811 Epoch 115/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1773 Epoch 116/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1737 Epoch 117/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1701 Epoch 118/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1666 Epoch 119/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1632 Epoch 120/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1599 Epoch 121/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1566 Epoch 122/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1534 Epoch 123/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1502 Epoch 124/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1471 Epoch 125/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1441 Epoch 126/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1411 Epoch 127/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1382 Epoch 128/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1354 Epoch 129/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1326 Epoch 130/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1299 Epoch 131/500 1/1 [==============================] - 0s 3ms/step - loss: 0.1272 Epoch 132/500 1/1 [==============================] - 0s 6ms/step - loss: 0.1246 Epoch 133/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1221 Epoch 134/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1195 Epoch 135/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1171 Epoch 136/500 1/1 [==============================] - 0s 5ms/step - loss: 0.1147 Epoch 137/500 1/1 [==============================] - 0s 7ms/step - loss: 0.1123 Epoch 138/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1100 Epoch 139/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1078 Epoch 140/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1056 Epoch 141/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1034 Epoch 142/500 1/1 [==============================] - 0s 4ms/step - loss: 0.1013 Epoch 143/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0992 Epoch 144/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0971 Epoch 145/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0951 Epoch 146/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0932 Epoch 147/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0913 Epoch 148/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0894 Epoch 149/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0876 Epoch 150/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0858 Epoch 151/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0840 Epoch 152/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0823 Epoch 153/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0806 Epoch 154/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0789 Epoch 155/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0773 Epoch 156/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0757 Epoch 157/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0742 Epoch 158/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0726 Epoch 159/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0712 Epoch 160/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0697 Epoch 161/500 1/1 [==============================] - 0s 281ms/step - loss: 0.0683 Epoch 162/500 1/1 [==============================] - 0s 10ms/step - loss: 0.0669 Epoch 163/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0655 Epoch 164/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0641 Epoch 165/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0628 Epoch 166/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0615 Epoch 167/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0603 Epoch 168/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0590 Epoch 169/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0578 Epoch 170/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0566 Epoch 171/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0555 Epoch 172/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0543 Epoch 173/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0532 Epoch 174/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0521 Epoch 175/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0510 Epoch 176/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0500 Epoch 177/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0490 Epoch 178/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0480 Epoch 179/500 1/1 [==============================] - 0s 25ms/step - loss: 0.0470 Epoch 180/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0460 Epoch 181/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0451 Epoch 182/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0441 Epoch 183/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0432 Epoch 184/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0424 Epoch 185/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0415 Epoch 186/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0406 Epoch 187/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0398 Epoch 188/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0390 Epoch 189/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0382 Epoch 190/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0374 Epoch 191/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0366 Epoch 192/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0359 Epoch 193/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0351 Epoch 194/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0344 Epoch 195/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0337 Epoch 196/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0330 Epoch 197/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0323 Epoch 198/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0317 Epoch 199/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0310 Epoch 200/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0304 Epoch 201/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0298 Epoch 202/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0291 Epoch 203/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0286 Epoch 204/500 1/1 [==============================] - 0s 9ms/step - loss: 0.0280 Epoch 205/500 1/1 [==============================] - 0s 16ms/step - loss: 0.0274 Epoch 206/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0268 Epoch 207/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0263 Epoch 208/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0257 Epoch 209/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0252 Epoch 210/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0247 Epoch 211/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0242 Epoch 212/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0237 Epoch 213/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0232 Epoch 214/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0227 Epoch 215/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0223 Epoch 216/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0218 Epoch 217/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0214 Epoch 218/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0209 Epoch 219/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0205 Epoch 220/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0201 Epoch 221/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0197 Epoch 222/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0192 Epoch 223/500 1/1 [==============================] - 0s 179ms/step - loss: 0.0189 Epoch 224/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0185 Epoch 225/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0181 Epoch 226/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0177 Epoch 227/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0173 Epoch 228/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0170 Epoch 229/500 1/1 [==============================] - 0s 15ms/step - loss: 0.0166 Epoch 230/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0163 Epoch 231/500 1/1 [==============================] - 0s 9ms/step - loss: 0.0160 Epoch 232/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0156 Epoch 233/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0153 Epoch 234/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0150 Epoch 235/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0147 Epoch 236/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0144 Epoch 237/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0141 Epoch 238/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0138 Epoch 239/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0135 Epoch 240/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0132 Epoch 241/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0130 Epoch 242/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0127 Epoch 243/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0124 Epoch 244/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0122 Epoch 245/500 1/1 [==============================] - 0s 17ms/step - loss: 0.0119 Epoch 246/500 1/1 [==============================] - 0s 17ms/step - loss: 0.0117 Epoch 247/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0115 Epoch 248/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0112 Epoch 249/500 1/1 [==============================] - 0s 16ms/step - loss: 0.0110 Epoch 250/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0108 Epoch 251/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0105 Epoch 252/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0103 Epoch 253/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0101 Epoch 254/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0099 Epoch 255/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0097 Epoch 256/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0095 Epoch 257/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0093 Epoch 258/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0091 Epoch 259/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0089 Epoch 260/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0087 Epoch 261/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0086 Epoch 262/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0084 Epoch 263/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0082 Epoch 264/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0080 Epoch 265/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0079 Epoch 266/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0077 Epoch 267/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0076 Epoch 268/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0074 Epoch 269/500 1/1 [==============================] - 0s 12ms/step - loss: 0.0073 Epoch 270/500 1/1 [==============================] - 0s 18ms/step - loss: 0.0071 Epoch 271/500 1/1 [==============================] - 0s 10ms/step - loss: 0.0070 Epoch 272/500 1/1 [==============================] - 0s 15ms/step - loss: 0.0068 Epoch 273/500 1/1 [==============================] - 0s 20ms/step - loss: 0.0067 Epoch 274/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0065 Epoch 275/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0064 Epoch 276/500 1/1 [==============================] - 0s 18ms/step - loss: 0.0063 Epoch 277/500 1/1 [==============================] - 0s 15ms/step - loss: 0.0061 Epoch 278/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0060 Epoch 279/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0059 Epoch 280/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0058 Epoch 281/500 1/1 [==============================] - 0s 14ms/step - loss: 0.0057 Epoch 282/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0055 Epoch 283/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0054 Epoch 284/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0053 Epoch 285/500 1/1 [==============================] - 0s 16ms/step - loss: 0.0052 Epoch 286/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0051 Epoch 287/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0050 Epoch 288/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0049 Epoch 289/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0048 Epoch 290/500 1/1 [==============================] - 0s 11ms/step - loss: 0.0047 Epoch 291/500 1/1 [==============================] - 0s 33ms/step - loss: 0.0046 Epoch 292/500 1/1 [==============================] - 0s 12ms/step - loss: 0.0045 Epoch 293/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0044 Epoch 294/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0043 Epoch 295/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0042 Epoch 296/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0041 Epoch 297/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0041 Epoch 298/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0040 Epoch 299/500 1/1 [==============================] - 0s 9ms/step - loss: 0.0039 Epoch 300/500 1/1 [==============================] - 0s 9ms/step - loss: 0.0038 Epoch 301/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0037 Epoch 302/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0037 Epoch 303/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0036 Epoch 304/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0035 Epoch 305/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0034 Epoch 306/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0034 Epoch 307/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0033 Epoch 308/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0032 Epoch 309/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0032 Epoch 310/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0031 Epoch 311/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0030 Epoch 312/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0030 Epoch 313/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0029 Epoch 314/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0029 Epoch 315/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0028 Epoch 316/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0027 Epoch 317/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0027 Epoch 318/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0026 Epoch 319/500 1/1 [==============================] - 0s 10ms/step - loss: 0.0026 Epoch 320/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0025 Epoch 321/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0025 Epoch 322/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0024 Epoch 323/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0024 Epoch 324/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0023 Epoch 325/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0023 Epoch 326/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0022 Epoch 327/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0022 Epoch 328/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0021 Epoch 329/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0021 Epoch 330/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0020 Epoch 331/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0020 Epoch 332/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0020 Epoch 333/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0019 Epoch 334/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0019 Epoch 335/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0018 Epoch 336/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0018 Epoch 337/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0018 Epoch 338/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0017 Epoch 339/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0017 Epoch 340/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0017 Epoch 341/500 1/1 [==============================] - 0s 9ms/step - loss: 0.0016 Epoch 342/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0016 Epoch 343/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0016 Epoch 344/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0015 Epoch 345/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0015 Epoch 346/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0015 Epoch 347/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0014 Epoch 348/500 1/1 [==============================] - 0s 338ms/step - loss: 0.0014 Epoch 349/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0014 Epoch 350/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0014 Epoch 351/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0013 Epoch 352/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0013 Epoch 353/500 1/1 [==============================] - 0s 3ms/step - loss: 0.0013 Epoch 354/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0012 Epoch 355/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0012 Epoch 356/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0012 Epoch 357/500 1/1 [==============================] - 0s 8ms/step - loss: 0.0012 Epoch 358/500 1/1 [==============================] - 0s 21ms/step - loss: 0.0011 Epoch 359/500 1/1 [==============================] - 0s 48ms/step - loss: 0.0011 Epoch 360/500 1/1 [==============================] - 0s 7ms/step - loss: 0.0011 Epoch 361/500 1/1 [==============================] - 0s 4ms/step - loss: 0.0011 Epoch 362/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0011 Epoch 363/500 1/1 [==============================] - 0s 5ms/step - loss: 0.0010 Epoch 364/500 1/1 [==============================] - 0s 6ms/step - loss: 0.0010 Epoch 365/500 1/1 [==============================] - 0s 5ms/step - loss: 9.8947e-04 Epoch 366/500 1/1 [==============================] - 0s 5ms/step - loss: 9.6915e-04 Epoch 367/500 1/1 [==============================] - 0s 8ms/step - loss: 9.4923e-04 Epoch 368/500 1/1 [==============================] - 0s 5ms/step - loss: 9.2974e-04 Epoch 369/500 1/1 [==============================] - 0s 8ms/step - loss: 9.1064e-04 Epoch 370/500 1/1 [==============================] - 0s 12ms/step - loss: 8.9194e-04 Epoch 371/500 1/1 [==============================] - 0s 5ms/step - loss: 8.7361e-04 Epoch 372/500 1/1 [==============================] - 0s 7ms/step - loss: 8.5567e-04 Epoch 373/500 1/1 [==============================] - 0s 4ms/step - loss: 8.3809e-04 Epoch 374/500 1/1 [==============================] - 0s 3ms/step - loss: 8.2088e-04 Epoch 375/500 1/1 [==============================] - 0s 4ms/step - loss: 8.0402e-04 Epoch 376/500 1/1 [==============================] - 0s 5ms/step - loss: 7.8750e-04 Epoch 377/500 1/1 [==============================] - 0s 3ms/step - loss: 7.7133e-04 Epoch 378/500 1/1 [==============================] - 0s 4ms/step - loss: 7.5548e-04 Epoch 379/500 1/1 [==============================] - 0s 4ms/step - loss: 7.3997e-04 Epoch 380/500 1/1 [==============================] - 0s 5ms/step - loss: 7.2476e-04 Epoch 381/500 1/1 [==============================] - 0s 3ms/step - loss: 7.0988e-04 Epoch 382/500 1/1 [==============================] - 0s 4ms/step - loss: 6.9530e-04 Epoch 383/500 1/1 [==============================] - 0s 3ms/step - loss: 6.8101e-04 Epoch 384/500 1/1 [==============================] - 0s 5ms/step - loss: 6.6703e-04 Epoch 385/500 1/1 [==============================] - 0s 4ms/step - loss: 6.5332e-04 Epoch 386/500 1/1 [==============================] - 0s 4ms/step - loss: 6.3991e-04 Epoch 387/500 1/1 [==============================] - 0s 5ms/step - loss: 6.2676e-04 Epoch 388/500 1/1 [==============================] - 0s 3ms/step - loss: 6.1389e-04 Epoch 389/500 1/1 [==============================] - 0s 6ms/step - loss: 6.0128e-04 Epoch 390/500 1/1 [==============================] - 0s 4ms/step - loss: 5.8893e-04 Epoch 391/500 1/1 [==============================] - 0s 3ms/step - loss: 5.7683e-04 Epoch 392/500 1/1 [==============================] - 0s 3ms/step - loss: 5.6498e-04 Epoch 393/500 1/1 [==============================] - 0s 3ms/step - loss: 5.5338e-04 Epoch 394/500 1/1 [==============================] - 0s 4ms/step - loss: 5.4201e-04 Epoch 395/500 1/1 [==============================] - 0s 5ms/step - loss: 5.3088e-04 Epoch 396/500 1/1 [==============================] - 0s 4ms/step - loss: 5.1997e-04 Epoch 397/500 1/1 [==============================] - 0s 4ms/step - loss: 5.0929e-04 Epoch 398/500 1/1 [==============================] - 0s 4ms/step - loss: 4.9883e-04 Epoch 399/500 1/1 [==============================] - 0s 6ms/step - loss: 4.8859e-04 Epoch 400/500 1/1 [==============================] - 0s 5ms/step - loss: 4.7855e-04 Epoch 401/500 1/1 [==============================] - 0s 5ms/step - loss: 4.6872e-04 Epoch 402/500 1/1 [==============================] - 0s 10ms/step - loss: 4.5909e-04 Epoch 403/500 1/1 [==============================] - 0s 8ms/step - loss: 4.4966e-04 Epoch 404/500 1/1 [==============================] - 0s 7ms/step - loss: 4.4043e-04 Epoch 405/500 1/1 [==============================] - 0s 4ms/step - loss: 4.3138e-04 Epoch 406/500 1/1 [==============================] - 0s 4ms/step - loss: 4.2252e-04 Epoch 407/500 1/1 [==============================] - 0s 5ms/step - loss: 4.1384e-04 Epoch 408/500 1/1 [==============================] - 0s 5ms/step - loss: 4.0534e-04 Epoch 409/500 1/1 [==============================] - 0s 4ms/step - loss: 3.9702e-04 Epoch 410/500 1/1 [==============================] - 0s 305ms/step - loss: 3.8886e-04 Epoch 411/500 1/1 [==============================] - 0s 6ms/step - loss: 3.8087e-04 Epoch 412/500 1/1 [==============================] - 0s 8ms/step - loss: 3.7305e-04 Epoch 413/500 1/1 [==============================] - 0s 8ms/step - loss: 3.6538e-04 Epoch 414/500 1/1 [==============================] - 0s 5ms/step - loss: 3.5788e-04 Epoch 415/500 1/1 [==============================] - 0s 4ms/step - loss: 3.5053e-04 Epoch 416/500 1/1 [==============================] - 0s 6ms/step - loss: 3.4333e-04 Epoch 417/500 1/1 [==============================] - 0s 9ms/step - loss: 3.3628e-04 Epoch 418/500 1/1 [==============================] - 0s 9ms/step - loss: 3.2937e-04 Epoch 419/500 1/1 [==============================] - 0s 18ms/step - loss: 3.2261e-04 Epoch 420/500 1/1 [==============================] - 0s 6ms/step - loss: 3.1598e-04 Epoch 421/500 1/1 [==============================] - 0s 5ms/step - loss: 3.0949e-04 Epoch 422/500 1/1 [==============================] - 0s 7ms/step - loss: 3.0313e-04 Epoch 423/500 1/1 [==============================] - 0s 6ms/step - loss: 2.9690e-04 Epoch 424/500 1/1 [==============================] - 0s 6ms/step - loss: 2.9081e-04 Epoch 425/500 1/1 [==============================] - 0s 7ms/step - loss: 2.8483e-04 Epoch 426/500 1/1 [==============================] - 0s 5ms/step - loss: 2.7898e-04 Epoch 427/500 1/1 [==============================] - 0s 5ms/step - loss: 2.7325e-04 Epoch 428/500 1/1 [==============================] - 0s 5ms/step - loss: 2.6764e-04 Epoch 429/500 1/1 [==============================] - 0s 9ms/step - loss: 2.6214e-04 Epoch 430/500 1/1 [==============================] - 0s 6ms/step - loss: 2.5676e-04 Epoch 431/500 1/1 [==============================] - 0s 7ms/step - loss: 2.5148e-04 Epoch 432/500 1/1 [==============================] - 0s 4ms/step - loss: 2.4632e-04 Epoch 433/500 1/1 [==============================] - 0s 11ms/step - loss: 2.4126e-04 Epoch 434/500 1/1 [==============================] - 0s 13ms/step - loss: 2.3630e-04 Epoch 435/500 1/1 [==============================] - 0s 16ms/step - loss: 2.3145e-04 Epoch 436/500 1/1 [==============================] - 0s 4ms/step - loss: 2.2669e-04 Epoch 437/500 1/1 [==============================] - 0s 3ms/step - loss: 2.2204e-04 Epoch 438/500 1/1 [==============================] - 0s 4ms/step - loss: 2.1748e-04 Epoch 439/500 1/1 [==============================] - 0s 4ms/step - loss: 2.1301e-04 Epoch 440/500 1/1 [==============================] - 0s 4ms/step - loss: 2.0863e-04 Epoch 441/500 1/1 [==============================] - 0s 5ms/step - loss: 2.0435e-04 Epoch 442/500 1/1 [==============================] - 0s 4ms/step - loss: 2.0015e-04 Epoch 443/500 1/1 [==============================] - 0s 4ms/step - loss: 1.9604e-04 Epoch 444/500 1/1 [==============================] - 0s 9ms/step - loss: 1.9201e-04 Epoch 445/500 1/1 [==============================] - 0s 4ms/step - loss: 1.8807e-04 Epoch 446/500 1/1 [==============================] - 0s 6ms/step - loss: 1.8421e-04 Epoch 447/500 1/1 [==============================] - 0s 4ms/step - loss: 1.8042e-04 Epoch 448/500 1/1 [==============================] - 0s 5ms/step - loss: 1.7671e-04 Epoch 449/500 1/1 [==============================] - 0s 3ms/step - loss: 1.7309e-04 Epoch 450/500 1/1 [==============================] - 0s 5ms/step - loss: 1.6953e-04 Epoch 451/500 1/1 [==============================] - 0s 4ms/step - loss: 1.6605e-04 Epoch 452/500 1/1 [==============================] - 0s 6ms/step - loss: 1.6264e-04 Epoch 453/500 1/1 [==============================] - 0s 4ms/step - loss: 1.5930e-04 Epoch 454/500 1/1 [==============================] - 0s 4ms/step - loss: 1.5602e-04 Epoch 455/500 1/1 [==============================] - 0s 5ms/step - loss: 1.5282e-04 Epoch 456/500 1/1 [==============================] - 0s 5ms/step - loss: 1.4968e-04 Epoch 457/500 1/1 [==============================] - 0s 6ms/step - loss: 1.4661e-04 Epoch 458/500 1/1 [==============================] - 0s 5ms/step - loss: 1.4360e-04 Epoch 459/500 1/1 [==============================] - 0s 6ms/step - loss: 1.4065e-04 Epoch 460/500 1/1 [==============================] - 0s 4ms/step - loss: 1.3776e-04 Epoch 461/500 1/1 [==============================] - 0s 4ms/step - loss: 1.3493e-04 Epoch 462/500 1/1 [==============================] - 0s 11ms/step - loss: 1.3216e-04 Epoch 463/500 1/1 [==============================] - 0s 26ms/step - loss: 1.2944e-04 Epoch 464/500 1/1 [==============================] - 0s 7ms/step - loss: 1.2678e-04 Epoch 465/500 1/1 [==============================] - 0s 11ms/step - loss: 1.2418e-04 Epoch 466/500 1/1 [==============================] - 0s 9ms/step - loss: 1.2163e-04 Epoch 467/500 1/1 [==============================] - 0s 9ms/step - loss: 1.1913e-04 Epoch 468/500 1/1 [==============================] - 0s 6ms/step - loss: 1.1668e-04 Epoch 469/500 1/1 [==============================] - 0s 5ms/step - loss: 1.1429e-04 Epoch 470/500 1/1 [==============================] - 0s 7ms/step - loss: 1.1194e-04 Epoch 471/500 1/1 [==============================] - 0s 6ms/step - loss: 1.0964e-04 Epoch 472/500 1/1 [==============================] - 0s 156ms/step - loss: 1.0739e-04 Epoch 473/500 1/1 [==============================] - 0s 6ms/step - loss: 1.0518e-04 Epoch 474/500 1/1 [==============================] - 0s 6ms/step - loss: 1.0302e-04 Epoch 475/500 1/1 [==============================] - 0s 6ms/step - loss: 1.0090e-04 Epoch 476/500 1/1 [==============================] - 0s 7ms/step - loss: 9.8830e-05 Epoch 477/500 1/1 [==============================] - 0s 4ms/step - loss: 9.6800e-05 Epoch 478/500 1/1 [==============================] - 0s 7ms/step - loss: 9.4813e-05 Epoch 479/500 1/1 [==============================] - 0s 4ms/step - loss: 9.2866e-05 Epoch 480/500 1/1 [==============================] - 0s 4ms/step - loss: 9.0957e-05 Epoch 481/500 1/1 [==============================] - 0s 5ms/step - loss: 8.9090e-05 Epoch 482/500 1/1 [==============================] - 0s 4ms/step - loss: 8.7260e-05 Epoch 483/500 1/1 [==============================] - 0s 5ms/step - loss: 8.5467e-05 Epoch 484/500 1/1 [==============================] - 0s 11ms/step - loss: 8.3712e-05 Epoch 485/500 1/1 [==============================] - 0s 9ms/step - loss: 8.1992e-05 Epoch 486/500 1/1 [==============================] - 0s 15ms/step - loss: 8.0308e-05 Epoch 487/500 1/1 [==============================] - 0s 6ms/step - loss: 7.8658e-05 Epoch 488/500 1/1 [==============================] - 0s 4ms/step - loss: 7.7042e-05 Epoch 489/500 1/1 [==============================] - 0s 4ms/step - loss: 7.5459e-05 Epoch 490/500 1/1 [==============================] - 0s 4ms/step - loss: 7.3909e-05 Epoch 491/500 1/1 [==============================] - 0s 3ms/step - loss: 7.2391e-05 Epoch 492/500 1/1 [==============================] - 0s 4ms/step - loss: 7.0905e-05 Epoch 493/500 1/1 [==============================] - 0s 7ms/step - loss: 6.9448e-05 Epoch 494/500 1/1 [==============================] - 0s 13ms/step - loss: 6.8022e-05 Epoch 495/500 1/1 [==============================] - 0s 8ms/step - loss: 6.6625e-05 Epoch 496/500 1/1 [==============================] - 0s 9ms/step - loss: 6.5256e-05 Epoch 497/500 1/1 [==============================] - 0s 4ms/step - loss: 6.3916e-05 Epoch 498/500 1/1 [==============================] - 0s 4ms/step - loss: 6.2603e-05 Epoch 499/500 1/1 [==============================] - 0s 4ms/step - loss: 6.1318e-05 Epoch 500/500 1/1 [==============================] - 0s 4ms/step - loss: 6.0058e-05 ###Markdown Ok, now you have a model that has been trained to learn the relationship between X and Y. You can use the **model.predict** method to have it figure out the Y for a previously unknown X. So, for example, if X = 10, what do you think Y will be? Take a guess before you run this code: ###Code print(model.predict([10.0])) ###Output [[18.977392]]
1_5_CNN_Layers/2. Pool Visualization.ipynb
###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output _____no_output_____ ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, filter_weights): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = filter_weights.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(filter_weights) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights filter_weights = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(filter_weights) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output _____no_output_____ ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output _____no_output_____ ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output _____no_output_____ ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output _____no_output_____ ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____ ###Markdown Pooling LayerIn this notebook, we add and visualize the output of a maxpooling layer in a CNN. Import the image ###Code import cv2 import matplotlib.pyplot as plt %matplotlib inline # %matplotlib notebook # TODO: Feel free to try out your own images here by changing img_path # to a file path to another image on your computer! img_path = 'images/udacity_sdc.png' # load color image bgr_img = cv2.imread(img_path) # convert to grayscale gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # normalize, rescale entries to lie in [0,1] gray_img = gray_img.astype("float32")/255 # plot image plt.imshow(gray_img, cmap='gray') plt.show() ###Output _____no_output_____ ###Markdown Define and visualize the filters ###Code import numpy as np ## TODO: Feel free to modify the numbers here, to try out another filter! filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) print('Filter shape: ', filter_vals.shape) # Defining four different filters, # all of which are linear combinations of the `filter_vals` defined above # define four filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # For an example, print out the values of filter 1 print('Filter 1: \n', filter_1) ###Output Filter 1: [[-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1] [-1 -1 1 1]] ###Markdown Define convolutional and pooling layersInitialize a convolutional layer so that it contains all your created filters. Then add a maxpooling layer, [documented here](http://pytorch.org/docs/master/_modules/torch/nn/modules/pooling.html), with a kernel size of (4x4) so you can really see that the image resolution has been reduced after this step! ###Code import torch import torch.nn as nn import torch.nn.functional as F # define a neural network with a convolutional layer with four filters # AND a pooling layer of size (4, 4) class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(4, 4) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) ###Output Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False) ) ###Markdown Visualize the output of each filterFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through. ###Code # helper function for visualizing the output of a given layer # default number of filters is 4 def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[]) # grab layer outputs ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) ###Output _____no_output_____ ###Markdown Let's look at the output of a convolutional layer after a ReLu activation function is applied. ###Code # plot original image plt.imshow(gray_img, cmap='gray') # visualize all filters fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) # convert the image into an input Tensor gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) # get all the layers conv_layer, activated_layer, pooled_layer = model(gray_img_tensor) # visualize the output of the activated conv layer viz_layer(activated_layer) ###Output _____no_output_____ ###Markdown Visualize the output of the pooling layerThen, take a look at the output of a pooling layer. The pooling layer takes as input the feature maps pictured above and reduces the dimensionality of those maps, by some pooling factor, by constructing a new, smaller image of only the maximum (brightest) values in a given kernel area. ###Code # visualize the output of the pooling layer viz_layer(pooled_layer) ###Output _____no_output_____
notebooks/dataset-projections/64/mnist/mnist-64-ae-only-embedding.ipynb
###Markdown Choose GPU (this may not be needed on your computer) ###Code %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=1 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices)>0: tf.config.experimental.set_memory_growth(gpu_devices[0], True) print(gpu_devices) tf.keras.backend.clear_session() ###Output [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] ###Markdown load packages ###Code from tfumap.umap import tfUMAP import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tqdm.autonotebook import tqdm import umap import pandas as pd ###Output _____no_output_____ ###Markdown Load dataset ###Code from tensorflow.keras.datasets import mnist # load dataset (train_images, Y_train), (test_images, Y_test) = mnist.load_data() X_train = (train_images/255.).astype('float32') X_test = (test_images/255.).astype('float32') X_train = X_train.reshape((len(X_train), np.product(np.shape(X_train)[1:]))) X_test = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) # subset a validation set n_valid = 10000 X_valid = X_train[-n_valid:] Y_valid = Y_train[-n_valid:] X_train = X_train[:-n_valid] Y_train = Y_train[:-n_valid] # flatten X X_train_flat = X_train.reshape((len(X_train), np.product(np.shape(X_train)[1:]))) X_test_flat = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) X_valid_flat= X_valid.reshape((len(X_valid), np.product(np.shape(X_valid)[1:]))) print(len(X_train), len(X_valid), len(X_test)) ###Output 50000 10000 10000 ###Markdown define networks ###Code dims = (28,28,1) n_components = 64 encoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=dims), tf.keras.layers.Conv2D( filters=64, kernel_size=3, strides=(2, 2), activation="relu" ), tf.keras.layers.Conv2D( filters=128, kernel_size=3, strides=(2, 2), activation="relu" ), tf.keras.layers.Flatten(), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=n_components), ]) decoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(n_components)), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=7 * 7 * 256, activation="relu"), tf.keras.layers.Reshape(target_shape=(7, 7, 256)), tf.keras.layers.Conv2DTranspose( filters=128, kernel_size=3, strides=(2, 2), padding="SAME", activation="relu" ), tf.keras.layers.Conv2DTranspose( filters=64, kernel_size=3, strides=(2, 2), padding="SAME", activation="relu" ), tf.keras.layers.Conv2DTranspose( filters=1, kernel_size=3, strides=(1, 1), padding="SAME", activation="sigmoid" ) ]) input_img = tf.keras.Input(dims) output_img = decoder(encoder(input_img)) autoencoder = tf.keras.Model(input_img, output_img) autoencoder.compile(optimizer='adam', loss='binary_crossentropy') X_train = X_train.reshape([len(X_train)] + list(dims)) history = autoencoder.fit(X_train, X_train, epochs=50, batch_size=256, shuffle=True, #validation_data=(X_valid, X_valid) ) z = encoder.predict(X_train) ###Output _____no_output_____ ###Markdown Plot model output ###Code fig, ax = plt.subplots( figsize=(8, 8)) sc = ax.scatter( z[:, 0], z[:, 1], c=Y_train.astype(int)[:len(z)], cmap="tab10", s=0.1, alpha=0.5, rasterized=True, ) ax.axis('equal') ax.set_title("UMAP in Tensorflow embedding", fontsize=20) plt.colorbar(sc, ax=ax); ###Output _____no_output_____ ###Markdown View loss ###Code from tfumap.umap import retrieve_tensors import seaborn as sns ###Output _____no_output_____ ###Markdown Save output ###Code from tfumap.paths import ensure_dir, MODEL_DIR output_dir = MODEL_DIR/'projections'/ 'mnist' / '64' / 'ae_only' ensure_dir(output_dir) encoder.save(output_dir / 'encoder') decoder.save(output_dir / 'encoder') #loss_df.to_pickle(output_dir / 'loss_df.pickle') np.save(output_dir / 'z.npy', z) ###Output _____no_output_____ ###Markdown compute metrics ###Code X_test.shape z_test = encoder.predict(X_test.reshape((len(X_test), 28,28,1))) ###Output _____no_output_____ ###Markdown silhouette ###Code from tfumap.silhouette import silhouette_score_block ss, sil_samp = silhouette_score_block(z, Y_train, n_jobs = -1) ss ss_test, sil_samp_test = silhouette_score_block(z_test, Y_test, n_jobs = -1) ss_test fig, axs = plt.subplots(ncols = 2, figsize=(10, 5)) axs[0].scatter(z[:, 0], z[:, 1], s=0.1, alpha=0.5, c=sil_samp, cmap=plt.cm.viridis) axs[1].scatter(z_test[:, 0], z_test[:, 1], s=1, alpha=0.5, c=sil_samp_test, cmap=plt.cm.viridis) ###Output _____no_output_____ ###Markdown KNN ###Code from sklearn.neighbors import KNeighborsClassifier neigh5 = KNeighborsClassifier(n_neighbors=5) neigh5.fit(z, Y_train) score_5nn = neigh5.score(z_test, Y_test) score_5nn neigh1 = KNeighborsClassifier(n_neighbors=1) neigh1.fit(z, Y_train) score_1nn = neigh1.score(z_test, Y_test) score_1nn ###Output _____no_output_____ ###Markdown Trustworthiness ###Code from sklearn.manifold import trustworthiness tw = trustworthiness(X_train_flat[:10000], z[:10000]) tw_test = trustworthiness(X_test_flat[:10000], z_test[:10000]) tw, tw_test ###Output _____no_output_____ ###Markdown Save output metrics ###Code from tfumap.paths import ensure_dir, MODEL_DIR, DATA_DIR dataset = 'mnist' ###Output _____no_output_____ ###Markdown train ###Code metrics_df = pd.DataFrame( columns=[ "dataset", "class_", "dim", "trustworthiness", "silhouette_score", "silhouette_samples", ] ) metrics_df.loc[len(metrics_df)] = [dataset, 'ae_only', n_components, tw, ss, sil_samp] metrics_df save_loc = DATA_DIR / 'projection_metrics' / 'ae_only' / 'train' / str(n_components) / (dataset + '.pickle') ensure_dir(save_loc) metrics_df.to_pickle(save_loc) ###Output _____no_output_____ ###Markdown test ###Code metrics_df_test = pd.DataFrame( columns=[ "dataset", "class_", "dim", "trustworthiness", "silhouette_score", "silhouette_samples", ] ) metrics_df_test.loc[len(metrics_df)] = [dataset, 'ae_only', n_components, tw_test, ss_test, sil_samp_test] metrics_df_test save_loc = DATA_DIR / 'projection_metrics' / 'ae' / 'test' / str(n_components) / (dataset + '.pickle') ensure_dir(save_loc) metrics_df.to_pickle(save_loc) ###Output _____no_output_____ ###Markdown knn ###Code nn_acc_df = pd.DataFrame(columns = ["method_","dimensions","dataset","1NN_acc","5NN_acc"]) nn_acc_df.loc[len(nn_acc_df)] = ['ae_only', n_components, dataset, score_1nn, score_5nn] nn_acc_df save_loc = DATA_DIR / 'knn_classifier' / 'ae_only' / 'train' / str(n_components) / (dataset + '.pickle') ensure_dir(save_loc) nn_acc_df.to_pickle(save_loc) ###Output _____no_output_____ ###Markdown Reconstruction ###Code from sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error, r2_score X_recon = decoder.predict(encoder.predict(X_test.reshape((len(X_test), 28, 28, 1)))) X_real = X_test.reshape((len(X_test), 28, 28, 1)) x_real = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) x_recon = X_recon.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) reconstruction_acc_df = pd.DataFrame( columns=["method_", "dimensions", "dataset", "MSE", "MAE", "MedAE", "R2"] ) MSE = mean_squared_error( x_real, x_recon ) MAE = mean_absolute_error( x_real, x_recon ) MedAE = median_absolute_error( x_real, x_recon ) R2 = r2_score( x_real, x_recon ) reconstruction_acc_df.loc[len(reconstruction_acc_df)] = ['ae_only', n_components, dataset, MSE, MAE, MedAE, R2] reconstruction_acc_df save_loc = DATA_DIR / 'reconstruction_acc' / 'ae_only' / str(n_components) / (dataset + '.pickle') ensure_dir(save_loc) reconstruction_acc_df.to_pickle(save_loc) save_loc ###Output _____no_output_____ ###Markdown Compute clustering quality ###Code from sklearn.cluster import KMeans from sklearn.metrics import homogeneity_completeness_v_measure def get_cluster_metrics(row, n_init=5): # load cluster information save_loc = DATA_DIR / 'clustering_metric_df'/ ('_'.join([row.class_, str(row.dim), row.dataset]) + '.pickle') print(save_loc) if save_loc.exists() and save_loc.is_file(): cluster_df = pd.read_pickle(save_loc) return cluster_df # make cluster metric dataframe cluster_df = pd.DataFrame( columns=[ "dataset", "class_", "dim", "silhouette", "homogeneity", "completeness", "v_measure", "init_", "n_clusters", "model", ] ) y = row.train_label z = row.train_z n_labels = len(np.unique(y)) for n_clusters in tqdm(np.arange(n_labels - int(n_labels / 2), n_labels + int(n_labels / 2)), leave=False, desc = 'n_clusters'): for init_ in tqdm(range(n_init), leave=False, desc='init'): kmeans = KMeans(n_clusters=n_clusters, random_state=init_).fit(z) clustered_y = kmeans.labels_ homogeneity, completeness, v_measure = homogeneity_completeness_v_measure( y, clustered_y ) ss, _ = silhouette_score_block(z, clustered_y) cluster_df.loc[len(cluster_df)] = [ row.dataset, row.class_, row.dim, ss, homogeneity, completeness, v_measure, init_, n_clusters, kmeans, ] # save cluster df in case this fails somewhere ensure_dir(save_loc) cluster_df.to_pickle(save_loc) return cluster_df projection_df = pd.DataFrame(columns = ['dataset', 'class_', 'train_z', 'train_label', 'dim']) projection_df.loc[len(projection_df)] = [dataset, 'ae_only', z, Y_train, n_components] projection_df get_cluster_metrics(projection_df.iloc[0], n_init=5) ###Output /mnt/cube/tsainbur/Projects/github_repos/umap_tf_networks/data/clustering_metric_df/ae_only_64_mnist.pickle
东南大学/D02机器学习与深度学习/Torch深度学习模型/01Torch编程模式-04Torch两种实现方式与框架结构说明.ipynb
###Markdown 说明 - 到目前为止,使用Torch实际上是可以实现基本上所有的机器学习与神经网络(包括深度神经网络)的算法模型。神经网络的模型核心是: 1. 预测输出模型; - 函数表达; 2. 梯度计算模型; - 函数的导数表达 - 某些运算的导数在Torch中提供内置的实现(一般的运算的导数都是采用默认的内置实现:原理就是无穷小量下的近似极限) - 为了速度某些时候,需要自己使用Function接口中的backward函数重载实现(自定义导数函数,通过导数函数实现导数计算) 3. 梯度循环迭代; - 计算梯度; - 更新梯度; 多层全链接神经网络的实现 思路 - 下面利用Torch的最基本的封装来实现一个全链接神经网络,对鸢尾花进行分类。构建的神经网络结构为: - 4 -> 12 -> 6 -> 3 - 两个隐藏层; - 多分类:三类鸢尾花 - 实现思路: - 预测模型: - 采用默认求导实现 - 激活函数采用sigmoid(可以选择其他) - 损失模型: - 采用交叉熵损失函数(可以选择其他) 实现代码 ###Code import torch import sklearn.datasets from sklearn.model_selection import train_test_split # 1. 准备数据 -------------------- data, target = sklearn.datasets.load_iris(return_X_y=True) # data, _, target, _ = train_test_split(data, target, test_size=0.01, random_state=42) x = torch.Tensor(data) # 全部150个样本,一共三类 y = torch.tensor(target) # 使用交叉熵需要LongTensor # 2. 准备预测模型 ---------------- w1 = torch.randn(12, 4) # 前面输出特征,后面输入特征 b1 = torch.randn(12) # 输出特征 w1.requires_grad=True b1.requires_grad=True w2 = torch.randn(6, 12) # 前面输出特征,后面输入特征 b2 = torch.randn(6) # 输出特征 w2.requires_grad=True b2.requires_grad=True w3 = torch.randn(3, 6) # 前面输出特征,后面输入特征 b3 = torch.randn(3) # 输出特征 w3.requires_grad=True b3.requires_grad=True # ######################### def forward(input): o1 = torch.nn.functional.linear(input, w1, b1) # y1 = torch.sigmoid(o1) # torch.nn.functional.sigmoid已经不推荐使用 y1 = torch.nn.functional.relu(o1) x1 = y1 # ---- o2= torch.nn.functional.linear(x1, w2, b2) # y2 = torch.sigmoid(o2) y2 = torch.nn.functional.relu(o2) x2 = y2 # ---- o3= torch.nn.functional.linear(x2, w3, b3) # y3 = torch.sigmoid(o3) return o3 # 迭代轮数 epoch = 20000 # 学习率 learn_rate = 0.01 for n in range(epoch): # 计算梯度 y_= forward(x) loss = torch.nn.functional.cross_entropy(y_, y) # 3.2 损失优化 loss.backward(retain_graph=True) with torch.autograd.no_grad(): # 更新梯度 w1 -= learn_rate * w1.grad b1 -= learn_rate * b1.grad w2 -= learn_rate * w2.grad b2 -= learn_rate * b2.grad w3 -= learn_rate * w3.grad b3 -= learn_rate * b3.grad # 清空上一轮的梯度 w1.grad.zero_() b1.grad.zero_() w2.grad.zero_() b2.grad.zero_() w3.grad.zero_() b3.grad.zero_() if n % 1000 == 0: print(F"损失值:{loss.detach().numpy():8.6f}, ", end="") y_ = forward(x) y_ = y_.log_softmax(dim=1) # 有使用交叉熵,其中做了一个log_softmax运算,所以这儿也作为概率使用,并调用了log_softmax运算 predict = y_.argmax(dim=1) print(F"\t训练集测试准确度:{(predict == y).float().mean()*100:8.2f}%") # # 4. 测试与评估------------------ # y_ = forward(x) # y_ = y_.log_softmax(dim=1) # 有使用交叉熵,其中做了一个log_softmax运算,所以这儿也作为概率使用,并调用了log_softmax运算 # predict = y_.argmax(dim=1) # print(predict) # print((predict == y).float().mean()) ###Output 损失值:24.356802, 训练集测试准确度: 33.33% 损失值:0.114688, 训练集测试准确度: 96.67% 损失值:0.065713, 训练集测试准确度: 97.33% 损失值:0.056335, 训练集测试准确度: 98.00% 损失值:0.051487, 训练集测试准确度: 98.67% 损失值:0.048233, 训练集测试准确度: 99.33% 损失值:0.045789, 训练集测试准确度: 99.33% 损失值:0.043852, 训练集测试准确度: 99.33% 损失值:0.042273, 训练集测试准确度: 98.67% 损失值:0.040961, 训练集测试准确度: 98.67% 损失值:0.039847, 训练集测试准确度: 98.67% 损失值:0.038890, 训练集测试准确度: 98.67% 损失值:0.038064, 训练集测试准确度: 98.67% 损失值:0.037350, 训练集测试准确度: 98.67% 损失值:0.036727, 训练集测试准确度: 98.67% 损失值:0.036185, 训练集测试准确度: 98.67% 损失值:0.035697, 训练集测试准确度: 98.67% 损失值:0.035270, 训练集测试准确度: 98.67% 损失值:0.034884, 训练集测试准确度: 98.67% 损失值:0.034534, 训练集测试准确度: 98.67% ###Markdown 说明 - 通过自动求导,实际上神经网络的实现变得很easy!但是这种重复与反复的工作本身是比较繁琐,Torch实际提供更好结构设计来实现。 - Model(容器) - Layer(操作) - 运算(函数表达式与内置求导) - 函数Function : 定制求导(`[forward]`与求导`[backward]`) - 这种结构从最底层到应用封装,基本上可以班组各种层次的需求。 - 问题: - 实际损失函数中的操作需要非常清楚,实际每个损失函数的操作在文档中都有描述。 - 正如我们上面中log_softmax运算一样。 卷积神经网络LeNet-5实现 - 实现LeNet-5卷积神经网络,并实现手写数字识别。 - 数据集采用手写数字数据集。 LeNet-5网络模型回顾 - ![image.png](attachment:image.png) - 输入图像:INPUT:`N*32*32*1` - N是图像数量 - 1是图像深度 - `32*32`是图像高宽(有的数据集图像高宽是`28*28`,这个可以在卷积运算的时候,指定Padding即可)- 池化层:C1:`6@28*28` -> `6@14*14` - 采用`2*2`的最大池化可以降维一半。- 从卷积层(图像特征学习层)到全连接层(分类层):C5: `120@1*1` - 这一层在上图中表示不清楚,需要特别注意,因为这儿有一个数据格式转换的问题(在Torch中就是view的问题) 实现思路 - 首先确定训练参数;- 实现预测模型;- 实现损失模型;- 损失优化迭代训练; LeNet-5模型手工实现代码 MINIST数据集加载- 数据集稳健已经放在本文档所在目录下的datasets目录中: - 训练集: - train-images.idx3-ubyte - train-labels.idx1-ubyte - 测试集: - t10k-images.idx3-ubyte - t10k-labels.idx1-ubyte- 数据使用二进制保存,具体的格式在官网参考: - http://yann.lecun.com/exdb/mnist/ - ![image.png](attachment:image.png) - 其他图片格式的数据也有,个人根据需要选择,这里选择二进制的数据集,读取速度快。 ###Code %matplotlib inline import struct import matplotlib.pyplot as plt import numpy as np # 读取图片 def load_image_fromfile(filename): with open(filename, 'br') as fd: # 读取图像的信息 header_buf = fd.read(16) # 16字节,4个int整数 # 按照字节解析头信息(具体参考python SL的struct帮助) magic_, nums_, width_, height_ = struct.unpack('>iiii', header_buf) # 解析成四个整数:>表示大端字节序,i表示4字节整数 # 保存成ndarray对象 imgs_ = np.fromfile(fd, dtype=np.uint8) imgs_ = imgs_.reshape(nums_, height_, width_) return imgs_ # 读取标签 def load_label_fromfile(filename): with open(filename, 'br') as fd: header_buf = fd.read(8) magic, nums = struct.unpack('>ii' ,header_buf) labels_ = np.fromfile(fd, np.uint8) return labels_ # 读取训练集 train_x = load_image_fromfile("datasets/train-images.idx3-ubyte") train_y = load_label_fromfile("datasets/train-labels.idx1-ubyte") train_x = train_x.astype(np.float64) train_y = train_y.astype(np.int64) # 读取测试集 test_x = load_image_fromfile("datasets/t10k-images.idx3-ubyte") test_y = load_label_fromfile("datasets/t10k-labels.idx1-ubyte") # 可视化验证读取的数据 ax1 = plt.subplot(121, title=F"训练集图像样本,标签:{train_y[0]}") ax1.imshow(train_x[0], cmap="gray") ax2 = plt.subplot(122, title=F"测试集图像样本,标签:{test_y[0]}") ax2.imshow(test_x[0], cmap="gray") plt.show() ###Output _____no_output_____ ###Markdown - 提示: - 图像是`28*28`大小的图像,在第一层卷积处理的时候,需要padding=True。这样在第二层图像参数可以保持一致。 网络模型- 网络模型包含两个方面: 1. 预测模型 2. 损失模型(优化模型)- 损失模型选择:交叉熵 - 分类采用逻辑分布应该是不错的选择; - 交叉熵有两个封装函数,我们选择nll_loss函数,原因是概率转换不一定选择log_softmax: - cross_entropy:使用log_softmax作为输出的概率转换 - nll_loss:无 ###Code # 数据由上一个Code Cell完成 import torch import math # 1. 定义训练参数(3层卷积,2层全链接) # 1.1. 1 @28 * 28 -> 6@28 * 28: 6@5*5 的卷积核 -> 6 @ 14 * 14(池化) # 1.2. 6@14 * 14 -> 16@10 * 10: 16@5*5 的卷积核 -> 10 @ 5 * 5(池化) # 1.3. 16@5 * 5 -> 120@1 * 1: 120@5*5 的卷积核 (没有池化) # 1.4. 120 * 84 # 1.5. 84 * 10 (输出10个特征,分类0-9十个数字) # 1.1 w_6_5_5 = torch.Tensor(6, 1, 5, 5) #(C_out, C_in, H_k, W_k) b_6_5_5 = torch.Tensor(6) # (C_out) # 卷积核也可以不使用偏置项的 # 初始化(模仿Torch的源代码,自己采用正态分布,每次计算都是无穷大) stdv = 1.0 / math.sqrt(1 * 5 * 5) w_6_5_5.data.uniform_(-stdv, stdv) b_6_5_5.data.uniform_(-stdv, stdv) # print(w_6_5_5) # 1.2 w_16_5_5 = torch.Tensor(16, 6, 5, 5) b_16_5_5 = torch.Tensor(16) # 初始化 stdv = 1.0 / math.sqrt(6 * 5 * 5) w_16_5_5.data.uniform_(-stdv, stdv) b_16_5_5.data.uniform_(-stdv, stdv) # 1.3 w_120_5_5 = torch.Tensor(120, 16, 5, 5) b_120_5_5 = torch.Tensor(120) # 初始化 stdv = 1.0 / math.sqrt(16 * 5 * 5) w_120_5_5.data.uniform_(-stdv, stdv) b_120_5_5.data.uniform_(-stdv, stdv) # 1.4 w_120_84 = torch.Tensor(84, 120) b_120_84 = torch.Tensor(84) # 初始化 stdv = 1.0 / math.sqrt(120) # 使用输入的特征数作为均匀分布的计算基数 w_120_84.data.uniform_(-stdv, stdv) b_120_84.data.uniform_(-stdv, stdv) # 1.5 w_84_10 =torch.Tensor(10, 84) b_84_10 = torch.Tensor(10) # 初始化 stdv = 1.0 / math.sqrt(84) w_84_10.data.uniform_(-stdv, stdv) b_84_10.data.uniform_(-stdv, stdv) # print(w_16_5_5) w_6_5_5.requires_grad = True b_6_5_5.requires_grad = True # 1.2 w_16_5_5.requires_grad = True b_16_5_5.requires_grad = True # 1.3 w_120_5_5.requires_grad = True b_120_5_5.requires_grad = True # 1.4 w_120_84.requires_grad = True b_120_84.requires_grad = True # 1.5 w_84_10.requires_grad = True b_84_10.requires_grad = True # 2. 定义forward模型(为了反复调用,封装成函数) @torch.enable_grad() def lenet5_forward(input): """ input的格式:4-D(N, 1, 28, 28):N表示每批次的样本数量 out的格式:与input相同4-D(N, 10):N表示每批次的样本数量 """ # 1.1 o_c1 = torch.nn.functional.conv2d(input=input, weight=w_6_5_5, bias=b_6_5_5, padding = 2) # 原始图像28*28 o_a1 = torch.nn.functional.relu(o_c1) o_p1 = torch.nn.functional.max_pool2d(input= o_a1, kernel_size=(2,2)) o1 = o_p1 # 1.2 o_c2 = torch.nn.functional.conv2d(input=o1, weight=w_16_5_5, bias=b_16_5_5) o_a2 = torch.nn.functional.relu(o_c2) o_p2 = torch.nn.functional.max_pool2d(input= o_a2, kernel_size=(2,2)) o2 = o_p2 # 1.3 o_c3 = torch.nn.functional.conv2d(input=o2, weight=w_120_5_5, bias=b_120_5_5) o_a3 = torch.nn.functional.relu(o_c3) # 无池化 # o3 = o_a3.squeeze() # 格式转换(把最后的1*1直接降维掉),转换为60000 * 120 o3 = o_a3.view(o_a3.shape[0], o_a3.shape[1]) # 1.4 o_c4 = torch.nn.functional.linear(o3, w_120_84, b_120_84) o_a4 = torch.nn.functional.relu(o_c4) o4 = o_a4 # 1.5 o_c5 = torch.nn.functional.linear(o4, w_84_10, b_84_10) o_a5 = torch.log_softmax(o_c5, dim=1) o5 = o_a5 return o5 # 3. 定义损失模型(封装成函数) @torch.enable_grad() def loss_model(out, target): loss_ = torch.nn.functional.cross_entropy(out, target) return loss_ # # 测试代码 # x = torch.Tensor(train_x).view(train_x.shape[0], 1, train_x.shape[1], train_x.shape[2]) # N,C,W,H # y = torch.LongTensor(train_y) # y_ = lenet5_forward(x) # loss = loss_model(y_, y) # print(loss) ###Output _____no_output_____ ###Markdown 迭代训练 - 由于训练样本60000个,所以训练采用随机梯度下降的方式,每次训练采用一部分样本,按照批次训练。 ###Code import torch # 为了速度取1000个样本训练 # train_x = train_x[0:10] # train_y = train_y[0:10] # 训练集 x = torch.Tensor(train_x).view(train_x.shape[0], 1, train_x.shape[1], train_x.shape[2]) # N,C,W,H y = torch.LongTensor(train_y) # # 测试集 t_x = torch.Tensor(test_x).view(test_x.shape[0], 1, test_x.shape[1], test_x.shape[2]) # N,C,W,H t_y = torch.LongTensor(test_y) # 训练超参数 # 学习率 learn_rate = 0.001 # 训练轮数 epoch = 500 # 没批样本数 batch_size = 2000 # 批次计算 batch_num = len(train_y) // batch_size # 轮次循环 for e in range(epoch): # 批次循环 for idx in range(batch_num): # 批次样本 start = idx *batch_size end = (idx + 1) * batch_size b_x = x[start: end] b_y = y[start: end] # 计算输出 b_y_ = lenet5_forward(b_x) # break # 计算损失 l_ = loss_model(b_y_, b_y) # 计算梯度 l_.backward(retain_graph=True) # print(w_6_5_5.grad) # 梯度更新(使用上下文管理器,进制对运算实现图跟踪) with torch.autograd.no_grad(): w_6_5_5 -= learn_rate * w_6_5_5.grad b_6_5_5 -= learn_rate * b_6_5_5.grad w_16_5_5 -= learn_rate * w_16_5_5.grad b_16_5_5 -= learn_rate * b_16_5_5.grad w_120_5_5 -= learn_rate * w_120_5_5.grad b_120_5_5 -= learn_rate * b_120_5_5.grad w_120_84 -= learn_rate * w_120_84.grad b_120_84 -= learn_rate * b_120_84.grad w_84_10 -= learn_rate * w_84_10.grad b_84_10 -= learn_rate * b_84_10.grad # 复原梯度 w_6_5_5.grad.zero_() b_6_5_5.grad.zero_() w_16_5_5.grad.zero_() b_16_5_5.grad.zero_() w_120_5_5.grad.zero_() b_120_5_5.grad.zero_() w_120_84.grad.zero_() b_120_84.grad.zero_() w_84_10.grad.zero_() b_84_10.grad.zero_() # 每一轮次完毕,输出损失度与测试集准确率 if e % 100 ==0: print(F"第{e:03d}轮") print(F"\t损失值:{l_:8.6f}",end="") # 测试集测试 with torch.autograd.no_grad(): predict = lenet5_forward(t_x) # 计算准确率 y_ = predict.argmax(dim=1) correct_rate = (y_ == t_y).float().mean() print(F"\t测试集准确率:{correct_rate*100: 6.2f}%") print("------训练完毕------") ###Output 第000轮 损失值:1.785437 测试集准确率: 41.43% 第100轮 损失值:0.064623 测试集准确率: 97.25% 第200轮 损失值:0.047923 测试集准确率: 98.04% 第300轮 损失值:0.039753 测试集准确率: 98.31% 第400轮 损失值:0.034219 测试集准确率: 98.48% ------训练完毕------ ###Markdown LetNet-5模型框架实现代码 - 技术点提示: 1. 数据集切分管理; 2. 决策模型 - 分成计算 3. 损失模型与优化模型 4. 训练过程 数据集加载与处理 ###Code # 与手工实现版本一样,加载MINST数据集 %matplotlib inline import struct import matplotlib.pyplot as plt import numpy as np import torch.utils.data # 读取图片 def load_image_fromfile(filename): with open(filename, 'br') as fd: # 读取图像的信息 header_buf = fd.read(16) # 16字节,4个int整数 # 按照字节解析头信息(具体参考python SL的struct帮助) magic_, nums_, width_, height_ = struct.unpack('>iiii', header_buf) # 解析成四个整数:>表示大端字节序,i表示4字节整数 # 保存成ndarray对象 imgs_ = np.fromfile(fd, dtype=np.uint8) imgs_ = imgs_.reshape(nums_, height_, width_) return imgs_ # 读取标签 def load_label_fromfile(filename): with open(filename, 'br') as fd: header_buf = fd.read(8) magic, nums = struct.unpack('>ii' ,header_buf) labels_ = np.fromfile(fd, np.uint8) return labels_ # 读取训练集 train_x = load_image_fromfile("datasets/train-images.idx3-ubyte") train_y = load_label_fromfile("datasets/train-labels.idx1-ubyte") train_x = train_x.astype(np.float64) train_y = train_y.astype(np.int64) # 读取测试集 test_x = load_image_fromfile("datasets/t10k-images.idx3-ubyte") test_y = load_label_fromfile("datasets/t10k-labels.idx1-ubyte") # 使用Torch的数据集管理工具管理 # 转换为Tensor x = torch.Tensor(train_x).view(train_x.shape[0], 1, train_x.shape[1], train_x.shape[2]) # N,C,W,H y = torch.LongTensor(train_y) t_x = torch.Tensor(test_x).view(test_x.shape[0], 1, test_x.shape[1], test_x.shape[2]) # N,C,W,H t_y = torch.LongTensor(test_y) # 使用TensorDataSet封装数据与标签 train_dataset = torch.utils.data.TensorDataset(x, y) test_dataset = torch.utils.data.TensorDataset(t_x, t_y) # 数据随机与切分器 train_loader = torch.utils.data.DataLoader(dataset=train_dataset, shuffle=True, batch_size=2000) # 批次数量1000 test_loader = torch.utils.data.DataLoader(dataset=test_dataset, shuffle=True, batch_size=10000) # 一个批次直接预测 ###Output _____no_output_____ ###Markdown 定义神经网络模型 ###Code %matplotlib inline import matplotlib.pyplot as plt class LeNet_5(torch.nn.Module): def __init__(self): super(LeNet_5, self).__init__() # 卷积层1 :1 @ 28 * 28 - > 6 @ 28 * 28 -> 6 @ 14 * 14 # 卷积层2 :6 @ 14 * 14 -> 16 @ 10 * 10 -> 16 @ 5 * 5 # 卷积层3 :16 @ 5 * 5 -> 120 @ 1 * 1 self.layer_1 = torch.nn.Conv2d(in_channels=1, out_channels=6, kernel_size=(5, 5), padding=2) self.layer_2 = torch.nn.Conv2d(in_channels=6, out_channels=16, kernel_size=(5, 5), padding=0) self.layer_3 = torch.nn.Conv2d(in_channels=16, out_channels=120, kernel_size=(5, 5), padding=0) # 连接层1 : 120 -> 84 # 链接层2 : 84 -> 10 self.layer_4 = torch.nn.Linear(120, 84) self.layer_5 = torch.nn.Linear(84, 10) def forward(self, input): # 预测模型实现 # 卷积层 t = self.layer_1(input) t = torch.nn.functional.relu(t) t = torch.nn.functional.max_pool2d(t, kernel_size=(2, 2)) t = self.layer_2(t) t = torch.nn.functional.relu(t) t = torch.nn.functional.max_pool2d(t, kernel_size=(2, 2)) t = self.layer_3(t) t = torch.nn.functional.relu(t) t = t.squeeze() # 长度为1的维数直接降维 # 链接层 t = self.layer_4(t) t= torch.nn.functional.relu(t) t = self.layer_5(t) t = torch.nn.functional.log_softmax(t, dim=1) return t ###Output _____no_output_____ ###Markdown 训练实现- 包含损失模型与优化模型 ###Code # 模型 model = LeNet_5() parameters = model.parameters() # 巡视函数 criterion = torch.nn.CrossEntropyLoss() # 优化器 optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 学习率 # 训练参数 epoch = 500 for e in range(epoch): # 批次处理 for data, target in train_loader: # 清空梯度 optimizer.zero_grad() # 计算输出 out = model(data) # 计算损失 loss = criterion(out, target) # 计算梯度 loss.backward() # 更新梯度 optimizer.step() # 一轮结束,可以使用测试集测试准确率 if e % 100 == 0: with torch.no_grad(): # 关闭梯度计算跟踪 for data, target in test_loader: y_ = model(data) predict = torch.argmax(y_, dim=1) correct_rate = (predict == target).float().mean() print(F"\t损失度:{loss:8.6f},\t准确率:{correct_rate * 100: 5.2f}%") ###Output 损失度:0.320754, 准确率: 91.86% 损失度:0.000031, 准确率: 98.89% 损失度:0.000005, 准确率: 98.87% 损失度:0.000001, 准确率: 98.87% 损失度:0.000000, 准确率: 98.86%
preparing-gcp-ml-engineer/launching-into-ml/decision_trees_and_random_Forests_in_Python.ipynb
###Markdown Decision Trees and Random Forests in Python**Learning Objectives**1. Explore and analyze data using a Pairplot2. Train a single Decision Tree3. Predict and evaluate the Decision Tree4. Compare the Decision Tree model to a Random Forest Introduction In this lab, you explore and analyze data using a Pairplot, train a single Decision Tree, predict and evaluate the Decision Tree, and compare the Decision Tree model to a Random Forest. Recall that the [Decision Tree](https://en.wikipedia.org/wiki/Decision_tree_learning) algorithm belongs to the family of supervised learning algorithms. Unlike other supervised learning algorithms, the decision tree algorithm can be used for solving both regression and classification problems too. Simply, the goal of using a Decision Tree is to create a training model that can use to predict the class or value of the target variable by learning simple decision rules inferred from prior data(training data). Each learning objective will correspond to a _TODO_ in this student lab notebook -- try to complete this notebook first and then review the [solution notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/launching_into_ml/solutions/decision_trees_and_random_Forests_in_Python.ipynb) ###Code !pip install scikit-learn==0.22.2 ###Output Collecting scikit-learn==0.22.2 Downloading scikit_learn-0.22.2-cp37-cp37m-manylinux1_x86_64.whl (7.1 MB)  |████████████████████████████████| 7.1 MB 7.0 MB/s eta 0:00:01 [?25hRequirement already satisfied: joblib>=0.11 in /opt/conda/lib/python3.7/site-packages (from scikit-learn==0.22.2) (1.0.1) Requirement already satisfied: scipy>=0.17.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn==0.22.2) (1.7.1) Requirement already satisfied: numpy>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from scikit-learn==0.22.2) (1.19.5) Installing collected packages: scikit-learn Attempting uninstall: scikit-learn Found existing installation: scikit-learn 0.24.2 Uninstalling scikit-learn-0.24.2: Successfully uninstalled scikit-learn-0.24.2 Successfully installed scikit-learn-0.22.2 ###Markdown **Restart** the kernel before proceeding further (On the Notebook menu, select Kernel > Restart Kernel > Restart). Load necessary libraries We will start by importing the necessary libraries for this lab. ###Code # Importing necessary tensorflow library and printing the TF version. import tensorflow as tf print("TensorFlow version: ",tf.version.VERSION) import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline ###Output _____no_output_____ ###Markdown Get the Data ###Code # Reading "kyphosis.csv" file using the read_csv() function included in the pandas library df = pd.read_csv('../kyphosis.csv') df.head() ###Output _____no_output_____ ###Markdown Exploratory Data Analysis **Lab Task 1:** Check a pairplot for this small dataset. ###Code # Use the pairplot() function to plot multiple pairwise bivariate distributions in a dataset # TODO 1 sns.pairplot(df,hue='Kyphosis',palette='Set1') ###Output _____no_output_____ ###Markdown Train Test SplitLet's split up the data into a training set and a test set! ###Code from sklearn.model_selection import train_test_split X = df.drop('Kyphosis',axis=1) y = df['Kyphosis'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30) ###Output _____no_output_____ ###Markdown Decision Trees **Lab Task 2:** Train a single decision tree. ###Code from sklearn.tree import DecisionTreeClassifier dtree = DecisionTreeClassifier() # Train Decision Tree Classifer # TODO 2 dtree.fit(X_train,y_train) ###Output _____no_output_____ ###Markdown Prediction and Evaluation **Lab Task 3:** Evaluate our decision tree. ###Code predictions = dtree.predict(X_test) from sklearn.metrics import classification_report,confusion_matrix # build a text report showing the main classification metrics # TODO 3a print(classification_report(y_test,predictions)) # compute confusion matrix to evaluate the accuracy of a classification # TODO 3b print(confusion_matrix(y_test,predictions)) ###Output [[19 2] [ 3 1]] ###Markdown Tree VisualizationScikit learn actually has some built-in visualization capabilities for decision trees, you won't use this often and it requires you to install the pydot library, but here is an example of what it looks like and the code to execute this: ###Code from IPython.display import Image from sklearn.externals.six import StringIO from sklearn.tree import export_graphviz import pydot features = list(df.columns[1:]) features dot_data = StringIO() export_graphviz(dtree, out_file=dot_data,feature_names=features,filled=True,rounded=True) graph = pydot.graph_from_dot_data(dot_data.getvalue()) Image(graph[0].create_png()) ###Output _____no_output_____ ###Markdown Random Forests **Lab Task 4:** Compare the decision tree model to a random forest. ###Code from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_estimators=100) rfc.fit(X_train, y_train) rfc_pred = rfc.predict(X_test) # compute confusion matrix to evaluate the accuracy # TODO 4a print(confusion_matrix(y_test,rfc_pred)) # build a text report showing the main metrics # TODO 4b print(classification_report(y_test,rfc_pred)) ###Output precision recall f1-score support absent 0.87 0.95 0.91 21 present 0.50 0.25 0.33 4 accuracy 0.84 25 macro avg 0.68 0.60 0.62 25 weighted avg 0.81 0.84 0.82 25
01_Regression.ipynb
###Markdown AutoML REGRESSION> API details. ###Code #hide from nbdev.showdoc import * #export import streamlit as st import streamlit.components.v1 as components from pdpbox import pdp import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import shap # load JS visualization code to notebook shap.initjs() import base64 from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris, load_digits #Simple Regressor from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.svm import SVR #Tree based Regressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.ensemble import ExtraTreesRegressor from xgboost import XGBRegressor #Gradient Based Regressor from sklearn.linear_model import SGDRegressor from sklearn.neural_network import MLPRegressor #Preprocessing packages from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import * from sklearn.decomposition import PCA #Metrics from sklearn import metrics from sklearn.metrics import * from sklearn.model_selection import GridSearchCV import random from sklearn.inspection import plot_partial_dependence import os import base64 from io import BytesIO def convert_str(a): a = str(a) return a def scaler(scaling_scheme='standard_scaler'): if scaling_scheme == 'max_abs_scaler': scal = MaxAbsScaler() elif scaling_scheme == 'min_max_scaler': scal = MinMaxScaler() elif scaling_scheme == 'normalizer': scal = Normalizer() elif scaling_scheme == 'quantile_transformer': scal = QuantileTransformer() elif scaling_scheme == 'robust_scaler': scal = RobustScaler() elif scaling_scheme == 'power_transformer': scal = PowerTransformer() elif scaling_scheme == 'standard_scaler': scal = StandardScaler() return scal def comb(X, pairwise_linear=False, pairwise_product=False): from itertools import combinations X_copy = X.copy() columns = [str(i) for i in X.columns] X.columns = columns comb = combinations(columns, 2) # Print the obtained combinations if pairwise_linear: for i in list(comb): a = i[0] b = i[1] col_name_add = a+'+'+b X_copy[col_name_add] = X[a]+X[b] col_name_sub = a+'-'+b X_copy[col_name_sub] = X[a]-X[b] if pairwise_product: comb = combinations(columns, 2) # Print the obtained combinations for i in list(comb): a = i[0] b = i[1] col_name = a+'*'+b X_copy[col_name] = X[a]*X[b] return X_copy def rf_colselector(X_train, y_train, no_of_cols, n_estimators=100): rf = RandomForestRegressor(n_estimators=n_estimators) rf.fit(X_train, y_train) importance = rf.feature_importances_ df_importance = pd.DataFrame(importance, index = X_train.columns, columns = ['importance']) importance_sorted = df_importance.sort_values(by=['importance'], ascending=False) selected_columns = importance_sorted[:no_of_cols].index return selected_columns def corr_colselector(X_train, y_train, threshold): d = pd.concat([X_train, y_train.reset_index(drop=True)], axis=1) columns = d.corr().iloc[:, -1][np.logical_or((d.corr().iloc[:, -1] > threshold), (d.corr().iloc[:, -1] < -threshold))].index return columns[:-1], d.corr() class ColProcessor(): def __init__(self, cardinality, rf_col=False, corr_col=False, label_enc=False, interaction_only=False, poly_feat=False): self.rf_col = rf_col self.corr_col = corr_col self.label_enc = label_enc self.interaction_only = interaction_only self.poly_feat = poly_feat self.cardinality = cardinality def fit(self, X, y=None): categorical_cols = [cname for cname in X.columns if X[cname].nunique() < self.cardinality and X[cname].dtype == "object"] numerical_cols = [cname for cname in X.columns if X[cname].dtype in ['int64', 'float64']] my_cols = categorical_cols + numerical_cols self.categorical_cols = categorical_cols self.numerical_cols = numerical_cols self.my_cols = my_cols X = X[my_cols].copy() imputer_num = SimpleImputer(strategy='constant') X_dum = imputer_num.fit_transform(X[self.numerical_cols]) self.imputer_num = imputer_num if self.categorical_cols: imputer_cat = SimpleImputer(strategy='most_frequent') X_cat = imputer_cat.fit_transform(X[self.categorical_cols]) self.imputer_cat = imputer_cat if not self.label_enc: Ohe = OneHotEncoder(handle_unknown='ignore') Ohe.fit(X_cat) self.Ohe = Ohe else: OrdEnc = OrdinalEncoder(handle_unknown='ignore') X_cat = OrdEnc.fit(X_cat) self.OrdEnc = OrdEnc return self def transform(self, X, y=None): X_num = pd.DataFrame(data=self.imputer_num.transform(X[self.numerical_cols]), columns=self.numerical_cols) if self.categorical_cols: if not self.label_enc: X_cat = pd.DataFrame(data=self.Ohe.transform(self.imputer_cat.transform(X[self.categorical_cols])).toarray(), columns=self.Ohe.get_feature_names(input_features=self.categorical_cols)) data = pd.concat([X_cat, X_num], axis = 1) else: X_cat = pd.DataFrame(self.OrdEnc.transform(self.imputer_cat.transform(X[self.categorical_cols])), columns=self.categorical_cols) data = pd.concat([X_cat.reset_index(drop=True), X_num], axis = 1) else: data = X_num return data, X_num def interaction_feats(X): interaction = PolynomialFeatures(2, interaction_only=True) interaction.fit(X) X_interaction = pd.DataFrame(data=interaction.transform(X), columns=interaction.get_feature_names(X.columns)) return X_interaction def poly_feats(X): poly = PolynomialFeatures(2) poly.fit(X) X_poly = pd.DataFrame(data=poly.transform(X), columns=poly.get_feature_names(X.columns)) return X_poly def pca_feats(X, n_comp): pca = PCA(n_components=n_comp) pca.fit(X) X_pca = pd.DataFrame(data=pca.transform(X)) return X_pca def clubbed_feats(X, polynomial_features, interaction_only, pca_on): if polynomial_features: X = poly_feats(X) elif interaction_only: X = interaction_feats(X) if pca_on: X = pca_feats(X, 100) return X def preprocess(X_train, y_train, X_valid, X_test=None, rf_col_selection=False, rf_no_of_cols=20, rf_n_estimators=100, corr_col_selection=False, corr_threshold=0.01, pairwise_linear=False, pairwise_product=False): X_train = comb(X=X_train, pairwise_linear=pairwise_linear, pairwise_product=pairwise_product) X_valid = comb(X=X_valid, pairwise_linear=pairwise_linear, pairwise_product=pairwise_product) if type(X_test)!=type(None): X_test = comb(X=X_test, pairwise_linear=pairwise_linear, pairwise_product=pairwise_product) return X_train, X_valid, X_test def final_preprocessor(X_train, y_train, X_valid, X_test=None, rf_col_selection=False, rf_no_of_cols=20, rf_n_estimators=100, corr_col_selection=False, corr_threshold=0.01, pairwise_linear=False, pairwise_product=False, cardinality=100, polynomial_features=False, interaction_only=False, pca_on=False, label_enc=False ): col = ColProcessor(cardinality=100, label_enc=label_enc) col.fit(X_train) data_train, X_train_num = col.transform(X_train) data_valid, X_valid_num = col.transform(X_valid) if type(X_test)!=type(None): data_test, X_test_num = col.transform(X_test) else: X_test_num = None X_train_num = clubbed_feats(X_train_num, polynomial_features=polynomial_features, interaction_only=interaction_only, pca_on=pca_on) X_valid_num = clubbed_feats(X_valid_num, polynomial_features=polynomial_features, interaction_only=interaction_only, pca_on=pca_on) if type(X_test)!=type(None): X_test_num = clubbed_feats(X_test_num, polynomial_features=polynomial_features, interaction_only=interaction_only, pca_on=pca_on) train, valid, test = preprocess(X_train_num, y_train, X_valid_num, X_test_num, rf_col_selection=rf_col_selection, rf_no_of_cols=rf_no_of_cols, rf_n_estimators=rf_n_estimators, corr_col_selection=corr_col_selection, corr_threshold=corr_threshold, pairwise_linear=pairwise_linear, pairwise_product=pairwise_product ) if col.categorical_cols: if not label_enc: Ohe_cat_cols = col.Ohe.get_feature_names(col.categorical_cols) train = pd.concat([train, data_train[Ohe_cat_cols]], axis=1) valid = pd.concat([valid, data_valid[Ohe_cat_cols]], axis=1) if type(X_test)!=type(None): test = pd.concat([test, data_test[Ohe_cat_cols]], axis=1) else: train = data_train valid = data_valid if type(X_test)!=type(None): test = data_test if rf_col_selection: columns_selected = rf_colselector(train, y_train, no_of_cols=rf_no_of_cols, n_estimators=rf_n_estimators) train = train[columns_selected] valid = valid[columns_selected] if type(X_test)!=type(None): test = test[columns_selected] if corr_col_selection: corr_cols, df = corr_colselector(train, y_train, threshold=corr_threshold) train = train[corr_cols] valid = valid[corr_cols] if type(X_test)!=type(None): test = test[corr_cols] return train, valid, test, col def combined_metrics(X_test, y_test, clf): metrics_list = [[explained_variance_score(y_test, clf.predict(X_test))], [max_error(y_test, clf.predict(X_test))], [mean_absolute_error(y_test, clf.predict(X_test))], [mean_squared_error(y_test, clf.predict(X_test))], # [mean_squared_log_error(y_test, clf.predict(X_test))], [median_absolute_error(y_test, clf.predict(X_test))], [mean_absolute_percentage_error(y_test, clf.predict(X_test))], [r2_score(y_test, clf.predict(X_test))], # [mean_poisson_deviance(y_test, clf.predict(X_test))], # [mean_gamma_deviance(y_test, clf.predict(X_test))], ] index = ['Explained Variance', 'Max Error', 'Mean Absolute Error', 'Mean Squared Error', # 'Mean Squared Log Error', 'Median Absolute Error', 'Mean Absolute Percentage Error', 'R2 Score', # 'Mean Poisson Deviance', # 'Mean Gamma Deviance' ] df_metric = pd.DataFrame(metrics_list, index = index, columns = ['Value']) return df_metric def to_excel(df): output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') df.to_excel(writer, index = False, sheet_name='Sheet1') workbook = writer.book worksheet = writer.sheets['Sheet1'] format1 = workbook.add_format({'num_format': '0.00'}) # Tried with '0%' and '#,##0.00' also. worksheet.set_column('A:A', None, format1) # Say Data are in column A writer.save() processed_data = output.getvalue() return processed_data def get_table_download_link(df): """Generates a link allowing the data in a given panda dataframe to be downloaded in: dataframe out: href string """ val = to_excel(df) b64 = base64.b64encode(val) # val looks like b'...' return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="Your_File.xlsx">Download output file</a>' # decode b'abc' => abc def GNB(): gnb_params = {'clf__estimator':[GaussianNB()] } return gnb_params def LinearReg(): lin_params = {'clf__estimator': [LinearRegression()] } st.subheader('Linear Regression') fit_intercept = st.multiselect('Fit Intercept', [True, False], [True]) normalize = st.multiselect('Normalize', [True, False], [False]) lin_params['clf__estimator__fit_intercept'] = fit_intercept lin_params['clf__estimator__normalize'] = normalize return lin_params def LogisticReg(): lr_params = {'clf__estimator': [LogisticRegression()] } st.subheader('Logistic Regression') penalty = st.multiselect('Penalty', ['l1', 'l2'], ['l2']) reg = st.multiselect('C', [0.1, 1.0, 2.0], [1.0]) solver = st.multiselect('Solver', ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga'], ['liblinear']) lr_params['clf__estimator__penalty'] = penalty lr_params['clf__estimator__C'] = reg lr_params['clf__estimator__solver'] = solver return lr_params def KNN(): knn_params = {'clf__estimator': [KNeighborsRegressor()] } st.subheader('KNN') n_neighbors = st.multiselect('Neighbors', list(range(1,30)), [5]) leaf_size = st.multiselect('Leaf Size', list(range(1,50)), [30]) p_distance = st.multiselect('Distance Metric', [1,2], [2]) knn_params['clf__estimator__n_neighbors'] = n_neighbors knn_params['clf__estimator__leaf_size'] = leaf_size knn_params['clf__estimator__p'] = p_distance return knn_params def SVM(): svm_params = {'clf__estimator': [SVR()] } st.subheader('Support Vector Machines') c = st.multiselect('C', [0.1, 1, 10, 100, 1000], [1]) gamma = st.multiselect('Gamma', ['scale', 'auto'], ['scale']) kernel = st.multiselect('Kernel', ['linear', 'rbf', 'poly', 'sigmoid'], ['rbf']) svm_params['clf__estimator__C'] = c svm_params['clf__estimator__gamma'] = gamma svm_params['clf__estimator__kernel'] = kernel return svm_params def DT(): dt_params = {'clf__estimator': [DecisionTreeRegressor()]} st.subheader('Decision Tree') criterion = st.multiselect('Criterion', ["gini", "entropy"], ['gini']) min_samp_split = st.multiselect('Min Samples Split', [2, 10], [2]) max_depth = st.multiselect('Max Depth', [2, 5, 10], [10]) dt_params['clf__estimator__criterion'] = criterion dt_params['clf__estimator__min_samples_leaf'] = min_samp_split dt_params['clf__estimator__max_depth'] = max_depth return dt_params def RF(): rf_params = {'clf__estimator': [RandomForestRegressor()] } st.subheader('Random Forest') n_estimators = st.multiselect('Number of Trees', [100, 200, 500], [100]) max_features = st.multiselect('Max Features', [2, 10, 'auto', 'sqrt', 'log2'], ['auto']) max_depth = st.multiselect('Max Depth', [4,5,6,7,8, None], [None]) criterion = st.multiselect('Criteria', ['gini', 'entropy'], ['gini']) rf_params['clf__estimator__n_estimators'] = n_estimators rf_params['clf__estimator__max_features'] = max_features rf_params['clf__estimator__max_depth'] = max_depth rf_params['clf__estimator__criterion'] = criterion return rf_params def GB(): gb_params = {'clf__estimator': [GradientBoostingRegressor()] } st.subheader('Gradient Booster') loss = st.multiselect('Loss Function', ['deviance', 'exponential'], ['deviance']) learning_rate = st.multiselect('Learning Rate', [0.001, 0.01, 0.1], [0.1]) min_samples_split = st.multiselect('Min Samples Split', list(range(1, 10)), [2]) min_samples_leaf = st.multiselect('Min Samples Leaf', list(range(1, 10)), [1]) max_depth = st.multiselect('Max Depth', [1, 2, 3, 4, 5, 6], [3]) max_features = st.multiselect('Max Features', ['auto', 'log2', 'sqrt', None], [None]) criterion = st.multiselect('Criterion', ['friedman_mse', 'mse', 'mae'], ['friedman_mse']) subsample = st.multiselect('Subsample', [0.5, 0.618, 0.8, 0.85, 0.9, 0.95, 1.0], [1.0]) n_estimators = st.multiselect('Number of Trees', [50, 100, 150, 200, 250], [100]) gb_params['clf__estimator__loss'] = loss gb_params['clf__estimator__learning_rate'] = learning_rate gb_params['clf__estimator__min_samples_split'] = min_samples_split gb_params['clf__estimator__min_samples_leaf'] = min_samples_leaf gb_params['clf__estimator__max_depth'] = max_depth gb_params['clf__estimator__max_features'] = max_features gb_params['clf__estimator__criterion'] = criterion gb_params['clf__estimator__subsample'] = subsample gb_params['clf__estimator__n_estimators'] = n_estimators return gb_params def ERT(): ert_params = {'clf__estimator': [ExtraTreesRegressor()] } st.subheader('Extra Random Trees') n_estimators = st.multiselect('Number of Trees', [100, 200, 500, 1000], [100]) #fix max_depth = st.multiselect('Max Depth', [None, 4, 5, 6, 7, 8, 9], [None]) #fix min_samples_leaf = st.multiselect('Min Sample per Leaf', [1, 2, 3, 4, 5], [1]) n_jobs = st.selectbox('Parallelism', [1, 2, 3, 4, -1], 4) ert_params['clf__estimator__n_estimators'] = n_estimators ert_params['clf__estimator__max_depth'] = max_depth ert_params['clf__estimator__min_samples_leaf'] = min_samples_leaf ert_params['clf__estimator__n_jobs'] = [n_jobs] return ert_params def XGB(): xgb_params ={'clf__estimator':[XGBRegressor()] } st.subheader('XGBoost') n_estimators = st.multiselect('Number of Trees', list(range(50, 1000, 50)), [100]) #fix max_depth = st.multiselect('Max Depth', list(range(1, 20)), [6]) #fix min_child_weight = st.multiselect('Min Child Weight', list(range(1, 10, 1)), [1]) gamma = st.multiselect('Gamma', list(range(0, 10)), [1]) learning_rate = st.multiselect('Learning Rate', [0.01, 0.05, 0.1, 0.2, 0.3], [0.3]) subsample = st.multiselect('Subsample', list(np.divide(range(5, 11), 10)), [1.0]) booster = st.multiselect('Booster', ['gbtree', 'gblinear'], ['gbtree']) xgb_params['clf__estimator__n_estimators'] = n_estimators xgb_params['clf__estimator__max_depth'] = max_depth xgb_params['clf__estimator__min_child_weight'] = min_child_weight xgb_params['clf__estimator__gamma'] = gamma xgb_params['clf__estimator__learning_rate'] = learning_rate xgb_params['clf__estimator__subsample'] = subsample xgb_params['clf__estimator__booster'] = booster return xgb_params def SGD(): sgd_params = {'clf__estimator': [SGDRegressor()] } st.subheader('SGD') loss = st.multiselect('Loss Function', ['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'], ['hinge']) #fix max_iter = st.multiselect('Max Iterations', list(np.multiply(range(5, 16), 100)), [1000]) #fix tol = st.multiselect('Tolerance', [0.0001, 0.001, 0.05, 0.1], [0.0001]) penalty = st.multiselect('Penalty', ['l2', 'l1', 'elasticnet'], ['l2']) alpha = st.multiselect('Alpha', [0.0001, 0.001, 0.05, 0.1, 0.2, 0.3], [0.0001]) n_jobs = st.selectbox('Parallelization', [1, 2, 3, 4, -1], 4) sgd_params['clf__estimator__loss'] = loss sgd_params['clf__estimator__max_iter'] = max_iter sgd_params['clf__estimator__tol'] = tol sgd_params['clf__estimator__penalty'] = penalty sgd_params['clf__estimator__alpha'] = alpha sgd_params['clf__estimator__n_jobs'] = [n_jobs] return sgd_params def NN(): nn_params = {'clf__estimator': [MLPRegressor()] } st.subheader('Neural Network') solver = st.multiselect('Solver', ['lbfgs', 'sgd', 'adam'], ['adam']) max_iter = st.multiselect('Max Iterations', [1000,1100,1200,1300,1400], [1000]) alpha = st.multiselect('Alpha', list(10.0 ** -np.arange(1, 10)), [0.0001]) hidden_layer_sizes = st.multiselect('Hidden Layer Sizes', list(range(50, 500, 50)), [100]) # hidden_layer_sizes = st.multiselect('Hidden Layer Sizes', [50, 100, 150, 200, 250, 300, 350, 400, 450, 500] , [100]) nn_params['clf__estimator__solver'] = solver nn_params['clf__estimator__max_iter'] = max_iter nn_params['clf__estimator__alpha'] = alpha nn_params['clf__estimator__hidden_layer_sizes'] = hidden_layer_sizes return nn_params data = st.file_uploader('Upload a csv') test_data = st.file_uploader('Upload a csv for prediction:') if (data != None) & (test_data != None): df = pd.read_csv(data) df_test = pd.read_csv(test_data) target_col =st.selectbox('Choose target variable', df.columns) X = df.drop(target_col, axis = 1) y = df[target_col] test_ratio = st.number_input('Enter test split ratio, 0 < ratio < 1', min_value = 0.0, max_value = 1.0, value = 0.2) if test_ratio: X_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, test_size=test_ratio, random_state = 0) rf_col_selection = st.sidebar.selectbox( 'Random Forest Column Selection', [True, False], 1) corr_col_selection = st.sidebar.selectbox( 'Correlation Column Selection', [True, False], 1) pairwise_linear = st.sidebar.selectbox( 'Pairwise Linear', [True, False], 1) pairwise_product = st.sidebar.selectbox( 'Pairwise Product', [True, False], 1) polynomial_features = st.sidebar.selectbox( 'Polynomial Features', [True, False], 1) interaction_only = st.sidebar.selectbox( 'Interaction Only', [True, False], 1) pca_on = st.sidebar.selectbox( 'Principal Component Analysis', [True, False], 1) label_enc = st.sidebar.selectbox( 'Label Encoding', [True, False], 1) selected_models = st.sidebar.multiselect( 'Choose Algorithms:',( 'Gaussian NB', 'Linear Regression', 'Logistic Regression', 'KNN', 'Support Vector Machines', 'Decision Tree', 'Random Forest', 'Gradient Boosting', 'Extra Random Trees', 'XGBoost', 'Stochastic Gradient Descent', 'Neural Network'), ['KNN', 'Support Vector Machines', 'Decision Tree']) if selected_models: func_dict = {'Gaussian NB': GNB(), 'Linear Regression': LinearReg(), 'Logistic Regression':LogisticReg(), 'KNN': KNN(), 'Support Vector Machines': SVM(), 'Decision Tree': DT(), 'Random Forest': RF(), 'Gradient Boosting': GB(), 'Extra Random Trees': ERT(), 'XGBoost': XGB(), 'Stochastic Gradient Descent': SGD(), 'Neural Network': NN() } param_dict = {} for i in selected_models: param_dict[i] = func_dict[i] from sklearn.base import BaseEstimator, RegressorMixin class MyRegressor(BaseEstimator, RegressorMixin): def __init__( self, estimator = XGBRegressor(), ): """ A Custom BaseEstimator that can switch between Regressor. :param estimator: sklearn object - The Regressor """ self.estimator = estimator def fit(self, X, y=None, **kwargs): self.estimator.fit(X, y) return self def predict(self, X, y=None): return self.estimator.predict(X) def predict_proba(self, X): return self.estimator.predict_proba(X) def score(self, X, y): return self.estimator.score(X, y) @property def classes_(self): return self.estimator.classes_ X_train, X_valid, df_test, col = final_preprocessor(X_train_full, y_train, X_valid_full, df_test, rf_col_selection=rf_col_selection, rf_no_of_cols=20, rf_n_estimators=100, corr_col_selection=corr_col_selection, corr_threshold=0.2, pairwise_linear=pairwise_linear, pairwise_product=pairwise_product, cardinality=100, polynomial_features=polynomial_features, interaction_only=interaction_only, pca_on=pca_on, label_enc=label_enc ) data_valid = pd.concat([X_valid, y_valid.reset_index(drop=True)], axis = 1) st.write(X_train.shape) my_pipeline = Pipeline([('scaler', scaler(scaling_scheme='power_transformer')), ('clf', MyRegressor()) ]) parameters = [] for i in selected_models: parameters.append(param_dict[i]) st.write(parameters) train = st.button('Train Model') if train: with st.spinner('Training Model...'): from sklearn.model_selection import GridSearchCV gscv = GridSearchCV(my_pipeline, parameters, cv=3, n_jobs=-1, return_train_score=False, verbose=3) gscv.fit(X_train, y_train) st.text('Best Parameters') st.write(gscv.best_params_) st.text('Best Score') st.write(gscv.best_score_) st.text('Validation Score') st.write(gscv.score(X_valid, y_valid)) st.text('Fit vs Time vs HyperParameters') data = gscv.cv_results_.values() columns = gscv.cv_results_.keys() df_fit = pd.DataFrame(data, columns).T df_fit['param_clf__estimator'] = df_fit['param_clf__estimator'].apply(convert_str) st.write(df_fit) st.text('Prediction on Validation Data') data_valid['Predicted'] = gscv.predict(X_valid) st.write(data_valid) st.text('Performance Metrics') st.write(combined_metrics(X_valid, y_valid, gscv)) st.text('Scatter Plot: Actual vs Predicted') #Scatter Plot of Actual vs Predicted fig, ax = plt.subplots(figsize=(20, 10)) sns.regplot(x=y_valid, y=gscv.predict(X_valid), scatter_kws={"color":"green"}, line_kws={"color": "orange"}, ax=ax, marker='.') ax.set_ylabel('Actual Values') ax.set_xlabel('Predicted Values') st.pyplot(fig) st.text('Error Distribution Plot') #Error Distribution Plot error = gscv.predict(X_valid) - y_valid fig, ax = plt.subplots(figsize=(10, 5)) sns.histplot(data=error, bins=40) st.pyplot(fig) st.text('Partial Dependence Plot') features = [0, 1, (0, 1)] fig, ax = plt.subplots(1,3, figsize = (15,9)) plot_partial_dependence(gscv,X_valid, features=features, ax=ax) plt.tight_layout() st.pyplot(fig) st.text('ICE Plot') features = [0, 1] fig, ax = plt.subplots(figsize=(14, 12)) plot_partial_dependence(gscv, X_valid, features, kind='both', ax=ax) plt.tight_layout() st.pyplot(fig) st.text('Prediction on Test file') df_test['Predicted'] = gscv.predict(df_test) st.write(df_test) st.text('Shapley Explainer') # X_test = df_test.drop('Predicted', axis = 1) explainer = shap.KernelExplainer(gscv.predict, X_valid) shap_values = explainer.shap_values(X_valid.iloc[2,:]) st.pyplot(shap.force_plot(explainer.expected_value, shap_values, X_valid.iloc[2,:], matplotlib=True, text_rotation=8)) st.text('Shapley Explainer WaterFall Plot') f = lambda x: gscv.predict(x) med = X_train.median().values.reshape(1,X_valid.shape[1]) explainer = shap.Explainer(f, med) shap_values = explainer(X_valid.iloc[0:100,:]) st.pyplot(shap.plots.waterfall(shap_values[0], max_display=7)) st.text('Partial Dependence Plot from pdp_box') pdp_ = pdp.pdp_isolate(model=gscv, dataset=X_valid, model_features=X_valid.columns, feature=X_valid.columns[0]) fig, axes = pdp.pdp_plot(pdp_isolate_out=pdp_, feature_name=X_valid.columns[0], center = True, ncols=1, figsize = (15, 10)) st.pyplot(fig) from nbdev.export import notebook2script; notebook2script() ###Output Converted 00_Classification.ipynb. Converted 01_Regression.ipynb. Converted index.ipynb.
hw_wordsim_training.ipynb
###Markdown Homework and bake-off: Word similarity ###Code __author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Fall 2020" ###Output _____no_output_____ ###Markdown Contents1. [Overview](Overview)1. [Set-up](Set-up)1. [Dataset readers](Dataset-readers)1. [Dataset comparisons](Dataset-comparisons) 1. [Vocab overlap](Vocab-overlap) 1. [Pair overlap and score correlations](Pair-overlap-and-score-correlations)1. [Evaluation](Evaluation) 1. [Dataset evaluation](Dataset-evaluation) 1. [Dataset error analysis](Dataset-error-analysis) 1. [Full evaluation](Full-evaluation)1. [Homework questions](Homework-questions) 1. [PPMI as a baseline [0.5 points]](PPMI-as-a-baseline-[0.5-points]) 1. [Gigaword with LSA at different dimensions [0.5 points]](Gigaword-with-LSA-at-different-dimensions-[0.5-points]) 1. [Gigaword with GloVe [0.5 points]](Gigaword-with-GloVe-[0.5-points]) 1. [Dice coefficient [0.5 points]](Dice-coefficient-[0.5-points]) 1. [t-test reweighting [2 points]](t-test-reweighting-[2-points]) 1. [Enriching a VSM with subword information [2 points]](Enriching-a-VSM-with-subword-information-[2-points]) 1. [Your original system [3 points]](Your-original-system-[3-points])1. [Bake-off [1 point]](Bake-off-[1-point]) OverviewWord similarity datasets have long been used to evaluate distributed representations. This notebook provides basic code for conducting such analyses with a number of datasets:| Dataset | Pairs | Task-type | Current best Spearman $\rho$ | Best $\rho$ paper | ||---------|-------|-----------|------------------------------|-------------------|---|| [WordSim-353](http://www.gabrilovich.com/resources/data/wordsim353/) | 353 | Relatedness | 82.8 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) || [MTurk-771](http://www2.mta.ac.il/~gideon/mturk771.html) | 771 | Relatedness | 81.0 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) || [The MEN Test Collection](https://staff.fnwi.uva.nl/e.bruni/MEN) | 3,000 | Relatedness | 86.6 | [Speer et al. 2017](https://arxiv.org/abs/1612.03975) | | [SimVerb-3500-dev](https://www.aclweb.org/anthology/D16-1235/) | 500 | Similarity | 61.1 | [Mrki&scaron;&cacute; et al. 2016](https://arxiv.org/pdf/1603.00892.pdf) || [SimVerb-3500-test](https://www.aclweb.org/anthology/D16-1235/) | 3,000 | Similarity | 62.4 | [Mrki&scaron;&cacute; et al. 2016](https://arxiv.org/pdf/1603.00892.pdf) |Each of the similarity datasets contains word pairs with an associated human-annotated similarity score. (We convert these to distances to align intuitively with our distance measure functions.) The evaluation code measures the distance between the word pairs in your chosen VSM (which should be a `pd.DataFrame`).The evaluation metric for each dataset is the [Spearman correlation coefficient $\rho$](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient) between the annotated scores and your distances, as is standard in the literature. We also macro-average these correlations across the datasets for an overall summary. (In using the macro-average, we are saying that we care about all the datasets equally, even though they vary in size.)This homework ([questions at the bottom of this notebook](Homework-questions)) asks you to write code that uses the count matrices in `data/vsmdata` to create and evaluate some baseline models as well as an original model $M$ that you design. This accounts for 9 of the 10 points for this assignment.For the associated bake-off, we will distribute two new word similarity or relatedness datasets and associated reader code, and you will evaluate $M$ (no additional training or tuning allowed!) on those new datasets. Systems that enter will receive the additional homework point, and systems that achieve the top score will receive an additional 0.5 points. Set-up ###Code from collections import defaultdict import csv import itertools import numpy as np import os import pandas as pd from scipy.stats import spearmanr import vsm from IPython.display import display VSM_HOME = os.path.join('data', 'vsmdata') WORDSIM_HOME = os.path.join('data', 'wordsim') ###Output _____no_output_____ ###Markdown Dataset readers ###Code def wordsim_dataset_reader( src_filename, header=False, delimiter=',', score_col_index=2): """ Basic reader that works for all similarity datasets. They are all tabular-style releases where the first two columns give the word and a later column (`score_col_index`) gives the score. Parameters ---------- src_filename : str Full path to the source file. header : bool Whether `src_filename` has a header. delimiter : str Field delimiter in `src_filename`. score_col_index : int Column containing the similarity scores Default: 2 Yields ------ (str, str, float) (w1, w2, score) where `score` is the negative of the similarity score in the file so that we are intuitively aligned with our distance-based code. To align with our VSMs, all the words are downcased. """ with open(src_filename) as f: reader = csv.reader(f, delimiter=delimiter) if header: next(reader) for row in reader: w1 = row[0].strip().lower() w2 = row[1].strip().lower() score = row[score_col_index] # Negative of scores to align intuitively with distance functions: score = -float(score) yield (w1, w2, score) def wordsim353_reader(): """WordSim-353: http://www.gabrilovich.com/resources/data/wordsim353/""" src_filename = os.path.join( WORDSIM_HOME, 'wordsim353', 'combined.csv') return wordsim_dataset_reader( src_filename, header=True) def mturk771_reader(): """MTURK-771: http://www2.mta.ac.il/~gideon/mturk771.html""" src_filename = os.path.join( WORDSIM_HOME, 'MTURK-771.csv') return wordsim_dataset_reader( src_filename, header=False) def simverb3500dev_reader(): """SimVerb-3500: https://www.aclweb.org/anthology/D16-1235/""" src_filename = os.path.join( WORDSIM_HOME, 'SimVerb-3500', 'SimVerb-500-dev.txt') return wordsim_dataset_reader( src_filename, delimiter="\t", header=False, score_col_index=3) def simverb3500test_reader(): """SimVerb-3500: https://www.aclweb.org/anthology/D16-1235/""" src_filename = os.path.join( WORDSIM_HOME, 'SimVerb-3500', 'SimVerb-3000-test.txt') return wordsim_dataset_reader( src_filename, delimiter="\t", header=False, score_col_index=3) def men_reader(): """MEN: https://staff.fnwi.uva.nl/e.bruni/MEN""" src_filename = os.path.join( WORDSIM_HOME, 'MEN', 'MEN_dataset_natural_form_full') return wordsim_dataset_reader( src_filename, header=False, delimiter=' ') ###Output _____no_output_____ ###Markdown This collection of readers will be useful for flexible evaluations: ###Code READERS = (wordsim353_reader, mturk771_reader, simverb3500dev_reader, simverb3500test_reader, men_reader) ###Output _____no_output_____ ###Markdown Dataset comparisonsThis section does some basic analysis of the datasets. The goal is to obtain a deeper understanding of what problem we're solving – what strengths and weaknesses the datasets have and how they relate to each other. For a full-fledged project, we would want to continue work like this and report on it in the paper, to provide context for the results. ###Code def get_reader_name(reader): """ Return a cleaned-up name for the dataset iterator `reader`. """ return reader.__name__.replace("_reader", "") ###Output _____no_output_____ ###Markdown Vocab overlapHow many vocabulary items are shared across the datasets? ###Code def get_reader_vocab(reader): """Return the set of words (str) in `reader`.""" vocab = set() for w1, w2, _ in reader(): vocab.add(w1) vocab.add(w2) return vocab def get_reader_vocab_overlap(readers=READERS): """ Get data on the vocab-level relationships between pairs of readers. Returns a a pd.DataFrame containing this information. """ data = [] for r1, r2 in itertools.product(readers, repeat=2): v1 = get_reader_vocab(r1) v2 = get_reader_vocab(r2) d = { 'd1': get_reader_name(r1), 'd2': get_reader_name(r2), 'overlap': len(v1 & v2), 'union': len(v1 | v2), 'd1_size': len(v1), 'd2_size': len(v2)} data.append(d) return pd.DataFrame(data) vocab_overlap = get_reader_vocab_overlap() def vocab_overlap_crosstab(vocab_overlap): """ Return an intuitively formatted `pd.DataFrame` giving vocab-overlap counts for all the datasets represented in `vocab_overlap`, the output of `get_reader_vocab_overlap`. """ xtab = pd.crosstab( vocab_overlap['d1'], vocab_overlap['d2'], values=vocab_overlap['overlap'], aggfunc=np.mean) # Blank out the upper right to reduce visual clutter: for i in range(0, xtab.shape[0]): for j in range(i+1, xtab.shape[1]): xtab.iloc[i, j] = '' return xtab vocab_overlap_crosstab(vocab_overlap) ###Output _____no_output_____ ###Markdown This looks reasonable. By design, the SimVerb dev and test sets have a lot of overlap. The other overlap numbers are pretty small, even adjusting for dataset size. Pair overlap and score correlationsHow many word pairs are shared across datasets and, for shared pairs, what is the correlation between their scores? That is, do the datasets agree? ###Code def get_reader_pairs(reader): """ Return the set of alphabetically-sorted word (str) tuples in `reader` """ return {tuple(sorted([w1, w2])): score for w1, w2, score in reader()} def get_reader_pair_overlap(readers=READERS): """Return a `pd.DataFrame` giving the number of overlapping word-pairs in pairs of readers, along with the Spearman correlations. """ data = [] for r1, r2 in itertools.product(READERS, repeat=2): if r1.__name__ != r2.__name__: d1 = get_reader_pairs(r1) d2 = get_reader_pairs(r2) overlap = [] for p, s in d1.items(): if p in d2: overlap.append([s, d2[p]]) if overlap: s1, s2 = zip(*overlap) rho = spearmanr(s1, s2)[0] else: rho = None # Canonical order for the pair: n1, n2 = sorted([get_reader_name(r1), get_reader_name(r2)]) d = { 'd1': n1, 'd2': n2, 'pair_overlap': len(overlap), 'rho': rho} data.append(d) df = pd.DataFrame(data) df = df.sort_values(['pair_overlap','d1','d2'], ascending=False) # Return only every other row to avoid repeats: return df[::2].reset_index(drop=True) if 'IS_GRADESCOPE_ENV' not in os.environ: display(get_reader_pair_overlap()) ###Output _____no_output_____ ###Markdown This looks reasonable: none of the datasets have a lot of overlapping pairs, so we don't have to worry too much about places where they give conflicting scores. EvaluationThis section builds up the evaluation code that you'll use for the homework and bake-off. For illustrations, I'll read in a VSM created from `data/vsmdata/giga_window5-scaled.csv.gz`: ###Code giga5 = pd.read_csv( os.path.join(VSM_HOME, "giga_window5-scaled.csv.gz"), index_col=0) ###Output _____no_output_____ ###Markdown Dataset evaluation ###Code def word_similarity_evaluation(reader, df, distfunc=vsm.cosine): """ Word-similarity evalution framework. Parameters ---------- reader : iterator A reader for a word-similarity dataset. Just has to yield tuples (word1, word2, score). df : pd.DataFrame The VSM being evaluated. distfunc : function mapping vector pairs to floats. The measure of distance between vectors. Can also be `vsm.euclidean`, `vsm.matching`, `vsm.jaccard`, as well as any other float-valued function on pairs of vectors. Raises ------ ValueError If `df.index` is not a subset of the words in `reader`. Returns ------- float, data `float` is the Spearman rank correlation coefficient between the dataset scores and the similarity values obtained from `df` using `distfunc`. This evaluation is sensitive only to rankings, not to absolute values. `data` is a `pd.DataFrame` with columns['word1', 'word2', 'score', 'distance']. """ data = [] for w1, w2, score in reader(): d = {'word1': w1, 'word2': w2, 'score': score} for w in [w1, w2]: if w not in df.index: raise ValueError( "Word '{}' is in the similarity dataset {} but not in the " "DataFrame, making this evaluation ill-defined. Please " "switch to a DataFrame with an appropriate vocabulary.". format(w, get_reader_name(reader))) d['distance'] = distfunc(df.loc[w1], df.loc[w2]) data.append(d) data = pd.DataFrame(data) rho, pvalue = spearmanr(data['score'].values, data['distance'].values) return rho, data rho, eval_df = word_similarity_evaluation(men_reader, giga5) rho eval_df.head() ###Output _____no_output_____ ###Markdown Dataset error analysisFor error analysis, we can look at the words with the largest delta between the gold score and the distance value in our VSM. We do these comparisons based on ranks, just as with our primary metric (Spearman $\rho$), and we normalize both rankings so that they have a comparable number of levels. ###Code def word_similarity_error_analysis(eval_df): eval_df['distance_rank'] = _normalized_ranking(eval_df['distance']) eval_df['score_rank'] = _normalized_ranking(eval_df['score']) eval_df['error'] = abs(eval_df['distance_rank'] - eval_df['score_rank']) return eval_df.sort_values('error') def _normalized_ranking(series): ranks = series.rank(method='dense') return ranks / ranks.sum() ###Output _____no_output_____ ###Markdown Best predictions: ###Code word_similarity_error_analysis(eval_df).head() ###Output _____no_output_____ ###Markdown Worst predictions: ###Code word_similarity_error_analysis(eval_df).tail() ###Output _____no_output_____ ###Markdown Full evaluation A full evaluation is just a loop over all the readers on which one want to evaluate, with a macro-average at the end: ###Code def full_word_similarity_evaluation(df, readers=READERS, distfunc=vsm.cosine): """ Evaluate a VSM against all datasets in `readers`. Parameters ---------- df : pd.DataFrame readers : tuple The similarity dataset readers on which to evaluate. distfunc : function mapping vector pairs to floats. The measure of distance between vectors. Can also be `vsm.euclidean`, `vsm.matching`, `vsm.jaccard`, as well as any other float-valued function on pairs of vectors. Returns ------- pd.Series Mapping dataset names to Spearman r values. """ scores = {} for reader in readers: try: score, _ = word_similarity_evaluation(reader, df, distfunc=distfunc) scores[get_reader_name(reader)] = score except Exception as e: print(e) scores[get_reader_name(reader)] = np.nan series = pd.Series(scores, name='Spearman r') series['Macro-average'] = series.mean() return series full_word_similarity_evaluation(giga5) if 'IS_GRADESCOPE_ENV' not in os.environ: display(full_word_similarity_evaluation(giga5)) ###Output _____no_output_____ ###Markdown Homework questionsPlease embed your homework responses in this notebook, and do not delete any cells from the notebook. (You are free to add as many cells as you like as part of your responses.) PPMI as a baseline [0.5 points]The insight behind PPMI is a recurring theme in word representation learning, so it is a natural baseline for our task. For this question, write a function called `run_giga_ppmi_baseline` that does the following:1. Reads the Gigaword count matrix with a window of 20 and a flat scaling function into a `pd.DataFrame`s, as is done in the VSM notebooks. The file is `data/vsmdata/giga_window20-flat.csv.gz`, and the VSM notebooks provide examples of the needed code.1. Reweights this count matrix with PPMI.1. Evaluates this reweighted matrix using `full_word_similarity_evaluation`. The return value of `run_giga_ppmi_baseline` should be the return value of this call to `full_word_similarity_evaluation`.The goal of this question is to help you get more familiar with the code in `vsm` and the function `full_word_similarity_evaluation`.The function `test_run_giga_ppmi_baseline` can be used to test that you've implemented this specification correctly. ###Code def run_giga_ppmi_baseline(): ##### YOUR CODE HERE # Reads the Gigaword count matrix with a window of 20 and a flat scaling function into a pd.DataFrame giga20 = pd.read_csv( os.path.join(VSM_HOME, "giga_window20-flat.csv.gz"), index_col=0) # Reweights this count matrix with PPMI giga20_PPMI = vsm.pmi(giga20) # Evaluates giga20_PPMI return full_word_similarity_evaluation(giga20_PPMI) if 'IS_GRADESCOPE_ENV' not in os.environ: display(run_giga_ppmi_baseline()) def test_run_giga_ppmi_baseline(func): """`func` should be `run_giga_ppmi_baseline""" result = func() ws_result = result.loc['wordsim353'].round(2) ws_expected = 0.58 assert ws_result == ws_expected, \ "Expected wordsim353 value of {}; got {}".format( ws_expected, ws_result) if 'IS_GRADESCOPE_ENV' not in os.environ: test_run_giga_ppmi_baseline(run_giga_ppmi_baseline) ###Output _____no_output_____ ###Markdown Gigaword with LSA at different dimensions [0.5 points]We might expect PPMI and LSA to form a solid pipeline that combines the strengths of PPMI with those of dimensionality reduction. However, LSA has a hyper-parameter $k$ – the dimensionality of the final representations – that will impact performance. For this problem, write a wrapper function `run_ppmi_lsa_pipeline` that does the following:1. Takes as input a count `pd.DataFrame` and an LSA parameter `k`.1. Reweights the count matrix with PPMI.1. Applies LSA with dimensionality `k`.1. Evaluates this reweighted matrix using `full_word_similarity_evaluation`. The return value of `run_ppmi_lsa_pipeline` should be the return value of this call to `full_word_similarity_evaluation`.The goal of this question is to help you get a feel for how much LSA alone can contribute to this problem. The function `test_run_ppmi_lsa_pipeline` will test your function on the count matrix in `data/vsmdata/giga_window20-flat.csv.gz`. ###Code def run_ppmi_lsa_pipeline(count_df, k): ##### YOUR CODE HERE # Reweights the count matrix with PPMI df_ppmi = vsm.pmi(count_df) # Applies LSA with dimensionality k df_lsa = vsm.lsa(df_ppmi, k=k) return full_word_similarity_evaluation(df_lsa) if 'IS_GRADESCOPE_ENV' not in os.environ: giga20 = pd.read_csv( os.path.join(VSM_HOME, "giga_window20-flat.csv.gz"), index_col=0) display(run_ppmi_lsa_pipeline(giga20, k=10)) def test_run_ppmi_lsa_pipeline(func): """`func` should be `run_ppmi_lsa_pipeline`""" giga20 = pd.read_csv( os.path.join(VSM_HOME, "giga_window20-flat.csv.gz"), index_col=0) results = func(giga20, k=10) men_expected = 0.57 men_result = results.loc['men'].round(2) assert men_result == men_expected,\ "Expected men value of {}; got {}".format(men_expected, men_result) if 'IS_GRADESCOPE_ENV' not in os.environ: test_run_ppmi_lsa_pipeline(run_ppmi_lsa_pipeline) ###Output _____no_output_____ ###Markdown Gigaword with GloVe [0.5 points]Can GloVe improve over the PPMI-based baselines we explored above? To begin to address this question, let's run GloVe and see how performance on our task changes throughout the optimization process.__Your task__: write a function `run_glove_wordsim_evals` that does the following:1. Has a parameter `n_runs` with default value `5`.1. Reads in `data/vsmdata/giga_window5-scaled.csv.gz`.1. Creates a `TorchGloVe` instance with `warm_start=True`, `max_iter=50`, and all other parameters set to their defaults.1. `n_runs` times, calls `fit` on your model and, after each, runs `full_word_similarity_evaluation` with default keyword parameters, extract the 'Macro-average' score, and add that score to a list.1. Returns the list of scores created.The trend should give you a sense for whether it is worth running GloVe for more iterations.Some implementation notes:* `TorchGloVe` will accept and return `pd.DataFrame` instances, so you shouldn't need to do any type conversions.* Performance will vary a lot for this function, so there is some uncertainty in the testing, but `run_glove_wordsim_evals` will at least check that you wrote a function with the right general logic. ###Code def run_glove_wordsim_evals(n_runs=5): from torch_glove import TorchGloVe ##### YOUR CODE HERE # reads Giga5 scaled as a DataFrame giga5 = pd.read_csv( os.path.join(VSM_HOME, "giga_window5-scaled.csv.gz"), index_col=0) # creates TorchGlove instance glove_model = TorchGloVe(warm_start=True, max_iter=50) # initiates the scores scores = list() for _ in range(n_runs): giga5_glv = glove_model.fit(giga5) scores.append(full_word_similarity_evaluation(giga5_glv)['Macro-average']) return scores def test_run_small_glove_evals(data): """`data` should be the return value of `run_glove_wordsim_evals`""" assert isinstance(data, list), \ "`run_glove_wordsim_evals` should return a list" assert all(isinstance(x, float) for x in data), \ ("All the values in the list returned by `run_glove_wordsim_evals` " "should be floats.") if 'IS_GRADESCOPE_ENV' not in os.environ: glove_scores = run_glove_wordsim_evals() print(glove_scores) test_run_small_glove_evals(glove_scores) ###Output Finished epoch 50 of 50; error is 2588608.03125 ###Markdown Dice coefficient [0.5 points]Implement the Dice coefficient for real-valued vectors, as$$\textbf{dice}(u, v) = 1 - \frac{ 2 \sum_{i=1}^{n}\min(u_{i}, v_{i})}{ \sum_{i=1}^{n} u_{i} + v_{i}}$$ You can use `test_dice_implementation` below to check that your implementation is correct. ###Code def dice(u, v): ##### YOUR CODE HERE d = 1 - 2 * np.minimum(u, v).sum()/(u + v).sum() return d def test_dice_implementation(func): """`func` should be an implementation of `dice` as defined above.""" X = np.array([ [ 4., 4., 2., 0.], [ 4., 61., 8., 18.], [ 2., 8., 10., 0.], [ 0., 18., 0., 5.]]) assert func(X[0], X[1]).round(5) == 0.80198 assert func(X[1], X[2]).round(5) == 0.67568 if 'IS_GRADESCOPE_ENV' not in os.environ: test_dice_implementation(dice) ###Output _____no_output_____ ###Markdown t-test reweighting [2 points] The t-test statistic can be thought of as a reweighting scheme. For a count matrix $X$, row index $i$, and column index $j$:$$\textbf{ttest}(X, i, j) = \frac{ P(X, i, j) - \big(P(X, i, *)P(X, *, j)\big)}{\sqrt{(P(X, i, *)P(X, *, j))}}$$where $P(X, i, j)$ is $X_{ij}$ divided by the total values in $X$, $P(X, i, *)$ is the sum of the values in row $i$ of $X$ divided by the total values in $X$, and $P(X, *, j)$ is the sum of the values in column $j$ of $X$ divided by the total values in $X$.For this problem, implement this reweighting scheme. You can use `test_ttest_implementation` below to check that your implementation is correct. You do not need to use this for any evaluations, though we hope you will be curious enough to do so! ###Code def ttest(df): ##### YOUR CODE HERE # get the estimated probability matrix proba = df / df.values.sum() # get the estimated proba of the rows and the columns rows = proba.values.sum(axis=1, keepdims=True) cols = proba.values.sum(axis=0, keepdims=True) prod = rows @ cols output = (proba - prod) / np.sqrt(prod) return output def test_ttest_implementation(func): """`func` should be `ttest`""" X = pd.DataFrame(np.array([ [ 4., 4., 2., 0.], [ 4., 61., 8., 18.], [ 2., 8., 10., 0.], [ 0., 18., 0., 5.]])) actual = np.array([ [ 0.33056, -0.07689, 0.04321, -0.10532], [-0.07689, 0.03839, -0.10874, 0.07574], [ 0.04321, -0.10874, 0.36111, -0.14894], [-0.10532, 0.07574, -0.14894, 0.05767]]) predicted = func(X) assert np.array_equal(predicted.round(5), actual) if 'IS_GRADESCOPE_ENV' not in os.environ: test_ttest_implementation(ttest) ###Output _____no_output_____ ###Markdown Enriching a VSM with subword information [2 points]It might be useful to combine character-level information with word-level information. To help you begin asssessing this idea, this question asks you to write a function that modifies an existing VSM so that the representation for each word $w$ is the element-wise sum of $w$'s original word-level representation with all the representations for the n-grams $w$ contains. The following starter code should help you structure this and clarify the requirements, and a simple test is included below as well.You don't need to write a lot of code; the motivation for this question is that the function you write could have practical value. ###Code def subword_enrichment(df, n=4): # 1. Use `vsm.ngram_vsm` to create a character-level # VSM from `df`, using the above parameter `n` to # set the size of the ngrams. ##### YOUR CODE HERE df_char = vsm.ngram_vsm(df, n) # 2. Use `vsm.character_level_rep` to get the representation # for every word in `df` according to the character-level # VSM you created above. ##### YOUR CODE HERE char_reps = dict() for word in df.index: char_reps[word] = vsm.character_level_rep(word, df_char, n) print('{}: {}'.format(word, char_reps[word])) # 3. For each representation created at step 2, add in its # original representation from `df`. (This should use # element-wise addition; the dimensionality of the vectors # will be unchanged.) ##### YOUR CODE HERE char_reps_array = pd.DataFrame.from_dict(char_reps, orient='index').reindex(df.index).values df = df + char_reps_array # 4. Return a `pd.DataFrame` with the same index and column # values as `df`, but filled with the new representations # created at step 3. ##### YOUR CODE HERE return df def test_subword_enrichment(func): """`func` should be an implementation of subword_enrichment as defined above. """ vocab = ["ABCD", "BCDA", "CDAB", "DABC"] df = pd.DataFrame([ [1, 1, 2, 1], [3, 4, 2, 4], [0, 0, 1, 0], [1, 0, 0, 0]], index=vocab) expected = pd.DataFrame([ [14, 14, 18, 14], [22, 26, 18, 26], [10, 10, 14, 10], [14, 10, 10, 10]], index=vocab) new_df = func(df, n=2) assert np.array_equal(expected.columns, new_df.columns), \ "Columns are not the same" assert np.array_equal(expected.index, new_df.index), \ "Indices are not the same" assert np.array_equal(expected.values, new_df.values), \ "Co-occurrence values aren't the same" if 'IS_GRADESCOPE_ENV' not in os.environ: test_subword_enrichment(subword_enrichment) ###Output ABCD: [13 13 16 13] BCDA: [19 22 16 22] CDAB: [10 10 13 10] DABC: [13 10 10 10] ###Markdown Your original system [3 points]This question asks you to design your own model. You can of course include steps made above (ideally, the above questions informed your system design!), but your model should not be literally identical to any of the above models. Other ideas: retrofitting, autoencoders, GloVe, subword modeling, ... Requirements:1. Your code must operate on one or more of the count matrices in `data/vsmdata`. You can choose which subset of them; this is an important design feature of your system. __Other pretrained vectors cannot be introduced__.1. Retrofitting is permitted.1. Your code must be self-contained, so that we can work with your model directly in your homework submission notebook. If your model depends on external data or other resources, please submit a ZIP archive containing these resources along with your submission.In the cell below, please provide a brief technical description of your original system, so that the teaching team can gain an understanding of what it does. This will help us to understand your code and analyze all the submissions to identify patterns and strategies. We also ask that you report the best score your system got during development, just to help us understand how systems performed overall. ###Code # PLEASE MAKE SURE TO INCLUDE THE FOLLOWING BETWEEN THE START AND STOP COMMENTS: # 1) Textual description of your system. # 2) The code for your original system. # 3) The score achieved by your system in place of MY_NUMBER. # With no other changes to that line. # You should report your score as a decimal value <=1.0 # PLEASE MAKE SURE NOT TO DELETE OR EDIT THE START AND STOP COMMENTS # NOTE: MODULES, CODE AND DATASETS REQUIRED FOR YOUR ORIGINAL SYSTEM # SHOULD BE ADDED BELOW THE 'IS_GRADESCOPE_ENV' CHECK CONDITION. DOING # SO ABOVE THE CHECK MAY CAUSE THE AUTOGRADER TO FAIL. # START COMMENT: Enter your system description in this cell. # My peak score was: 0.531219 # Description of the system: # DataSet required: data/vsmdata/giga_window5-scaled.csv.gz saved as a Pandas DataFrame in variable giga5 # The original dataset is re-weighted using PPMI # Dimensionality reduction is applied to the resulting DataFrame using LSA # Retrofitting is finally apply to the resulting DataFrame using NLTK Wordnet graph for synonymy API. # For that purpose in order to mapp strings to lemmas we collapse together all the senses that a given string # can have as is done in the course Notebook. We hope that our vectors can model multiple senses at the same time. # Testing across test datasets seems to confirm the value of this retrofitting assumption, as results are significally # improved for the two similarity dataset (no improvement for relatedness datasets) # Code: if 'IS_GRADESCOPE_ENV' not in os.environ: from retrofitting import Retrofitter def get_wordnet_edges(): """ From the NLTK Wordnet graph for synonymy API, creates the edge dictionary we need for using the Retrofitter class. """ from nltk.corpus import wordnet as wn edges = defaultdict(set) for ss in wn.all_synsets(): lem_names = {lem.name() for lem in ss.lemmas()} for lem in lem_names: edges[lem] |= lem_names return edges def convert_edges_to_indices(edges, Q): """ Tools used for retrofitting. Replaces strings in edges by corresponding row rank in Q :param edges: edge dictionary built from NLTK Worldnet API :param Q: matrix of embedded space :return: """ lookup = dict(zip(Q.index, range(Q.shape[0]))) index_edges = defaultdict(set) for start, finish_nodes in edges.items(): s = lookup.get(start) if s: f = {lookup[n] for n in finish_nodes if n in lookup} if f: index_edges[s] = f return index_edges def wordsim_model(words: pd.DataFrame = giga5) -> pd.DataFrame: """ Model used to transform a co-occurence matrix in order to make it more efficient for finding word similarities. :param words: co-occurence matrix :return: transformed co-occurence matrix """ # re-weights words using PPMI words_pmi = vsm.pmi(words) # Dimentionality reduction using LSA applied to words_pmi words_lsa = vsm.lsa(words_pmi, 350) # creates the wordnet synonymy edge dictionary we need for using the Retrofitter class wn_edges = get_wordnet_edges() wn_index_edges = convert_edges_to_indices(wn_edges, words_lsa) # Applies retrofitting to words_lsa wn_retro = Retrofitter(verbose=True) words_retro = wn_retro.fit(words_lsa, wn_index_edges) return words_retro # STOP COMMENT: Please do not remove this comment. # apply our model to giga5 words = wordsim_model(giga5) # get results full_word_similarity_evaluation(words) if 'IS_GRADESCOPE_ENV' not in os.environ: full_word_similarity_evaluation(words) ###Output _____no_output_____ ###Markdown Bake-off [1 point]For the bake-off, we will release two additional datasets. The announcement will go out on the discussion forum. We will also release reader code for these datasets that you can paste into this notebook. You will evaluate your custom model $M$ (from the previous question) on these new datasets using `full_word_similarity_evaluation`. Rules:1. Only one evaluation is permitted.1. No additional system tuning is permitted once the bake-off has started.The cells below this one constitute your bake-off entry.People who enter will receive the additional homework point, and people whose systems achieve the top score will receive an additional 0.5 points. We will test the top-performing systems ourselves, and only systems for which we can reproduce the reported results will win the extra 0.5 points.Late entries will be accepted, but they cannot earn the extra 0.5 points. Similarly, you cannot win the bake-off unless your homework is submitted on time.The announcement will include the details on where to submit your entry. ###Code if 'IS_GRADESCOPE_ENV' not in os.environ: # Please enter your code in the scope of the above conditional. ##### YOUR CODE HERE def mturk287_reader(): """MTurk-287: http://tx.technion.ac.il/~kirar/Datasets.html""" src_filename = os.path.join( WORDSIM_HOME, 'bakeoff-wordsim-test-data', 'MTurk-287.csv') return wordsim_dataset_reader( src_filename, header=False) def simlex999_reader(wordsim_test_home=WORDSIM_HOME): """SimLex999: https://www.cl.cam.ac.uk/~fh295/SimLex-999.zip""" src_filename = os.path.join( WORDSIM_HOME, 'bakeoff-wordsim-test-data', 'SimLex-999', 'SimLex-999.txt') return wordsim_dataset_reader( src_filename, delimiter="\t", header=True, score_col_index=3) BAKEOFF = (simlex999_reader, mturk287_reader) print(full_word_similarity_evaluation(words, readers=BAKEOFF)) # Enter your bake-off assessment code into this cell. # Please do not remove this comment. if 'IS_GRADESCOPE_ENV' not in os.environ: pass # Please enter your code in the scope of the above conditional. ##### YOUR CODE HERE # On an otherwise blank line in this cell, please enter # your "Macro-average" value as reported by the code above. # Please enter only a number between 0 and 1 inclusive. # Please do not remove this comment. if 'IS_GRADESCOPE_ENV' not in os.environ: pass # Please enter your score in the scope of the above conditional. ##### YOUR CODE HERE ###Output _____no_output_____
notebooks/Covariate_testing_master.ipynb
###Markdown CREATING THE DATAFRAME OF PAIRS OF DIRECTORS AND ACTORS ###Code movie_industry = pd.read_csv("../data/movie_industry.csv", encoding = "ISO-8859-1" ) movie_industry.loc[movie_industry.rating == "Not specified", "rating"] = "NOT RATED" movie_industry.loc[movie_industry.rating == "UNRATED", "rating"] = "NOT RATED" movie_industry.head() val_genre=movie_industry['genre'].value_counts() val_genre picked_genre = val_genre[:8].index picked_genre movie_industry['genre'][~ movie_industry['genre'].isin(picked_genre)] = 'Other_genre' movie_industry['genre'].value_counts() val_rating=movie_industry['rating'].value_counts() val_rating picked_rating = val_rating[:5].index picked_rating movie_industry['rating'][~ movie_industry['rating'].isin(picked_rating)] = 'Other_rating' movie_industry['rating'].value_counts() class Graph: """ Wrapper class Graph to create a bipartite graph Takes in the following paramaters directors_to_actors_relation : Dataframe with the data for directors and actors weight func : function which defined the weight of an edge. Takes the dateframe to calcuate weights from and the nodes values to calculate for weight_func_args : column names used to calculate the weights director_column : Column name for director actor_column : Column name for actor, bipartite : default true """ def __init__(self, directors_to_actors_relation, weight_func, weight_func_args, director_column="director", actor_column="star", bipartite=True): self.G = nx.Graph() directors = set(directors_to_actors_relation[director_column].values) actors = set(directors_to_actors_relation[actor_column].values) #store the director node as a tuple with director name and boolean True to indicate director for director in directors: self.G.add_node((director, True)) #store the actor node as a tuple with actor name and boolean False to indicate actor for actor in actors: self.G.add_node((actor, False)) #add weights to all edges for director in directors: rows = directors_to_actors_relation[directors_to_actors_relation[director_column] == director] for index in rows.index.values: self.G.add_edge((director, True), (rows.loc[index, actor_column], False), weight=weight_func(*[rows.loc[index, i] for i in weight_func_args], directors_to_actors_relation)) #calcualtes edge weight as the number of collaborations #takes in director name, star name and data to calculate weight from def example_weight_func(director, star, df): return len(df.loc[((df["director"] == director) & (df["star"] == star))]) storage = Graph(movie_industry, example_weight_func, ["director", "star"]) directors = list(set(movie_industry["director"].values)) actors = list(set(movie_industry["star"].values)) collabs = [] for director in directors: for actor in actors: if storage.G.get_edge_data((director, True), (actor, False)): collabs.append(storage.G.get_edge_data((director, True), (actor, False))["weight"]) else: collabs.append(0) res = [director for director in directors for i in range(len(actors))] df = pd.DataFrame({"director": res, "actor": actors*len(directors), "collabs": collabs}) df.head() df['collabs'].value_counts() ###Output _____no_output_____ ###Markdown ADDING AND TESTING COVARIATES ###Code df["collab indicator"] = (df.collabs > 0)*1 def add_feature_actor(feature_total, feature_mean, feature_name): for actor in actors: temp = movie_industry[movie_industry.star == actor] sum_feature = sum(temp[feature_name].values) mean_feature = np.mean(temp[feature_name].values) feature_total[actor] = sum_feature feature_mean[actor] = mean_feature def add_feature_director(feature_total, feature_mean, feature_name): for director in directors: temp = movie_industry[movie_industry.director == director] sum_feature = sum(temp[feature_name].values) mean_feature = np.mean(temp[feature_name].values) feature_total[director] = sum_feature feature_mean[director] = mean_feature ###Output _____no_output_____ ###Markdown gross ###Code actor_total_gross = {} actor_mean_gross = {} add_feature_actor(actor_total_gross, actor_mean_gross, 'gross') df["actor_total_gross"] = df.actor.map(actor_total_gross) df["actor_mean_gross"] = df.actor.map(actor_mean_gross) df["actor_total_gross"] = np.log(df["actor_total_gross"]+1) df["actor_mean_gross"] = np.log(df["actor_mean_gross"]+1) director_total_gross = {} director_mean_gross = {} add_feature_director(director_total_gross, director_mean_gross, 'gross') df["director_total_gross"] = df.director.map(director_total_gross) df["director_mean_gross"] = df.director.map(director_mean_gross) df["director_total_gross"] = np.log(df["director_total_gross"]+1) df["director_mean_gross"] = np.log(df["director_mean_gross"]+1) df["total_gross_diff"] = abs(df.director_total_gross - df.actor_total_gross) df["mean_gross_diff"] = abs(df.director_mean_gross - df.actor_mean_gross) df.head() df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.mean_gross_diff.values), max(df_dropped.mean_gross_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].mean_gross_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].mean_gross_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('mean_gross_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].mean_gross_diff.values))) print('mean_gross_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].mean_gross_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].mean_gross_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_gross_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].mean_gross_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_gross_diff.values) df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.total_gross_diff.values), max(df_dropped.total_gross_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].total_gross_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].total_gross_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('total_gross_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].total_gross_diff.values))) print('total_gross_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].total_gross_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].total_gross_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_gross_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].total_gross_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_gross_diff.values) ###Output _____no_output_____ ###Markdown budget ###Code actor_total_budget = {} actor_mean_budget = {} add_feature_actor(actor_total_budget, actor_mean_budget, 'budget') df["actor_total_budget"] = df.actor.map(actor_total_budget) df["actor_mean_budget"] = df.actor.map(actor_mean_budget) df["actor_total_budget"] = np.log(df["actor_total_budget"]+1) df["actor_mean_budget"] = np.log(df["actor_mean_budget"]+1) director_total_budget = {} director_mean_budget = {} add_feature_director(director_total_budget, director_mean_budget, 'budget') df["director_total_budget"] = df.director.map(director_total_budget) df["director_mean_budget"] = df.director.map(director_mean_budget) df["director_total_budget"] = np.log(df["director_total_budget"]+1) df["director_mean_budget"] = np.log(df["director_mean_budget"]+1) df["total_budget_diff"] = abs(df.director_total_budget - df.actor_total_budget) df["mean_budget_diff"] = abs(df.director_mean_budget - df.actor_mean_budget) df.head() df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.mean_budget_diff.values), max(df_dropped.mean_budget_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].mean_budget_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].mean_budget_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() from scipy.stats import ttest_ind print('mean_budget_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].mean_budget_diff.values))) print('mean_budget_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].mean_budget_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].mean_budget_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_budget_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].mean_budget_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_budget_diff.values) df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.total_budget_diff.values), max(df_dropped.total_budget_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].total_budget_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].total_budget_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('total_budget_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].total_budget_diff.values))) print('total_budget_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].total_budget_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].total_budget_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_budget_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].total_budget_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_budget_diff.values) ###Output _____no_output_____ ###Markdown score ###Code actor_total_score = {} actor_mean_score = {} add_feature_actor(actor_total_score, actor_mean_score, 'score') df["actor_total_score"] = df.actor.map(actor_total_score) df["actor_mean_score"] = df.actor.map(actor_mean_score) df["actor_total_score"] = np.log(df["actor_total_score"]+1) df["actor_mean_score"] = np.log(df["actor_mean_score"]+1) director_total_score = {} director_mean_score = {} add_feature_director(director_total_score, director_mean_score, 'score') df["director_total_score"] = df.director.map(director_total_score) df["director_mean_score"] = df.director.map(director_mean_score) df["director_total_score"] = np.log(df["actor_total_score"]+1) df["director_mean_score"] = np.log(df["actor_mean_score"]+1) df["total_score_diff"] = abs(df.director_total_score - df.actor_total_score) df["mean_score_diff"] = abs(df.director_mean_score - df.actor_mean_score) df.head() df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.mean_score_diff.values), max(df_dropped.mean_score_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].mean_score_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].mean_score_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('mean_score_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].mean_score_diff.values))) print('mean_score_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].mean_score_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].mean_score_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_score_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].mean_score_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_score_diff.values) bins = np.linspace(min(df_dropped.total_score_diff.values), max(df_dropped.total_score_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].total_score_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].total_score_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('total_score_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].total_score_diff.values))) print('total_score_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].total_score_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].total_score_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_score_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].total_score_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_score_diff.values) ###Output _____no_output_____ ###Markdown votes ###Code actor_total_votes = {} actor_mean_votes = {} add_feature_actor(actor_total_votes, actor_mean_votes, 'votes') df["actor_total_votes"] = df.actor.map(actor_total_votes) df["actor_mean_votes"] = df.actor.map(actor_mean_votes) df["actor_total_votes"] = np.log(df["actor_total_score"]+1) df["actor_mean_votes"] = np.log(df["actor_mean_score"]+1) director_total_votes = {} director_mean_votes = {} add_feature_director(director_total_votes, director_mean_votes, 'votes') df["director_total_votes"] = df.director.map(director_total_votes) df["director_mean_votes"] = df.director.map(director_mean_votes) df["director_total_votes"] = np.log(df["actor_total_votes"]+1) df["director_mean_votes"] = np.log(df["actor_mean_votes"]+1) df["total_votes_diff"] = abs(df.director_total_votes - df.actor_total_votes) df["mean_votes_diff"] = abs(df.director_mean_votes - df.actor_mean_votes) df.head() df_dropped = df.copy().dropna() bins = np.linspace(min(df_dropped.mean_votes_diff.values), max(df_dropped.mean_votes_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].mean_votes_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].mean_votes_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('mean_votes_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].mean_votes_diff.values))) print('mean_votes_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].mean_votes_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].mean_votes_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_votes_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].mean_votes_diff.values, df_dropped[df_dropped["collab indicator"] == 0].mean_votes_diff.values) bins = np.linspace(min(df_dropped.total_votes_diff.values), max(df_dropped.total_votes_diff.values), 50) plt.hist(df_dropped[df_dropped["collab indicator"] == 1].total_votes_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_dropped[df_dropped["collab indicator"] == 0].total_votes_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('total_votes_diff variance in pairs w/ collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 1].total_votes_diff.values))) print('total_votes_diff variance in pairs w/o collab is {}'.format(np.var(df_dropped[df_dropped["collab indicator"] == 0].total_votes_diff.values))) ttest_ind(df_dropped[df_dropped["collab indicator"] == 1].total_votes_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_votes_diff.values, equal_var=False) ks_2samp(df_dropped[df_dropped["collab indicator"] == 1].total_votes_diff.values, df_dropped[df_dropped["collab indicator"] == 0].total_votes_diff.values) ###Output _____no_output_____ ###Markdown oscar nomination ###Code oscar = pd.read_csv("../data/the_oscar_award.csv") oscar.head() oscar.category = oscar.category.str.lower() filtered = oscar[oscar.category.str.contains("(actor)|(actress)|(directing)", regex = True)] filtered filtered.loc[filtered.category.str.contains("(actor)|(actress)"), 'is_director'] = 0 filtered.loc[filtered.category.str.contains("directing"), 'is_director'] = 1 oscar_ppl = filtered[~filtered.name.str.contains("( and)|(,)|(and )", regex = True)] oscar_ppl.is_director = oscar_ppl.is_director.astype(np.uint8) oscar_ppl.head() gp_ppl = oscar_ppl.groupby(['name', 'is_director']).size().reset_index(name='nomination_counts') gp_ppl_director = gp_ppl.groupby(['is_director']).get_group(1) gp_ppl_actor = gp_ppl.groupby(['is_director']).get_group(0) gp_ppl_director.head() gp_ppl_actor.head() df_w_oscar= pd.merge(df, gp_ppl_director, left_on='director', right_on='name') df_w_oscar= pd.merge(df_w_oscar, gp_ppl_actor, left_on='actor', right_on='name') df_w_oscar.drop(['name_x', 'is_director_x', 'name_y', 'is_director_y'], axis=1, inplace=True) df_w_oscar.rename(columns={'nomination_counts_x': 'director_nominations', 'nomination_counts_y': 'actor_nominations'}, inplace=True) df_w_oscar.head() df_w_oscar['nominations_diff']=df_w_oscar['director_nominations'] - df_w_oscar['actor_nominations'] df_w_oscar.head() bins = np.linspace(min(df_w_oscar.nominations_diff.values), max(df_w_oscar.nominations_diff.values), 50) plt.hist(df_w_oscar[df_w_oscar["collab indicator"] == 1].nominations_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_w_oscar[df_w_oscar["collab indicator"] == 0].nominations_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('nominations_diff variance in pairs w/ collab is {}'.format(np.var(df_w_oscar[df_w_oscar["collab indicator"] == 1].nominations_diff.values))) print('nominations_diff variance in pairs w/o collab is {}'.format(np.var(df_w_oscar[df_w_oscar["collab indicator"] == 0].nominations_diff.values))) ttest_ind(df_w_oscar[df_w_oscar["collab indicator"] == 1].nominations_diff.values, df_w_oscar[df_w_oscar["collab indicator"] == 0].nominations_diff.values, equal_var=False) ks_2samp(df_w_oscar[df_w_oscar["collab indicator"] == 1].nominations_diff.values, df_w_oscar[df_w_oscar["collab indicator"] == 0].nominations_diff.values) ###Output _____no_output_____ ###Markdown oscar win ###Code oscar_ppl.head() gp_pplw = oscar_ppl.groupby(['name', 'is_director']).agg({'winner': 'sum'}).reset_index() gp_pplw_director = gp_pplw.groupby(['is_director']).get_group(1) gp_pplw_actor = gp_pplw.groupby(['is_director']).get_group(0) gp_pplw_director.head() gp_pplw_actor.head() df_w_oscar2= pd.merge(df, gp_pplw_director, left_on='director', right_on='name') df_w_oscar2= pd.merge(df_w_oscar2, gp_pplw_actor, left_on='actor', right_on='name') df_w_oscar2.drop(['name_x', 'is_director_x', 'name_y', 'is_director_y'], axis=1, inplace=True) df_w_oscar2.rename(columns={'winner_x': 'director_wins', 'winner_y': 'actor_wins'}, inplace=True) df_w_oscar2.head() df_w_oscar2['wins_diff']=df_w_oscar2['director_wins'] - df_w_oscar2['actor_wins'] df_w_oscar2.head() bins = np.linspace(min(df_w_oscar2.wins_diff.values), max(df_w_oscar2.wins_diff.values), 50) plt.hist(df_w_oscar2[df_w_oscar2["collab indicator"] == 1].wins_diff.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df_w_oscar2[df_w_oscar2["collab indicator"] == 0].wins_diff.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() print('wins_diff variance in pairs w/ collab is {}'.format(np.var(df_w_oscar2[df_w_oscar2["collab indicator"] == 1].wins_diff.values))) print('wins_diff variance in pairs w/o collab is {}'.format(np.var(df_w_oscar2[df_w_oscar2["collab indicator"] == 0].wins_diff.values))) ttest_ind(df_w_oscar2[df_w_oscar2["collab indicator"] == 1].wins_diff.values, df_w_oscar2[df_w_oscar2["collab indicator"] == 0].wins_diff.values, equal_var=False) ks_2samp(df_w_oscar2[df_w_oscar2["collab indicator"] == 1].wins_diff.values, df_w_oscar2[df_w_oscar2["collab indicator"] == 0].wins_diff.values) ###Output _____no_output_____ ###Markdown genre ###Code genre = np.unique(movie_industry.genre.values) genre dir_genre_prop = {} for director in directors: temp = movie_industry[movie_industry.director == director].groupby(["genre"])["director"].count() prop = [] total = sum(temp.values) for category in genre: if category in temp.index: prop.append(temp[category]/total) else: prop.append(0) dir_genre_prop[director] = np.array(prop) act_genre_prop = {} for actor in actors: temp = movie_industry[movie_industry.star == actor].groupby(["genre"])["star"].count() prop = [] total = sum(temp.values) for category in genre: if category in temp.index: prop.append(temp[category]/total) else: prop.append(0) act_genre_prop[actor] = np.array(prop) %%time genre_tvd = [] for i in df.index: director = df.director[i] actor = df.actor[i] tvd = sum(abs(dir_genre_prop[director] - act_genre_prop[actor]))/2 genre_tvd.append(tvd) df["genre_tvd"] = genre_tvd bins = np.linspace(min(genre_tvd), max(genre_tvd), 20) bins plt.hist(df[df["collab indicator"] == 1].genre_tvd.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df[df["collab indicator"] == 0].genre_tvd.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() ttest_ind(df[df["collab indicator"] == 1].genre_tvd.values, df[df["collab indicator"] == 0].genre_tvd.values, equal_var=False) ks_2samp(df[df["collab indicator"] == 1].genre_tvd.values, df[df["collab indicator"] == 0].genre_tvd.values) ###Output _____no_output_____ ###Markdown Rating ###Code rating = np.unique(movie_industry.rating.values) rating dir_rating_prop = {} for director in directors: temp = movie_industry[movie_industry.director == director].groupby(["rating"])["director"].count() prop = [] total = sum(temp.values) for category in rating: if category in temp.index: prop.append(temp[category]/total) else: prop.append(0) dir_rating_prop[director] = np.array(prop) act_rating_prop = {} for actor in actors: temp = movie_industry[movie_industry.star == actor].groupby(["rating"])["star"].count() prop = [] total = sum(temp.values) for category in rating: if category in temp.index: prop.append(temp[category]/total) else: prop.append(0) act_rating_prop[actor] = np.array(prop) %%time rating_tvd = [] for i in df.index: director = df.director[i] actor = df.actor[i] tvd = sum(abs(dir_rating_prop[director] - act_rating_prop[actor]))/2 rating_tvd.append(tvd) df["rating_tvd"] = rating_tvd bins = np.linspace(min(rating_tvd), max(rating_tvd), 20) bins plt.hist(df[df["collab indicator"] == 1].rating_tvd.values, density = True, bins = bins, label = "1", alpha = 0.5) plt.hist(df[df["collab indicator"] == 0].rating_tvd.values, density = True, bins = bins, label = "0", alpha = 0.5) plt.legend() ttest_ind(df[df["collab indicator"] == 1].rating_tvd.values, df[df["collab indicator"] == 0].rating_tvd.values, equal_var=False) ks_2samp(df[df["collab indicator"] == 1].rating_tvd.values, df[df["collab indicator"] == 0].rating_tvd.values) ###Output _____no_output_____ ###Markdown Visualization ###Code df_dropped = df.dropna() fig = plt.figure() f, axes = plt.subplots(4, 2, figsize=(26,16), sharex=False) plt.suptitle("T-test for Significant Covariants", fontsize=16) bins1 = np.linspace(min(df_dropped.mean_votes_diff.values), max(df_dropped.mean_votes_diff.values), 50) axes[0, 0].hist(df_dropped[df_dropped["collab indicator"] == 1].mean_votes_diff.values, density = True, bins = bins1, label = "1", alpha = 0.5) axes[0, 0].hist(df_dropped[df_dropped["collab indicator"] == 0].mean_votes_diff.values, density = True, bins = bins1, label = "0", alpha = 0.5) axes[0, 0].legend() axes[0, 0].title.set_text('Difference in Mean Votes P-Value=2.43e-25') bins2 = np.linspace(min(df_dropped.mean_score_diff.values), max(df_dropped.mean_score_diff.values), 50) axes[0, 1].hist(df_dropped[df_dropped["collab indicator"] == 1].mean_score_diff.values, density = True, bins = bins2, label = "1", alpha = 0.5) axes[0, 1].hist(df_dropped[df_dropped["collab indicator"] == 0].mean_score_diff.values, density = True, bins = bins2, label = "0", alpha = 0.5) axes[0, 1].legend() axes[0, 1].title.set_text('Difference in Mean Score P-Value=0.0') bins3 = np.linspace(min(df_dropped.mean_gross_diff.values), max(df_dropped.mean_gross_diff.values), 50) axes[1, 0].hist(df_dropped[df_dropped["collab indicator"] == 1].mean_gross_diff.values, density = True, bins = bins3, label = "1", alpha = 0.5) axes[1, 0].hist(df_dropped[df_dropped["collab indicator"] == 0].mean_gross_diff.values, density = True, bins = bins3, label = "0", alpha = 0.5) axes[1, 0].legend() axes[1, 0].title.set_text('Difference in Total Gross P-Value=0.0') bins4 = np.linspace(min(df_w_oscar.nominations_diff.values), max(df_w_oscar.nominations_diff.values), 50) axes[1, 1].hist(df_w_oscar[df_w_oscar["collab indicator"] == 1].nominations_diff.values, density = True, bins = bins4, label = "1", alpha = 0.5) axes[1, 1].hist(df_w_oscar[df_w_oscar["collab indicator"] == 0].nominations_diff.values, density = True, bins = bins4, label = "0", alpha = 0.5) axes[1, 1].legend() axes[1, 1].title.set_text('Difference in Number of Oscar Nominations P-Value=7.97e-05') bins5 = np.linspace(min(df_w_oscar2.wins_diff.values), max(df_w_oscar2.wins_diff.values), 50) axes[2, 0].hist(df_w_oscar2[df_w_oscar2["collab indicator"] == 1].wins_diff.values, density = True, bins = bins5, label = "1", alpha = 0.5) axes[2, 0].hist(df_w_oscar2[df_w_oscar2["collab indicator"] == 0].wins_diff.values, density = True, bins = bins5, label = "0", alpha = 0.5) axes[2, 0].legend() axes[2, 0].title.set_text('Difference in Number of Oscar Wins P-Value=1.80e-04') bins6 = np.linspace(min(genre_tvd), max(genre_tvd), 20) axes[2, 1].hist(df[df["collab indicator"] == 1].genre_tvd.values, density = True, bins = bins6, label = "1", alpha = 0.5) axes[2, 1].hist(df[df["collab indicator"] == 0].genre_tvd.values, density = True, bins = bins6, label = "0", alpha = 0.5) axes[2, 1].legend() axes[2, 1].title.set_text('Difference in Genre P-Value=0.0') bins7 = np.linspace(min(rating_tvd), max(rating_tvd), 20) axes[3, 0].hist(df[df["collab indicator"] == 1].rating_tvd.values, density = True, bins = bins7, label = "1", alpha = 0.5) axes[3, 0].hist(df[df["collab indicator"] == 0].rating_tvd.values, density = True, bins = bins7, label = "0", alpha = 0.5) axes[3, 0].legend() axes[3, 0].title.set_text('Difference in Rating P-Value=0.0') axes[3,1].set_axis_off() f.savefig('../figures/T-test_for_Significant_Covariants.png', bbox_inches='tight') ###Output _____no_output_____
notebooks/23_Validation-MK4.ipynb
###Markdown Validation of mini drone MK4_Written by Marc Budinger, Aitor Ochotorena (INSA Toulouse) and Scott Delbecq (ISAE Supaero)_ ![DesignGraph](pictures/MikroQuadro.JPG) ###Code import scipy import scipy.optimize from math import pi from math import sqrt import math import timeit import time import numpy as np import ipywidgets as widgets from ipywidgets import interactive from IPython.display import display import pandas as pd ###Output _____no_output_____ ###Markdown 2.- Problem Definition ###Code # Specifications # Load M_load=1 # [kg] load mass # Autonomy t_h=15 # [min] time of hover fligth k_maxthrust=2.5 #[-] ratio max thrust # Architecture of the multi-rotor drone (4,6, 8 arms, ...) Narm=4 # [-] number of arm Np_arm=1 # [-] number of propeller per arm (1 or 2) Npro=Np_arm*Narm # [-] Propellers number # Motor Architecture Mod=0 # Chose between 0 for 'Direct Drive' or 1 for Gear Drive #Maximum climb speed V_cl=10 # [m/s] max climb speed CD= 1.3 #[] drag coef A_top=0.09/2 #[m^2] top surface. For a quadcopter: Atop=1/2*Lb^2+3*pi*Dpro^2/4 # Propeller characteristics NDmax= 105000/60*.0254# [Hz.m] max speed limit (N.D max) # Air properties rho_air=1.18 # [kg/m^3] air density # MTOW MTOW = 2. # [kg] maximal mass # Objectif MaxTime=False # Objective ###Output _____no_output_____ ###Markdown 3.- Sizing Code ###Code # ----------------------- # sizing code # ----------------------- # inputs: # - param: optimisation variables vector (reduction ratio, oversizing coefficient) # - arg: selection of output # output: # - objective if arg='Obj', problem characteristics if arg='Prt', constraints other else def SizingCode(param, arg): # Design variables # --- k_M=param[0] # over sizing coefficient on the load mass k_mot=param[1] # over sizing coefficient on the motor torque k_speed_mot=param[2] # over sizing coefficient on the motor speed k_vb=param[3] # over sizing coefficient for the battery voltage k_ND=param[4] # slow down propeller coef : ND = kNDmax / k_ND D_ratio=param[5] # aspect ratio e/c (thickness/side) for the beam of the frame k_Mb=param[6] # over sizing coefficient on the battery load mass beta=param[7] # pitch/diameter ratio of the propeller J=param[8] # advance ratio k_ESC=param[9] # over sizing coefficient on the ESC power if Mod==1: Nred=param[10] # Reduction Ratio [-] # Hover, Climbing & Take-Off thrust # --- Mtotal=k_M*M_load # [kg] Estimation of the total mass (or equivalent weight of dynamic scenario) F_pro_hov=Mtotal*(9.81)/Npro # [N] Thrust per propeller for hover F_pro_to=F_pro_hov*k_maxthrust # [N] Max Thrust per propeller F_pro_cl=(Mtotal*9.81+0.5*rho_air*CD*A_top*V_cl**2)/Npro # [N] Thrust per propeller for climbing # Propeller characteristicss # Ref : APC static C_t_sta=4.27e-02 + 1.44e-01 * beta # Thrust coef with T=C_T.rho.n^2.D^4 C_p_sta=-1.48e-03 + 9.72e-02 * beta # Power coef with P=C_p.rho.n^3.D^5 Dpro_ref=11*.0254 # [m] diameter Mpro_ref=0.53*0.0283 # [kg] mass # Ref: APC dynamics C_t_dyn=0.02791-0.06543*J+0.11867*beta+0.27334*beta**2-0.28852*beta**3+0.02104*J**3-0.23504*J**2+0.18677*beta*J**2 # thrust coef for APC props in dynamics C_p_dyn=0.01813-0.06218*beta+0.00343*J+0.35712*beta**2-0.23774*beta**3+0.07549*beta*J-0.1235*J**2 # power coef for APC props in dynamics #Choice of diameter and rotational speed from a maximum thrust Dpro=(F_pro_to/(C_t_sta*rho_air*(NDmax*k_ND)**2))**0.5 # [m] Propeller diameter n_pro_to=NDmax*k_ND/Dpro # [Hz] Propeller speed n_pro_cl=sqrt(F_pro_cl/(C_t_dyn*rho_air*Dpro**4)) # [Hz] climbing speed # Propeller selection with take-off scenario Wpro_to=n_pro_to*2*3.14 # [rad/s] Propeller speed Mpro=Mpro_ref*(Dpro/Dpro_ref)**3 # [kg] Propeller mass Ppro_to=C_p_sta*rho_air*n_pro_to**3*Dpro**5# [W] Power per propeller Qpro_to=Ppro_to/Wpro_to # [N.m] Propeller torque # Propeller torque& speed for hover n_pro_hover=sqrt(F_pro_hov/(C_t_sta*rho_air*Dpro**4)) # [Hz] hover speed Wpro_hover=n_pro_hover*2*3.14 # [rad/s] Propeller speed Ppro_hover=C_p_sta*rho_air*n_pro_hover**3*Dpro**5# [W] Power per propeller Qpro_hover=Ppro_hover/Wpro_hover # [N.m] Propeller torque V_bat_est=k_vb*1.84*(Ppro_to)**(0.36) # [V] battery voltage estimation #Propeller torque &speed for climbing Wpro_cl=n_pro_cl*2*3.14 # [rad/s] Propeller speed for climbing Ppro_cl=C_p_dyn*rho_air*n_pro_cl**3*Dpro**5# [W] Power per propeller for climbing Qpro_cl=Ppro_cl/Wpro_cl # [N.m] Propeller torque for climbing # Motor selection & scaling laws # --- # Motor reference sized from max thrust # Ref : AXI 5325/16 GOLD LINE Tmot_ref=2.32 # [N.m] rated torque Tmot_max_ref=85/70*Tmot_ref # [N.m] max torque Rmot_ref=0.03 # [Ohm] resistance Mmot_ref=0.575 # [kg] mass Ktmot_ref=0.03 # [N.m/A] torque coefficient Tfmot_ref=0.03 # [N.m] friction torque (zero load, nominal speed) #Motor speeds: if Mod==1: W_hover_motor=Wpro_hover*Nred # [rad/s] Nominal motor speed with reduction W_cl_motor=Wpro_cl*Nred # [rad/s] Motor Climb speed with reduction W_to_motor=Wpro_to*Nred # [rad/s] Motor take-off speed with reduction else: W_hover_motor=Wpro_hover # [rad/s] Nominal motor speed W_cl_motor=Wpro_cl # [rad/s] Motor Climb speed W_to_motor=Wpro_to # [rad/s] Motor take-off speed #Motor torque: if Mod==1: Tmot_hover=Qpro_hover/Nred # [N.m] motor nominal torque with reduction Tmot_to=Qpro_to/Nred # [N.m] motor take-off torque with reduction Tmot_cl=Qpro_cl/Nred # [N.m] motor climbing torque with reduction else: Tmot_hover=Qpro_hover# [N.m] motor take-off torque Tmot_to=Qpro_to # [N.m] motor take-off torque Tmot_cl=Qpro_cl # [N.m] motor climbing torque Tmot=k_mot*Tmot_hover# [N.m] required motor nominal torque for reductor Tmot_max=Tmot_max_ref*(Tmot/Tmot_ref)**(1) # [N.m] max torque Mmot=Mmot_ref*(Tmot/Tmot_ref)**(3/3.5) # [kg] Motor mass # Selection with take-off speed Ktmot=V_bat_est/(k_speed_mot*W_to_motor) # [N.m/A] or [V/(rad/s)] Kt motor (RI term is missing) Rmot=Rmot_ref*(Tmot/Tmot_ref)**(-5/3.5)*(Ktmot/Ktmot_ref)**(2) # [Ohm] motor resistance Tfmot=Tfmot_ref*(Tmot/Tmot_ref)**(3/3.5) # [N.m] Friction torque # Hover current and voltage Imot_hover = (Tmot_hover+Tfmot)/Ktmot # [I] Current of the motor per propeller Umot_hover = Rmot*Imot_hover + W_hover_motor*Ktmot # [V] Voltage of the motor per propeller P_el_hover = Umot_hover*Imot_hover # [W] Hover : output electrical power # Take-Off current and voltage Imot_to = (Tmot_to+Tfmot)/Ktmot # [I] Current of the motor per propeller Umot_to = Rmot*Imot_to + W_to_motor*Ktmot # [V] Voltage of the motor per propeller P_el_to = Umot_to*Imot_to # [W] Takeoff : output electrical power # Climbing current and voltage Imot_cl = (Tmot_cl+Tfmot)/Ktmot # [I] Current of the motor per propeller for climbing Umot_cl = Rmot*Imot_cl + W_cl_motor*Ktmot # [V] Voltage of the motor per propeller for climbing P_el_cl = Umot_cl*Imot_cl # [W] Power : output electrical power for climbing #Gear box model if Mod==1: mg1=0.0309*Nred**2+0.1944*Nred+0.6389 # Ratio input pinion to mating gear WF=1+1/mg1+mg1+mg1**2+Nred**2/mg1+Nred**2 # Weight Factor (ƩFd2/C) [-] k_sd=1000 # Surface durability factor [lb/in] C=2*8.85*Tmot_hover/k_sd # Coefficient (C=2T/K) [in3] Fd2=WF*C # Solid rotor volume [in3] Mgear=Fd2*0.3*0.4535 # Mass reducer [kg] (0.3 is a coefficient evaluated for aircraft application and 0.4535 to pass from lb to kg) Fdp2=C*(Nred+1)/Nred # Solid rotor pinion volume [in3] dp=(Fdp2/0.7)**(1/3)*0.0254 # Pinion diameter [m] (0.0254 to pass from in to m) dg=Nred*dp # Gear diameter [m] di=mg1*dp # Inler diameter [m] # Battery selection & scaling laws sized from hover # --- # Battery # Ref : Prolitex TP3400-4SPX25 Mbat_ref=.329 # [kg] mass #Ebat_ref=4*3.7*3.3*3600 # [J] energy #Ebat_ref=220*3600*.329 # [J] Cbat_ref= 3.400*3600#[A.s] Vbat_ref=4*3.7#[V] Imax_ref=170#[A] Ncel=V_bat_est/3.7# [-] Cell number, round (up value) V_bat=3.7*Ncel # [V] Battery voltage Mbat=k_Mb*M_load # Battery mass # Hover --> autonomy C_bat = Mbat/Mbat_ref*Cbat_ref/V_bat*Vbat_ref # [A.s] Capacity of the battery I_bat = (P_el_hover*Npro)/.95/V_bat # [I] Current of the battery t_hf = .8*C_bat/I_bat/60 # [min] Hover time Imax=Imax_ref*C_bat/Cbat_ref # [A] max current battery # ESC sized from max speed # Ref : Turnigy K_Force 70HV Pesc_ref=3108 # [W] Power Vesc_ref=44.4 #[V]Voltage Mesc_ref=.115 # [kg] Mass P_esc=k_ESC*(P_el_to*V_bat/Umot_to) # [W] power electronic power max thrust P_esc_cl=P_el_cl*V_bat/Umot_cl # [W] power electronic power max climb Mesc = Mesc_ref*(P_esc/Pesc_ref) # [kg] Mass ESC Vesc = Vesc_ref*(P_esc/Pesc_ref)**(1/3)# [V] ESC voltage # Frame sized from max thrust # --- Mfra_ref=.347 #[kg] MK7 frame Marm_ref=0.14#[kg] Mass of all arms # Length calculation # sep= 2*pi/Narm #[rad] interior angle separation between propellers Lbra=Dpro/2/(math.sin(pi/Narm)) #[m] length of the arm # Static stress # Sigma_max=200e6/4 # [Pa] Alu max stress (2 reduction for dynamic, 2 reduction for stress concentration) Sigma_max=280e6/4 # [Pa] Composite max stress (2 reduction for dynamic, 2 reduction for stress concentration) # Tube diameter & thickness Dout=(F_pro_to*Lbra*32/(pi*Sigma_max*(1-D_ratio**4)))**(1/3) # [m] outer diameter of the beam D_ratio # [m] inner diameter of the beam # Mass Marm=pi/4*(Dout**2-(D_ratio*Dout)**2)*Lbra*1700*Narm # [kg] mass of the arms Mfra=Mfra_ref*(Marm/Marm_ref)# [kg] mass of the frame # Thrust Bearing reference # Ref : SKF 31309/DF Life=5000 # Life time [h] k_bear=1 Cd_bear_ref=2700 # Dynamic reference Load [N] C0_bear_ref=1500 # Static reference load[N] Db_ref=0.032 # Exterior reference diameter [m] Lb_ref=0.007 # Reference lenght [m] db_ref=0.020 # Interior reference diametere [m] Mbear_ref=0.018 # Reference mass [kg] # Thrust bearing model""" L10=(60*(Wpro_hover*60/2/3.14)*(Life/10**6)) # Nominal endurance [Hours of working] Cd_ap=(2*F_pro_hov*L10**(1/3))/2 # Applied load on bearing [N] Fmax=2*4*F_pro_to/2 C0_bear=k_bear*Fmax # Static load [N] Cd_bear=Cd_bear_ref/C0_bear_ref**(1.85/2)*C0_bear**(1.85/2) # Dynamic Load [N] Db=Db_ref/C0_bear_ref**0.5*C0_bear**0.5 # Bearing exterior Diameter [m] db=db_ref/C0_bear_ref**0.5*C0_bear**0.5 # Bearing interior Diameter [m] Lb=Lb_ref/C0_bear_ref**0.5*C0_bear**0.5 # Bearing lenght [m] Mbear=Mbear_ref/C0_bear_ref**1.5*C0_bear**1.5 # Bearing mass [kg] # Objective and Constraints sum up # --- if Mod==0: Mtotal_final = (Mesc+Mpro+Mmot+Mbear)*Npro+M_load+Mbat+Mfra+Marm #total mass without reducer else: Mtotal_final = (Mesc+Mpro+Mmot+Mgear+Mbear)*Npro+M_load+Mbat+Mfra+Marm #total mass with reducer if MaxTime==True: constraints = [(Mtotal-Mtotal_final)/Mtotal_final, (NDmax-n_pro_cl*Dpro)/NDmax, (Tmot_max-Tmot_to)/Tmot_max, (Tmot_max-Tmot_cl)/Tmot_max, (-J*n_pro_cl*Dpro+V_cl), 0.01+(J*n_pro_cl*Dpro-V_cl), (V_bat-Umot_to)/V_bat, (V_bat-Umot_cl)/V_bat, (V_bat-Vesc)/V_bat, (V_bat*Imax-Umot_to*Imot_to*Npro/0.95)/(V_bat*Imax), (V_bat*Imax-Umot_cl*Imot_cl*Npro/0.95)/(V_bat*Imax), (P_esc-P_esc_cl)/P_esc, (MTOW-Mtotal_final)/Mtotal_final ] else: constraints = [(Mtotal-Mtotal_final)/Mtotal_final, (NDmax-n_pro_cl*Dpro)/NDmax, (Tmot_max-Tmot_to)/Tmot_max, (Tmot_max-Tmot_cl)/Tmot_max, (-J*n_pro_cl*Dpro+V_cl), 0.01+(J*n_pro_cl*Dpro-V_cl), (V_bat-Umot_to)/V_bat, (V_bat-Umot_cl)/V_bat, (V_bat-Vesc)/V_bat, (V_bat*Imax-Umot_to*Imot_to*Npro/0.95)/(V_bat*Imax), (V_bat*Imax-Umot_cl*Imot_cl*Npro/0.95)/(V_bat*Imax), (P_esc-P_esc_cl)/P_esc, (t_hf-t_h)/t_hf, ] # Objective and contraints if arg=='Obj': P=0 # Penalisation nulle if MaxTime==False: for C in constraints: if (C<0.): P=P-1e9*C return Mtotal_final+P # for mass optimisation else: for C in constraints: if (C<0.): P=P-1e9*C return 1/t_hf+P # for time optimisation elif arg=='Prt': col_names_opt = ['Type', 'Name', 'Min', 'Value', 'Max', 'Unit', 'Comment'] df_opt = pd.DataFrame() df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_M', 'Min': bounds[0][0], 'Value': k_M, 'Max': bounds[0][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient on the load mass '}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_mot', 'Min': bounds[1][0], 'Value': k_mot, 'Max': bounds[1][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient on the motor torque '}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_speed_mot', 'Min': bounds[2][0], 'Value': k_speed_mot, 'Max': bounds[2][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient on the motor speed'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_vb', 'Min': bounds[3][0], 'Value': k_vb, 'Max': bounds[3][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient for the battery voltage'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_ND', 'Min': bounds[4][0], 'Value': k_ND, 'Max': bounds[4][1], 'Unit': '[-]', 'Comment': 'Ratio ND/NDmax'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'D_ratio', 'Min': bounds[5][0], 'Value': D_ratio, 'Max': bounds[5][1], 'Unit': '[-]', 'Comment': 'aspect ratio e/c (thickness/side) for the beam of the frame'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_Mb', 'Min': bounds[6][0], 'Value': k_Mb, 'Max': bounds[6][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient on the battery load mass '}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'beta_pro', 'Min': bounds[7][0], 'Value': beta, 'Max': bounds[7][1], 'Unit': '[-]', 'Comment': 'pitch/diameter ratio of the propeller'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'J', 'Min': bounds[8][0], 'Value': J, 'Max': bounds[8][1], 'Unit': '[-]', 'Comment': 'Advance ratio'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'k_ESC', 'Min': bounds[9][0], 'Value': k_ESC, 'Max': bounds[9][1], 'Unit': '[-]', 'Comment': 'over sizing coefficient on the ESC power'}])[col_names_opt] if Mod==1: df_opt = df_opt.append([{'Type': 'Optimization', 'Name': 'N_red', 'Min': bounds[10][0], 'Value': N_red, 'Max': bounds[10][1], 'Unit': '[-]', 'Comment': 'Reduction ratio'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 0', 'Min': 0, 'Value': constraints[0], 'Max': '-', 'Unit': '[-]', 'Comment': '(Mtotal-Mtotal_final)'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 1', 'Min': 0, 'Value': constraints[1], 'Max': '-', 'Unit': '[-]', 'Comment': '(NDmax-n_pro_cl*Dpro)/NDmax'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 2', 'Min': 0, 'Value': constraints[2], 'Max': '-', 'Unit': '[-]', 'Comment': '(Tmot_max-Tmot_to)/Tmot_max'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 3', 'Min': 0, 'Value': constraints[3], 'Max': '-', 'Unit': '[-]', 'Comment': '(Tmot_max-Tmot_cl)/Tmot_max'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 4', 'Min': 0, 'Value': constraints[4], 'Max': '-', 'Unit': '[-]', 'Comment': '(-J*n_pro_cl*Dpro+V_cl)'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 5', 'Min': 0, 'Value': constraints[5], 'Max': '-', 'Unit': '[-]', 'Comment': '0.01+(+J*n_pro_cl*Dpro-V_cl)'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 6', 'Min': 0, 'Value': constraints[6], 'Max': '-', 'Unit': '[-]', 'Comment': '(V_bat-Umot_to)/V_bat'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 7', 'Min': 0, 'Value': constraints[7], 'Max': '-', 'Unit': '[-]', 'Comment': '(V_bat-Umot_cl)/V_bat'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 8', 'Min': 0, 'Value': constraints[8], 'Max': '-', 'Unit': '[-]', 'Comment': '(V_bat-Vesc)/V_bat'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 9', 'Min': 0, 'Value': constraints[9], 'Max': '-', 'Unit': '[-]', 'Comment': '(V_bat*Imax-Umot_to*Imot_to*Npro/0.95)/(V_bat*Imax)'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 10', 'Min': 0, 'Value': constraints[10], 'Max': '-', 'Unit': '[-]', 'Comment': '(V_bat*Imax-Umot_cl*Imot_cl*Npro/0.95)/(V_bat*Imax)'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 11', 'Min': 0, 'Value': constraints[11], 'Max': '-', 'Unit': '[-]', 'Comment': '(P_esc-P_esc_cl)/P_esc'}])[col_names_opt] if MaxTime==False: df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 12', 'Min': 0, 'Value': constraints[12], 'Max': '-', 'Unit': '[-]', 'Comment': '(t_hf-t_h)/t_hf'}])[col_names_opt] else: df_opt = df_opt.append([{'Type': 'Constraints', 'Name': 'Const 12', 'Min': 0, 'Value': constraints[12], 'Max': '-', 'Unit': '[-]', 'Comment': '(MTOW-Mtotal_final)/Mtotal_final'}])[col_names_opt] df_opt = df_opt.append([{'Type': 'Objective', 'Name': 'Objective', 'Min': 0, 'Value': Mtotal_final, 'Max': '-', 'Unit': '[kg]', 'Comment': 'Total mass'}])[col_names_opt] col_names = ['Type', 'Name', 'Value', 'Unit', 'Comment'] df = pd.DataFrame() df = df.append([{'Type': 'Propeller', 'Name': 'F_pro_to', 'Value': F_pro_to, 'Unit': '[N]', 'Comment': 'Thrust for 1 propeller during Take Off'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'F_pro_cl', 'Value': F_pro_cl, 'Unit': '[N]', 'Comment': 'Thrust for 1 propeller during Take Off'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'F_pro_hov', 'Value': F_pro_hov, 'Unit': '[N]', 'Comment': 'Thrust for 1 propeller during Hover'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'rho_air', 'Value': rho_air, 'Unit': '[kg/m^3]', 'Comment': 'Air density'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'ND_max', 'Value': NDmax, 'Unit': '[Hz.m]', 'Comment': 'Max speed limit (N.D max)'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'Dpro_ref', 'Value': Dpro_ref, 'Unit': '[m]', 'Comment': 'Reference propeller diameter'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'M_pro_ref', 'Value': Mpro_ref, 'Unit': '[kg]', 'Comment': 'Reference propeller mass'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'C_t_sta', 'Value': C_t_sta, 'Unit': '[-]', 'Comment': 'Static thrust coefficient of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'C_t_dyn', 'Value': C_t_dyn, 'Unit': '[-]', 'Comment': 'Dynamic thrust coefficient of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'C_p_sta', 'Value': C_p_sta, 'Unit': '[-]', 'Comment': 'Static power coefficient of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'C_p_dyn', 'Value': C_p_dyn, 'Unit': '[-]', 'Comment': 'Dynamic power coefficient of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'D_pro', 'Value': Dpro, 'Unit': '[m]', 'Comment': 'Diameter of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'n_pro_cl', 'Value': n_pro_cl, 'Unit': '[Hz]', 'Comment': 'Rev speed of the propeller during climbing'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'n_pro_to', 'Value': n_pro_to, 'Unit': '[Hz]', 'Comment': 'Rev speed of the propeller during takeoff'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'n_pro_hov', 'Value': n_pro_hover, 'Unit': '[Hz]', 'Comment': 'Rev speed of the propeller during hover'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'P_pro_cl', 'Value': Ppro_cl, 'Unit': '[W]', 'Comment': 'Power on the mechanical shaft of the propeller during climbing'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'P_pro_to', 'Value': Ppro_to, 'Unit': '[W]', 'Comment': 'Power on the mechanical shaft of the propeller during takeoff'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'P_pro_hov', 'Value': Ppro_hover, 'Unit': '[W]', 'Comment': 'Power on the mechanical shaft of the propeller during hover'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'M_pro', 'Value': Mpro, 'Unit': '[kg]', 'Comment': 'Mass of the propeller'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'Omega_pro_cl', 'Value': Wpro_cl, 'Unit': '[rad/s]', 'Comment': 'Rev speed of the propeller during climbing'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'Omega_pro_to', 'Value': Wpro_to, 'Unit': '[rad/s]', 'Comment': 'Rev speed of the propeller during takeoff'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'Omega_pro_hov', 'Value': Wpro_hover, 'Unit': '[rad/s]', 'Comment': 'Rev speed of the propeller during hover'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'T_pro_hov', 'Value': Qpro_hover, 'Unit': '[N.m]', 'Comment': 'Torque on the mechanical shaft of the propeller during hover'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'T_pro_to', 'Value': Qpro_to, 'Unit': '[N.m]', 'Comment': 'Torque on the mechanical shaft of the propeller during takeoff'}])[col_names] df = df.append([{'Type': 'Propeller', 'Name': 'T_pro_cl', 'Value': Qpro_cl, 'Unit': '[N.m]', 'Comment': 'Torque on the mechanical shaft of the propeller during climbing'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_max_mot_ref', 'Value': Tmot_max_ref, 'Unit': '[N.m]', 'Comment': 'Max torque'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'R_mot_ref', 'Value': Rmot_ref, 'Unit': '[Ohm]', 'Comment': 'Resistance'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'M_mot_ref', 'Value': Mmot_ref, 'Unit': '[kg]', 'Comment': 'Reference motor mass'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'K_mot_ref', 'Value': Ktmot_ref, 'Unit': '[N.m/A]', 'Comment': 'Torque coefficient'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_mot_fr_ref', 'Value': Tfmot_ref, 'Unit': '[N.m]', 'Comment': 'Friction torque (zero load, nominal speed)'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_nom_mot', 'Value': Tmot_hover, 'Unit': '[N.m]', 'Comment': 'Continuous of the selected motor torque'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_mot_to', 'Value': Tmot_to, 'Unit': '[N.m]', 'Comment': 'Transient torque possible for takeoff'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_max_mot', 'Value': Tmot_max, 'Unit': '[N.m]', 'Comment': 'Transient torque possible for climbing'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'R_mot', 'Value': Rmot, 'Unit': '[Ohm]', 'Comment': 'Resistance'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'M_mot', 'Value': Mmot, 'Unit': '[kg]', 'Comment': 'Motor mass'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'K_mot', 'Value': Ktmot, 'Unit': '[rad/s]', 'Comment': 'Torque constant of the selected motor'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'T_mot_fr', 'Value': Tfmot, 'Unit': '[N.m]', 'Comment': 'Friction torque of the selected motor'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'I_mot_hov', 'Value': Imot_hover, 'Unit': '[A]', 'Comment': 'Motor current for hover'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'I_mot_to', 'Value': Imot_to, 'Unit': '[A]', 'Comment': 'Motor current for takeoff'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'I_mot_cl', 'Value': Imot_cl, 'Unit': '[A]', 'Comment': 'Motor current for climbing'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'U_mot_cl', 'Value': Umot_hover, 'Unit': '[V]', 'Comment': 'Motor voltage for climbing'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'U_mot_to', 'Value': Umot_to, 'Unit': '[V]', 'Comment': 'Motor voltage for takeoff'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'U_mot', 'Value': Umot_hover, 'Unit': '[V]', 'Comment': 'Nominal voltage '}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'P_el_mot_cl', 'Value': P_el_cl, 'Unit': '[W]', 'Comment': 'Motor electrical power for climbing'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'P_el_mot_to', 'Value': P_el_to, 'Unit': '[W]', 'Comment': 'Motor electrical power for takeoff'}])[col_names] df = df.append([{'Type': 'Motor', 'Name': 'P_el_mot_hov', 'Value': P_el_hover, 'Unit': '[W]', 'Comment': 'Motor electrical power for hover'}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'M_bat_ref', 'Value': Mbat_ref, 'Unit': '[kg]', 'Comment': 'Mass of the reference battery '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'M_esc_ref', 'Value': Mesc_ref, 'Unit': '[kg]', 'Comment': 'Reference ESC mass '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'P_esc_ref', 'Value': Pesc_ref, 'Unit': '[W]', 'Comment': 'Reference ESC power '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'N_s_bat', 'Value': np.ceil(Ncel), 'Unit': '[-]', 'Comment': 'Number of battery cells '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'U_bat', 'Value': V_bat, 'Unit': '[V]', 'Comment': 'Battery voltage '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'M_bat', 'Value': Mbat, 'Unit': '[kg]', 'Comment': 'Battery mass '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'C_bat', 'Value': C_bat, 'Unit': '[A.s]', 'Comment': 'Battery capacity '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'I_bat', 'Value': I_bat, 'Unit': '[A]', 'Comment': 'Battery current '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 't_hf', 'Value': t_hf, 'Unit': '[min]', 'Comment': 'Hovering time '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'P_esc', 'Value': P_esc, 'Unit': '[W]', 'Comment': 'Power electronic power (corner power or apparent power) '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'M_esc', 'Value': Mesc, 'Unit': '[kg]', 'Comment': 'ESC mass '}])[col_names] df = df.append([{'Type': 'Battery & ESC', 'Name': 'V_esc', 'Value': Vesc, 'Unit': '[V]', 'Comment': 'ESC voltage '}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'N_arm', 'Value': Narm, 'Unit': '[-]', 'Comment': 'Number of arms '}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'N_pro_arm', 'Value': Np_arm, 'Unit': '[-]', 'Comment': 'Number of propellers per arm '}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'sigma_max', 'Value': Sigma_max, 'Unit': '[Pa]', 'Comment': 'Max admisible stress'}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'L_arm', 'Value': Lbra, 'Unit': '[m]', 'Comment': 'Length of the arm'}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'D_out', 'Value': Dout, 'Unit': '[m]', 'Comment': 'Outer diameter of the arm (tube)'}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'Marm', 'Value': Marm, 'Unit': '[kg]', 'Comment': '1 Arm mass'}])[col_names] df = df.append([{'Type': 'Frame', 'Name': 'M_frame', 'Value': Mfra, 'Unit': '[kg]', 'Comment': 'Frame mass'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'M_load', 'Value': M_load, 'Unit': '[kg]', 'Comment': 'Payload mass'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 't_hf', 'Value': t_h, 'Unit': '[min]', 'Comment': 'Hovering time '}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'k_maxthrust', 'Value': k_maxthrust, 'Unit': '[-]', 'Comment': 'Ratio max thrust'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'N_arm', 'Value': Narm, 'Unit': '[-]', 'Comment': 'Number of arms '}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'N_pro_arm', 'Value': Np_arm, 'Unit': '[-]', 'Comment': 'Number of propellers per arm '}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'V_cl', 'Value': V_cl, 'Unit': '[m/s]', 'Comment': 'Climb speed'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'CD', 'Value': CD, 'Unit': '[-]', 'Comment': 'Drag coefficient'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'A_top', 'Value': A_top, 'Unit': '[m^2]', 'Comment': 'Top surface'}])[col_names] df = df.append([{'Type': 'Specifications', 'Name': 'MTOW', 'Value': MTOW, 'Unit': '[kg]', 'Comment': 'Max takeoff Weight'}])[col_names] items = sorted(df['Type'].unique().tolist())+['Optimization'] return df, df_opt else: return constraints ###Output _____no_output_____ ###Markdown 4.-Optimization variables ###Code #bounds design variables bounds= [(1,400),#k_M (1,20),#k_mot (1,10),#k_speed_mot (1,5),#k_vb (0.01,1),#k_ND (0.05,.99),#D_ratio (.01,60),#k_Mb (0.3,0.6),#beta (0.01,0.5),#J (1,15),#k_ESC (1,20),#Nred ] ###Output _____no_output_____ ###Markdown 5.-Result ###Code # optimization with SLSQP algorithm contrainte=lambda x: SizingCode(x, 'Const') objectif=lambda x: SizingCode(x, 'Obj') # Differential evolution omptimisation start = time.time() result = scipy.optimize.differential_evolution(func=objectif, bounds=[(1,400),#k_M (1,20),#k_mot (1,10),#k_speed_mot (1,5),#k_vb (0.01,1),#k_ND (0.05,.99),#D_ratio (.01,60),#k_Mb (0.3,0.6),#beta (0.01,0.5),#J (1,15),#k_ESC (1,20),#Nred ],maxiter=1000, tol=1e-12) # Final characteristics after optimization end = time.time() print("Operation time: %.5f s" %(end - start)) print("-----------------------------------------------") print("Final characteristics after optimization :") data=SizingCode(result.x, 'Prt')[0] data_opt=SizingCode(result.x, 'Prt')[1] pd.options.display.float_format = '{:,.3f}'.format def view(x=''): #if x=='All': return display(df) if x=='Optimization' : return display(data_opt) return display(data[data['Type']==x]) items = sorted(data['Type'].unique().tolist())+['Optimization'] w = widgets.Select(options=items) interactive(view, x=w) ###Output Operation time: 18.05689 s ----------------------------------------------- Final characteristics after optimization :
mergesort.ipynb
###Markdown - https://www.youtube.com/watch?v=Nso25TkBsYI- https://github.com/joeyajames/Python/blob/master/Sorting%20Algorithms/merge_sort.py Also see lt88_merge_sorted_array_merge_sort.ipynb ###Code def mergesort(arr): """ sorts items in n log n time and n space. works well with larger arrays according to https://www.youtube.com/watch?v=Nso25TkBsYI """ def merge(arr,first,middle,last): """ merges two lists by updating the proper indicies in place in the primary input array """ L = arr[first:middle+1] R = arr[middle+1:last+1] L.append(float('inf')) R.append(float('inf')) i,j = 0,0 for k in range(first, last+1): if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j+=1 def sort(arr, first, last): """ main sorting function which divides the sorting into two chunks recursively until we only have arrays of len 1 """ if first < last: middle = (first+last)//2 sort(arr, first, middle) sort(arr, middle+1,last) merge(arr,first,middle,last) sort(arr, 0, len(arr)-1) print(arr) %time arr = [5,9,1,3,2,8,84,30] mergesort(arr) %time arr = [5,9,1,3,2,8,84,30] quicksort(arr) def mergesort(arr): def merge(arr, low, mid, high): L = arr[low:mid+1] R = arr[mid+1:high+1] L.append(float('inf')) R.append(float('inf')) i,j = 0,0 for k in range(low,high+1): if L[i] <= R[j]: arr[k] = L[i] i+=1 else: arr[k] = R[j] j+=1 def sort(arr, low, high): if low < high: mid = (low+high)//2 sort(arr,low,mid) sort(arr,mid+1,high) merge(arr, low, mid, high) sort(arr,0,len(arr)-1) arr = [5,9,1,3,2,8,84,30] mergesort(arr) arr ###Output _____no_output_____ ###Markdown Mergesort ###Code public class MergeSort { // java -ea NameOfProgram public static boolean isSorted(Comparable[] a, int low, int high) { if (low == high) { return true; } for(int i = low; i < high; i++) { if (less(a[i],a[i++]) == false) { return false; } } return true; } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void exch(Comparable[] a, int i, int j) { Comparable t = aux[i]; aux[i] = a[j]; aux[j] = t; } public static void sort(Comparable[] a, Comparable[] aux,int lo, int hi) { if(hi <= lo) { return; } int mid = lo + (hi - lo) / 2; sort(a,aux, lo, mid); sort(a,aux, mid +1 ,hi); merge(a,aux,lo,mid,hi); } public static void sort(Comparable[] a) { Comparable[] aux = new Comparable[a.length]; // an array that implements interface Comparable sort(a,aux,0,a.length -1); } public static void merge(Comparable[] a, Comparable[] aux,int lo, int mid, int hi) { int i = lo; int j= mid+1; assert isSorted(a,lo,mid); // fail if sub arrays are not sorted assert isSorted(a,mid+1,hi); for(int k = lo; k <= hi; k++) { aux[k] = a[k]; // copy the elements into aux array } for (int k = lo; k <= hi; k++) { if (i > mid) { a[k] = aux[j++]; } else if(j > hi) { a[k] = aux[i++]; } else if(less(aux[j] , aux[i])) { a[k] = aux[j++]; } else { a[k] = aux[i++]; } } assert isSorted(a,lo,hi); } } ###Output _____no_output_____ ###Markdown Given a list of unique random intergers:- Split and merge sub lists into a sorted list PREQUISITES ###Code import random def make(n): nums = [i for i in range(n)] for i in range(n): rnd = random.randint(0, n - 1) nums[i], nums[rnd] = nums[rnd], nums[i] return nums ###Output _____no_output_____ ###Markdown ALGORITHM ###Code def mergeSort(nums): if len(nums) > 1: L = nums[:len(nums) // 2] R = nums[len(nums) // 2:] mergeSort(L) mergeSort(R) idx_l, idx_r, idx = 0, 0, 0 while idx_l < len(L) and idx_r < len(R): if L[idx_l] < R[idx_r]: nums[idx] = L[idx_l] idx_l += 1 else: nums[idx] = R[idx_r] idx_r += 1 idx += 1 while idx_l < len(L): nums[idx] = L[idx_l] idx_l += 1 idx += 1 while idx_r < len(R): nums[idx] = R[idx_r] idx_r += 1 idx += 1 ###Output _____no_output_____ ###Markdown TEST ###Code nums = make(20) mergeSort(nums) print(nums) for idx, val in enumerate(nums): assert idx == val ###Output _____no_output_____
authenticators.ipynb
###Markdown Custom AuthenticatorsLet's peek at the Authenticator classes: ###Code from jupyterhub.auth import Authenticator, PAMAuthenticator Authenticator.authenticate? ###Output Signature: Authenticator.authenticate(self, handler, data) Docstring: Authenticate a user with login form data. This must be a tornado gen.coroutine. It must return the username on successful authentication, and return None on failed authentication. Checking the whitelist is handled separately by the caller. Args: handler (tornado.web.RequestHandler): the current request handler data (dict): The formdata of the login form. The default form has 'username' and 'password' fields. Return: str: the username of the authenticated user None: Authentication failed File: ~/conda/envs/jupyterhub-tutorial/lib/python3.5/site-packages/jupyterhub/auth.py Type: function ###Markdown PAM calls out to a library with the given username and password: ###Code PAMAuthenticator.authenticate?? ###Output Signature: PAMAuthenticator.authenticate(self, handler, data) Source: @gen.coroutine  def authenticate(self, handler, data):  """Authenticate with PAM, and return the username if login is successful.    Return None otherwise.  """  username = data['username']  try:  pamela.authenticate(username, data['password'], service=self.service)  except pamela.PAMError as e:  if handler is not None:  self.log.warning("PAM Authentication failed (%s@%s): %s", username, handler.request.remote_ip, e)  else:  self.log.warning("PAM Authentication failed: %s", e)  else:  return username File: ~/conda/envs/jupyterhub-tutorial/lib/python3.5/site-packages/jupyterhub/auth.py Type: function ###Markdown Here's a super advanced Authenticator that does very secure password verification: ###Code class SecureAuthenticator(Authenticator): def authenticate(self, handler, data): username = data['username'] # check password: if data['username'] == data['password']: return username ###Output _____no_output_____ ###Markdown Exercise:Write a custom username+password Authenticator where:1. passwords are loaded from a dict2. hashed+salted passwords are stored somewhere, but not cleartext passwords ###Code # possibly useful: from jupyterhub.utils import hash_token, compare_token hash_token('mypassword') compare_token(_, 'mypassword') ###Output _____no_output_____
projects/student_intervention/student_intervention.ipynb
###Markdown Machine Learning Engineer Nanodegree Supervised Learning Project 2: Building a Student Intervention System Welcome to the second project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. Question 1 - Classification vs. Regression*Your goal for this project is to identify students who might need early intervention before they fail to graduate. Which type of supervised learning problem is this, classification or regression? Why?* **Answer: ** This is a case of classification problem as we need to classify students to two groups - the one who need intervention vs others. Exploring the DataRun the code cell below to load necessary Python libraries and load the student data. Note that the last column from this dataset, `'passed'`, will be our target label (whether the student graduated or didn't graduate). All other columns are features about each student. ###Code # Import libraries import numpy as np import pandas as pd from time import time from sklearn.metrics import f1_score # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" rand_seed = 25 # To be used throughout the notebook ###Output Student data read successfully! ###Markdown Implementation: Data ExplorationLet's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following:- The total number of students, `n_students`.- The total number of features for each student, `n_features`.- The number of those students who passed, `n_passed`.- The number of those students who failed, `n_failed`.- The graduation rate of the class, `grad_rate`, in percent (%). ###Code # TODO: Calculate number of students n_students = len(student_data) # TODO: Calculate number of features n_features = len(student_data.columns) - 1 # TODO: Calculate passing students n_passed = sum([1 if x == 'yes' else 0 for x in student_data['passed'] ]) # TODO: Calculate failing students n_failed = n_students - n_passed # TODO: Calculate graduation rate grad_rate = n_passed * 100.0 / n_students # Print the results print "Total number of students: {}".format(n_students) print "Number of features: {}".format(n_features) print "Number of students who passed: {}".format(n_passed) print "Number of students who failed: {}".format(n_failed) print "Graduation rate of the class: {:.2f}%".format(grad_rate) ###Output Total number of students: 395 Number of features: 30 Number of students who passed: 265 Number of students who failed: 130 Graduation rate of the class: 67.09% ###Markdown Preparing the DataIn this section, we will prepare the data for modeling, training and testing. Identify feature and target columnsIt is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.Run the code cell below to separate the student data into feature and target columns to see if any features are non-numeric. ###Code # Extract feature columns feature_cols = list(student_data.columns[:-1]) # Extract target column 'passed' target_col = student_data.columns[-1] # Show the list of columns print "Feature columns:\n{}".format(feature_cols) print "\nTarget column: {}".format(target_col) # Separate the data into feature data and target data (X_all and y_all, respectively) X_all = student_data[feature_cols] y_all = student_data[target_col] # Show the feature information by printing the first five rows print "\nFeature values:" print X_all.head() ###Output Feature columns: ['school', 'sex', 'age', 'address', 'famsize', 'Pstatus', 'Medu', 'Fedu', 'Mjob', 'Fjob', 'reason', 'guardian', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences'] Target column: passed Feature values: school sex age address famsize Pstatus Medu Fedu Mjob Fjob \ 0 GP F 18 U GT3 A 4 4 at_home teacher 1 GP F 17 U GT3 T 1 1 at_home other 2 GP F 15 U LE3 T 1 1 at_home other 3 GP F 15 U GT3 T 4 2 health services 4 GP F 16 U GT3 T 3 3 other other ... higher internet romantic famrel freetime goout Dalc Walc health \ 0 ... yes no no 4 3 4 1 1 3 1 ... yes yes no 5 3 3 1 1 3 2 ... yes yes no 4 3 2 2 3 3 3 ... yes yes yes 3 2 2 1 1 5 4 ... yes no no 4 3 2 1 2 5 absences 0 6 1 4 2 10 3 2 4 4 [5 rows x 30 columns] ###Markdown Preprocess Feature ColumnsAs you can see, there are several non-numeric columns that need to be converted! Many of them are simply `yes`/`no`, e.g. `internet`. These can be reasonably converted into `1`/`0` (binary) values.Other columns, like `Mjob` and `Fjob`, have more than two values, and are known as _categorical variables_. The recommended way to handle such a column is to create as many columns as possible values (e.g. `Fjob_teacher`, `Fjob_other`, `Fjob_services`, etc.), and assign a `1` to one of them and `0` to all others.These generated columns are sometimes called _dummy variables_, and we will use the [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummiespandas.get_dummies) function to perform this transformation. Run the code cell below to perform the preprocessing routine discussed in this section. ###Code def preprocess_features(X): ''' Preprocesses the student data and converts non-numeric binary variables into binary (0/1) variables. Converts categorical variables into dummy variables. ''' # Initialize new output DataFrame output = pd.DataFrame(index = X.index) # Investigate each feature column for the data for col, col_data in X.iteritems(): # If data type is non-numeric, replace all yes/no values with 1/0 if col_data.dtype == object: col_data = col_data.replace(['yes', 'no'], [1, 0]) # If data type is categorical, convert to dummy variables if col_data.dtype == object: # Example: 'school' => 'school_GP' and 'school_MS' col_data = pd.get_dummies(col_data, prefix = col) # Collect the revised columns output = output.join(col_data) return output X_all = preprocess_features(X_all) print "Processed feature columns ({} total features):\n{}".format(len(X_all.columns), list(X_all.columns)) ###Output Processed feature columns (48 total features): ['school_GP', 'school_MS', 'sex_F', 'sex_M', 'age', 'address_R', 'address_U', 'famsize_GT3', 'famsize_LE3', 'Pstatus_A', 'Pstatus_T', 'Medu', 'Fedu', 'Mjob_at_home', 'Mjob_health', 'Mjob_other', 'Mjob_services', 'Mjob_teacher', 'Fjob_at_home', 'Fjob_health', 'Fjob_other', 'Fjob_services', 'Fjob_teacher', 'reason_course', 'reason_home', 'reason_other', 'reason_reputation', 'guardian_father', 'guardian_mother', 'guardian_other', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences'] ###Markdown Implementation: Training and Testing Data SplitSo far, we have converted all _categorical_ features into numeric values. For the next step, we split the data (both features and corresponding labels) into training and test sets. In the following code cell below, you will need to implement the following:- Randomly shuffle and split the data (`X_all`, `y_all`) into training and testing subsets. - Use 300 training points (approximately 75%) and 95 testing points (approximately 25%). - Set a `random_state` for the function(s) you use, if provided. - Store the results in `X_train`, `X_test`, `y_train`, and `y_test`. ###Code # TODO: Import any additional functionality you may need here from sklearn.cross_validation import train_test_split # TODO: Set the number of training points num_train = 300 # Set the number of testing points num_test = X_all.shape[0] - num_train # TODO: Shuffle and split the dataset into the number of training and testing points above #X_train = None #X_test = None #y_train = None #y_test = None (X_train, X_test, y_train, y_test ) = train_test_split(X_all,y_all, train_size = num_train, random_state = rand_seed) # Show the results of the split print "Training set has {} samples.".format(X_train.shape[0]) print "Testing set has {} samples.".format(X_test.shape[0]) ###Output Training set has 300 samples. Testing set has 95 samples. ###Markdown Training and Evaluating ModelsIn this section, you will choose 3 supervised learning models that are appropriate for this problem and available in `scikit-learn`. You will first discuss the reasoning behind choosing these three models by considering what you know about the data and each model's strengths and weaknesses. You will then fit the model to varying sizes of training data (100 data points, 200 data points, and 300 data points) and measure the F1 score. You will need to produce three tables (one for each model) that shows the training set size, training time, prediction time, F1 score on the training set, and F1 score on the testing set.**The following supervised learning models are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**- Gaussian Naive Bayes (GaussianNB)- Decision Trees- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)- K-Nearest Neighbors (KNeighbors)- Stochastic Gradient Descent (SGDC)- Support Vector Machines (SVM)- Logistic Regression Question 2 - Model Application*List three supervised learning models that are appropriate for this problem. For each model chosen*- Describe one real-world application in industry where the model can be applied. *(You may need to do a small bit of research for this — give references!)* - What are the strengths of the model; when does it perform well? - What are the weaknesses of the model; when does it perform poorly?- What makes this model a good candidate for the problem, given what you know about the data? **Answer: ** Running some basic experiments and visualizations (saved in Experiement.ipynb in same folder), shows that the data points are not linearly separable. I have choosen following tree models - 1. Gaussian Naive Bayes - * Naive Bayes has been successfully used in many applications including text classification [1]* Major strength is that the model requires realtively fewer training points. As the Naive assumes independence of features, the class conditional feature distribution can be decoupled. This leads to alleviate problem of "curse of dimentionality" and hence works well with smaller datasets [2]* Naive Bayes assume independence of features, which is often a strong assumption to make and if often inaccuarate in real world. The models where the there is a strong dependence of features, this model does not perform well. The features have to be carefully examined to avoid such dependences. * The reason for picking this model as a candidate is that the dataset provided for the problem is quite small and most of the features appear independent. 2. Gradient Boosting * Gradient Boosting is a used in field of "learning to rank". It is used in commercial web engines.[3]* Gradient Boosting belongs to family of machine learning algorithms called Ensemble learning. These algorithms outperform other simpler algorithms as they are built upon multiple such simpler models. Gradient boosting has been shown to out perform other ensemble algorithms like Random Forest when tuned appropriately [4].* Gradient Boosting can overfit quite easily and appropriate tuning is required for its parameters specially depth of trees. Also, the Gradient boost requires that the trees are constructed sequentially as compared to random Forest which can build trees in parallel.[5]* Reason for picking GB for this problem is that the dataset is small and hence overfitting and large time to construct is of lesser issue than getting good result. GB have shown to outperform other ensemble methods. 3. K-nearest neighbours * KNN is used commonly in recommender systems and is even used in face recognition systems[6]. It is also used in computaional genetic applications [7]* KNN does not have a preprocessing step of "training" before making predictions. This is specifically useful when the data is large and prediction is required for small set of values. Its quite resilient to noise.[8]* Performance of KNN and its computational cost is dependent on the hyperparameter k. Its very important to get appropriate value to get better results (changing K can change predicted class for a point). Another decision is to define the distance function between different data points in dataset.* Based on the results of plotting various attributes vs each other (Experiments.ipynp), the classes seemed to have big local clusters separable by non-linear boundaries. I suspect local information for predicting class will give good results here.[1] http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html[2] https://en.wikipedia.org/wiki/Naive_Bayes_classifier[3] https://en.wikipedia.org/wiki/Gradient_boostingUsage[4] https://databricks.com/blog/2015/01/21/random-forests-and-boosting-in-mllib.html[5] https://www.quora.com/When-would-one-use-Random-Forests-over-Gradient-Boosted-Machines-GBMs/answer/Tianqi-Chen-1?srid=OqDt[6] https://www.quora.com/What-are-industry-applications-of-the-K-nearest-neighbor-algorithm/answer/Chris-McCormick-12?srid=OqDt[7] https://saravananthirumuruganathan.wordpress.com/2010/05/17/a-detailed-introduction-to-k-nearest-neighbor-knn-algorithm/[8] http://people.revoledu.com/kardi/tutorial/KNN/Strength%20and%20Weakness.htm SetupRun the code cell below to initialize three helper functions which you can use for training and testing the three supervised learning models you've chosen above. The functions are as follows:- `train_classifier` - takes as input a classifier and training data and fits the classifier to the data.- `predict_labels` - takes as input a fit classifier, features, and a target labeling and makes predictions using the F1 score.- `train_predict` - takes as input a classifier, and the training and testing data, and performs `train_clasifier` and `predict_labels`. - This function will report the F1 score for both the training and testing data separately. ###Code def train_classifier(clf, X_train, y_train): ''' Fits a classifier to the training data. ''' # Start the clock, train the classifier, then stop the clock start = time() clf.fit(X_train, y_train) end = time() # Print the results print "Trained model in {:.4f} seconds".format(end - start) def predict_labels(clf, features, target): ''' Makes predictions using a fit classifier based on F1 score. ''' # Start the clock, make predictions, then stop the clock start = time() y_pred = clf.predict(features) end = time() # Print and return results print "Made predictions in {:.4f} seconds.".format(end - start) return f1_score(target.values, y_pred, pos_label='yes') def train_predict(clf, X_train, y_train, X_test, y_test): ''' Train and predict using a classifer based on F1 score. ''' # Indicate the classifier and the training set size print "Training a {} using a training set size of {}. . .".format(clf.__class__.__name__, len(X_train)) # Train the classifier train_classifier(clf, X_train, y_train) # Print the results of prediction for both training and testing print "F1 score for training set: {:.4f}.".format(predict_labels(clf, X_train, y_train)) print "F1 score for test set: {:.4f}.".format(predict_labels(clf, X_test, y_test)) ###Output _____no_output_____ ###Markdown Implementation: Model Performance MetricsWith the predefined functions above, you will now import the three supervised learning models of your choice and run the `train_predict` function for each one. Remember that you will need to train and predict on each classifier for three different training set sizes: 100, 200, and 300. Hence, you should expect to have 9 different outputs below — 3 for each model using the varying training set sizes. In the following code cell, you will need to implement the following:- Import the three supervised learning models you've discussed in the previous section.- Initialize the three models and store them in `clf_A`, `clf_B`, and `clf_C`. - Use a `random_state` for each model you use, if provided. - **Note:** Use the default settings for each model — you will tune one specific model in a later section.- Create the different training set sizes to be used to train each model. - *Do not reshuffle and resplit the data! The new training points should be drawn from `X_train` and `y_train`.*- Fit each model with each training set size and make predictions on the test set (9 in total). **Note:** Three tables are provided after the following code cell which can be used to store your results. ###Code # TODO: Import the three supervised learning models from sklearn # from sklearn import model_A # from sklearn import model_B # from skearln import model_C from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import GradientBoostingClassifier from sklearn.neighbors import KNeighborsClassifier # TODO: Initialize the three models clf_A = GaussianNB() clf_B = GradientBoostingClassifier() clf_C = KNeighborsClassifier() # TODO: Set up the training set sizes X_train_100 = X_train[0:100] y_train_100 = y_train[0:100] X_train_200 = X_train[0:200] y_train_200 = y_train[0:200] X_train_300 = X_train[0:300] y_train_300 = y_train[0:300] # TODO: Execute the 'train_predict' function for each classifier and each training set size # train_predict(clf, X_train, y_train, X_test, y_test) for model in (clf_A, clf_B, clf_C): for dataset in ((X_train_100,y_train_100), (X_train_200, y_train_200), (X_train_300,y_train_300)): train_predict(model, dataset[0], dataset[1], X_test, y_test) ###Output Training a GaussianNB using a training set size of 100. . . Trained model in 0.0148 seconds Made predictions in 0.0632 seconds. F1 score for training set: 0.3333. Made predictions in 0.0012 seconds. F1 score for test set: 0.1176. Training a GaussianNB using a training set size of 200. . . Trained model in 0.0034 seconds Made predictions in 0.0018 seconds. F1 score for training set: 0.8339. Made predictions in 0.0010 seconds. F1 score for test set: 0.7692. Training a GaussianNB using a training set size of 300. . . Trained model in 0.0027 seconds Made predictions in 0.0016 seconds. F1 score for training set: 0.8066. Made predictions in 0.0011 seconds. F1 score for test set: 0.7402. Training a GradientBoostingClassifier using a training set size of 100. . . Trained model in 0.2583 seconds Made predictions in 0.0011 seconds. F1 score for training set: 1.0000. Made predictions in 0.0010 seconds. F1 score for test set: 0.7176. Training a GradientBoostingClassifier using a training set size of 200. . . Trained model in 0.2137 seconds Made predictions in 0.0016 seconds. F1 score for training set: 0.9926. Made predictions in 0.0011 seconds. F1 score for test set: 0.6825. Training a GradientBoostingClassifier using a training set size of 300. . . Trained model in 0.2560 seconds Made predictions in 0.0020 seconds. F1 score for training set: 0.9810. Made predictions in 0.0010 seconds. F1 score for test set: 0.7132. Training a KNeighborsClassifier using a training set size of 100. . . Trained model in 0.0016 seconds Made predictions in 0.0046 seconds. F1 score for training set: 0.8075. Made predictions in 0.0030 seconds. F1 score for test set: 0.7194. Training a KNeighborsClassifier using a training set size of 200. . . Trained model in 0.0023 seconds Made predictions in 0.0090 seconds. F1 score for training set: 0.8212. Made predictions in 0.0040 seconds. F1 score for test set: 0.7259. Training a KNeighborsClassifier using a training set size of 300. . . Trained model in 0.0020 seconds Made predictions in 0.0152 seconds. F1 score for training set: 0.8667. Made predictions in 0.0057 seconds. F1 score for test set: 0.7576. ###Markdown Tabular ResultsEdit the cell below to see how a table can be designed in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheettables). You can record your results from above in the tables provided. ** Classifer 1 - GaussianNB** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 | 0.0024 | 0.0010 | 0.8550 | 0.7481 || 200 | 0.0020 | 0.0009 | 0.8321 | 0.7132 || 300 | 0.0039 | 0.0013 | 0.8088 | 0.7500 |** Classifer 2 - GradientBoostingClassifier** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 | 0.1647 | 0.0011 | 1.000 | 0.7761 || 200 | 0.2048 | 0.0010 | 0.9852 | 0.7879 || 300 | 0.2362 | 0.0010 | 0.9740 | 0.7727 |** Classifer 3 - KNeighborsClassifier** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 | 0.0012 | 0.0038 | 0.7972 | 0.7068 || 200 | 0.0018 | 0.0039 | 0.8571 | 0.7121 || 300 | 0.0016 | 0.0057 | 0.8722 | 0.7482 | Choosing the Best ModelIn this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F1 score. Question 3 - Choosing the Best Model*Based on the experiments you performed earlier, in one to two paragraphs, explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?* **Answer: ** - I would choose KNearest Neighbour model over the other two based on following reasoning - Performace Based on the above table of observations on F1 score (training and test), Gradient Boost seem to be overfitting data. So we should avoid GB model for this problem. Test F1 score for GaussianNB and KNearestNeighbour are quite close and shows both models performed well on the task. The training and test score are a bit appart which may point to that the size of dataset was not enough to learn bring training and error to be approx same. Resources The above table shows that the time to train model is two order of magnitute higher for Gradient boost algorithms than the other two. KNearestNeighbour outperforms GaussianNB in the training time and hence will be more useful in Applicability Given that the performance of GaussianNB and KNN is similar, I would prefer to pick KNN as this provides slight edge in training time and does not depend on the assumption that the features are independent. Question 4 - Model in Layman's Terms*In one to two paragraphs, explain to the board of directors in layman's terms how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical or technical jargon, such as describing equations or discussing the algorithm implementation.* **Answer: **In summary, K Nearest Neighbour works by looking at k data points which are nearest and assign the class of most occuring class in the chosen data points. Training Although there is no training phase for KNNs, this phase is used to set up data structures to speed up the prediction phase. Prediction To assign a class to a new data point, we calculate the distance of the data point to all the other points. Then k points with min distance are chosen to new point. Then the resulting class of the new data point is calcualted based on the max num of class of other k-near points. Hyper parameters One of the initial step is setting up parameters. The most important parameter for the model is how many datapoint we want to look at locally for making a prediction. This parameter is called K. This parameter determines the performance and computational cost of the algorithm. If K is chosen small, the model may not generalize well and hence accuracy may be low. If we choose K higher, the accuracy should generally increase but it becomes more computationally expensive. Distance In the discussion above we did not define the meaning of distance amoung the data points. A function has to be defined as the distance function between datapoints. If the features are all numerical, distance function be simple euclidian distance between the points. In case some features are strings, we may need to define distance based on the either num of characters, amount of difference in two strings or perhaps based on semantics of the words. There are other distance has to be used in domain-specific case like distance between two genomes may be the number of neucletides it differ etc. Implementation: Model TuningFine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:- Import [`sklearn.grid_search.gridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).- Create a dictionary of parameters you wish to tune for the chosen model. - Example: `parameters = {'parameter' : [list of values]}`.- Initialize the classifier you've chosen and store it in `clf`.- Create the F1 scoring function using `make_scorer` and store it in `f1_scorer`. - Set the `pos_label` parameter to the correct value!- Perform grid search on the classifier `clf` using `f1_scorer` as the scoring method, and store it in `grid_obj`.- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_obj`. ###Code # TODO: Import 'GridSearchCV' and 'make_scorer' from sklearn.grid_search import GridSearchCV from sklearn.metrics import make_scorer from sklearn.metrics import f1_score # TODO: Create the parameters list you wish to tune parameters = {'n_neighbors':[3,5,7,9], 'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute']} # TODO: Initialize the classifier clf = KNeighborsClassifier() # TODO: Make an f1 scoring function using 'make_scorer' f1_scorer = make_scorer(f1_score, pos_label = 'yes') # TODO: Perform grid search on the classifier using the f1_scorer as the scoring method grid_obj = GridSearchCV(clf, parameters, f1_scorer) # TODO: Fit the grid search object to the training data and find the optimal parameters grid_obj = grid_obj.fit(X_train,y_train) # Get the estimator clf = grid_obj.best_estimator_ # Report the final F1 score for training and testing after parameter tuning print "Tuned model has a training F1 score of {:.4f}.".format(predict_labels(clf, X_train, y_train)) print "Tuned model has a testing F1 score of {:.4f}.".format(predict_labels(clf, X_test, y_test)) ###Output Made predictions in 0.0154 seconds. Tuned model has a training F1 score of 0.8437. Made predictions in 0.0057 seconds. Tuned model has a testing F1 score of 0.7972. ###Markdown Machine Learning Engineer Nanodegree Supervised Learning Project 2: Building a Student Intervention System Welcome to the second project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. Question 1 - Classification vs. Regression*Your goal for this project is to identify students who might need early intervention before they fail to graduate. Which type of supervised learning problem is this, classification or regression? Why?* **Answer: **We want to identify students who might need early intervention before they fail to graduate, so we have to seperate them into two classes based on whether they are likely to pass or fail. This is a classification problem as we are predicting discrete labels instead of continuous output. Exploring the DataRun the code cell below to load necessary Python libraries and load the student data. Note that the last column from this dataset, `'passed'`, will be our target label (whether the student graduated or didn't graduate). All other columns are features about each student. ###Code # Import libraries import numpy as np import pandas as pd from time import time from sklearn.metrics import f1_score # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" student_data.head() student_data["passed"].value_counts() ###Output _____no_output_____ ###Markdown Implementation: Data ExplorationLet's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following:- The total number of students, `n_students`.- The total number of features for each student, `n_features`.- The number of those students who passed, `n_passed`.- The number of those students who failed, `n_failed`.- The graduation rate of the class, `grad_rate`, in percent (%). ###Code # TODO: Calculate number of students n_students = student_data.shape[0] # TODO: Calculate number of features n_features = student_data.shape[1] - 1 # TODO: Calculate passing students n_passed = student_data["passed"].value_counts()["yes"] # TODO: Calculate failing students n_failed = student_data["passed"].value_counts()["no"] # TODO: Calculate graduation rate grad_rate = (265/395.0)*100 # Print the results print "Total number of students: {}".format(n_students) print "Number of features: {}".format(n_features) print "Number of students who passed: {}".format(n_passed) print "Number of students who failed: {}".format(n_failed) print "Graduation rate of the class: {:.2f}%".format(grad_rate) ###Output Total number of students: 395 Number of features: 30 Number of students who passed: 265 Number of students who failed: 130 Graduation rate of the class: 67.09% ###Markdown Preparing the DataIn this section, we will prepare the data for modeling, training and testing. Identify feature and target columnsIt is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.Run the code cell below to separate the student data into feature and target columns to see if any features are non-numeric. ###Code # Extract feature columns feature_cols = list(student_data.columns[:-1]) # Extract target column 'passed' target_col = student_data.columns[-1] # Show the list of columns print "Feature columns:\n{}".format(feature_cols) print "\nTarget column: {}".format(target_col) # Separate the data into feature data and target data (X_all and y_all, respectively) X_all = student_data[feature_cols] y_all = student_data[target_col] # Show the feature information by printing the first five rows print "\nFeature values:" print X_all.head() ###Output Feature columns: ['school', 'sex', 'age', 'address', 'famsize', 'Pstatus', 'Medu', 'Fedu', 'Mjob', 'Fjob', 'reason', 'guardian', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences'] Target column: passed Feature values: school sex age address famsize Pstatus Medu Fedu Mjob Fjob \ 0 GP F 18 U GT3 A 4 4 at_home teacher 1 GP F 17 U GT3 T 1 1 at_home other 2 GP F 15 U LE3 T 1 1 at_home other 3 GP F 15 U GT3 T 4 2 health services 4 GP F 16 U GT3 T 3 3 other other ... higher internet romantic famrel freetime goout Dalc Walc health \ 0 ... yes no no 4 3 4 1 1 3 1 ... yes yes no 5 3 3 1 1 3 2 ... yes yes no 4 3 2 2 3 3 3 ... yes yes yes 3 2 2 1 1 5 4 ... yes no no 4 3 2 1 2 5 absences 0 6 1 4 2 10 3 2 4 4 [5 rows x 30 columns] ###Markdown Preprocess Feature ColumnsAs you can see, there are several non-numeric columns that need to be converted! Many of them are simply `yes`/`no`, e.g. `internet`. These can be reasonably converted into `1`/`0` (binary) values.Other columns, like `Mjob` and `Fjob`, have more than two values, and are known as _categorical variables_. The recommended way to handle such a column is to create as many columns as possible values (e.g. `Fjob_teacher`, `Fjob_other`, `Fjob_services`, etc.), and assign a `1` to one of them and `0` to all others.These generated columns are sometimes called _dummy variables_, and we will use the [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummiespandas.get_dummies) function to perform this transformation. Run the code cell below to perform the preprocessing routine discussed in this section. ###Code def preprocess_features(X): ''' Preprocesses the student data and converts non-numeric binary variables into binary (0/1) variables. Converts categorical variables into dummy variables. ''' # Initialize new output DataFrame output = pd.DataFrame(index = X.index) # Investigate each feature column for the data for col, col_data in X.iteritems(): # If data type is non-numeric, replace all yes/no values with 1/0 if col_data.dtype == object: col_data = col_data.replace(['yes', 'no'], [1, 0]) # If data type is categorical, convert to dummy variables if col_data.dtype == object: # Example: 'school' => 'school_GP' and 'school_MS' col_data = pd.get_dummies(col_data, prefix = col) # Collect the revised columns output = output.join(col_data) return output X_all = preprocess_features(X_all) print "Processed feature columns ({} total features):\n{}".format(len(X_all.columns), list(X_all.columns)) ###Output Processed feature columns (48 total features): ['school_GP', 'school_MS', 'sex_F', 'sex_M', 'age', 'address_R', 'address_U', 'famsize_GT3', 'famsize_LE3', 'Pstatus_A', 'Pstatus_T', 'Medu', 'Fedu', 'Mjob_at_home', 'Mjob_health', 'Mjob_other', 'Mjob_services', 'Mjob_teacher', 'Fjob_at_home', 'Fjob_health', 'Fjob_other', 'Fjob_services', 'Fjob_teacher', 'reason_course', 'reason_home', 'reason_other', 'reason_reputation', 'guardian_father', 'guardian_mother', 'guardian_other', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences'] ###Markdown Implementation: Training and Testing Data SplitSo far, we have converted all _categorical_ features into numeric values. For the next step, we split the data (both features and corresponding labels) into training and test sets. In the following code cell below, you will need to implement the following:- Randomly shuffle and split the data (`X_all`, `y_all`) into training and testing subsets. - Use 300 training points (approximately 75%) and 95 testing points (approximately 25%). - Set a `random_state` for the function(s) you use, if provided. - Store the results in `X_train`, `X_test`, `y_train`, and `y_test`. ###Code # TODO: Import any additional functionality you may need here from sklearn.cross_validation import train_test_split # TODO: Set the number of training points num_train = 300 # Set the number of testing points num_test = X_all.shape[0] - num_train # TODO: Shuffle and split the dataset into the number of training and testing points above X_train,X_test,y_train, y_test = train_test_split(X_all,y_all,test_size = num_test, random_state = 0) # Show the results of the split print "Training set has {} samples.".format(X_train.shape[0]) print "Testing set has {} samples.".format(X_test.shape[0]) ###Output Training set has 300 samples. Testing set has 95 samples. ###Markdown Training and Evaluating ModelsIn this section, you will choose 3 supervised learning models that are appropriate for this problem and available in `scikit-learn`. You will first discuss the reasoning behind choosing these three models by considering what you know about the data and each model's strengths and weaknesses. You will then fit the model to varying sizes of training data (100 data points, 200 data points, and 300 data points) and measure the F1 score. You will need to produce three tables (one for each model) that shows the training set size, training time, prediction time, F1 score on the training set, and F1 score on the testing set. Question 2 - Model Application*List three supervised learning models that are appropriate for this problem. What are the general applications of each model? What are their strengths and weaknesses? Given what you know about the data, why did you choose these models to be applied?* **Answer: **The three supervised learning models that I've chosen are :1. Decision Trees2. Support Vector Machines3. K-Nearest Neighbors**1. Decision Trees** : Decision Trees are widely used in several industries including medicine(to classify diseases based on patient's features for example), biomedical research, financial analysis(fraud detection,credit defaulting etc) for both classification and regression problem, astronomy to social media websites for predicting engagement/ad clicks for it's interpretability and versatality.* Strengths : 1. Decision Trees are interpretable and easy to visualize. 2. Decision Trees can handle both categorical and numerical data 3. All else being equal, decision trees prefer shorter trees to longer trees by splitting on the "best features"(using information gain or gini impurity index), so it's easy to understand what are the most important features in a dataset* Weeknesses : 1. Decision trees grow exponentially with the number of instances and more features 2. Decision trees overfit very easily as it picks up subtle variances in the data set. However, over-fitting can be minimized by calculating best maximum depth of the tree, minimum number of samples to spilt per node and pruning techniques after creating the tree. Random forest, another model based on decision trees are incredibly popular as it minimizes errors by ensembling over many decision trees.* Reasons for choosing this model : 1. This dataset has many features and a problem like predicting which students need intervention is unlikely to be linear relationship completely as many details influence a student's learning. 2. Most features in this data set are binary which is for a decision tree to handle with conditionals and the resulting tree will be easier to interpret and thus determine a course of action to ensure student's learning rate improves. ** 2. Support Vector Machine :** Support vector machines classify data by finding the maximum margin hyperplane that seperates class labels, it's also a very popular model like the other two, decision trees and K-nearest neighbors and used in industry for classification and regression tasks. Support Vector Machines have been successfully used on high dimensional data such as genetic data(protein structure prediction), music(song genre classification, music retrival), image classification(histogram based), image retrieval etc.* Strengths : 1. As Support Vector Machine tries to find the seperator hyperplane that has the maximum distance between the seperate classes, it's not prone to overfitting. 2. Linear SVM produces a line as decision boundary, but SVM is also effetive with high dimensional data by using Kernel-trick (mapping the data points to higher dimensional spaces to find the appropriate class labels) * Weeknesses : 1. Performance depends on the choice of Kernel. Large data sets may take a lot of time to train. 2. SVM works really well for datasets that has a clear margin of seperation, but performs poorly on noisy datasets. * Reasons for choosing this model : 1. As there are many features in this dataset, if this datset has a good margin of seperation SVM would be able to pick it up. 2. SVM also works well with high dimensional data with kernel trick, and this dataset has many features.**3. K Nearest Neighbor ** :K nearest neighbor is a method of 'instance based learning'/lazy learning as the computation begins when we start predicting, it's also a non-parametric method. K nearest neighbor tries to find similar instances for each query and predicts based on their average/majority voting for classification and regression problem. It can be used in many different cases including content retrieval for photos, videos, text and recommending products etc. It's one of the most popular methods in data mining.* Strengths : 1. It does not make any assumptions about the distribution of data. Rather it simply tries to find the most similar k neighbors for each query based on some distance metric/similarity measurement and uses the whole data set for each query. 2. After choosing the number of neighbors k and the similarity metric d , the algorithm is simple to implement in production. 3. It's possible to weight the contribution of the neighbors for predicting labels (weighting the nearest neighbors highest and the distant one's lower) for higher accuracy. For datasets that don't follow a general pattern, K nearest neighbor is often a really good choice. * Weeknesses: 1. K-nearest neighbor requires the entire dataset to be preserved in the memory. Unlike a parametric model like linear regression where we just have to train once to find the parameters, we can't throw away the data set and this can make the space requirement incredibly high. 2. It's important to use domain knowledge and grid search techniques to find a good similarity measure and a good k, in practice there can be many variations of distance metrics which can yield different performances. 3. It's less interpretable than models like decision tree where we can understand which features are the strongest. * Reasons for choosing this model: 1. Students who are failing may have similar patterns such as similar amount of time invested in recreation over studying, similar number of family members and income, similar geographic region etc which K nearest neighbor can deal with easily. SetupRun the code cell below to initialize three helper functions which you can use for training and testing the three supervised learning models you've chosen above. The functions are as follows:- `train_classifier` - takes as input a classifier and training data and fits the classifier to the data.- `predict_labels` - takes as input a fit classifier, features, and a target labeling and makes predictions using the F1 score.- `train_predict` - takes as input a classifier, and the training and testing data, and performs `train_clasifier` and `predict_labels`. - This function will report the F1 score for both the training and testing data separately. ###Code def train_classifier(clf, X_train, y_train): ''' Fits a classifier to the training data. ''' # Start the clock, train the classifier, then stop the clock start = time() clf.fit(X_train, y_train) end = time() # Print the results print "Trained model in {:.4f} seconds".format(end - start) def predict_labels(clf, features, target): ''' Makes predictions using a fit classifier based on F1 score. ''' # Start the clock, make predictions, then stop the clock start = time() y_pred = clf.predict(features) end = time() # Print and return results print "Made predictions in {:.4f} seconds.".format(end - start) return f1_score(target.values, y_pred, pos_label='yes') def train_predict(clf, X_train, y_train, X_test, y_test): ''' Train and predict using a classifer based on F1 score. ''' # Indicate the classifier and the training set size print "Training a {} using a training set size of {}. . .".format(clf.__class__.__name__, len(X_train)) # Train the classifier train_classifier(clf, X_train, y_train) # Print the results of prediction for both training and testing print "F1 score for training set: {:.4f}.".format(predict_labels(clf, X_train, y_train)) print "F1 score for test set: {:.4f}.".format(predict_labels(clf, X_test, y_test)) print "\n" ###Output _____no_output_____ ###Markdown Implementation: Model Performance MetricsWith the predefined functions above, you will now import the three supervised learning models of your choice and run the `train_predict` function for each one. Remember that you will need to train and predict on each classifier for three different training set sizes: 100, 200, and 300. Hence, you should expect to have 9 different outputs below — 3 for each model using the varying training set sizes. In the following code cell, you will need to implement the following:- Import the three supervised learning models you've discussed in the previous section.- Initialize the three models and store them in `clf_A`, `clf_B`, and `clf_C`. - Use a `random_state` for each model you use, if provided. - **Note:** Use the default settings for each model — you will tune one specific model in a later section.- Create the different training set sizes to be used to train each model. - *Do not reshuffle and resplit the data! The new training points should be drawn from `X_train` and `y_train`.*- Fit each model with each training set size and make predictions on the test set (9 in total). **Note:** Three tables are provided after the following code cell which can be used to store your results. ###Code # TODO: Import the three supervised learning models from sklearn from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier # TODO: Initialize the three models clf_A = DecisionTreeClassifier(random_state =0) clf_B = SVC(random_state = 0) clf_C = KNeighborsClassifier() training_sizes = [100,200,300] # TODO: Execute the 'train_predict' function for each classifier and each training set size # Decision Tree for size in training_sizes: train_predict(clf_A, X_train[:size], y_train[:size], X_test, y_test) print "\n\n\n" # Support Vector Machine for size in training_sizes: train_predict(clf_B, X_train[:size], y_train[:size], X_test, y_test) print "\n\n\n" # K Neareset Neighbor Classifier for size in training_sizes: train_predict(clf_C, X_train[:size], y_train[:size], X_test, y_test) ###Output Training a DecisionTreeClassifier using a training set size of 100. . . Trained model in 0.0050 seconds Made predictions in 0.0010 seconds. F1 score for training set: 1.0000. Made predictions in 0.0010 seconds. F1 score for test set: 0.6942. Training a DecisionTreeClassifier using a training set size of 200. . . Trained model in 0.0050 seconds Made predictions in 0.0010 seconds. F1 score for training set: 1.0000. Made predictions in 0.0000 seconds. F1 score for test set: 0.7132. Training a DecisionTreeClassifier using a training set size of 300. . . Trained model in 0.0000 seconds Made predictions in 0.0000 seconds. F1 score for training set: 1.0000. Made predictions in 0.0000 seconds. F1 score for test set: 0.7167. Training a SVC using a training set size of 100. . . Trained model in 0.0000 seconds Made predictions in 0.0000 seconds. F1 score for training set: 0.8591. Made predictions in 0.0000 seconds. F1 score for test set: 0.7838. Training a SVC using a training set size of 200. . . Trained model in 0.0180 seconds Made predictions in 0.0000 seconds. F1 score for training set: 0.8693. Made predictions in 0.0150 seconds. F1 score for test set: 0.7755. Training a SVC using a training set size of 300. . . Trained model in 0.0310 seconds Made predictions in 0.0160 seconds. F1 score for training set: 0.8692. Made predictions in 0.0000 seconds. F1 score for test set: 0.7586. Training a KNeighborsClassifier using a training set size of 100. . . Trained model in 0.0000 seconds Made predictions in 0.0000 seconds. F1 score for training set: 0.7972. Made predictions in 0.0000 seconds. F1 score for test set: 0.7068. Training a KNeighborsClassifier using a training set size of 200. . . Trained model in 0.0000 seconds Made predictions in 0.0220 seconds. F1 score for training set: 0.8571. Made predictions in 0.0070 seconds. F1 score for test set: 0.7121. Training a KNeighborsClassifier using a training set size of 300. . . Trained model in 0.0030 seconds Made predictions in 0.0250 seconds. F1 score for training set: 0.8722. Made predictions in 0.0000 seconds. F1 score for test set: 0.7482. ###Markdown Tabular ResultsEdit the cell below to see how a table can be designed in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheettables). You can record your results from above in the tables provided. ** Classifer 1 - DecisionTreeClassifier?** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 |0.0050 seconds |0.0010 seconds. |1.0000 |0.6942 || 200 |0.0050 seconds |0.0000 seconds |1.0000 |0.7132 || 300 |0.0000 seconds |0.0000 seconds |1.0000 |0.7167 |** Classifer 2 - SVM?** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 |0.0000 seconds |0.0000 seconds |0.8591 |0.7838 || 200 |0.0180 seconds |0.0150 seconds |0.8693 | 0.7755 || 300 |0.0310 seconds |0.0000 seconds |0.8692 |0.7586 |** Classifer 3 - K-Nearest Neighbor ** | Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) || :---------------: | :---------------------: | :--------------------: | :--------------: | :-------------: || 100 |0.0000 seconds |0.0000 seconds |0.7972 |0.7068 || 200 |0.0000 seconds |0.0070 seconds |0.8571 |0.7121 || 300 | 0.0030 seconds |0.0000 seconds |0.8722 |0.7482 | ###Code print y_train.value_counts() print y_test.value_counts() decision_tree_f1_average = (0.6942+0.7132+0.7167)/3.0 svm_f1_average = (0.7838 + 0.7755 + 0.7586)/3.0 k_nearest_f1_average = (0.7068+0.7121+0.7482)/3.0 print decision_tree_f1_average print svm_f1_average print k_nearest_f1_average ###Output 0.708033333333 0.772633333333 0.722366666667 ###Markdown Choosing the Best ModelIn this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F1 score. Question 3 - Chosing the Best Model*Based on the experiments you performed earlier, in one to two paragraphs, explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?* **Answer: **The model I would choose as the best model is SVM.Reasons : 1. DecisionTreeClassifier shows clear signs of overfitting. It fits the training data perfectly with a F1-score of 1, but performs worse on the testing data compared to both SVM and k-nearest neighbor. So Decision Tree would clearly not be an appropriate model for this data set. 2. K-Nearest Neighbor actually shows quite stable performance over training and testing data sets and performs better both on the training and testing data sets steadily as the score increased with more training data(possibly because it found similar students with more training instances for the query instances). However, K-nearest's performance on the test data set is still poor compared to SVM. 3. SVM's average test score is 0.7726, beating both decision tree(average f1 on test set = 0.7080) and k-nearest neighbor(average f1 score 0.7223), based on scores SVM is the best choice. It's true that there's subtle differences of computation time for training and testing phases but for a small data set like this the differences are not that important. Question 4 - Model in Layman's Terms*In one to two paragraphs, explain to the board of directors in layman's terms how the final model chosen is supposed to work. For example if you've chosen to use a decision tree or a support vector machine, how does the model go about making a prediction?* **Answer: **The model that was chosen is called Support Vector Machine which is a linear seperator. Intuitively in the simplest case, we can imagine a 2D plane where we plot the data and labels on the x and y axis respective and we want to seperate the labels using a line. We can choose many lines for this task, assuming the labels are not overlapping, however, support vector machine will choose the "maximum margin" line, the line that has the biggest distance from the nearest points of both classes, i.e the line which is actually in the 'middle'. We choose this line to generalize the model to test data and avoid overfitting, a line too close to either of the classes can misclassify quickly.For the higher dimension data sets instead of a line we map the datapoints to higher dimensions(with 'kernel trick') and find the maximum margin hyperplane to seperate the classes with as much gap as possible. For example in the image below a line could not have seperated circular data in 2D, so data has been mapped to 3D space where a clear seperating hyperplane was found, then the labels were used to classify the instances.For practical purposes, choosing decision tree would have been more interpretable, but in this case would have led to overfitting (as we have seen in the table) and intervention of a student who's actually doing well because of a bad model would have led to negative consequences in this student's life. Choosing something like K-Nearest perhaps would have been stable perhaps, but not as interpretable as decision trees. However if we scale to millions of students, decision trees will also grow exponentially and K-Nearest neighbors woudld have to iterate over all the millions of students to find similar one's.On the other hand, Support vector machine's clearly showed best performance so far and it's an widely used algorithm in the industry too, so SVM was chosen. Visualizing SVM is not as easy as decision tree's, but it has better performance. Implementation: Model TuningFine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:- Import [`sklearn.grid_search.gridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).- Create a dictionary of parameters you wish to tune for the chosen model. - Example: `parameters = {'parameter' : [list of values]}`.- Initialize the classifier you've chosen and store it in `clf`.- Create the F1 scoring function using `make_scorer` and store it in `f1_scorer`. - Set the `pos_label` parameter to the correct value!- Perform grid search on the classifier `clf` using `f1_scorer` as the scoring method, and store it in `grid_obj`.- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_obj`. ###Code # TODO: Import 'GridSearchCV' and 'make_scorer' from sklearn.grid_search import GridSearchCV from sklearn.metrics import make_scorer # TODO: Create the parameters list you wish to tune parameters = {'kernel':('linear', 'poly','rbf'), 'C':[0.25,0.5,1, 10,50]} # TODO: Initialize the classifier clf = SVC() # TODO: Make an f1 scoring function using 'make_scorer' f1_scorer = make_scorer(f1_score,pos_label = "yes") # TODO: Perform grid search on the classifier using the f1_scorer as the scoring method grid_obj = GridSearchCV(clf,param_grid = parameters,scoring = f1_scorer) # TODO: Fit the grid search object to the training data and find the optimal parameters grid_obj.fit(X_train,y_train) # Get the estimator clf = grid_obj.best_estimator_ print clf.get_params() # Report the final F1 score for training and testing after parameter tuning print "Tuned model has a training F1 score of {:.4f}.".format(predict_labels(clf, X_train, y_train)) print "Tuned model has a testing F1 score of {:.4f}.".format(predict_labels(clf, X_test, y_test)) ###Output {'kernel': 'rbf', 'C': 1, 'verbose': False, 'probability': False, 'degree': 3, 'shrinking': True, 'max_iter': -1, 'decision_function_shape': None, 'random_state': None, 'tol': 0.001, 'cache_size': 200, 'coef0': 0.0, 'gamma': 'auto', 'class_weight': None} Made predictions in 0.0250 seconds. Tuned model has a training F1 score of 0.8692. Made predictions in 0.0100 seconds. Tuned model has a testing F1 score of 0.7586.
notebooks/2_event_detection_(Syn-I).ipynb
###Markdown uncomment and run the following cell if you are on Google Colab ###Code # !pip install git+https://github.com/vafaei-ar/drama.git ###Output _____no_output_____ ###Markdown Unsupervised outliers detection (event detection) This notebook is evaluated DRAMA on a known set of dataset where X and y (outlier label) exist. ###Code import drama as drm from drama.v1.outlier_finder import grid_run_drama import numpy as np import matplotlib.pylab as plt from matplotlib import gridspec from drama.run_tools import synt_event from drama.v1.outlier_finder import sk_check %matplotlib inline ###Output WARNING:tensorflow:From /home/gf/packages/anaconda3/envs/drama/lib/python3.7/site-packages/tensorflow_core/python/compat/v2_compat.py:68: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version. Instructions for updating: non-resource variables are not supported in the long term ###Markdown Signal synthesis Here you can simulation inliers and outliers using "synt_event" fucntion. ###Code i_sig = 1 # signal number n_ftrs = 100 noise = 0.2 scl = 0.01 sft = 0.01 X, y = synt_event(i_sig,n_ftrs,sigma = noise,n1 = scl,n2 = sft,n3 = scl,n4 = sft) gs = gridspec.GridSpec(1, 2) plt.figure(figsize=(8,3)) ax1 = plt.subplot(gs[0, 0]) ax2 = plt.subplot(gs[0, 1]) ax1.set_title('Inliers') ax2.set_title('Outliers') inliers = X[y==0] outliers = X[y==1] for i in range(10): ax1.plot(inliers[i],'b') ax2.plot(outliers[i],'r') ###Output _____no_output_____ ###Markdown Outlier detection We run DRAMA 5 times. DRAMA can be run in grid mode so one can compare different hyperparameter configuration. ###Code n_try = 5 result = [] for i in range(n_try): auc,mcc,rws,conf = grid_run_drama(X_seen=X,y_seen=y) arr = np.stack([auc,mcc,rws],axis=-1) result.append(arr) result = np.array(result) drts = np.unique(conf[:,1]) metrs = np.unique(conf[:,2]) res = result.reshape(n_try,5,10,-1) ###Output Unsupervised outlier detection mode. ###Markdown DRAMA runs in two mode for now: - supervised - semi-supervised The "grid_run_drama" fucntion gets four arguments: - X_seen - y_seen - X_unseen = None - y_unseen = None - X_seen and y_seen sould be given when one wants to evaluate unsupervised outlier detection. DRAMA will run on the X_seen and return the metrics (AUC,MCC,RWS) comparing the result with y_seen.- X_unseen and y_unseen are None by default. Pass part of data to them when you want evaluate drama in semi-supervised outlier detection mode. DRAMA will run on the seen data and select the best hyperparameter configuration set and use them on the unseen data. Finally it compares the results with y_unseen and returns the metrics (AUC,MCC,RWS).We are evaluating unsupervised mode in this notebook. ###Code drm.plot_table(np.mean(res,axis=0),drts,metrs) ###Output _____no_output_____ ###Markdown Now we can compare DRAMA resualts with LOF and iforest. "sk_check" is used for this purpose. ###Code lof_all = np.zeros((n_try,3)) ifr_all = np.zeros((n_try,3)) df = sk_check(X,X,y,[1]) for i in range(n_try): for j,scr in enumerate(['AUC','MCC','RWS']): lof_all[i,j] = df[scr][0] ifr_all[i,j] = df[scr][1] ###Output /home/gf/packages/anaconda3/lib/python3.6/site-packages/sklearn/ensemble/iforest.py:223: FutureWarning: behaviour="old" is deprecated and will be removed in version 0.22. Please use behaviour="new", which makes the decision_function change to match other anomaly detection algorithm API. FutureWarning) ###Markdown Here we compare howmany DRAMA wins using different hyperpameter congifs. ###Code auc = np.sum((res[:, :, :, 0].T>lof_all[:, 0]) & (res[:, :, :, 0].T>ifr_all[:, 0]),axis=-1).T mcc = np.sum((res[:, :, :, 1].T>lof_all[:, 1]) & (res[:, :, :, 1].T>ifr_all[:, 1]),axis=-1).T rws = np.sum((res[:, :, :, 2].T>lof_all[:, 2]) & (res[:, :, :, 2].T>ifr_all[:, 2]),axis=-1).T fig = plt.figure(figsize=(20,10)) plt.clf() ax = fig.add_subplot(111) ax.set_aspect('auto') ax.imshow(auc, cmap=plt.cm.jet,interpolation='nearest') width, height = auc.shape for x in range(width): for y in range(height): ax.annotate('AUC: {:d}\n MCC: {:d}\n RWS: {:d}'.format(auc[x][y],mcc[x][y],rws[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center',fontsize=18); plt.xticks(range(10),metrs,fontsize=15) plt.yticks(range(5), drts,fontsize=15) plt.title('Number of successes (LOF and i-forest) out of 20 data set',fontsize=25) plt.annotate('** Colors depend on AUC.', (0,0), (0, -30), xycoords='axes fraction', textcoords='offset points', va='top',fontsize=15) # plt.savefig('AND_success.jpg',dpi=150,bbox_inches='tight') ###Output _____no_output_____
books/pythonMachineLearning/ch3_scikit_learn/.ipynb_checkpoints/ch03-checkpoint.ipynb
###Markdown Training a logistic regression model with scikit-learn ###Code from sklearn.linear_model import LogisticRegression lr = LogisticRegression(C=100, random_state=1, solver='lbfgs', multi_class='ovr') lr.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=lr, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() # plt.savefig('images/03_06.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown Add regularization to logistic regressionNote that scikit learn is different than the by-hand implementation: `coef_` and `intercept_` are equivalent to my definition of `w_` ###Code weights, params = [], [] for c in np.arange(-5, 5): lr = LogisticRegression(C=10.**c, random_state=1, solver='lbfgs', multi_class='ovr') lr.fit(X_train_std, y_train) weights.append(lr.coef_[1]) params.append(10.**c) weights = np.array(weights) plt.plot(params, weights[:, 0], label='petal length') plt.plot(params, weights[:, 1], linestyle='--', label='petal width') plt.ylabel('weight coefficient') plt.xlabel('C') plt.legend(loc='upper left') plt.xscale('log') #plt.savefig('images/03_08.png', dpi=300) plt.show() ###Output _____no_output_____ ###Markdown Maximum margin classification with support vector machines ###Code Image(filename='images/03_10.png', width=600) from sklearn.svm import SVC svm = SVC(kernel='linear', C=10**0, random_state=1) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() plt.savefig('images/03_11.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown Alternative implementations in scikit-learn ###Code from sklearn.linear_model import SGDClassifier ppn = SGDClassifier(loss='perceptron') lr = SGDClassifier(loss='log') svm = SGDClassifier(loss='hinge') ###Output _____no_output_____ ###Markdown Solving non-linear problems using a kernel SVM ###Code import matplotlib.pyplot as plt import numpy as np np.random.seed(1) X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0) y_xor = np.where(y_xor, 1, -1) plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1], c='b', marker='x', label='1') plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1], c='r', marker='s', label='-1') plt.xlim([-3, 3]) plt.ylim([-3, 3]) plt.legend(loc='best') plt.tight_layout() #plt.savefig('images/03_12.png', dpi=300) plt.show() ###Output _____no_output_____ ###Markdown Using the kernel trick to find separating hyperplanes in higher dimensional space ###Code svm = SVC(kernel='rbf', random_state=1, gamma=0.10, C=10.0) svm.fit(X_xor, y_xor) plot_decision_regions(X_xor, y_xor, classifier=svm) plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_14.png', dpi=300) plt.show() svm = SVC(kernel='rbf', random_state=1, gamma=0.2, C=1.0) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_15.png', dpi=300) plt.show() svm = SVC(kernel='rbf', random_state=1, gamma=100.0, C=1.0) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_16.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown Maximizing information gain - getting the most bang for the buck ###Code import matplotlib.pyplot as plt import numpy as np def gini(p): return p * (1 - p) + (1 - p) * (1 - (1 - p)) def entropy(p): return - p * np.log2(p) - (1 - p) * np.log2((1 - p)) def error(p): return 1 - np.max([p, 1 - p]) x = np.arange(0.0, 1.0, 0.01) ent = [entropy(p) if p != 0 else None for p in x] sc_ent = [e * 0.5 if e else None for e in ent] err = [error(i) for i in x] fig = plt.figure() ax = plt.subplot(111) for i, lab, ls, c, in zip([ent, sc_ent, gini(x), err], ['Entropy', 'Entropy (scaled)', 'Gini impurity', 'Misclassification error'], ['-', '-', '--', '-.'], ['black', 'lightgray', 'red', 'green', 'cyan']): line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=5, fancybox=True, shadow=False) ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--') ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--') plt.ylim([0, 1.1]) plt.xlabel('p(i=1)') plt.ylabel('impurity index') #plt.savefig('images/03_19.png', dpi=300, bbox_inches='tight') plt.show() ###Output _____no_output_____ ###Markdown Building a decision tree ###Code from sklearn.tree import DecisionTreeClassifier tree_model = DecisionTreeClassifier(criterion='gini', max_depth=4, random_state=1) tree_model.fit(X_train, y_train) X_combined = np.vstack((X_train, X_test)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X_combined, y_combined, classifier=tree_model, test_idx=range(105, 150)) plt.xlabel('petal length [cm]') plt.ylabel('petal width [cm]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_20.png', dpi=300) plt.show() from sklearn import tree tree.plot_tree(tree_model) plt.show() from pydotplus import graph_from_dot_data from sklearn.tree import export_graphviz dot_data = export_graphviz(tree_model, filled=True, rounded=True, class_names=['Setosa', 'Versicolor', 'Virginica'], feature_names=['petal length', 'petal width'], out_file=None) graph = graph_from_dot_data(dot_data) graph.write_png('images/tree.png') Image(filename='images/tree.png', width=600) ###Output _____no_output_____ ###Markdown Combining weak to strong learners via random forests ###Code from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(criterion='gini', n_estimators=25, random_state=1, n_jobs=2) forest.fit(X_train, y_train) plot_decision_regions(X_combined, y_combined, classifier=forest, test_idx=range(105, 150)) plt.xlabel('petal length [cm]') plt.ylabel('petal width [cm]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_22.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown K-nearest neighbors - a lazy learning algorithm ###Code from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski') knn.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=knn, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_24.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown Chapter 3 - A Tour of Machine Learning Classifiers Using Scikit-Learn ###Code %load_ext watermark %watermark -a "Othmane Rifki" -u -d -p numpy,pandas,matplotlib,scikit-learn from IPython.display import Image %matplotlib inline ###Output _____no_output_____ ###Markdown First attempt with scikit-learnImportant methods:* `datasets`: to get various datasets* `model_selection`: to get `train_test_split`* `preprocessing`: for feature scaling `StandardScaler`* `linear_model`: for various linear learning algorithms * `metrics`: to evaluate model Load data ###Code from sklearn import datasets import numpy as np iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target print('Class labels:', np.unique(y)) ###Output Class labels: [0 1 2] ###Markdown Split data ###Code from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=1, stratify=y) print('Labels count in y:', np.bincount(y)) print('Labels count in y_train:', np.bincount(y_train)) print('Labels count in y_test:', np.bincount(y_test)) ###Output Labels count in y: [50 50 50] Labels count in y_train: [35 35 35] Labels count in y_test: [15 15 15] ###Markdown Feature scaling ###Code from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) ###Output _____no_output_____ ###Markdown Train a perceptron ###Code from sklearn.linear_model import Perceptron ppn = Perceptron(eta0=0.1, random_state=1) ppn.fit(X_train_std, y_train) y_pred = ppn.predict(X_test_std) print('Misclassified examples: %d' % (y_test != y_pred).sum()) ###Output Misclassified examples: 1 ###Markdown Show metrics ###Code # 1-manually print(f'Accuracy: {(y_pred == y_test).sum()/len(y_test):.2%}') # 2-built-in from sklearn.metrics import accuracy_score print(f'Accuracy: {accuracy_score(y_test, y_pred):.2%}') # 3-fit+score print(f'Accuracy: {ppn.score(X_test_std, y_test):.2%}') ###Output Accuracy: 97.78% ###Markdown Plot ###Code from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolor='black') # highlight test examples if test_idx: # plot all examples X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', edgecolor='black', alpha=1.0, linewidth=1, marker='o', s=100, label='test set') X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() plt.savefig('images/03_01.png', dpi=300) plt.show() ###Output <ipython-input-12-4cd5e22e52b7>:37: MatplotlibDeprecationWarning: Using a string of single character colors as a color sequence is deprecated since 3.2 and will be removed two minor releases later. Use an explicit list instead. plt.scatter(X_test[:, 0], ###Markdown Playing with logistic regression odds and logits ###Code # example of converting between probability and log-odds from math import log from math import exp # define our probability of success prob = 0.8 print('Probability %.1f' % prob) # convert probability to odds odds = prob / (1 - prob) print('Odds %.1f' % odds) # convert odds to log-odds logodds = log(odds) print('Log-Odds %.1f' % logodds) # convert log-odds to a probability prob = 1 / (1 + exp(-logodds)) print('Probability %.1f' % prob) # test of Bernoulli likelihood function # likelihood function for Bernoulli distribution def likelihood(y, yhat): return yhat * y + (1 - yhat) * (1 - y) # test for y=1 y, yhat = 1, 0.9 print('y=%.1f, yhat=%.1f, likelihood: %.3f' % (y, yhat, likelihood(y, yhat))) y, yhat = 1, 0.1 print('y=%.1f, yhat=%.1f, likelihood: %.3f' % (y, yhat, likelihood(y, yhat))) # test for y=0 y, yhat = 0, 0.1 print('y=%.1f, yhat=%.1f, likelihood: %.3f' % (y, yhat, likelihood(y, yhat))) y, yhat = 0, 0.9 print('y=%.1f, yhat=%.1f, likelihood: %.3f' % (y, yhat, likelihood(y, yhat))) ###Output y=1.0, yhat=0.9, likelihood: 0.900 y=1.0, yhat=0.1, likelihood: 0.100 y=0.0, yhat=0.1, likelihood: 0.900 y=0.0, yhat=0.9, likelihood: 0.100 ###Markdown Plot sigmoid function = logistic function ###Code import matplotlib.pyplot as plt import numpy as np def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) z = np.arange(-7, 7, 0.1) phi_z = sigmoid(z) plt.plot(z, phi_z) plt.axvline(0.0, color='k') plt.ylim(-0.1, 1.1) plt.xlabel('z') plt.ylabel('$\phi (z)$') # y axis ticks and gridline plt.yticks([0.0, 0.5, 1.0]) ax = plt.gca() ax.yaxis.grid(True) plt.tight_layout() plt.savefig('images/03_02.png', dpi=300) plt.show() ###Output _____no_output_____ ###Markdown Learning the weights of the logistic cost function ###Code def cost_1(z): return - np.log(sigmoid(z)) def cost_0(z): return - np.log(1 - sigmoid(z)) z = np.arange(-10, 10, 0.1) phi_z = sigmoid(z) c1 = [cost_1(x) for x in z] plt.plot(phi_z, c1, label='J(w) if y=1') c0 = [cost_0(x) for x in z] plt.plot(phi_z, c0, linestyle='--', label='J(w) if y=0') plt.ylim(0.0, 5.1) plt.xlim([0, 1]) plt.xlabel('$\phi$(z)') plt.ylabel('J(w)') plt.legend(loc='best') plt.tight_layout() #plt.savefig('images/03_04.png', dpi=300) plt.show() ###Output _____no_output_____ ###Markdown Logistic regression algorithm ###Code import numpy as np class LogisticRegressionGD(object): """ Implementation of logistic regression using the gradient descent minimization algorithm """ def __init__(self, eta=0.01, n_iter=10, random_state=1): self.eta = eta self.n_iter = n_iter self.random_state = random_state def fit(self, X, y): """Fit function to your data X with dimensions [number of examples, number of features] and y [number of examples]""" self.w_ = np.random.normal(0, 0.01, 1+X.shape[1]) self.cost_ = [] for _ in range(self.n_iter): net_input = self.net_input(X) output = self.activation(net_input) errors = (y - output) self.w_[1:] += self.eta * np.dot(X.T,errors) self.w_[0] += self.eta * np.sum(errors) cost = (-y.dot(np.log(output)) - ((1 - y).dot(np.log(1-output)))) self.cost_.append(cost) return self def net_input(self, X): return np.dot(X, self.w_[1:]) + self.w_[0] def activation(self, z): return 1. / (1. + np.exp(-np.clip(z, -250, 250))) def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, 0) X_train_01_subset = X_train_std[(y_train == 0) | (y_train == 1)] y_train_01_subset = y_train[(y_train == 0) | (y_train == 1)] lrgd = LogisticRegressionGD(eta=0.05, n_iter=1000, random_state=1) lrgd.fit(X_train_01_subset, y_train_01_subset) plot_decision_regions(X=X_train_01_subset, y=y_train_01_subset, classifier=lrgd) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.tight_layout() #plt.savefig('images/03_05.png', dpi=300) plt.show() ###Output _____no_output_____
Hyper Basis Function Models 0.2.ipynb
###Markdown Hyper Basis Function Models Table of Contents Framinga) Learning as Hypersurface reconstruction b) Approximating the Hypersurfacec) Network representation of approximated Hypersurfaces Interpolation and Radial Basis Functions (RBFs)a) Interpolation Problem b) Radial Basis Functions (RBFs) c) RBF approach to interpolation An examplea) Loading and looking at data b) Linear RBF interpolation c) Multiquadratic RBF interpolation 1) FramingIn the absence of a complete section on this I'll get down the gist: Learning as Hypersurface reconstructiona) TL/DR Allot of super relevent types of learning boil down to input-output mappings;Lots of the learning that we do, as agents in the world (as humans, animals, plants, fungi, and bacteria are) can be described as learning a mapping from an input to an output space. The input could be sensory information and the output some behavior. Examples of such mappings include sensing a bad smell and exiting a room, or a plant leaning towards sunlight. The input can be sensory information and the output representational (learning new categories, recognizing new faces). The input and output both can be represntational. Many of the types of learning we do can be represented this way. b) Input to output mappings, when the output is a single dimension, is a question of hypersurface reconstructionAs a potentially important note I say hypersurface a bit lightly, I think it has a deeper meaning than I currently understand. I mean it as a surface in any number of dimensions that has the singular constraint of having a one dimensional output for any input vector of arbitrary dimension. Another note: the more broad context of multidimensional output spaces can be represented in tis framework as a collection of surfaces.c) We want to able to generate mappings from sparse data Approximating the Hypersurfacea) Given sparse noisy data we want to try to estimate a point on a surface. This is an approximation problem.Insert definition of approximation problem here Network representation of approximated hypersurfacesMany classical sollutions to the approximation problem can be represented by network.Linear regression and spline interprolation (as exampels) can be represented by networks of one hidden layer. 2) Interprolation and Radial Basis Functions This section is an interactive "playthrough" of the section of the same name of Piggio and Girosi's 1989 paper "A theory of Networks for Approximation and Learning" With some spinoffs. Interpolation ProblemGiven $N$ different points {$\vec{x_i} \in R^n | i = 1,...N$} and $N$ real numbers {$y_i \in R^n | i = 1,...N$} find a function $F$ from $R^n$ to $R$ satisfying the interpolation conditions:$$F(\vec{x_i}) = y_i, \ \ \ i = 1,...N$$(Poggio & Girosi 1989) Described in words, we want some function that can recreate our data but also generate guesses about points that we haven't seen before.As a note: I can see no way for such a process to be possible in the case where two examples with identitical feature vectors yield conflicting label values. Indeed we will, at least in the case of the interprolation strategy we'll be looking at, where this situation leads to an attempt to invert a square matrix that has rank less than that of it's size! Edit: I'm less confident about this now, certainly if clusters of points very close together (or identical) will create regions in the H matrix that have similar (or identical) values, which could in principle decrease the rank. THis is all a bit fuzzy to me.! I realize I've used the term rank. Given that I would like, ultimately, this to be accessible to anybody with high school or GED equivalent I need to link to a descriptive definition of rank Radial Basis Functions (RBFs) I'm going to give a basic and unsatisfying definition of Radial Basis Functions here. This is, largely, based out of my current limited understanding of what a radial basis function is. As such this definition is temporary, and only as descriptive as my understanding is deep.The context: function $F$ is from a vector space of dimension $N$, the basis of the space being the set of functions $$\{h(||x-x_i||)|i = 1,...N\}$$s.t. $h$ is a continuous funciton from $R^m \rightarrow R^n$ where $m>n$ & $||.||$ is the Euclidean norm. This $h$ is the radial basis functionNote here the relationship between the Euclidian Norm and $L2$ distance, where a difference in any dimension yields a non-zero value, and additional dimensions can only increase or unchange the value of h between two pointsThere are some constraints on the types of functions $h$ can be, and this is one area where my current understanding is quite lacking. So far as I can tell it boils down to the matrix $H$ that one gets out of $\{h(||x-x_i||)|i = 1,...N\}$ being invertible.Some examples of valid radial basis functions are listed:$$h(r) = e^{-(\frac{r}{c})^2}\ \ \ (gaussian)$$$$h(r) = \frac{1}{(c^2+r^2)^\alpha} \ \ \ \alpha>0$$$$h(r) = (c^2+r^2)^\beta \ \ \ 0<\beta<1$$$$h(r) = \sqrt{c^2 + r^2} \ \ \ (multiquadratic)$$$$h(r) = r \ \ \ \ \ (linear)$$ RBF approach to interpolationA satisfying explanation of this, as with many things, is missing.All I will say for now is the interpolation problem can be solved, given that $h(r)$ is a valid RBF, by setting our function $F$ to a linear combination of the RBFs that form the basis of our previously definied vector space $$F(x) = \sum_{i=1}^N c_ih(||x-x_i||)$$Furthermore the unknown coefficients $c_i$ can be recovered by reimposing our interpolation conditions defined previously. Simply substituting those conditions into the above function yields a solvable system.$$y_j = \sum_{i=1}^N c_ih(||(x_j - x_i||) \ \ j=1,...,N$$By setting some definitions: $(y)_j = y_j; \ \ (c)_i = c_i; \ \ (H)_{ij} = h(||x_j - x_i||)$ the system simplifies nicely:$$c = H^{-1}y$$ Network representation of RBF 3) An Example Loading and looking at dataFirst we'll load some packages and data ###Code %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import math from mpl_toolkits.mplot3d import Axes3D num_examples = 100 test_examples = 100 california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",") california_housing_dataframe = california_housing_dataframe.reindex( np.random.permutation(california_housing_dataframe.index)) data_train = np.zeros([num_examples,3]) data_train[:,0] = california_housing_dataframe.median_house_value[0:(num_examples)].values # Median house value for household within a block ($1) data_train[:,1] = california_housing_dataframe.population[0:(num_examples)].values # population in block data_train[:,2] = california_housing_dataframe.median_income[0:(num_examples)].values # Median income for households within a block ($10k) california_housing_dataframe = california_housing_dataframe.reindex( np.random.permutation(california_housing_dataframe.index)) # I should be splitting the data into non-overlapping test and training examples, the only benefit of this is it allows some flexibility (if the training data set and the test data set together make up more than the total number of exampels I won't get an error here, I'll only get an error if either individually are too large) data_test = np.zeros([test_examples,3]) data_test[:,0] = california_housing_dataframe.median_house_value[0:(test_examples)].values data_test[:,1] = california_housing_dataframe.population[0:(test_examples)].values data_test[:,2] = california_housing_dataframe.median_income[0:(test_examples)].values ###Output _____no_output_____ ###Markdown Next lets see what we're working with ###Code plt.subplot(1,2,1) plt.scatter(data_train[:,0], data_train[:,2]) plt.xlabel('median house value per block') plt.ylabel('Income') plt.title('Income x median house value') plt.subplot(1,2,2) plt.scatter(data_train[:,1], data_train[:,2]) plt.xlabel('population per block') plt.ylabel('Income') plt.title('Income x block population') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(data_train[:,0],data_train[:,1],data_train[:,2]) plt.show() ###Output _____no_output_____ ###Markdown As a note: Recall how we mentioned a limit of interprolation before (namely that two identical input vectors with different outputs would break our ability to perform interprolation). The distance between any two points in a feature space necesarally increases as we increase the dimensionality of that feature space. We can see this intuitively in the $R^1 \rightarrow R^2$ case but by simply looking at the definition of $L2$ distance we can see this extends to any increase in dimension (relevance of $L2$ distance will be made more clear when we talk about radial basis functions).The following defines $L2$ distance between two vectors of length n $\vec{p}=(p_1,p_2,...,p_n)$ and $\vec{q}=(q_1,q_2,...,q_n)$$$\rho_{L2}(\vec{p},\vec{q}) = \sqrt{\sum_{i=1}^n(q_i-p_i)^2}$$ Linear RBF interpolation ###Code # Linear RBF interpolation (in 1D & 2D feature vectors) # Next hopefully I'll add loss and comparison to simple linear regression # Ultimately I want to have a switch-case here that allows users to choose their basis function. Ideally if they picked a paramterized basis they would be prompted to input paramters (or even better I guess the parameter space would be samples/explored) # Median House value -> income H_0 = np.zeros([num_examples,num_examples]) for i in range(num_examples): for j in range(num_examples): H_0[i,j] = (np.linalg.norm(data_train[j,0]-data_train[i,0])) c_0 = np.matmul(np.linalg.inv(H_0),np.reshape(data_train[:,2],[num_examples,1])) y_hats_test_linear_0 = np.zeros(test_examples) for test_val in range(test_examples): temp = 0 for node in range(num_examples): temp = temp + c_0[node]*np.linalg.norm(data_test[test_val,0]-data_train[node,0]) y_hats_test_linear_0[test_val] = temp plt.subplot(1,3,1) plt.scatter(data_train[:,0], data_train[:,2]) plt.xlabel('Median House value'); plt.ylabel('Income'); plt.title('Training data') plt.subplot(1,3,2) plt.scatter(data_test[:,0], data_test[:,2]) plt.xlabel('Median House value'); plt.ylabel('True Income'); plt.title('Test data') plt.subplot(1,3,3) plt.scatter(data_test[:,0], y_hats_test_linear_0) plt.xlabel('Median House value'); plt.ylabel('Estimated Income (Linear)'); plt.title('Estimated Income') plt.subplots_adjust(wspace = 0.5) plt.show() #Loss calculation y_est = np.zeros([test_examples,1]); L2Loss = 0 for i in range(0,(test_examples)): L2Loss = L2Loss + (data_test[i,2]-(y_hats_test_linear_0[i]))**2 print("L2Loss = %s" %L2Loss) # Block Population -> income H_1 = np.zeros([num_examples,num_examples]) for i in range(num_examples): for j in range(num_examples): H_1[i,j] = (np.linalg.norm(data_train[j,1]-data_train[i,1])) c_1 = np.matmul(np.linalg.inv(H_1),np.reshape(data_train[:,2],[num_examples,1])) y_hats_test_linear_1 = np.zeros(test_examples) for test_val in range(test_examples): temp = 0 for node in range(num_examples): temp = temp + c_1[node]*np.linalg.norm(data_test[test_val,1]-data_train[node,1]) y_hats_test_linear_1[test_val] = temp plt.subplot(1,3,1) plt.scatter(data_train[:,1], data_train[:,2]) plt.xlabel('population per block'); plt.ylabel('Income'); plt.title('Training data') plt.subplot(1,3,2) plt.scatter(data_test[:,1], data_test[:,2]) plt.xlabel('population per block'); plt.ylabel('True Income'); plt.title('Testing data') plt.subplot(1,3,3) plt.scatter(data_test[:,1], y_hats_test_linear_1) plt.xlabel('population per block'); plt.ylabel('Estimated Income (Linear)'); plt.title('Estimated Income') plt.subplots_adjust(wspace = 0.5) plt.show() #Loss calculation y_est = np.zeros([test_examples,1]); L2Loss = 0 for i in range(0,(test_examples)): L2Loss = L2Loss + (data_test[i,2]-(y_hats_test_linear_1[i]))**2 print("L2Loss = %s" %L2Loss) #Block Population*Population -> Income H_01 = np.zeros([num_examples,num_examples]) for i in range(num_examples): for j in range(num_examples): H_01[i,j] = (np.linalg.norm(data_train[j,[0,1]]-data_train[i,[0,1]])) c_01 = np.matmul(np.linalg.inv(H_01),np.reshape(data_train[:,2],[num_examples,1])) y_hats_test_linear_01 = np.zeros(test_examples) for test_val in range(test_examples): temp = 0 for node in range(num_examples): temp = temp + c_01[node]*np.linalg.norm(data_test[test_val,[0,1]]-data_train[node,[0,1]]) y_hats_test_linear_01[test_val] = temp fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(data_train[:,0],data_train[:,1],data_train[:,2]) plt.show() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(data_test[:,0],data_test[:,1],data_test[:,2]) plt.show() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(data_test[:,0],data_test[:,1],y_hats_test_linear_01) plt.show() #Loss calculation y_est = np.zeros([test_examples,1]); L2Loss = 0 for i in range(0,(test_examples)): L2Loss = L2Loss + (data_test[i,2]-(y_hats_test_linear_01[i]))**2 print("L2Loss = %s" %L2Loss) california_housing_dataframe.shape # multiquaradic (Population) const = 10 H = np.zeros([num_examples,num_examples]) for i in range(num_examples): for j in range(num_examples): H[i,j] = math.sqrt((np.linalg.norm(data_train[j,1]-data_train[i,1]))**2 + const**2) c = np.matmul(np.linalg.inv(H),np.reshape(data_train[:,2],[num_examples,1])) y_hats_test_multiquad = np.zeros(test_examples) for test_val in range(test_examples): temp = 0 for node in range(num_examples): temp = temp + c[node]*math.sqrt(np.linalg.norm(data_test[test_val,1]-data_train[node,1])**2 + const**2) y_hats_test_multiquad[test_val] = temp # gauss (Population) const = 10 H = np.zeros([num_examples,num_examples]) for i in range(num_examples): for j in range(num_examples): H[i,j] = math.exp(-(((np.linalg.norm(data_train[j,1]-data_train[i,1]))/const)**2)) c = np.matmul(np.linalg.inv(H),np.reshape(data_train[:,2],[num_examples,1])) y_hats_test_gauss = np.zeros(test_examples) for test_val in range(test_examples): temp = 0 for node in range(num_examples): temp = temp + c[node]*math.exp(-(((np.linalg.norm(data_test[test_val,1]-data_train[node,1]))/const)**2)) y_hats_test_gauss[test_val] = temp plt.scatter(data_train[:,1], data_train[:,2]) plt.xlabel('population per block') plt.ylabel('Income') plt.title('Population training data') plt.show() plt.scatter(data_test[:,1], data_test[:,2]) plt.xlabel('population per block') plt.ylabel('True Income') plt.title('Population testing data') plt.show() plt.scatter(data_test[:,1], y_hats_test_linear) plt.xlabel('population per block') plt.ylabel('Estimated Income (Linear)') plt.title('Estimated Income from Population Density') plt.show() plt.scatter(data_test[:,1], y_hats_test_multiquad) plt.xlabel('population per block') plt.ylabel('Estimated Income (Multiquardatic)') plt.show() plt.scatter(data_test[:,1], y_hats_test_gauss) plt.xlabel('population per block') plt.ylabel('Estimated Income (Gauss)') plt.show() from sklearn.cluster import KMeans #numTarg = 5 numTarg = int(len(x1train)/20) x1trainLess = KMeans(n_clusters=numTarg, init='random').fit(data_train[:,[0,2]]) y_kmeans1 = x1trainLess.predict(data_train[:,[0,2]]) x2trainLess = KMeans(n_clusters=numTarg, init='random').fit(data_train[:,[1,2]]) y_kmeans2 = x1trainLess.predict(data_train[:,[1,2]]) plt.scatter(data_train[:,0], data_train[:,2], c = y_kmeans1, s=50, cmap='viridis') centers1 = x1trainLess.cluster_centers_ plt.show() plt.scatter(centers1[:, 0], centers1[:, 1], c='black', s=50, alpha=0.5); plt.show() plt.scatter(data_train[:,1], data_train[:,2], c = y_kmeans1, s=50, cmap='viridis') centers2 = x2trainLess.cluster_centers_ plt.show() plt.scatter(centers2[:, 0], centers2[:, 1], c='black', s=50, alpha=0.5); plt.show() tottrainLess = KMeans(n_clusters=numTarg, init='random').fit(data_train) y_kmeanstot = tottrainLess.predict(data_train) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs,ys,zs,c = y_kmeanstot,cmap='viridis') plt.show() centerstot = tottrainLess.cluster_centers_ fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(centerstot[:,0],centerstot[:,1],centerstot[:,2],c = 'blac') plt.show() ###Output _____no_output_____
keras_3.ipynb
###Markdown ###Code import tensorflow as tf tf.__version__ ###Output _____no_output_____ ###Markdown 在Keras中,每个layer instance 都可以被看成是一个函数,其输入是一个tensor,输出也是一个tensor。例如在下面这个实现全连接网络的例子中,你可以看到第一个Dense层的输入是inputs,其输出是x,而且这个x又被当做是第二个Dense层的输入。最初的输入tensor和最后的输出tensor共同定义了模型。而模型的训练方法则跟Sequential model中的情况一致。 ###Code from keras.layers import Input,Dense from keras.models import Model # this return a tensor inputs = Input(shape=(784,)) # a layer instance is callable on a tensor, and returns a tensor x = Dense(64, activation = 'relu')(inputs) x= Dense(64,activation = 'relu')(x) predictions = Dense(10,activation = 'softmax')(x) # This creates a model that includes # the Input layer and three Dense layers model =Model(input = inputs,outputs = predictions) model.compile (optimizer = 'rmsprop',loss = 'categorical_crossentropy',metrix = ['accuracy']) # model.fit(data,label) model.summary() ###Output _____no_output_____ ###Markdown “多输入-多输出”模型---![avatar][doge] [doge]:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR4AAAGJCAIAAADTyMt6AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAB9ASURBVHhe7Z1vaB5Hfsd9F3qld1zLcYUWjoMeftEchVIohb7pqxb0qqUchb4IhBwlEKcYXIMxNQZDCKQPGB8BYwjpGQcH2UZOhBMTYWFsHNn5h2OSGKuy/kWWLMuSLMtSZMmWZbvfR7/JaLzP86yeZ5+dndmZ7wchZubZnZ39zX5m9nme3X22PCWEWIBqBc4W0gYqiJmorqyqIZmQOHqL/y30ljZDp9SSDGkVqhUwVMslVCtgqJZLqFbAUC2XUK2AoVouoVoBQ7VcQrUChmq5hGoFDNVyCdUKGKrlEqrVPseOHUMjR0ZGVN4bolCrUqn42Uj/Q+d/C70lCrW8hWo1YuvWrZiOVGa9GX19fSrzLCjXjZS1kBWk0BVtNqC6sqt92LZtG0IpacxLOl0Lwq1fRWt19FNWKQa0QaV8xVUL0aEdHR2SNruvloRaOo3VcYRI2glthq66ssPjA5tGH+A8G4mUs+2EWjqNBFaXtBMchq5JXLXQ7FNIktJNtbOWpJHQcjqhzdBVV3Z4fEhYNzUkoZY+tcBapR7YCsBhC8WoTcfNFLV0pzuhzdBVV3Z7fKADNm1AilqlHtgKwGELpdfwP72PqJYVJHwIffrkY0YZraVazeOwhTJfmbbUhWpZAZtGZKUPtDC1UK3MuG0hemfTBlCt/DEnK0iSEkeqlRm3LUT/uu2gdiixWgFAtdIxZ6HSQbVcQrVSkDM9/dkgZjBkE7g95UsHzVOpTPillpyaJ/D5jALNUylf8b+F3tJm6PxSq3RQrYChWi6hWgFDtVxCtQKGarmEagUM1XIJ1QoYquWSUNXq6Ogo7/dRJu3siDO1GH0QpFp9fX3666bcr3dJVIg0SlTGAujZzO13oxajLwSp1rZ1JF32zgWIQMotLSm4UYvRF9qMfgFkaKF5dZLZF1KOCgUplEFWl+uFzSNELr/Gf5TIYkCWrNu5aon122SRTRwPuma52kPQDcaSujHSp3U30QyoQaUyUV05QxWMvoAaVMpXWm2h7gjJJjpX14ZCM8J6GaQlkroLgFlnoqdqI4+tyJJSM9JArw6QxktSiARKzAVQobkwMFvSEqhHpTJRXbnVKsw9AYy+z7TaQh1SySY6Vw9PSEi5LC+FQC9vhtQM/qada4K1pPv0YtgumoFEo3pqK0ws2Tythi5BdeVWq2D0Na2GrnhabWGjzgKJzpUgJ5bXnZ65c6VCjXSu3pxeHv/VEt8j5bUVIivrtgrqVKlMVFdutQpGX4M6VcpXWm2hxFY6AiAyui+a6Vy9PBIZOleWlA4FtelG9WgSFYJGS24KtqVSmaiu3GoVjL4G21IpX2m1hWZHADMyKZ2r+xFpWQb/9aZRg65Trygk+sLcutSgOxdLYkXdGFlSv6pJVAiq4/f3zWsJ3f5sVFdutQpz/wGj7zMZWmh2YpOdi8XwH5hhxIpSKN2kDxgplCX1MgJq01XhJWxCd59UohsAZNMaWbK2c2tLmgR1qlQmqitnqILRF1CnSvlKhhYi7GYfpSMRVhmbyIb0EdI8ut9bpc39qq7M6LuKfgFkaCFCIWNiMxTWueYI3jx6fM9Am/tVXZnRdxX9AsjWQgTEnPxTKKxz0aQMZxY4HprckVra3K/qyoy+q+gXgP8t9BZnahFAtQKGarmEagUM1XIJ1QoYquUSqhUwVMslVCtgqJZLqFbAUC2XUK2AoVouoVoBQ7VcUgq1vOWv/+U/VcpXVBAzodTyE/9DDySOJAMvvH1NpULE6yMj7NATquUMqhU2VMsZVCtsqJYzqFbYUC1nUK2woVrOoFphQ7WcQbXChmo5g2qFDdVyBtUKG6rlDKoVNlTLGVQrbKiWM6hW2FAtZ1CtsKFazqBaYUO1nEG1woZqOYNqhQ3VcgbVChuq5QyqFTZUyxlUK2yoljOoVthQLWdQrbChWs6gWmFDtZxBtcKGajmDaoUN1XIG1QobquUMqhU2VMsZVCtsqJYzqFbYUC1nUK2woVrOoFphQ7WcQbXChmo5g2qFDdVyBtUKG6rlDKoVNlTLGVQrbKiWM6hW2FAtZ1CtsKFazqBaYUO1nEG1woZqOYNqhQ3VcgbVChuq5QyqFTZUyxlUK2yoljOoVthQLWdQrbChWs6gWmFDtQpl7M7Ke1/OyB9Cr9ND08tqCRIKVKtQ7j9ce/mdAQTd/HvpcP+95UdqCRIK6FmVChEfTwhlvjL/jn46pV4jJSeesxIf1UpMXJyyQiKesxJPP8aQIU3+OGUFhtm5AXexp2rpsY1TVnhEclbiqVpAxjZOWUESw1mJv2phbHv13eucsoIkhrOSDbW2+Mcf//mvVMp7VBBJ0wR/VvKMWipFWqQUoVsfATziRz/+6W/2X/ijP/lTlfcbFcRWoFo5UIrQedjIyfkHKuU3VMsZVCtsqJYzqFbYUC1nUK2woVrOoFphQ7WcQbXChmo5g2qFje9qVSqVjo4OlQkLqhU2VKshIyMj2LutW7eqfN5QLcChM0EUamG7gGqplB2c9C+2iP3S9PX1qRdyBTWrVCvYVUumC8EMPUKgSrdsOXbsmBTi0EdalRqN0eHTq6MqKQHYhBQ2AnViRfynWiplB1dqYbsqY41sodtYx0bocTTLnotjEnpJywAjadEDC+s2YMlt27YhUauE6KfT6cLo+qmWjUZKeAUnQydWiVEtia/KGKOa2QdAR0dCL4VIyDLSGWZ8E9HEqymnAXph1EO1VCo/EFIJrzgmXSbpYoZO1IOFBanQBqhcpVphY51s66eA4Jpx0UYhsR6KDaR7sDBCub7sMzGVWAPpLTOaQiO1EpWkd1I7oA0q5TG5NxJhN+s0+1cSAtJ1+1eWkc7NPHRqxGFzxRzJFrqNdbKtn0KTodc0UkuQPkAiEfoUMIxhlQTN9FOroFqV8pjcG4lImn1k9u96pDeQ/mrUv9KzQLoGlUhW02SXobvrHlftgzaoVCtsrJNt/XRQp4RVNJM9N08YTNLVkhqQkJ6QwuaprTBHMrSneHJvpO4RwVSr7iGe3r+6W7GuHDOtArWAyuRKttBtrGPj+JDoAwmrjrguF0SzuqFHsNRCho0IvSpaRwrTqe3LHGmyDW6x0UjU6XDoxCraJVm9dqO50GR7Emysk219AkoROhuNlAMaiDbFD52oRC1kzSuAylWqFTbWybY+AaUIHfs3M/GqlRgjNfaGsQTYlkp5TCka6SfZQheCWs6hWlYp6dBJtXKgFKFj/2aGajmDaoUN1XIG1QobquUMqhU2VMsZVCtsvFar79nrzQqjmO1SrbDxWq2O9ZsRJY0NmZhXPdsAatn+lBZ7oVIeY7WRHDprKUItuahMK4S0PtblgjFtnQ0qlYqlqzY19kKXI1YbyaGzliLU0heMCdiQGQuxS9IoR1rQXYV1ZRlBCgG6U0r0pWvmtWe6R6VOSVvCdv25YK+RHDrrsrGOvdBjz82dN0MPpGNQohO6UHoLaum2wSKpCr2VOBOQXtRp/apZlSX0dn3GXiMTfYENmf1r9gvKkRZQLoWhDp0b69hrn/ZBwIbM0AMpQeB0EAHSKEFCQi+FSMgy0hmmMHp5wdxK7RbzBfWrlMfYa+T6yMmhM8nGOtnWb4aUgx7oiJtjklBXLR1TiTWQ2rAVyWr0VpDWNdgA9auUx9hrpPZBMCMvSAl6E0uqIuOoSPSvLCOdawqjlxfMrdRuMV9Qv0q1QkFqpYRegohEIvSaRmoJevVE6E0SW8wde6HLEXuNTDnoQbRD58Y62dZvhurpQgO1kNBx0X0gL2nS1ZIakJCekEITqdYc/3Kn7nZ9w14jOXTWZWOdbOs3QyJe2JCJedCLJxqJV93Qoy/VQkZYE+OiFEqdkraE7fpzwV4j10dODp1JNtbJtn4zFLDzKTQaLHPEXuhyxF4jEz5gQyZmv4snGtEs1KFzYx2r7cPBrcNXMGbPWcJ21+aCvUZy6KxLQWolBrbCwJBWwHYjVwtw6KylILXChmpx6KyFauUA1QobquUMqhU2VMsZVCtsqJYzqFbYUC1nUK2woVrOoFphQ7WcQbXChmo5g2qFTQ5qkcyoIHpMKRrpJ9lC53u4e6/NzSyuqgxpg/URgGREBbEVfFer+8rswXMTKkPCYnXtyQdfzapMcPiuFqK/88RQ/60llScB8cnwwv4z4yoTHL6rBS6PLe55f2Tt8ROVJ6EAry4O3VOZ4CiBWuCNj8bO9t9VGRIEiytrL78zgLMSlQ+Ocqg1Of/g1Xev33+4pvKk/PRem3vrwqTKhEg51AJHLk3hT2VI+dl3avTqzZDfQpdGLUxZmLgm7j5QeVJmbi883N45GPb759KoBfB2C2+6VIaUmfe+nOn87LbKBEqZ1MIgt+f9kctjiypPSsvOE0Njd1ZUJlDKpBbov7WEXgn4Y6UYGJi6v/vksMqES8nUAgfPTXRfCfYr/Bg4fPFWwBdhaMqn1szi6itHB+aWeGFhKcFZfSTdVz61AN4EHzp/U2VIqcBb5ddPR/FZVCnVwnutHccHccqu8qQ8vHl24vzAvMoETSnVAp8ML+ztHlUZUhJWVh+//M4A/qt80JRVLfDah99GMv4FA/oLs5bKhE6J1Rq7s7K9c5AXFpYIvMuK52vJEqsFDl+8FfyX+sEwt1T9aDeem4PKrdbiyhp6a3KeFxaWgA++msVQqDIRUG61QM/VuUrPDZUhHrP75HBUH+qWXi2cYOzqGv564juVJ16CN8Y7TwypTByUXi1w9Wb1wsJ4TuLLCN4Sd12eVpk4CEEtcKB3PIbL0koKRr3tnYO3Fx6qfBwEoha67dV3r99bfqTyxCdwWrHvVHTf7weiFjj+xXTYz1ooL4fO3+y5Oqcy0RCOWiurjzFxjc4uqzzxg9W1Jy+/M7C4Et03++GoBS4O3YvwxMNz0CkBP8czhaDUAlAr4KdGlpFKz404eyQ0tYaml3FaGMm11f4T/HM8UwhNLfDWhcnjX8T1FYq39FwN/DmeKQSo1r3lR5i4YvsWxU/2dgf+HM8UAlQLfPDV7IHeGN86e0UMz/FMIUy10J07TwxFO156Qtfl6Zhv+QlTLXDlxuKurmFeWOiQHccHg3+OZwrBqgUqPTcivAjAEyJ5jmcKIas1Of/glaMxXgfgA5E8xzOFkNUCONeP6s5WT1hdi+U5nikErpb8dFDMZ/xOiOc5nikErhY4PzD/2offqgwphHie45lC+GqtPX6yt3v0k+EFlSeWwZlCPM/xTCF8tcDA1P3tnYP86aBiiOo5nilEoRY4dP5mbM9mcAVOv/nzgiAWteaWVnGWMrPInw6yS2zP8UwhFrVA95XZg+d4omIXBJnfdggRqSU/HdR/ixcWWmRXV1zP8UwhIrXA56MLu0/ywkJbRPgczxTiUgu88dHY2f67KkNy5einU/ysSBOdWhN3qxcW8qeDcgfnArwD1SQ6tQDeZx+5NKUyJCfifI5nCjGqhSkLExemL5UneRDnczxTiFEtgLdbeNOlMqRt5EeKef+OSaRq4Y3B7pPDn4/ywsJ8iPY5nilEqhbAe4Mdx3lhYT5E+xzPFOJVC7x5dqL7Cn86qF3uLT+K9jmeKUSt1sxi9YK3yG+GbZ+Yn+OZQtRqga7L04fO31QZkok974/wuXS1xK4WTmO2dw7ysrfMTM4/iPk5ninErhbA+++93aM8OLIR+XM8U6BaVV778Fs+yyEbmLL4VJ+6UK0qo7PLOER4YWGr8DmeKVAtxdsfT/LEplUQtMif45kC1VLcW370ytEBvClXebIZq+s/UsyvLhpBtTY4/c2dSs8NlSGbwed4pkO1Nlh7/GRX1/CVG3waUVMc6B3nZz8pUK1n+Hriu50nhvQH8XwCVCPkR4r5HM8UqFaS/WfG8dYcbyS6Lk+/dLifR09d+BzPTaFaSW4vPMR4vL1z8IW3r+GPE5cGkdEDDZ/juSlU6xlGZ5f3nRoVqeSPNyNrMFNhGj90/ubFoXt8juemUK0N3vtyxpRK/vjcQg3eiOqwYGLv/Ow2x50UqNYGONs5cmlKHz3yxw8MNZPzDxLBwR8f4NMIqpVkYOr+rq5hfehcuM7PlxWra090WOQP77j4MU8jqFYdcAzhbOfF3/fj6Om9xqcUbYC3WPSqSahWQ4amlzF94Q2YypOnT/d2q8949p8Zp1fpUK00MH3xjgmTA73j8OrNsxP8eHBTClVrCyk5f/vvu//hld/94IfPqXxJUMdfsRStlkqRFvEkdKOzy6Wbr6gWSYOhywzVImkwdJmhWiQNhi4zVIukwdBlhmqRNBi6zFAtkgZDlxmqRdJg6DJDtQixAtUixApUixArUC1CrEC1CLEC1SLEClSLECtQLUKsQLUIsQLVCpBjx451dHSojAcg/n19fSoTDVQrQOAV7JL0tm3bsPt1Tdu6dSte0kvao1KpeKV6MVCt0BgZGTH3F2qJQol5A0YVphY2HVUXCK52mWrZIjFFQC1kARKqaB2UYMli1ALQuJgN+QPVCo2ERaIWDmszCHoaSaiFJVEiqKLvrZBCmfpkYjRBiSxctwaQaFUMJCJQGIVu1dVOOgEmYDpSme/VQgJB0BahUA50sxCLyZIANaAeSct5o3k+qTchjumXGtUAdDPiwdVRR7VsgQPanIj0Ma2PddMHJGRhKdSTj7mMFklILKk3l1IDQA1Uqxioli0aqaWPdfMoR4ksjHKkE9RVC+Alcy1ZLKUGQLUKg2rZImGCeSaGBLKme4hM3TnHpK5aGl1VSg2AJ4SFQbVsIf6ozLPHNDSo2mBEA2ntBhQyV9Qk1MJEhBKVeZZGNYBEq2LAjHORUC1bQAPz0DfVAgiFeYibagGsiBJBV4JEYtZCDWqhdTatASBrLhYD2GWVKhaqZQt5z9PoxKx9YIjpDLKbhtd2k/yEagUIDn17UwRmMHMaTEySdUmsEglUK0ASE0vuwBOEVKNKG4PG6I8K46GZyNiAapHAoVqEWIFqEWIFqkWIFagWIVagWoRYgWoRYgWqRYgVqBZJg6HLDNUiaTB0maFaJA2GLjNUi6TB0GWGapE0GLrMUC2SBkOXGapF0mDoMkO1SBoMXWaoFkmDocsM1SINuTy2+OuO3/Zem+u5Orf2+IkqJc0Ri1qkJX7ww+f+5jf/9a//0/vzv/irn/z8F/+48387/rvzZ798Xr1MmkMdf8XCacRf5pZWX/vw2/1nxu8/XFNFT59euD7/6rvXOz+7vbrG6ctrqJanXL25tL1z8IOvZlXeYHFl7a0LkzuOD2IZVUT8g2p5B95NvfflDLwamLqviuoBr2AXHINpqoj4BNXyC3hS6bnxxkdj95YfqaLG4JwQZ4Y4P7w4dE8VEW+gWh6BaQqTFaaslj4GHLuzsu/UKGycWVxVRcQDqJYv9Fydw/zz9cR3Kt8KUBGrv3J04PQ3d/jpvCdQLffcf7h2oHccM8/cUlvTDmat/WfG97w/Mjq7rIqIO6iWY3A6t/PE0NFPp/KabT4ZXpBP51dWH6si4gKq5ZKz/XdxFnd5bFHlcwLT4NsfVz+dv3Ij55pJ81AtN2BKeevCJE7ebi88VEV5039raVfX8MFzE/x03glUywETdx/sPjkMtWxfUYH6uy5PY2K8cH1eFZGioFpFc3HoHt4LFXmsw+R9p0ZfPz02Of9AFRH7UK3iwBxy+OKtnSeGcKyroqJYe/yk91r1w/3uK7P8dL4YqFZBzCyu4p0V3vk4/OBubmn1QO84zkWHpvnpvHWoVhFcHlvEGx7MGyrvlM9HF3YcHzxyaYqfzluFatkFZ1+dn93GoezV17j3H67h1HR752Dun/sTDdWyiNxwVem5Yd5w5Q84LdzVNfzm2Yk2rwIhdaFatrh6c+nVd6/XveHKHzCpvvflDNp5tv+uKiI5QbXyR45XnG713yrHrYqT8w8wu+KPn87nCNXKmcWVtTc+GmvyhiuvwMSF6QuDAh8NkAtUK0/khqvjX0yX9LsjDAd464U3YOk3OJNmoFq5cfqbOxj1s91w5RVXbixigDh88Zafn76UBaqVA3LD1d7u0WDu811ZfXzk0tSO44Ofjy6oItIiVKtdxu6s4BDM8YYrfxiaXt59cnj/mXF+Op8BqtUWcsPVJ8PBDu0YLz74alYuJQlv7LAK1coITpkOnb9p9YYrf8A+vn56bN+p0eIvLC4vVCsL+oarqC7Du3B9HtNX1+VpfjrfDFSrZYq/4cofFlfWMFfvPDFUlm/DHUK1WkDfcDV2Z0UVRcnXE9/tWH9wLz+dT4FqNYsPN1z5A4IgD+4N+COcNqFaTSE3XPVc9eKGK38YnV3GcLP/zDgf3FsL1dqEtfUbrrZ3+nXDlT8gPnIZCh/cm4BqpaFvuOLzxtLBrIUo7e0ejfxdqAnVagjerGMw7r7i9Q1XXiGfnWKS56fzgGrVASc2csMVfxuuVTC9v7X+s3oBXKbcJlQryb3lR298NPb66fLdcOUPGJJ2nhg6dP5mzCfSVOsZyn7DlT/gnBBhjPa7dUC1NpDrUHkmkyMx/6we1aoS3g1X/oD5X35WDyNXVOcCVKv6vSfedh+5FOANV/4wt6R+Vi+eB/fGrlbwN1x5xeejC3gre/TTKB7cG69a6N2D5yZ2nxzmE8KKBOfekfysXqRqxXnDlT/on9UL+BuOGNWSW/rOD/DX3Fyyulb9Xj7gjohLLd5w5Rs4Gw/1Z/UiUuv2wsM9748c6B3nSaBvBPmzerGoxRuuPGdu/Wf18AYsmE/nw1cLA+HRT6e2dw7ypxD9ByMgeurIpakAHg0QuFq84ap0QCqoBcHK/rN6IaslN1y99+WMypPykPKzemV5PxamWog+b7gqO+jE7iuzGBwTvwF9+ps7pZjQQlAr8bmt3HCF88DaAY+UDnSuPLhXenlmcfWlw/07jg/6fyNz6dWCSP9x5P/0RxS84SpIzg9Uv+XHmQg0e+Hta/jrujytXvOV0quFECPQ0GlxZU1uuCr7219SF4yhmLvEK/xh7vL8afvlVuv+w7WX3xmQWEMq3nAVMBg6dV/LX6XnhnrNS8qtFs4QzFj7f5JAMnPw3ITZ1/Ln8xlKidXCG1nMVGagX/x9Pz8SDJK5pepzDnefHE70uM+fZzRUa4v3PP9PL5pRlr9/+93FH/34p2oJd6gglhm1J/7x3B/84U9+/os/+8u/+9Xf//OvO377s18+r17wiWoAJY61yMvegrHq1XevwyW8nd3z/sjbH0/2Xpsbml724dJbz0PXJGHshRPKrdbk/IPzA/Njd1Y8/JCdakVOudXyGaoVOVTLFlQrcqiWLahW5FAtW1CtyKFatqBakUO1bEG1Iodq2YJqRU74avX19TnZC6rlCSMjI9gL/Ff5opDQNQxfAJGlWu0QwF7ErpYIgP9ISywk3QgsIGzdulVKjh07ptMAaZQAtdw66rVCKHhzlihsLyqVSkdHh8o8fbptHZWpB/p3vUurSEliDEVtqFMKNUUKhs1V/0umFnm5GBBKcUOCIoV1Qav0AlgYIFFXLSQSES8MJxvNncL2IjG3IJ0ytqJztXj6sKmrFhKJmgtDGtMwfGZbCwAxElS+HgmFdECplg2K3AstQ6IrEyQ6VJtDtdJATLFFUaIReFWmKUEHLtEfVCsXitwL3YPairqgQxPioZEoTHQ01XoGbA7ze/pGEwrpgCJBtXKn4L3A5qS/UkxIdKg2RxKqlGqZQCqABIIiiUagVXpU0wtLBBF3pPEq0qKW28iWnYL3Ar2JMRH/Vb4BWEYfIUjo5XWn4z/S+iBBWg6MIpHQuVdLYiFpU5K6yAKCKaEYJYUIt0QZII1Cc04rAGxRpcpMwXshh4HuuBSwmGB6KKtLIY4BrRbSUi7ZYpDNNdxkwa0JiTBCV/BebHo2WCKoli2oVgYwz5izUKnxVy09uScoy5CGpqpUmSl4L3DSrs/iZAarpfh3TdlAU6v/JVOLvEwyEEboeABkhmrZgmpFDtWyBdWKHKplC6oVOVTLFlQrcqiWLahW5LhUq6/mOstiKGa7VGtTYjgA3KhlXouEDZnY/vIKkbX99Qj2QqXKjNW9iOEAcKCWXAeoI4i03lX5slgH3QaVSsW8+NAG9kJXJDwAMiOhc6AWAmdOymZkgQRX0ihHWtDhxrqyjCCFAAOhlOjrZRBEKQG6I6VOSVvCdv3FYG8vIjkAGm7D3uYxZpjDBjZkRlaGNJTohC6U6CCyum0IolSV6C1g9pD5qlmVJfR2S429vYjkAGgYPt2s3NHhELAhM7JASjDk6OEHII0SJBAjREoKkZBlJI5mvPTygrmV2i3mC+pXqTJjby8iOQDcqNVon4EMKhJZJEzqRlaPRhJcILVhK5LVmJHVNdgA9atUmbG3F5EcAG7UShm0JEBIII5YUgpNGkVW0Ksn+s8kscXcsRe6IrG3F5EcAA3DJy/bAGFtFFkkkJXA6dFLXtKkR1ZqQEKHOIFUa5455E7d7ZYOe3sRyQHQMHx1m5ULiXBgQybmPkuYNBLlupFFV6mFjM7AoKWK1pFCHXp72K6/GOztRSQHQMNt2Nt8AcNGCo1OM3LEds8VAw+AzEjoHKgFsG964CkYc8yzBNXalBgOADdq6Xm8YHAyUMB2qdamxHAAuFErbKhW5FAtW1CtyKFatqBakUO1bEG1Iodq2YJqRQ7VsgXVihyqZQuqFTlUyxZUK3Koli2oVuRsrhbJjApimVF7QjJRDaDEkRCSJ0+f/j+c3tvTMsnWggAAAABJRU5ErkJggg== ###Code from keras.layers import concatenate x_in = Input(shape = (100,) ,name = 'x_in') y_in = Input(shape = (100,) ,name = 'y_in') x = Dense (64,activation = 'relu')(x_in) y = Dense( 64,activation = 'relu')(y_in) z = concatenate ([x,y]) x = Dense(1,activation = 'sigmoid' ,name = 'x_out')(z) y = Dense(10,activation = 'softmax', name = 'y_out')(z) model = Model(inputs=[x_in, y_in], outputs=[x, y]) model.summary() from keras.utils import to_categorical import numpy as np data = np.random.random((1000, 100)) xs = np.random.randint(2, size=(1000, 1)) ys = np.random.randint(10, size=(1000, 1)) model.compile(optimizer='rmsprop', loss=['binary_crossentropy', 'categorical_crossentropy'], loss_weights=[1., 0.2]) model.fit([data, data], [xs, to_categorical(ys)], epochs=10, batch_size=32) ###Output _____no_output_____ ###Markdown 你也可以使用字典 (refering to the names of the output tensors): ###Code model.compile(optimizer='rmsprop', loss={'x_out': 'binary_crossentropy', 'y_out': 'categorical_crossentropy'}, loss_weights={'x_out': 1., 'y_out': 0.2}) # And trained it via: model.fit({'x_in': data, 'y_in': data}, {'x_out': xs, 'y_out': to_categorical(ys)}, epochs=1, batch_size=32) ###Output _____no_output_____ ###Markdown 共享层 ###Code inputs = Input(shape=(64,)) # a layer instance is callable on a tensor, and returns a tensor layer_we_share = Dense(64, activation='relu') # Now we apply the layer twice x = layer_we_share(inputs) x = layer_we_share(x) predictions = Dense(10, activation='softmax')(x) model = Model(inputs=inputs, outputs=predictions) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.summary() ###Output _____no_output_____
dont_overfit.ipynb
###Markdown [Don't Overfit! II](https://www.kaggle.com/c/dont-overfit-ii) This repository proposes a solution for the Don't Overfit! II Kaggle competition. The proposed solution involves a [Support-vector machine](https://en.wikipedia.org/wiki/Support-vector_machine) with Linear Kernel ###Code import numpy as np import pandas as pd from sklearn import svm df_train = pd.read_csv('data/train.csv') df_test = pd.read_csv('data/test.csv') df_train df_test ###Output _____no_output_____ ###Markdown Train/Test split Shuffle train set ###Code df_train = df_train.sample(frac=1) len(df_train) train_test = 0.8 middle = int(len(df_train)*train_test) middle train_df = df_train.iloc[:middle, :] test_df = df_train.iloc[middle:, :] train_df test_df def separate_x_y(df): return df.iloc[:, 2:], df['target'] X_train, y_train = separate_x_y(train_df) X_test, y_test = separate_x_y(test_df) ###Output _____no_output_____ ###Markdown Fitting Default Model ###Code # clf = svm.SVC(C=1, gamma=0.0000000001) # just a test clf = svm.SVC(kernel='linear') clf clf.fit(X_train, y_train) test_pred = pd.Series(clf.predict(X_cross)) test_val = pd.DataFrame(data={'pred_y': test_pred, 'y': y_test.reset_index(drop=True)}) test_val['correct'] = test_val.apply(lambda row: row['pred_y'] == row['y'], axis=1) test_val test_val_res = list(test_val['correct']).count(True) / len(test_val) test_val_res ###Output _____no_output_____ ###Markdown Predict on test set ###Code df_test result = clf.predict(df_test.iloc[:, 1:]) result sub_df = pd.DataFrame(data={'id': df_test['id'], 'target': result}) sub_df sub_df.to_csv('data/submission.csv', index=False) ###Output _____no_output_____ ###Markdown Don't OverfitOne of the main objectives of predictive modelling is to build a model that will give accurate predictions on unseen data.A necessary step in the building of models is to ensure that they have not overfit the training data, which leads to sub optimal predictions on new data.The purpose of this challenge is to stimulate research and highlight existing algorithms, techniques or strategies that can be used to guard against overfitting. ObjectiveThe objective is to score greater than 0.8 in leader board ###Code import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score, KFold, cross_validate import matplotlib.pyplot as plt import seaborn as sns from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.metrics import plot_roc_curve, confusion_matrix, plot_confusion_matrix, classification_report from sklearn.model_selection import train_test_split, RandomizedSearchCV, GridSearchCV from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from math import ceil from sklearn.tree import DecisionTreeClassifier import warnings import scipy import scipy.stats warnings.filterwarnings('ignore') RANDOM_STATE = 0 test = pd.read_csv('test.csv') train = pd.read_csv('train.csv') ###Output _____no_output_____ ###Markdown Data Background- The train set has 250 observation and 301 features with no missing value.- The features are of float datatypes- The observation has no duplicate value- The standard deviation for train_set is between 0.8 and 1.125 while mean is between -0.20 and 0.2- The min and max values of trainset +/- -0.425 and +/- 3.8 respectively.Therefore, it can be concluded that the train and test dataset are from the same distribution/population ###Code train.shape train.isnull().values.any() train.info() train.duplicated().sum() fig, axes = plt.subplots(2, 4, figsize = (20,8)) fig.suptitle('Data Distribution of train and test for all columns') axes[0,0].set_title('train standard deviation') sns.histplot( data=train[train.columns[2:]].std() , ax=axes[0,0]) axes[0,1].set_title('train mean') sns.histplot(data=train[train.columns[2:]].mean(), ax=axes[0,1]) axes[0,2].set_title('train min') sns.histplot(data=train[train.columns[2:]].min(), ax = axes[0,2]) axes[0,3].set_title('train max') sns.histplot(data=train[train.columns[2:]].max(), ax = axes[0,3]) axes[1,0].set_title('test standard deviation') sns.histplot( data=test[test.columns[2:]].std(), ax=axes[1,0]) axes[1,1].set_title('test mean') sns.histplot(data=test[test.columns[2:]].mean(), ax=axes[1,1]) axes[1,2].set_title('test min') sns.histplot(data=test[test.columns[2:]].min(), ax = axes[1,2]) axes[1,3].set_title('test max') sns.histplot(data=test[test.columns[2:]].max(), ax = axes[1,3]); ###Output _____no_output_____ ###Markdown SkewnessTo review the skewness: 1. Random features will be selected and visualized2. Skewness will be computedThe result showed that the data assumes a binomial distribution ###Code pd.cut(train.skew(), bins=5).value_counts() num = 30 r = np.random.randint(0,299,num,dtype=int) n_cols = 6 n_rows = ceil(num/n_cols) counter = 1 fig = plt.figure(figsize=(20,20)) for col in range(num): plt.subplot(n_rows, n_cols, counter) plt.xlabel(f"{col} feature") g = sns.distplot(train[str(r[col])]) counter += 1 plt.show(); ###Output _____no_output_____ ###Markdown OutliersBoxplot is used to visualize the mean distribution of train datasetThe visualization showed that the distribution of the train dataset are close and have similar mean ###Code fig = plt.figure(figsize=(120,20)) sns.boxplot(x="variable", y="value", data=pd.melt(train.drop(columns=['id', 'target']))) plt.show() ###Output _____no_output_____ ###Markdown Correlationreviewing the correlations showed that features correlation with target ranges from +0.37 to -0.2Also, the features do not have strong correlation with each other considering the population of 250. Therefore, it can be assumed that colinearity doesnt exist in the dataset ###Code corr_matrix = train.corr() corr_cols = corr_matrix.nlargest(25, 'target')['target'].index cm = np.corrcoef(train[corr_cols].values.T) mask = np.zeros_like(cm) mask[np.triu_indices_from(mask)] = True with sns.axes_style("white"): fig = plt.figure(figsize=(25,15)) sns.set(font_scale=1.25) hm = sns.heatmap(cm, mask=mask, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=corr_cols.values, xticklabels=corr_cols.values) plt.show() corr_cols = corr_matrix.nsmallest(25, 'target')['target'].index cm = np.corrcoef(train[corr_cols].values.T) mask = np.zeros_like(cm) mask[np.triu_indices_from(mask)] = True with sns.axes_style("white"): fig = plt.figure(figsize=(25,15)) sns.set(font_scale=1.25) hm = sns.heatmap(cm, mask=mask, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=corr_cols.values, xticklabels=corr_cols.values) plt.show() ###Output _____no_output_____ ###Markdown Target The dataset target is imbalanced. 2/3 of the target belong to class 1 ###Code fig = plt.figure(figsize=(10,6)) g = sns.countplot(train['target']) for p in g.patches: x = p.get_bbox().get_points()[:,0] y = p.get_bbox().get_points()[1,1] g.annotate('{:.2g}%'.format(100.*y/len(train['target'])), (x.mean(), y), ha='center', va='bottom') ###Output _____no_output_____ ###Markdown Preprocessing ###Code target = train['target'] test_Id = test['id'] train = train.drop(columns=['target', 'id']) train_columns = train.columns test = test.drop(columns = 'id') std_scaler = StandardScaler() std_scaler.fit(train) train = std_scaler.transform(train) test = std_scaler.transform(test) ###Output _____no_output_____ ###Markdown ModelSince goal of the project is to achieve a score greater than 0.8 on the public board while avaoiding overfitting, cross validation is done for classifiers and the best result is used for the test result. ###Code models = [ ('LogReg', LogisticRegression(C=0.1, class_weight='balanced', max_iter=10000, penalty='l1', solver='liblinear')), ('RF', RandomForestClassifier(class_weight='balanced', n_estimators = 1000, max_depth = 5, max_features = 0.9, min_samples_split = 8 )), ('KNN', KNeighborsClassifier()), ('SVM', SVC()), ('GNB', GaussianNB()), ('GB', GradientBoostingClassifier(criterion="mse", learning_rate=0.1, max_depth=5, max_features=0.1, min_samples_split=2, n_estimators=1000)), ('DT', DecisionTreeClassifier(class_weight="balanced")) ] dfs = [] results = [] names = [] scoring = ['f1_weighted', 'roc_auc'] for name, model in models: kfold = KFold(n_splits=10, shuffle=True, random_state=RANDOM_STATE) cv_results = cross_validate(model, train, target, cv=kfold, scoring=scoring, return_train_score=True) results.append(cv_results) names.append(name) this_df = pd.DataFrame(cv_results) this_df['model'] = name dfs.append(this_df) final = pd.concat(dfs, ignore_index=True) result = final.groupby(['model']).agg({'test_f1_weighted':'mean', 'train_f1_weighted':'mean', 'test_roc_auc':'mean', 'train_roc_auc':'mean' }).reset_index() result['auc_diff'] = result['train_roc_auc'] - result['test_roc_auc'] result.sort_values(by='auc_diff') ###Output _____no_output_____ ###Markdown Selected Model Based on the cross validation result, Logistic Regression will be used for the result.Logistic Regression performed better than the others fairly because the dataset isnt complex and has a simple patternFor Logistic Regression, feature importance is also viewed since the features are fairly correlated to the target ###Code logistic = LogisticRegression(C=0.1, class_weight='balanced', max_iter=10000, penalty='l1', random_state=RANDOM_STATE, solver='liblinear' ) logistic.fit(train, target) importances = pd.DataFrame(data={ 'Attribute': train_columns, 'Importance': logistic.coef_[0] }) importances = importances.sort_values(by='Importance', ascending=False) importances logistic_pred = logistic.predict(test) probs = logistic.predict_proba(test) output = pd.DataFrame( { 'id': test_Id, 'target': probs[:,1] }) output.to_csv('output.csv', index=False) ###Output _____no_output_____
tutorials/nlp/01_Pretrained_Language_Models_for_Downstream_Tasks.ipynb
###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/v1.0.0b2/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/v1.0.0b2/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True) ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There are might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and a HuggingFace model. Downstream tasks with Megatron and BioMegatron LM[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown If you have a different checkpoint or a model configuration file, use these general Megatron-LM model names:* `megatron-bert-uncased` or * `megatron-bert-cased` and provide associated bert_config and bert_checkpoint files, as follows:`model.language_model.pretrained_model_name=megatron-bert-uncased \model.language_model.lm_checkpoint= \model.language_model.config_file=` or `model.language_model.pretrained_model_name=megatron-bert-cased \model.language_model.lm_checkpoint= \model.language_model.config_file=`The general Megatron-LM model names are used to download the correct vocabulary file needed to setup the model correctly. Note, the data preprocessing and model training is done in NeMo. Megatron-LM has its own set of training arguments (including tokenizer) that are ignored during finetuning in NeMo. Please see downstream task [config files and training scripts](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) for all NeMo supported arguments. Download pretrained modelWith NeMo, the original and domain-specific Megatron-LM BERT models and model configuration files will be downloaded automatically, but they also could be downloaded with the links below:[Megatron-LM BERT Uncased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m](https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m/files?version=v0.1_uncased)[Megatron-LM BERT Cased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m](https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m/files?version=v0.1_cased)[BioMegatron-LM BERT Cased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345mcased](https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345mcased)[BioMegatron-LM BERT Uncased 345M (~345M parameters)](https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345muncased): https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345muncased Using any HuggingFace Pretrained ModelCurrently, there are 4 HuggingFace language models that have the most extensive support in [NeMo](https://github.com/NVIDIA/NeMo/tree/main/nemo/collections/nlp/modules/common/huggingface): * BERT* RoBERTa* ALBERT* DistilBERTAs was mentioned before, just set `model.language_model.pretrained_model_name` to the desired model name in your config and get_lm_model() will take care of the rest.If you want to use another language model from [https://huggingface.co/models](https://huggingface.co/models), NeMo will use AutoModelEncoder. ###Code new_model_name = 't5-small' # change your config like this: # model.language_model.pretrained_model_name = new_model_name nemo_nlp.modules.get_lm_model(pretrained_model_name=new_model_name) ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above pretrained_model_name = 'distilbert-base-uncased' config = {"language_model": {"pretrained_model_name": pretrained_model_name}, "tokenizer": {}} omega_conf = OmegaConf.create(config) nemo_nlp.modules.get_lm_model(cfg=omega_conf) ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.To see the list of available Megatron-LM models in NeMo, run: ###Code #nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code #config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.To see the list of available Megatron-LM models in NeMo, run: ###Code #nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code #config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True) ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/v1.0.0b2/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There are might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and a HuggingFace model. Downstream tasks with Megatron and BioMegatron LM[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown If you have a different checkpoint or a model configuration file, use these general Megatron-LM model names:* `megatron-bert-uncased` or * `megatron-bert-cased` and provide associated bert_config and bert_checkpoint files, as follows:`model.language_model.pretrained_model_name=megatron-bert-uncased \model.language_model.lm_checkpoint= \model.language_model.config_file=` or `model.language_model.pretrained_model_name=megatron-bert-cased \model.language_model.lm_checkpoint= \model.language_model.config_file=`The general Megatron-LM model names are used to download the correct vocabulary file needed to setup the model correctly. Note, the data preprocessing and model training is done in NeMo. Megatron-LM has its own set of training arguments (including tokenizer) that are ignored during finetuning in NeMo. Please see downstream task [config files and training scripts](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) for all NeMo supported arguments. Download pretrained modelWith NeMo, the original and domain-specific Megatron-LM BERT models and model configuration files will be downloaded automatically, but they also could be downloaded with the links below:[Megatron-LM BERT Uncased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m](https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m/files?version=v0.1_uncased)[Megatron-LM BERT Cased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m](https://ngc.nvidia.com/catalog/models/nvidia:megatron_bert_345m/files?version=v0.1_cased)[BioMegatron-LM BERT Cased 345M (~345M parameters): https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345mcased](https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345mcased)[BioMegatron-LM BERT Uncased 345M (~345M parameters)](https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345muncased): https://ngc.nvidia.com/catalog/models/nvidia:biomegatron345muncased Using any HuggingFace Pretrained ModelCurrently, there are 4 HuggingFace language models that have the most extensive support in [NeMo](https://github.com/NVIDIA/NeMo/tree/main/nemo/collections/nlp/modules/common/huggingface): * BERT* RoBERTa* ALBERT* DistilBERTAs was mentioned before, just set `model.language_model.pretrained_model_name` to the desired model name in your config and get_lm_model() will take care of the rest.If you want to use another language model from [https://huggingface.co/models](https://huggingface.co/models), NeMo will use AutoModelEncoder. ###Code new_model_name = 't5-small' # change your config like this: # model.language_model.pretrained_model_name = new_model_name nemo_nlp.modules.get_lm_model(pretrained_model_name=new_model_name) ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).Note: Megatron BERT is not supported in NeMo 1.5.0. Please use [NeMo 1.4.0](https://github.com/NVIDIA/NeMo/tree/r1.4.0) for Megatron BERT support.To see the list of available Megatron-LM models in NeMo, run: ###Code #nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code #config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download('https://raw.githubusercontent.com/NVIDIA/NeMo/v1.0.0b2/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/main/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____ ###Markdown Language modelsNatural Language Processing (NLP) field experienced a huge leap in recent years due to the concept of transfer learning enabled through pretrained language models.[BERT](https://arxiv.org/abs/1810.04805), [RoBERTa](https://arxiv.org/abs/1907.11692), [Megatron-LM](https://arxiv.org/abs/1909.08053), and many other proposed language models achieve state-of-the-art results on many NLP tasks, such as:* question answering* sentiment analysis* named entity recognition and many others.In NeMo, most of the NLP models represent a pretrained language model followed by a Token Classification layer or a Sequence Classification layer or a combination of both. By changing the language model, you can improve the performance of your final model on the specific downstream task you are solving.With NeMo you can use either pretrain a BERT model from your data or use a pretrained language model from [HuggingFace transformers](https://github.com/huggingface/transformers) or [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) libraries.Let's take a look at the list of available pretrained language models, note the complete list of HuggingFace model could be found at [https://huggingface.co/models](https://huggingface.co/models): ###Code nemo_nlp.modules.get_pretrained_lm_models_list() ###Output _____no_output_____ ###Markdown NLP models for downstream tasks use `get_lm_model` helper function to easily switch between language models from the list above to another: ###Code # use any pretrained model name from the list above nemo_nlp.modules.get_lm_model(pretrained_model_name='distilbert-base-uncased') ###Output _____no_output_____ ###Markdown All NeMo [NLP models](https://github.com/NVIDIA/NeMo/tree/main/examples/nlp) have an associated config file. As an example, let's examine the config file for the Named Entity Recognition (NER) model (more details about the model and the NER task could be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb)). ###Code MODEL_CONFIG = "token_classification_config.yaml" # download the model's configuration file if not os.path.exists(MODEL_CONFIG): print('Downloading config file...') wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG) else: print ('Config file already exists') # this line will print the entire config of the model config = OmegaConf.load(MODEL_CONFIG) print(OmegaConf.to_yaml(config)) ###Output _____no_output_____ ###Markdown For this tutorial, we are interested in the language_model part of the Named Entity Recognition Model. ###Code print(OmegaConf.to_yaml(config.model.language_model)) ###Output _____no_output_____ ###Markdown There might be slight differences from one model to another, but most of them have the following important parameters associated with the language model:* `pretrained_model_name` - a name of the pretrained model from either HuggingFace or Megatron-LM libraries, for example, bert-base-uncased or megatron-bert-345m-uncased.* `lm_checkpoint` - a path to the pretrained model checkpoint if, for example, you trained a BERT model with your data* `config_file` - path to the model configuration file* `config` or `config_dict` - path to the model configuration dictionaryTo modify the default language model, specify the desired language model name with the `model.language_model.pretrained_model_name` argument, like this: ###Code config.model.language_model.pretrained_model_name = 'roberta-base' ###Output _____no_output_____ ###Markdown and then start the training as usual (please see [tutorials/nlp](https://github.com/NVIDIA/NeMo/tree/main/tutorials/nlp) for more details about training of a particular model). You can also provide a pretrained language model checkpoint and a configuration file if available.Note, that `pretrained_model_name` is used to set up both Language Model and Tokenizer.All the above holds for both HuggingFace and Megatron-LM pretrained language models. Let's separately examine some specifics of finetuning with Megatron-LM and HuggingFace models. Downstream tasks with Megatron and BioMegatron Language Models[Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) is a large, powerful transformer developed by the Applied Deep Learning Research team at NVIDIA. More details could be found at [Megatron-LM github repo](https://github.com/NVIDIA/Megatron-LM).To see the list of available Megatron-LM models in NeMo, run: ###Code nemo_nlp.modules.get_megatron_lm_models_list() ###Output _____no_output_____ ###Markdown If you want to use one of the available Megatron-LM models, specify its name with `model.language_model.pretrained_model_name` argument, for example: ###Code config.model.language_model.pretrained_model_name = 'megatron-bert-345m-uncased' ###Output _____no_output_____
Notebooks/Bonus01-Scikit-Learn/Bonus01-Scikit-Learn-3-Transformations.ipynb
###Markdown Copyright (c) 2017-21 Andrew GlassnerPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Deep Learning: A Visual Approach by Andrew Glassner, https://glassner.com Order: https://nostarch.com/deep-learning-visual-approach GitHub: https://github.com/blueberrymusic------ What's in this notebookThis notebook is provided to help you work with Keras and TensorFlow. It accompanies the bonus chapters for my book. The code is in Python3, using the versions of libraries as of April 2021.Note that I've included the output cells in this saved notebook, but Jupyter doesn't save the variables or data that were used to generate them. To recreate any cell's output, evaluate all the cells from the start up to that cell. A convenient way to experiment is to first choose "Restart & Run All" from the Kernel menu, so that everything's been defined and is up to date. Then you can experiment using the variables, data, functions, and other stuff defined in this notebook. Bonus Chapter 1 - Notebook 3: Transformations ###Code import numpy as np import math import matplotlib.pyplot as plt from sklearn.datasets import make_moons from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import Ridge import seaborn as sns ; sns.set() # Make a File_Helper for saving and loading files. save_files = False import os, sys, inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) sys.path.insert(0, os.path.dirname(current_dir)) # path to parent dir from DLBasics_Utilities import File_Helper file_helper = File_Helper(save_files) np.random.seed(44) moon_data = make_moons(n_samples=100, noise=.2) training_samples = moon_data[0] train_x = training_samples[:,0] train_y = training_samples[:,1] plt.figure(figsize=(8,5)) plt.scatter(train_x, train_y, color='#007F77', s=60) plt.title('original data') file_helper.save_figure('scaling-start') plt.show() mm_scaler = MinMaxScaler() mm_scaler.fit(training_samples) transformed_training_samples = mm_scaler.transform(training_samples) plt.figure(figsize=(5,5)) plt.scatter(transformed_training_samples[:,0], transformed_training_samples[:,1], color='#007F77', s=60) plt.title("MinMaxScaler transformed data") file_helper.save_figure('scaling-fits') plt.show() np.random.seed(42) test_moon_data = make_moons(n_samples=100, noise=0.05) test_samples = test_moon_data[0] test_samples = np.array([[ts[0]*2, ts[1]*.6] for ts in test_samples]) test_x = test_samples[:,0] test_y = test_samples[:,1] transformed_test_samples = mm_scaler.transform(test_samples) plt.figure(figsize=(8,4)) plt.subplot(1, 2, 1) plt.scatter(test_x, test_y, color='#7F3900', s=40) plt.title('test data') plt.subplot(1, 2, 2) plt.scatter(transformed_test_samples[:,0], transformed_test_samples[:,1], color='#7F3900', s=10) plt.plot([0,1], [0,0], color='black') plt.plot([1,1], [0,1], color='black') plt.plot([0,1], [1,1], color='black') plt.plot([0,0], [0,1], color='black') plt.title("MinMaxScaler transformed test data") file_helper.save_figure('scaling-test-pair') plt.show() np.random.seed(42) num_pts = 100 noise_range = 0.2 sine_x_vals = [] sine_y_vals = [] (sine_x_left, sine_x_right) = (.9, 5.5) sine_training_samples = [] for i in range(num_pts): x = np.random.uniform(sine_x_left, sine_x_right) y = np.random.uniform(-noise_range, noise_range) + (2*math.sin(x)) sine_x_vals.append(x) sine_y_vals.append(y) sine_samples = list(zip(sine_x_vals, sine_y_vals)) mm_scaler = MinMaxScaler() mm_scaler.fit(sine_samples) transformed_sine_samples = mm_scaler.transform(sine_samples) plt.figure(figsize=(8,4)) plt.subplot(1, 2, 1) plt.scatter(sine_x_vals, sine_y_vals, color='#70008A', s=10) plt.locator_params(axis='x', nbins=4) plt.title('starting data') plt.subplot(1, 2, 2) plt.scatter(transformed_sine_samples[:,0], transformed_sine_samples[:,1], color='#70008A', s=10) plt.locator_params(axis='x', nbins=4) plt.title("transformed") file_helper.save_figure('inverse-demo-1') plt.show() ridge_estimator = Ridge() sine_x_column = np.array(transformed_sine_samples[:,0]).reshape(-1, 1) ridge_estimator.fit(sine_x_column, transformed_sine_samples[:,1]) sine_y_left = ridge_estimator.predict([[0]]) sine_y_right = ridge_estimator.predict([[1]]) line_data = [[0, sine_y_left[0]], [1, sine_y_right[0]]] inverse_line = mm_scaler.inverse_transform(line_data) plt.figure(figsize=(10,4)) plt.subplot(1, 3, 1) plt.scatter(transformed_sine_samples[:,0], transformed_sine_samples[:,1], color='#70008A', s=10) plt.plot([0, 1], [sine_y_left, sine_y_right], color='#ff0000', linewidth=3) plt.locator_params(axis='x', nbins=4) plt.title('line in transformed data') plt.subplot(1, 3, 2) plt.scatter(sine_x_vals, sine_y_vals, color='#70008A', s=10) plt.locator_params(axis='x', nbins=4) plt.plot([0, 1], [sine_y_left, sine_y_right], color='#ff0000', linewidth=3) plt.title('data and computed line') plt.subplot(1, 3, 3) plt.scatter(sine_x_vals, sine_y_vals, color='#70008A', s=10) plt.locator_params(axis='x', nbins=4) plt.plot(inverse_line[:,0], inverse_line[:,1], color='#ff0000', linewidth=3) plt.title('inverse line') file_helper.save_figure('inverse-demo-2') plt.show() ###Output _____no_output_____
naive-bayes/Naive Bayes Classifiers Example Project.ipynb
###Markdown Naive Bayes Classifiers Example Project¶ In this lecture we will learn how to use Naive Bayes Classifier to perform a Multi Class Classification on a data set we are already familiar with: the Iris Data Set. This Lecture will consist of 7 main parts:Part 1: Note on Notation and Math TermsPart 2: Bayes' TheoremPart 3: Introduction to Naive BayesPart 4: Naive Bayes Classifier Mathematics OverviewPart 5: Constructing a classifier from the probability modelPart 6: Gaussian Naive BayesPart 7: Gaussian Naive Bayes with SciKit LearnLet's go ahead and begin! Part 1: Note on Notation and Math Terms¶ There are a few more advanced notations and amthematical terms used during the explanation of naive Bayes Classification. You should be familiar with the following:Product of SequenceThe product of a sequence of terms can be written with the product symbol, which derives from the capital letter Π (Pi) in the Greek alphabet. The meaning of this notation is given by:∏i=14i=1⋅2⋅3⋅4,that is∏i=14i=24.Arg MaxIn mathematics, the argument of the maximum (abbreviated arg max or argmax) is the set of points of the given argument for which the given function attains its maximum value. In contrast to global maximums, which refer to a function's largest outputs, the arg max refers to the inputs which create those maximum outputs.The arg max is defined byargmaxxf(x):={x∣∀y:f(y)≤f(x)}In other words, it is the set of points x for which f(x) attains its largest value. This set may be empty, have one element, or have multiple elements. For example, if f(x) is 1−|x|, then it attains its maximum value of 1 at x = 0 and only there, soargmaxx(1−|x|)={0} Part 2: Bayes' Theorem First, for a quick introduction to Bayes' Theorem, check out the Bayes' Theorem Lecture in the statistics appendix portion of this course, in order ot fully understand Naive Bayes, you'll need a complete understanding of the Bayes' Theorem. Part 3: Introduction to Naive Bayes¶ Naive Bayes is probably one of the practical machine learning algorithms. Despite its name, it is actually performs very well considering its classification performance. It proves to be quite robust to irrelevant features, which it ignores. It learns and predicts very fast and it does not require lots of storage. So, why is it then called naive?The naive was added to the account for one assumption that is required for Bayes to work optimally: all features must be independent of each other. In reality, this is usually not the case, however, it still returns very good accuracy in practice even when the independent assumption does not hold.Naive Bayes classifiers have worked quite well in many real-world situations, famously document classification and spam filtering. We will be working with the Iris Flower data set in this lecture. Part 4: Naive Bayes Classifier Mathematics Overview Naive Bayes methods are a set of supervised learning algorithms based on applying Bayes’ theorem with the “naive” assumption of independence between every pair of features. Given a class variable y and a dependent feature vector x1 through xn, Bayes’ theorem states the following relationship:P(y∣x1,…,xn)=P(y)P(x1,…xn∣y)P(x1,…,xn)Using the naive independence assumption thatP(xi|y,x1,…,xi−1,xi+1,…,xn)=P(xi|y)for all i, this relationship is simplified to:P(y∣x1,…,xn)=P(y)∏ni=1P(xi∣y)P(x1,…,xn)We now have a relationship between the target and the features using Bayes Theorem along with a Naive Assumption that all features are independent. Part 5: Constructing a classifier from the probability model So far we have derived the independent feature model, the Naive Bayes probability model. The Naive Bayes classifier combines this model with a decision rule, this decision rule will decide which hypothesis is most probable, in our example case this will be which class of flower is most probable.Picking the hypothesis that is most probable is known as the maximum a posteriori or MAP decision rule. The corresponding classifier, a Bayes classifier, is the function that assigns a class label to y as follows:Since P(x1, ..., xn) is constant given the input, we can use the following classification rule:P(y∣x1,…,xn)∝P(y)∏i=1nP(xi∣y)⇓ŷ =argmaxyP(y)∏i=1nP(xi∣y),and we can use Maximum A Posteriori (MAP) estimation to estimate P(y) and P(xi | y); the former is then the relative frequency of class y in the training set.There are different naive Bayes classifiers that differ mainly by the assumptions they make regarding the distribution of P(xi | y). Part 6: Gaussian Naive Bayes When dealing with continuous data, a typical assumption is that the continuous values associated with each class are distributed according to a Gaussian distribution. Go back to the normal distribution lecture to review the formulas for the Gaussian/Normal Distribution.For example of using the Gaussian Distribution, suppose the training data contain a continuous attribute, x. We first segment the data by the class, and then compute the mean and variance of x in each class. Let μc be the mean of the values in x associated with class c, and let σ2c be the variance of the values in x associated with class c. Then, the probability distribution of some value given a class, p(x=v|c), can be computed by plugging v into the equation for a Normal distribution parameterized by μc and σ2c. That is:p(x=v|c)=12πσ2c‾‾‾‾‾√e−(v−μc)22σ2cThe key to Naive Bayes is making the (rather large) assumption that the presences (or absences) of each data feature are independent of one another, conditional on a data having a certain label. Part 7: Gaussian Naive Bayes with SciKit Learn We'll start by importing the usual.Quick note we will actually only use the SciKit Learn Library in this lecture: ###Code import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt import seaborn as sns # Gaussian Naive Bayes from sklearn import datasets from sklearn import metrics from sklearn.naive_bayes import GaussianNB # Load the iris datasets iris = datasets.load_iris() # Grab features (X) and the Target (Y) X = iris.data Y = iris.target # Show the Built-In Data Description print(iris.DESCR) # Fit a Naive Bayes model to the data model = GaussianNB() from sklearn.model_selection import train_test_split # Split the data into Training and Testing sets X_train, X_test, Y_train, Y_test = train_test_split(X, Y) # Fit the training model model.fit(X_train,Y_train) # Predicted Outcomes predicted = model.predict(X_test) # Actual Expected Outcomes expected = Y_test print(metrics.accuracy_score(expected, predicted)) ###Output 0.9473684210526315
courses/machine_learning/deepdive/06_structured/3_tensorflow_wd.ipynb
###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %%bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown When I ran it, the final lines of the output (above) were:INFO:tensorflow:Saving dict for global step 1000: average_loss = 1.2693067, global_step = 1000, loss = 635.9226INFO:tensorflow:Restoring parameters from babyweight_trained/model.ckpt-1000INFO:tensorflow:Assets added to graph.INFO:tensorflow:No assets to write.INFO:tensorflow:SavedModel written to: babyweight_trained/export/exporter/temp-1517899936/saved_model.pbThe exporter directory contains the final model and the final RMSE (the average_loss) is 1.2693067 Monitor and experiment with training ###Code from google.datalab.ml import TensorBoard TensorBoard().start('./babyweight_trained') ###Output _____no_output_____ ###Markdown In TensorBoard, look at the learned embeddings. Are they getting clustered? How about the weights for the hidden layers? What if you run this longer? What happens if you change the batchsize? ###Code for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print('Stopped TensorBoard with pid {}'.format(pid)) ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown When I ran it, the final lines of the output (above) were:INFO:tensorflow:Saving dict for global step 1000: average_loss = 1.2693067, global_step = 1000, loss = 635.9226INFO:tensorflow:Restoring parameters from babyweight_trained/model.ckpt-1000INFO:tensorflow:Assets added to graph.INFO:tensorflow:No assets to write.INFO:tensorflow:SavedModel written to: babyweight_trained/export/exporter/temp-1517899936/saved_model.pbThe exporter directory contains the final model and the final RMSE (the average_loss) is 1.2693067 Monitor and experiment with training ###Code from google.datalab.ml import TensorBoard TensorBoard().start('./babyweight_trained') ###Output _____no_output_____ ###Markdown In TensorBoard, look at the learned embeddings. Are they getting clustered? How about the weights for the hidden layers? What if you run this longer? What happens if you change the batchsize? ###Code for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print('Stopped TensorBoard with pid {}'.format(pid)) ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %%bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %bash ls *.csv ###Output eval.csv train.csv ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset.make_one_shot_iterator().get_next() return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown When I ran it, the final lines of the output (above) were:INFO:tensorflow:Saving dict for global step 1000: average_loss = 1.2693067, global_step = 1000, loss = 635.9226INFO:tensorflow:Restoring parameters from babyweight_trained/model.ckpt-1000INFO:tensorflow:Assets added to graph.INFO:tensorflow:No assets to write.INFO:tensorflow:SavedModel written to: babyweight_trained/export/exporter/temp-1517899936/saved_model.pbThe exporter directory contains the final model and the final RMSE (the average_loss) is 1.2693067 Monitor and experiment with training ###Code from google.datalab.ml import TensorBoard TensorBoard().start('./babyweight_trained') ###Output _____no_output_____ ###Markdown In TensorBoard, look at the learned embeddings. Are they getting clustered? How about the weights for the hidden layers? What if you run this longer? What happens if you change the batchsize? ###Code for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print 'Stopped TensorBoard with pid {}'.format(pid) ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %%bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.compat.v1.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.compat.v1.gfile.Glob(filename) # Create dataset from file list dataset = (tf.compat.v1.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.compat.v1.placeholder(tf.string, [None]), 'mother_age': tf.compat.v1.placeholder(tf.float32, [None]), 'plurality': tf.compat.v1.placeholder(tf.string, [None]), 'gestation_weeks': tf.compat.v1.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.compat.v1.summary.FileWriterCache.clear() train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset.make_one_shot_iterator().get_next() return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown When I ran it, the final lines of the output (above) were:INFO:tensorflow:Saving dict for global step 1000: average_loss = 1.2693067, global_step = 1000, loss = 635.9226INFO:tensorflow:Restoring parameters from babyweight_trained/model.ckpt-1000INFO:tensorflow:Assets added to graph.INFO:tensorflow:No assets to write.INFO:tensorflow:SavedModel written to: babyweight_trained/export/exporter/temp-1517899936/saved_model.pbThe exporter directory contains the final model and the final RMSE (the average_loss) is 1.2693067 Monitor and experiment with training ###Code from google.datalab.ml import TensorBoard TensorBoard().start('./babyweight_trained') ###Output _____no_output_____ ###Markdown In TensorBoard, look at the learned embeddings. Are they getting clustered? How about the weights for the hidden layers? What if you run this longer? What happens if you change the batchsize? ###Code for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print('Stopped TensorBoard with pid {}'.format(pid)) ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %%bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = (tf.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), 'gestation_weeks': tf.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate('babyweight_trained') ###Output _____no_output_____ ###Markdown Create TensorFlow wide-and-deep model This notebook illustrates: Creating a model using the high-level Estimator API ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi %%bash ls *.csv ###Output _____no_output_____ ###Markdown Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. ###Code import shutil import numpy as np import tensorflow as tf print(tf.__version__) # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], ['nokey']] TRAIN_STEPS = 1000 # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename, mode, batch_size = 512): def _input_fn(): def decode_csv(value_column): columns = tf.compat.v1.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) return features, label # Create list of files that match pattern file_list = tf.compat.v1.gfile.Glob(filename) # Create dataset from file list dataset = (tf.compat.v1.data.TextLineDataset(file_list) # Read text file .map(decode_csv)) # Transform each elem by applying decode_csv fn if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size=10*batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset return _input_fn ###Output _____no_output_____ ###Markdown Next, define the feature columns ###Code # Define feature columns def get_wide_deep(): # Define column types is_male,mother_age,plurality,gestation_weeks = \ [\ tf.feature_column.categorical_column_with_vocabulary_list('is_male', ['True', 'False', 'Unknown']), tf.feature_column.numeric_column('mother_age'), tf.feature_column.categorical_column_with_vocabulary_list('plurality', ['Single(1)', 'Twins(2)', 'Triplets(3)', 'Quadruplets(4)', 'Quintuplets(5)','Multiple(2+)']), tf.feature_column.numeric_column('gestation_weeks') ] # Discretize age_buckets = tf.feature_column.bucketized_column(mother_age, boundaries=np.arange(15,45,1).tolist()) gestation_buckets = tf.feature_column.bucketized_column(gestation_weeks, boundaries=np.arange(17,47,1).tolist()) # Sparse columns are wide, have a linear relationship with the output wide = [is_male, plurality, age_buckets, gestation_buckets] # Feature cross all the wide columns and embed into a lower dimension crossed = tf.feature_column.crossed_column(wide, hash_bucket_size=20000) embed = tf.feature_column.embedding_column(crossed, 3) # Continuous columns are deep, have a complex relationship with the output deep = [mother_age, gestation_weeks, embed] return wide, deep ###Output _____no_output_____ ###Markdown To predict with the TensorFlow model, we also need a serving input function. We will want all the inputs from our user. ###Code # Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.compat.v1.placeholder(tf.string, [None]), 'mother_age': tf.compat.v1.placeholder(tf.float32, [None]), 'plurality': tf.compat.v1.placeholder(tf.string, [None]), 'gestation_weeks': tf.compat.v1.placeholder(tf.float32, [None]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create estimator to train and evaluate def train_and_evaluate(output_dir): wide, deep = get_wide_deep() EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) estimator = tf.estimator.DNNLinearCombinedRegressor( model_dir = output_dir, linear_feature_columns = wide, dnn_feature_columns = deep, dnn_hidden_units = [64, 32], config = run_config) train_spec = tf.estimator.TrainSpec( input_fn = read_dataset('train.csv', mode = tf.estimator.ModeKeys.TRAIN), max_steps = TRAIN_STEPS) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn = read_dataset('eval.csv', mode = tf.estimator.ModeKeys.EVAL), steps = None, start_delay_secs = 60, # start evaluating after N seconds throttle_secs = EVAL_INTERVAL, # evaluate every N seconds exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ###Output _____no_output_____ ###Markdown Finally, train! ###Code # Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time tf.compat.v1.summary.FileWriterCache.clear() train_and_evaluate('babyweight_trained') ###Output _____no_output_____
1. Data Cleaning.ipynb
###Markdown Import Libraries ###Code import pandas as pd import numpy as np ###Output _____no_output_____ ###Markdown Load Training Data ###Code training_dataframe = pd.read_csv(filepath_or_buffer="./data/TrainingSet.csv") print('Total number of training records',len(training_dataframe)) training_dataframe.head(10) training_dataframe.describe() ###Output _____no_output_____ ###Markdown All the attributes have significant sd ###Code np.array(training_dataframe.describe().loc['std'])<0.001 ###Output _____no_output_____ ###Markdown Max number of Nones in a Columns ###Code training_dataframe.isnull().sum().max() ###Output _____no_output_____ ###Markdown Columns having at least one None Value ###Code null_column_series = training_dataframe.isnull().sum()>0 null_column_names = list(null_column_series[null_column_series].index) print("Column Name -> None Counts :\n",training_dataframe[null_column_names].isnull().sum(),'\n') print("Number of Columns having None : ",len(null_column_names),'\n') print("Column Names containing at least one None value : \n",null_column_names) ###Output Column Name -> None Counts : V1 56 V8 56 V15 56 V22 56 V29 56 V36 56 V43 56 V50 56 V57 56 V64 56 V71 56 V78 56 V85 56 V92 56 V99 56 V106 56 V113 56 V120 56 V127 56 V134 56 V141 56 V148 56 V155 56 V162 56 V169 56 V176 56 V183 56 V190 56 V197 56 V205 56 V213 56 Machine_State 19 dtype: int64 Number of Columns having None : 32 Column Names containing at least one None value : ['V1', 'V8', 'V15', 'V22', 'V29', 'V36', 'V43', 'V50', 'V57', 'V64', 'V71', 'V78', 'V85', 'V92', 'V99', 'V106', 'V113', 'V120', 'V127', 'V134', 'V141', 'V148', 'V155', 'V162', 'V169', 'V176', 'V183', 'V190', 'V197', 'V205', 'V213', 'Machine_State'] ###Markdown Number of rows having None Values ###Code null_rows = training_dataframe.isnull().sum(axis=1)>0 print(len(null_rows[null_rows])) feature_none_column_rows = training_dataframe.isnull().sum(axis=1)==31 print("Number of Rows having all 31 columns as None: ",len(feature_none_column_rows[feature_none_column_rows])) decision_none_column_rows = training_dataframe.isnull().sum(axis=1)==1 print("Number of Rows having all 1 columns as None: ",len(decision_none_column_rows[decision_none_column_rows])) ###Output Number of Rows having all 31 columns as None: 56 Number of Rows having all 1 columns as None: 19 ###Markdown Missing data percentage wrt decision column ###Code missing_percentage = len(decision_none_column_rows[decision_none_column_rows])*100/len(training_dataframe) print("missing data percentage: %0.2f"%missing_percentage,"%") non_null_rows = training_dataframe.isnull().sum(axis=1)==0 print(len(non_null_rows[non_null_rows])) non_null_rows_index = non_null_rows[non_null_rows].index ###Output 3647 ###Markdown Select only those row for which 'Machine_State' has valid value ###Code decision_states = ['Good','Bad'] decision_attribute_name = 'Machine_State' training_dataframe_cleaned = training_dataframe[training_dataframe[decision_attribute_name].isin(decision_states)] print("Original Training dataframe size : ",len(training_dataframe)) print("Cleaned Training dataframe size : ",len(training_dataframe_cleaned)) print("Number of rows dropped : ", len(training_dataframe)-len(training_dataframe_cleaned)) ###Output Original Training dataframe size : 3722 Cleaned Training dataframe size : 3703 Number of rows dropped : 19 ###Markdown Save the Cleaned Training Data ###Code training_dataframe_cleaned.to_csv("./data/cleaned_training_data.csv",index=False) ###Output _____no_output_____
Data_Analysis_And_Viz/Data_Analysis_and_Viz.ipynb
###Markdown 4. Calculating Correlations Create a correlation matrix ###Code mtcars <- mtcars cor(mtcars) ###Output _____no_output_____ ###Markdown Simplify the matrix to increase readability We can use the round() function to wrap the cor() function ###Code round(cor(mtcars), 2) ###Output _____no_output_____ ###Markdown Correlate One pair of variables at a timeDerives r, hypothesis test, and CI\Pearson's product-moment correlation\ ###Code cor.test(mtcars$mpg, mtcars$wt) ###Output _____no_output_____ ###Markdown Graphical Check of bivariate regression ###Code hist(mtcars$mpg) hist(mtcars$wt) plot(mtcars$wt, mtcars$mpg, abline(lm(mtcars$mpg~mtcars$wt))) ###Output _____no_output_____ ###Markdown 5. Creating a Linear regression model**Correlation:** is the strength of the association**Regression:** is a function that can be used to predict values of another variable Create a LM for miles per gallon & weight from mtcars ###Code reg1 <- lm(mpg~wt, data = mtcars) reg1 summary(reg1) ###Output _____no_output_____ ###Markdown The slope being statsitcally significant means that wt is a good predictor of mpg\The variable weight can accounts for 0.75 or 75% of the variation in mpg\ 6. Calculate Multiple Regression**Hint:** Saving models as an R object allows for the extraction of additional information from model Use Six Predictors to model mpg ###Code reg1 <- lm(mpg ~cyl + disp + hp + wt + gear + carb, data = mtcars) reg1 ###Output _____no_output_____ ###Markdown Extract model details ###Code summary(reg1) anova(reg1) coef(reg1) confint(reg1) #Confindence intervals for coefficients resid(reg1) hist(residuals(reg1)) #histogram of the residuals ###Output _____no_output_____ ###Markdown Data Analysis and Visualization with R Workshop Summary and Contact Information**Summary:** R is a free and powerful programming language that is commonly used by researchers in both qualitative and quantitative disciplines. R provides a near comprehensive, and still expanding set of research and data analysis tools. This workshop explores the power of R for data analysis and visualization. The focus of this workshop will be hands-on exercises. No programming experience is required, but a basic comprehension of programming and statistics is benefiticial.**Contact:** Email: [email protected] Location: 240 Braunstein Hall (GMP Library) Research & Data Services Website: https://libraries.uc.edu/research-teaching-support/research-data-services.htmlGitHub: https://github.com/RAJohansen/UCL_WorkshopsTwitter: https://twitter.com/johansen_phd Section I: Brief Introduction R 1. R for basic calculation ###Code sin(pi*15)/100 ###Output _____no_output_____ ###Markdown 2. R Objects & AssignmentR stores values and objects so they can be reused throughout an equation or script\Hint alt - is a shortcut for the < - ###Code x <- 1+2 y <- x +1 y ###Output _____no_output_____ ###Markdown 3. Understanding functions & Getting Help in RGeneral recipe for functions: ###Code #{r eval=FALSE} function_name(argument #1 = value #1, argument #2 = value #2) ###Output _____no_output_____ ###Markdown Going back to our series task, we want to create a series of numbers from 1 to 100 by 2. Luckily there are many functions already available to use in base R (many many more available from packages, which we will discuss later).\\Given that we are just learning R, I will tell you that the function is called "seq()"\The first thing I do when using a new functions is to look at the documentation. You can use the ? to find R documentation.\ **HINT: Scroll to the bottom of the help page for workable examples.**\ ###Code ?seq() ###Output _____no_output_____ ###Markdown **HINT: if you can't remember exactly what function you are looking for, Use Tab.** ###Code me<tab> ###Output _____no_output_____ ###Markdown Additionally, if you are not sure what the function is called try a fuzzy search.\ ###Code apropos("mea") ###Output _____no_output_____ ###Markdown Section II: Exploring the Tidyverse! Install and Load the tidyverse package ###Code require("tidyverse") require("gapminder") ###Output _____no_output_____ ###Markdown Explore the Tidyverse https://www.tidyverse.org/R packages only have to be installed once but loaded everytime.\Using require is a nice way to make sure every script has the packages needed which combines install.packages() & library() 1. Basic Data ExplorationIn this section we will use the gapminder data sethttps://www.gapminder.org/ Lets assign this data to an object called "gapminder" ###Code # Lets assign this data to an object called "gapminder" gapminder <- gapminder ###Output _____no_output_____ ###Markdown View our table ###Code #View(gapminder) head(gapminder) ###Output _____no_output_____ ###Markdown Lists the variables ###Code names(gapminder) ###Output _____no_output_____ ###Markdown Lets Examine the structure of the dataThis will become very useful when we visualize or analyze data, because we must make sure our variables are in the appropriate format!! ###Code str(gapminder) ###Output _____no_output_____ ###Markdown Statistical summary of the data ###Code summary(gapminder) ###Output _____no_output_____ ###Markdown 2. Exploring our data further**HINT: Understanding how data is indexed is crutial for R programming** Lets look at column 2 ###Code gapminder[,2] ###Output _____no_output_____ ###Markdown Lets look at row 5 ###Code gapminder[5,] ###Output _____no_output_____ ###Markdown Selecting a single cell (row 5 column 3) ###Code gapminder[5,3] ###Output _____no_output_____ ###Markdown Based on this idea, we can make more complicated searches. Lets take the first ten observations and look at the variables:Country (1), Continent(2), Year (3), and population (5) ###Code gapminder[1:10,c(1:3, 5)] ###Output _____no_output_____ ###Markdown What if we want to know the highest gpdPercap ###Code max(gapminder$gdpPercap) ###Output _____no_output_____ ###Markdown Lets find the row number of the country with the highest gpdpercapThen show me all columns for row that row ###Code which.max(gapminder$gdpPercap) gapminder[854,] ###Output _____no_output_____ ###Markdown 2. The filter verbThe filter verb is used to look at a subset of a data set.\Typically you combine filter with a pipe %>% Use the filter verb to find the the data for the US ###Code gapminder %>% filter(country == "United States") ###Output _____no_output_____ ###Markdown Multiple conditionsUse filter to return the US for only the year 2007 ###Code gapminder %>% filter(year == 2007, country == "United States") ###Output _____no_output_____ ###Markdown The arrange verb Used for sorting data by ascending or descending condition\ Ascending OrderUse the arrange verb to sort the data in ascending order by GDP per capita ###Code gapminder %>% arrange(gdpPercap) ###Output _____no_output_____ ###Markdown Descending order ###Code gapminder %>% arrange(desc(gdpPercap)) ###Output _____no_output_____ ###Markdown Combining verbsUse filter and arrange to return the results for 2007 in ascending order by GDP per capita ###Code gapminder %>% filter(year == 2007) %>% arrange(gdpPercap) ###Output _____no_output_____ ###Markdown The mutate verbChange or Add variables to a data set Change a variable ###Code gapminder %>% mutate(pop = pop/1000000) ###Output _____no_output_____ ###Markdown Add a new variable called gdp ###Code gapminder %>% mutate(gdp = gdpPercap * pop) ###Output _____no_output_____ ###Markdown Combine all three verbs ###Code gapminder %>% mutate(gdp = gdpPercap * pop) %>% filter(year == 2007) %>% arrange(desc(gdp)) ###Output _____no_output_____ ###Markdown The Summarize Verb Summarize entire data set ###Code gapminder %>% summarize(meanLifeExp = mean(lifeExp)) ###Output _____no_output_____ ###Markdown What if we want to return the mean life exp just for 2007 ###Code gapminder %>% filter(year == 2007) %>% summarize(meanLifeExp = mean(lifeExp)) ###Output _____no_output_____ ###Markdown Creating multiple Summaries ###Code gapminder %>% filter(year == 2007) %>% summarize(meanLifeExp = mean(lifeExp), totalPop = sum(pop)) ###Output _____no_output_____ ###Markdown **HINT: What data type is pop? Use str(gapminder)** Convert pop to a numeric data type instead of an integer ###Code gapminder$pop <- as.numeric(gapminder$pop) gapminder %>% filter(year == 2007) %>% summarize(meanLifeExp = mean(lifeExp), totalPop = sum(pop)) ###Output _____no_output_____ ###Markdown The group_by Verb The group_by verb is useful for creating aggregated groups, especially when combined with the summarize function Summarize by each unique year ###Code gapminder %>% group_by(year) %>% summarize(meanLifeExp = mean(lifeExp), totalPop = sum(pop)) ###Output _____no_output_____ ###Markdown Summarize data from 2007 by continent ###Code gapminder %>% filter(year == 2007) %>% group_by(continent) %>% summarize(meanLifeExp = mean(lifeExp), totalPop = sum(pop)) ###Output _____no_output_____ ###Markdown What if we want to summarize by continent over all years?**HINT: Simply add an additional arguement to the group_by verb** ###Code gapminder %>% group_by(year, continent) %>% summarize(meanLifeExp = mean(lifeExp), totalPop = sum(pop)) ###Output _____no_output_____ ###Markdown Section II TaskAnswer the following questions using the mtcars dataset ###Code mtcars <- mtcars #View() #Str() #names() ###Output _____no_output_____ ###Markdown Find the median mpg & wt for each group of cylinders ###Code mtcars %>% group_by() %>% summarize( = median(), = median()) ###Output _____no_output_____ ###Markdown Section III: Data VisualizationUseful resources for using base plot in R: \https://www.harding.edu/fmccown/r/ \https://www.statmethods.net/graphs/index.html 1. Default Plot ###Code plot(mtcars$mpg) ###Output _____no_output_____ ###Markdown 2. Dotchart ###Code dotchart(mtcars$mpg) ###Output _____no_output_____ ###Markdown Adding details and labels to a Simple Dotplot ###Code dotchart(mtcars$mpg, labels=row.names(mtcars), main="Gas Milage for Car Models", xlab="Miles Per Gallon") ###Output _____no_output_____ ###Markdown 3. Histogram ###Code hist(mtcars$mpg) ###Output _____no_output_____ ###Markdown Add color and explore bin sizes ###Code hist(mtcars$mpg, breaks=5, col="red") hist(mtcars$mpg, breaks=10, col="red") hist(mtcars$mpg, breaks=15, col="red") ###Output _____no_output_____ ###Markdown 4. Kernel Density PlotFirst you need to save the density of the data you want to an R object\Then plot that object using plot() ###Code d <- density(mtcars$mpg) # returns the density data plot(d) # plots the results ###Output _____no_output_____ ###Markdown 5. Barplot ###Code barplot(mtcars$cyl) ###Output _____no_output_____ ###Markdown **HINT:** To fist create a variable called "count" to count the number of each group\Then use the barplot() function on the object counts ###Code counts <- table(mtcars$cyl) barplot(counts) ###Output _____no_output_____ ###Markdown Add Chart Title and Axes ###Code barplot(counts, main="Car Distribution", xlab="Number of Gears") ###Output _____no_output_____ ###Markdown Converting a Bar chart into a Stacked Bar ###Code counts <- table(mtcars$cyl, mtcars$gear) barplot(counts, main="Car Distribution by Cylinders and Gears", xlab="Number of Gears", col = c("darkred","darkblue","orange"), legend = rownames(counts)) ###Output _____no_output_____ ###Markdown 6. Box Plots ###Code boxplot(mtcars$mpg~mtcars$cyl) boxplot(mpg~cyl, data=mtcars, main="Car Milage Data", xlab="Number of Cylinders", ylab="Miles Per Gallon") ###Output _____no_output_____ ###Markdown 7. Pie Charts ###Code slices <- table(mtcars$cyl) lbls <- c("Four", "Six", "Eight") pie(slices, labels = lbls, main="Pie Chart of mtcars Cylindars") ###Output _____no_output_____ ###Markdown 8. Scatterplot Simple Scatterplot ###Code plot(mtcars$wt,mtcars$mpg) plot(mtcars$wt, mtcars$mpg, main="Scatterplot Example", xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19) ###Output _____no_output_____ ###Markdown Add linear regression line Regression line is (y~x) ###Code plot(mtcars$wt, mtcars$mpg, main="Scatterplot Example", xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19, abline(lm(mtcars$mpg~mtcars$wt), col="red")) ###Output _____no_output_____ ###Markdown 9. Line Graphs ###Code lines <- c(1:2,4,7,5,8,10,7) plot(lines) plot(lines, type="o", col="blue") plot(lines, type="o", col="blue", main="My Line Graph") ###Output _____no_output_____ ###Markdown 10. Get Inspired!!! Use the Iris data set to make a scatterplot matrix ###Code data("iris") pairs(iris[1:4]) #only quantitative variables ###Output _____no_output_____ ###Markdown Explore pastel theme in RColorBrewer (Might not work in Jupyter) ###Code require("RColorBrewer") display.brewer.pal(3,"Pastel1") #display colorpalette ###Output _____no_output_____ ###Markdown Use the function below to modify the scatterplot matrixPut Histograms on the diagonal (from "pairs" Help) ###Code panel.hist <- function(x,...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(usr[1:2], 0,1.5) ) h <- hist(x, plot = FALSE) breaks <- h$breaks; nB <- length(breaks) y <- h$counts; y <- y/max(y) rect(breaks[-nB], 0, breaks[-1], y, ...) } # Create a fancy scatterplot matrix pairs(iris[1:4], panel = panel.smooth, main = "Scatterplot Maxtris for Iris Data Using pairs Function", diag.panel = panel.hist, pch = 16, col = brewer.pal(3, "Pastel1")[unclass(iris$Species)]) # jpeg('C:/temp/My_Awesome_Plot.jpg') # Run your fancy scatter plot matrix code here! #dev.off() ###Output _____no_output_____ ###Markdown Section IV: Data Analysis 1. Basic Stats with RStatistics are used to summerize data!\We use stats because it is difficult to memorize and decipher raw numbers\ **Example 1: Average daily car traffic for a week ** ###Code total <- sum(5,16,15,16,13,20,25) days <- 7 total/days ###Output _____no_output_____ ###Markdown Two basic types of Statistics**Descriptive Stats:** Uses data to describe the characteristics of a group**Inferential Stats:** Uses the data to make predictions or draw conclusions 2. Calculating descriptive statistics One variable vs. the Entire Data set ###Code summary(mtcars$mpg) summary(mtcars) ###Output _____no_output_____ ###Markdown Tukey's five-number summary: Min, Lower-hinge, Median, Upper-Hinge, Max (Not Labeled)**Hint:: These five numbers are the same as a boxplot** ###Code fivenum(cars$mpg) ###Output _____no_output_____ ###Markdown Alternative Descriptive Stats using the psych packagevars, n, mean, sd, median, trimmed, mad, min, max, range, skew, kurtosis, se ###Code #install.packages("psych") library(psych) describe(mtcars) #vars, n, mean, sd, median, trimmed, mad, min, max, range, skew, kurtosis, se ###Output _____no_output_____ ###Markdown Alternative Descriptive Stats using the pastecs pacakge ###Code #install.packages("pastecs") library(pastecs) ?stat.desc() stat.desc(mtcars) ###Output _____no_output_____ ###Markdown 3. Analyzing data by groupsFor this section we will use the iris dataset ###Code data(iris) View(iris) mean(iris$Petal.Width) #mean of all observation's petal.width ###Output _____no_output_____ ###Markdown Split the data file and repeat analysis using "aggregate"Allowing for the comparison of means by group ###Code aggregate(iris$Petal.Width ~ iris$Species, FUN = mean) # ~ means a function of... means <- aggregate(iris$Petal.Width ~ iris$Species, FUN = mean) plot(means) ###Output _____no_output_____ ###Markdown **Hint:** There is significant difference between species Conducting multiple calculations at once**Hint:** The results do not keep the column headers so you need to remember the order you wrote them ###Code aggregate(cbind(iris$Petal.Width, iris$Petal.Length)~ iris$Species, FUN = mean) ###Output _____no_output_____
docs/tutorial/13_Work_with_binary_logs.ipynb
###Markdown How to work with binary logsWe will invent a binary log -- maybe you can load it from an LAS file with `welly`. ###Code import numpy as np %matplotlib inline import matplotlib.pyplot as plt fake_depth = np.linspace(100, 150, 101) fake_log = np.array([np.random.choice([0, 1]) for _ in fake_depth]) plt.figure(figsize=(15, 1)) plt.plot(fake_depth, fake_log, 'o-') ###Output _____no_output_____ ###Markdown Make a striplogA `Striplog` is a sequence of `Interval` objects (representing a layer). Each `Interval` must contain a `Component` (representing the layer, perhaps a rock). ###Code from striplog import Striplog, Component comps = [ Component({'pay': True}), Component({'pay': False}) ] s = Striplog.from_log(fake_log, cutoff=0.5, components=comps, basis=fake_depth) s[-1].base.middle = 150.5 # Adjust the bottom thickness... not sure if this is a bug. ###Output _____no_output_____ ###Markdown Each `Interval` in the striplog looks like: ###Code s[0] ###Output _____no_output_____ ###Markdown Plot the intervalsTo plot we need a legend, but we can generate a random one. This maps each `Component` to a colour (and a width and hatch, if you want). We can generate a random legend: ###Code from striplog import Legend legend = Legend.random(comps) legend.get_decor(comps[-1]).width = 0.2 legend.plot() ###Output _____no_output_____ ###Markdown Or we can make one with a bit more control: ###Code legend_csv = """colour,hatch,width,component pay #48cc0e,None,1,True #5779e2,None,0.2,False""" legend = Legend.from_csv(text=legend_csv) legend.plot() s.plot(legend=legend, aspect=5) ###Output _____no_output_____ ###Markdown Remove thin thingsWe can remove thin intervals: ###Code pruned = s.prune(limit=1.0, keep_ends=True) ###Output _____no_output_____ ###Markdown Now we can anneal the gaps: ###Code annealed = pruned.anneal() ###Output _____no_output_____ ###Markdown Then merge the adjacent intervals that are alike... ###Code merged = annealed.merge_neighbours() # Anneal works on a copy ###Output _____no_output_____ ###Markdown We could have chained these commands: merged = s.prune(limit=1.0, keep_ends=True).anneal().merge_neighbours()Let's plot all these steps, just for illustration: ###Code fig, axs = plt.subplots(ncols=4, figsize=(6, 10)) axs[0] = s.plot(legend=legend, ax=axs[0], lw=1, aspect=5) axs[0].set_title('Original') axs[1] = pruned.plot(legend=legend, ax=axs[1], lw=1, aspect=5) axs[1].set_yticklabels([]) axs[1].set_title('Pruned') axs[2] = annealed.plot(legend=legend, ax=axs[2], lw=1, aspect=5) axs[2].set_yticklabels([]) axs[2].set_title('Annealed') axs[3] = merged.plot(legend=legend, ax=axs[3], lw=1, aspect=5) axs[3].set_yticklabels([]) axs[3].set_title('Merged') plt.show() ###Output _____no_output_____ ###Markdown Dilate and erodeThis would be a binary thing, at least for now. I made an issue for this: https://github.com/agile-geoscience/striplog/issues/95You need to be on striplog v 0.8.1 at least for this to work. ###Code fig, axs = plt.subplots(ncols=4, figsize=(6, 10)) opening = s.binary_morphology('pay', 'opening', step=0.1, p=7) closing = s.binary_morphology('pay', 'closing', step=0.1, p=7) axs[0] = s.plot(legend=legend, ax=axs[0], lw=1, aspect=5) ntg = s.net_to_gross('pay') axs[0].set_title(f'Original\n{ntg:.2f}') axs[1] = merged.plot(legend=legend, ax=axs[1], lw=1, aspect=5) axs[1].set_yticklabels([]) ntg = merged.net_to_gross('pay') axs[1].set_title(f'PAM\n{ntg:.2f}') # Prune-anneal-merge axs[2] = opening.plot(legend=legend, ax=axs[2], lw=1, aspect=5) axs[2].set_yticklabels([]) ntg = opening.net_to_gross('pay') axs[2].set_title(f'Opening\n{ntg:.2f}') axs[3] = closing.plot(legend=legend, ax=axs[3], lw=1, aspect=5) axs[3].set_yticklabels([]) ntg = closing.net_to_gross('pay') axs[3].set_title(f'Closing\n{ntg:.2f}') plt.show() ###Output _____no_output_____ ###Markdown Some statisticsWe can get the unique components and their thicknesses: ###Code s.unique ###Output _____no_output_____ ###Markdown We can get at the thickest (and thinnest, with `.thinnest()`) intervals: ###Code s.thickest() ###Output _____no_output_____ ###Markdown These functions optionally take an integer argument `n` specifying how many of the thickest or thinnest intervals you want to see. If `n` is greater than 1, a `Striplog` object is returned so you can see the positions of those items: ###Code s.thickest(5).plot(legend=legend, lw=1, aspect=5) ###Output _____no_output_____ ###Markdown Bar plots and histograms We can make a bar plot of the layers: ###Code s.bar(legend=legend) ###Output _____no_output_____ ###Markdown More interesting is to sort the thicknesses: ###Code s.bar(legend=legend, sort=True) ###Output _____no_output_____ ###Markdown Finally, we can make a thickness histogram of the various types of `component` present in the log. ###Code n, ents, ax = s.hist(legend=legend) s legend data = [c[1] for c in s.unique] colors = [c['_colour'] for c in legend.table] fig, axs = plt.subplots(ncols=2, gridspec_kw={'width_ratios': [1, 3]}) axs[0] = s.plot(ax=axs[0], legend=legend) axs[0].set_title("Striplog") axs[1].pie(data, colors=colors) axs[1].set_title("Pay proportions") plt.show() ###Output _____no_output_____
src/deep_learning/training.ipynb
###Markdown ###Code import tensorflow as tf import tensorflow_hub as hub import numpy as np from tensorflow.keras.models import save_model, load_model, Sequential from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Dense, Dropout, Flatten, GlobalAveragePooling2D from tensorflow.keras.optimizers import Adam, Adamax from tensorflow.keras.callbacks import EarlyStopping import matplotlib.pyplot as plt import os from google.colab import drive drive.mount("/content/drive") data_dir = "/content/drive/MyDrive/BuildOnAsean2021/Training_Data" batch_size = 3 img_size = (512, 512) datagen = ImageDataGenerator(rescale=1./255, horizontal_flip=True, vertical_flip=True, brightness_range=[0.8, 1.2]) dataset = datagen.flow_from_directory( data_dir, color_mode="rgb", batch_size=batch_size, target_size=img_size, shuffle=True) print(dataset.class_indices) URL = "https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet21k_xl/feature_vector/2" pretrained_model = hub.KerasLayer(URL, input_shape=(512,512,3)) model = Sequential() model.add(pretrained_model) model.add(Dense(512, activation="relu")) model.add(Dropout(0.30)) model.add(Dense(7, activation="softmax")) model.summary() model.compile(optimizer = Adamax(), loss= 'categorical_crossentropy', metrics = ['accuracy']) es = EarlyStopping(monitor = 'loss', patience =1) history = model.fit(dataset, epochs = 10, callbacks = es) plt.plot(history.history['accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train'], loc = 'upper left') plt.show() plt.plot(history.history['loss']) plt.title('Model Loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['Train'], loc = 'upper left') plt.show() os.chdir('/content/drive/MyDrive/BuildOnAsean2021') model.save("EfficientNetv2_xl.h5") ###Output _____no_output_____
main/Plot/Infernece_latency_graph.ipynb
###Markdown Q1 ###Code import tensorflow as tf from tensorflow.keras.datasets import cifar10 import os import pandas as pd import matplotlib.pyplot as plt import matplotlib.pylab as plt import numpy as np import time import pathlib import timeit import seaborn as sns ###Output _____no_output_____ ###Markdown cifar_vgg ###Code df = pd.read_csv('cifar-vgg-Avg.csv') plt.rcParams.update({'figure.figsize':(7,3)}) df = df[['q_name','BO','RS','GHO']] dd=pd.melt(df,id_vars=['q_name'],value_vars=['BO','RS','GHO'],var_name='HPO Algorithms') #sns.set_theme(style="white") sns.set_style("ticks") sns.boxplot(x='q_name',y='value',data=dd,hue='HPO Algorithms', palette="Set2",linewidth=0.7) x = [0,1,2,3] layers = ['No quantization','Float16','Dynamic Range','INT8'] #plt.title('HPO Algorithms intermidate output latency- Vgg16/CIFAR10', fontsize=12) plt.ylabel('Latency (s)', fontsize=16.5,fontweight = 550) plt.xlabel('Post-training quantization options', fontsize=16.5, fontweight = 550) plt.rc('xtick', labelsize=13.5) plt.rc('ytick', labelsize=13.5) plt.xticks(x, layers) plt.grid(linestyle = '--', linewidth = 0.5) plt.tight_layout(pad=.9) #plt.ylim(0.215, 0.250) plt.savefig('cifar-vgg-Avg.pdf',dpi=100) plt.show() ###Output _____no_output_____ ###Markdown cifar_resnet ###Code df = pd.read_csv('cifar-resnet-avg.csv') plt.rcParams.update({'figure.figsize':(7,3)}) df = df[['q_name','BO','RS','GHO']] dd=pd.melt(df,id_vars=['q_name'],value_vars=['BO','RS','GHO'],var_name='HPO Algorithms') #sns.set_theme(style="white") sns.set_style("ticks") sns.boxplot(x='q_name',y='value',data=dd,hue='HPO Algorithms', palette="Set2",linewidth=0.7) x = [0,1,2,3] layers = ['No quantization','Float16','Dynamic Range','INT8'] #plt.title('HPO Algorithms intermidate output latency- ResNet50/CIFAR10', fontsize=12) plt.ylabel('Latency (s)', fontsize=16.5,fontweight = 550) plt.xlabel('Post-training quantization options', fontsize=16.5,fontweight = 550) plt.rc('xtick', labelsize=13.5) plt.rc('ytick', labelsize=13.5) plt.xticks(x, layers) plt.grid(linestyle = '--', linewidth = 0.5) plt.tight_layout(pad=.9) plt.ylim(0.225, 0.255) plt.savefig('cifar-resnet-avg.pdf',dpi=100) plt.show() ###Output _____no_output_____ ###Markdown intel_resnet ###Code df = pd.read_csv('intel_resnet_avg.csv') plt.rcParams.update({'figure.figsize':(7,3)}) df = df[['q_name','BO','RS','GHO']] dd=pd.melt(df,id_vars=['q_name'],value_vars=['BO','RS','GHO'],var_name='HPO Algorithms') #sns.set_theme(style="white") sns.set_style("ticks") sns.boxplot(x='q_name',y='value',data=dd,hue='HPO Algorithms', palette="Set2",linewidth=0.7) x = [0,1,2,3] layers = ['No quantization','Float16','Dynamic Range','INT8'] #plt.title('HPO Algorithms intermidate output latency- ResNet50/Intel', fontsize=12) plt.ylabel('Latency (s)', fontsize=16.5,fontweight = 550) plt.xlabel('Post-training quantization options', fontsize=16.5,fontweight = 550) plt.rc('xtick', labelsize=13.5) plt.rc('ytick', labelsize=13.5) plt.xticks(x, layers) plt.grid(linestyle = '--', linewidth = 0.5) plt.tight_layout(pad=.9) plt.ylim(0.23, 0.26) plt.savefig('intel_resnet-avg.pdf',dpi=100) plt.show() ###Output _____no_output_____ ###Markdown intel_vgg ###Code df = pd.read_csv('intel-vgg-avg.csv') plt.rcParams.update({'figure.figsize':(7,3)}) df = df[['q_name','BO','RS','GHO']] dd=pd.melt(df,id_vars=['q_name'],value_vars=['BO','RS','GHO'],var_name='HPO Algorithms') #sns.set_theme(style="white") sns.set_style("ticks") sns.boxplot(x='q_name',y='value',data=dd,hue='HPO Algorithms', palette="Set2",linewidth=0.7) x = [0,1,2,3] layers = ['No quantization','Float16','Dynamic Range','INT8'] #plt.title('HPO Algorithms intermidate output latency- VGG16/Intel', fontsize=12) plt.ylabel('Latency (s)', fontsize=16.5,fontweight = 550) plt.xlabel('Post-training quantization options', fontsize=16.5,fontweight = 550) plt.rc('xtick', labelsize=13.5) plt.rc('ytick', labelsize=13.5) plt.xticks(x, layers) plt.grid(linestyle = '--', linewidth = 0.5,) plt.tight_layout(pad=.9) plt.savefig('intel-vgg-avg.pdf',dpi=100) plt.show() ###Output _____no_output_____
3. Project_3_The GitHub History of the Scala Language.ipynb
###Markdown 1. Scala's real-world project repository dataWith almost 30k commits and a history spanning over ten years, Scala is a mature programming language. It is a general-purpose programming language that has recently become another prominent language for data scientists.Scala is also an open source project. Open source projects have the advantage that their entire development histories -- who made changes, what was changed, code reviews, etc. -- are publicly available. We're going to read in, clean up, and visualize the real world project repository of Scala that spans data from a version control system (Git) as well as a project hosting site (GitHub). We will find out who has had the most influence on its development and who are the experts.The dataset we will use, which has been previously mined and extracted from GitHub, is comprised of three files:pulls_2011-2013.csv contains the basic information about the pull requests, and spans from the end of 2011 up to (but not including) 2014.pulls_2014-2018.csv contains identical information, and spans from 2014 up to 2018.pull_files.csv contains the files that were modified by each pull request. ###Code # Importing pandas import pandas as pd # Loading in the data pulls_one = pd.read_csv('datasets/pulls_2011-2013.csv') pulls_two = pd.read_csv('datasets/pulls_2014-2018.csv') pull_files = pd.read_csv('datasets/pull_files.csv') ###Output _____no_output_____ ###Markdown 2. Preparing and cleaning the dataFirst, we will need to combine the data from the two separate pull DataFrames. Next, the raw data extracted from GitHub contains dates in the ISO8601 format. However, pandas imports them as regular strings. To make our analysis easier, we need to convert the strings into Python's DateTime objects. DateTime objects have the important property that they can be compared and sorted.The pull request times are all in UTC (also known as Coordinated Universal Time). The commit times, however, are in the local time of the author with time zone information (number of hours difference from UTC). To make comparisons easy, we should convert all times to UTC. ###Code # Append pulls_one to pulls_two pulls = pulls_two.append(pulls_one, ignore_index=True) # Convert the date for the pulls object pulls['date'] = pd.to_datetime(pulls['date'], utc=True) ###Output _____no_output_____ ###Markdown 3. Merging the DataFramesThe data extracted comes in two separate files. Merging the two DataFrames will make it easier for us to analyze the data in the future tasks. ###Code # Merge the two DataFrames data = pulls.merge(pull_files, on='pid') ###Output _____no_output_____ ###Markdown 4. Is the project still actively maintained?The activity in an open source project is not very consistent. Some projects might be active for many years after the initial release, while others can slowly taper out into oblivion. Before committing to contributing to a project, it is important to understand the state of the project. Is development going steadily, or is there a drop? Has the project been abandoned altogether?The data used in this project was collected in January of 2018. We are interested in the evolution of the number of contributions up to that date.For Scala, we will do this by plotting a chart of the project's activity. We will calculate the number of pull requests submitted each (calendar) month during the project's lifetime. We will then plot these numbers to see the trend of contributions.A helpful reminder of how to access various components of a date can be found in this exercise of Data Manipulation with pandasAdditionally, recall that you can group by multiple variables by passing a list to groupby(). This video from Data Manipulation with pandas should help! ###Code %matplotlib inline # Create a column that will store the month data['month'] = data['date'].dt.month # Create a column that will store the year data['year'] = data['date'].dt.year # Group by month_year and count the pull requests counts = data.groupby(['year', 'month'])['pid'].count() # Plot the results counts.plot(kind='bar', figsize = (12,4)) ###Output _____no_output_____ ###Markdown 5. Is there camaraderie in the project?The organizational structure varies from one project to another, and it can influence your success as a contributor. A project that has a very small community might not be the best one to start working on. The small community might indicate a high barrier of entry. This can be caused by several factors, including a community that is reluctant to accept pull requests from "outsiders," that the code base is hard to work with, etc. However, a large community can serve as an indicator that the project is regularly accepting pull requests from new contributors. Such a project would be a good place to start.In order to evaluate the dynamics of the community, we will plot a histogram of the number of pull requests submitted by each user. A distribution that shows that there are few people that only contribute a small number of pull requests can be used as in indicator that the project is not welcoming of new contributors. ###Code # Required for matplotlib %matplotlib inline # Group by the submitter by_user = data.groupby('user').agg({'pid': 'count'}) # Plot the histogram by_user.hist() ###Output _____no_output_____ ###Markdown 6. What files were changed in the last ten pull requests?Choosing the right place to make a contribution is as important as choosing the project to contribute to. Some parts of the code might be stable, some might be dead. Contributing there might not have the most impact. Therefore it is important to understand the parts of the system that have been recently changed. This allows us to pinpoint the "hot" areas of the code where most of the activity is happening. Focusing on those parts might not the most effective use of our times. ###Code # Identify the last 10 pull requests last_10 = pulls.sort_values(by = 'date').tail(10) last_10 # Join the two data sets joined_pr = pull_files.merge(last_10, on='pid') # Identify the unique files files = set(joined_pr['file']) # Print the results files ###Output _____no_output_____ ###Markdown 7. Who made the most pull requests to a given file?When contributing to a project, we might need some guidance. We might find ourselves needing some information regarding the codebase. It is important direct any questions to the right person. Contributors to open source projects generally have other day jobs, so their time is limited. It is important to address our questions to the right people. One way to identify the right target for our inquiries is by using their contribution history.We identified src/compiler/scala/reflect/reify/phases/Calculate.scala as being recently changed. We are interested in the top 3 developers who changed that file. Those developers are the ones most likely to have the best understanding of the code. ###Code # This is the file we are interested in: file = 'src/compiler/scala/reflect/reify/phases/Calculate.scala' # Identify the pull requests that changed the file file_pr = data[data['file'] == file] # Count the number of changes made by each developer author_counts = file_pr.groupby('user').count() # Print the top 3 developers author_counts.nlargest(3, 'file') ###Output _____no_output_____ ###Markdown 8. Who made the last ten pull requests on a given file?Open source projects suffer from fluctuating membership. This makes the problem of finding the right person more challenging: the person has to be knowledgeable and still be involved in the project. A person that contributed a lot in the past might no longer be available (or willing) to help. To get a better understanding, we need to investigate the more recent history of that particular part of the system. Like in the previous task, we will look at the history of src/compiler/scala/reflect/reify/phases/Calculate.scala. ###Code file = 'src/compiler/scala/reflect/reify/phases/Calculate.scala' # Select the pull requests that changed the target file file_pr = pull_files[pull_files['file'] == file] # Merge the obtained results with the pulls DataFrame joined_pr = pulls.merge(file_pr, on='pid') # Find the users of the last 10 most recent pull requests users_last_10 = set(joined_pr.nlargest(10, 'date')['user']) # Printing the results users_last_10 ###Output _____no_output_____ ###Markdown 9. The pull requests of two special developersNow that we have identified two potential contacts in the projects, we need to find the person who was most involved in the project in recent times. That person is most likely to answer our questions. For each calendar year, we are interested in understanding the number of pull requests the authors submitted. This will give us a high-level image of their contribution trend to the project. ###Code %matplotlib inline # The developers we are interested in authors = ['xeno-by', 'soc'] # Get all the developers' pull requests by_author = pulls[pulls['user'].isin(authors)] # Count the number of pull requests submitted each year counts = by_author.groupby([by_author['user'], by_author['date'].dt.year]).agg({'pid': 'count'}).reset_index() # Convert the table to a wide format counts_wide = counts.pivot_table(index='date', columns='user', values='pid', fill_value=0) # Plot the results counts_wide.plot(kind='bar') ###Output _____no_output_____ ###Markdown 10. Visualizing the contributions of each developerAs mentioned before, it is important to make a distinction between the global expertise and contribution levels and the contribution levels at a more granular level (file, submodule, etc.) In our case, we want to see which of our two developers of interest have the most experience with the code in a given file. We will measure experience by the number of pull requests submitted that affect that file and how recent those pull requests were submitted. ###Code authors = ['xeno-by', 'soc'] file = 'src/compiler/scala/reflect/reify/phases/Calculate.scala' # Merge DataFrames and select the pull requests by the author by_author = data[data['user'].isin(authors)] # Select the pull requests that affect the file by_file = by_author[by_author['file'] == file] # Group and count the number of PRs done by each user each year grouped = by_file.groupby(['user', by_file['date'].dt.year]).count()['pid'].reset_index() # Transform the data into a wide format by_file_wide = grouped.pivot_table(index='date', columns='user', values='pid', fill_value=0) # Plot the results by_file_wide.plot(kind='bar') ###Output _____no_output_____
course2/test-notebook.ipynb
###Markdown "My Jupyter Notebook on IBM Data Science Experience" **William Morgan** Any software engineering/data science position *I am interested in data science, because i love compute power and numbers. I love answering questions hidden in data and uncovering other insights that were not even considered in the first place. I am a very curious person and love using data to answer questions and prove my case.* In the next cell, you will see code that scrapes the first page of results from a website I have recently been working on. It puts the data into a pandas DataFrame and displays the first 15 columns of the first 5 results. ###Code import numpy as np import pandas as pd import re import time from bs4 import BeautifulSoup import requests start_time = time.time() page_n = 1 #keep track of which page the scraper is on games = []# list to collect data base_url = 'https://boardgamegeek.com/' #the base url start_url = 'https://boardgamegeek.com/browse/boardgame/page/' #start page # a list of attributes to be collected from 'all_d' collect_list = ["objectid","name","yearpublished","sortindex","minplayers", "maxplayers","minplaytime","maxplaytime","minage","best", "max","totalvotes","playerage","languagedependence", "usersrated","average","baverage","stddev","avgweight", "numweights","numgeeklists","numtrading","numwanting", "numcomments","views","numplays","numplays_month","news", "blogs","weblink","podcast","label","boardgamedesigner", "boardgameartist","boardgamepublisher","boardgamehonor", "boardgamecategory","boardgamemechanic","boardgameexpansion", "boardgameversion","boardgamefamily"] #a list of attributes to be collected from "credit_d" credit_collect_list = ["boardgamedesigner","boardgameartist","boardgamepublisher", "boardgamehonor","boardgamecategory","boardgameversion","boardgamemechanic"] # while loop to continue until page_n reached the decided limit while page_n <= 1 : #request the page game_names = BeautifulSoup(requests.get(start_url+str(page_n)).text,'lxml') #get list of games from page game_list = game_names.find_all('td',{'class':'collection_objectname'}) #below is logic to stop the loop if no additional links are available if not game_list: print('No more results: Exiting...') break else: print('Getting page:{}'.format(page_n)) #iterate through game list for page_n for game in game_list: game_data = [] #collect data #request game page game_page = BeautifulSoup(requests.get(base_url+\ game.select('a')[0]['href']+'/stats').text,'html.parser') #capture whole description of game desc_tag = game_page.find_all('meta',{'property':'og:description'}) desc_str = str(desc_tag).split('>',1)[0][16:-27].replace('&amp;ldquo;','"')\ .replace('&amp;rdquo;','"').replace('\n',' ') #manipulate js script data and create dictionaries for attribute look up script =game_page.find("script", text=re.compile("GEEK.geekitemPreload\s+=")) data_list = str(script).replace('=4&mt=8&at=','').replace(':{"link"','')\ .split("=",9)[9].strip().split(':{') comm_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[3][:-1].split(',') if len(i.split(':'))> 1 } stats_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[5][:-1].split(',') if len(i.split(':'))> 1 } counts_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[6][:-1].split(',') if len(i.split(':'))> 1 } info_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[7][:-1].split(',') if len(i.split(':'))> 1 } cr_cnt_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[9][:-1].split(',') if len(i.split(':'))> 1 } rank_d = {i.split(':')[0]:' '.join(i.split(':')[1:])\ for i in data_list[10][:-1].split(',') if len(i.split(':'))> 1 } all_d = {**comm_d, **stats_d,**counts_d,**info_d,**cr_cnt_d,**rank_d} #extract data from messy string credit_d = {} for i in data_list[8].split('],'): item = i.split(":",1) try: values = [h.split(',')[0] for h in\ [j.split(':')[1] for j in item[1].split('},{')]] except: pass credit_d[item[0]]=values #iterate through list of desired attributes to capture values for i in collect_list: if '"'+i+'"' in all_d.keys(): game_data.append(all_d['"'+i+'"'].replace('"','')) else: game_data.append('NaN') for i in credit_collect_list: if '"'+i+'"' in credit_d.keys(): game_data.append(credit_d['"'+i+'"']) else: game_data.append('NaN') game_data.append(desc_str) #append game description game_data.append(game.select('a')[0]['href']) games.append(game_data) page_n += 1 end_time = time.time() print('total_time: {} minutes'.format((end_time-start_time)/60)) df = pd.DataFrame.from_records(games) df.iloc[:,:15].head() ###Output Getting page:1 total_time: 0.10658369461695354 minutes
notebooks/pySUMMA_General_Plot.ipynb
###Markdown Modeling the Impact of Stomatal Resistance Parameterizations on Total Evapotranspiration in the Reynolds Mountain East catchment using pySUMMA 1. Introduction One part of the Clark et al. (2015) study explored the impact of different stomatal resistance parameterizations on total evapotranspiration (ET) using a SUMMA model for the Reynolds Mountain East catchment. This study looked at three different stomatal resistance parameterizations: the simple soil resistance method, the Ball Berry method, and the Jarvis method.In this Jupyter Notebook, the pySUMMA library is used to reproduce this analysis. First, the three different stomatal resistance parameterizations are described. Next, the Methods section describes how the pySUMMA can be used to create three different versions of the Reynolds Mountain East catchment model, one for each stomatal resistance parameterization. The Results section shows how to use pySUMMA and the Pandas library to reproduce Figure 7 from Clark et al. (2015). Collectively, this Jupyter Notebook serves as an example of how hydrologic modeling can be conducted directly within a Jupyter Notebook by leveraging the pySUMMA library. 2. Background The stomatal resistance parameterizations available in SUMMA ###Code #import libraries to display equations within the notebook from IPython.display import display, Math, Latex ###Output _____no_output_____ ###Markdown 1.) The simple soil resistance method \begin{equation*}r_{{s},{sun}} = r_{{s},{shd}} = \frac{r_{0c}}{\beta_v} \,\,\,\, \end{equation*}$r_{0c} \,(s\,m^{-1})$ : the minimum stomatal resistance , ${\beta_v}\,(-)$ : the total soil water stress function \begin{equation*}{\beta_v} = \sum f_{{roots},{j}} \beta_{{v},{j}} + f_{roots}^{aq} \beta_{v}^{aq}\end{equation*}$z_{soil}$ : the soil depth, $f_{{roots},{j}}$ : the root density in the $j$-th soil layer$\beta_{{v},{j}}$ : the water availability stress funtion in the $j$-th soil layer $f_{roots}^{aq}$ : the fraction of roots for the aquifer, $\beta_{v}^{aq}$ : water availability stress function for the aquiferFor additional detail, see: https://github.com/DavidChoi76/pysumma/blob/master/simple1.png 2.) The Ball-Berry method \begin{equation*}g_i = v_t \frac{A_i}{c_{air}}\frac{e_{air}}{e_{sat}(T_{veg})}P_{air} + g_{min}\beta_v, \,\,\,\, i = sun, shd\end{equation*} $g_i\, (micromol \,\, m^{-2} s^{-1})$ : Stomatal conductance per unit sunlit and shaded leaf area $A_i\, (micromol \,\, m^{-2} s^{-1})$ : a function of the rate of photosynthesis $c_{air}\, (Pa)$ : $CO_2$ concentration at the leaf surface (time varying model forcing, representing carbon fertilization) $g_{min}\, (micromol \,\, m^{-2} s^{-1})$ : the minimum stomatal conductance $v_t\,(-)$ : an empirical parameter to relate transpiration to the $CO_2$ flux, where a greater value of $v_t$ means the leaf consumes more water to produce the same carbon mass For additinoal detail, see: https://github.com/DavidChoi76/pysumma/blob/master/BallBerry.png 3) The Jarvis method \begin{equation*}r_{{s},{i}} = \frac{r_{0c}}{f(Q_{{PAR},{i}})f(T_{air})f(e_{d})\beta_v} \,\,\,\, i = sun, shd\end{equation*} the subscript $i$ defines either sunlit or shaded leaves $f(Q_{{PAR},{i}})$, $f(T_{air})$, $f(e_{d})$ : all limited to the range 0-1, represent the effects of photosynthetically-active radiation(PAR), air temperature, and vapor pressure deficit, where $ Q_{{PAR},{i}} $ represents PAR absorbed on sunlit or shaded leaves For additional detail, see: https://github.com/DavidChoi76/pysumma/blob/master/Jarvis.png The above images are taken from the Stomal Resistance Method section within the manual Structure for Unifying Multiple Modeling Alternatives (SUMMA), Version 1.0: Technical Description (April, 2015). 3. Methods 1) Study Area The Reynolds Mountain East catchment is located in southwestern Idaho as shown in the figure below. ###Code from ipyleaflet import Map, GeoJSON import json m = Map(center=[43.06745, -116.75489], zoom=15) with open('reynolds_geojson_latlon.geojson') as f: data = json.load(f) g = GeoJSON(data=data) m.add_layer(g) m ###Output _____no_output_____ ###Markdown 2) Create pySUMMA Simulation Object ###Code from pysumma.Simulation import Simulation # create a pySUMMA simulation object using the SUMMA 'file manager' input file S = Simulation('../../summaTestCases_2.x/settings/wrrPaperTestCases/figure07/summa_fileManager_riparianAspenSimpleResistance.txt') # set the simulation start and finish times S.decision_obj.simulStart.value = "2007-07-01 00:00" S.decision_obj.simulFinsh.value = "2007-08-20 00:00" ###Output _____no_output_____ ###Markdown 3) Run SUMMA for the different stomatal resistance parameterization options with Developing version of Docker image ###Code # query for the available stomatal resistance parameterizations S.decision_obj.stomResist.options ###Output _____no_output_____ ###Markdown 3.4) assign the Jarvis method ###Code S.decision_obj.stomResist.value = 'Jarvis' S.decision_obj.stomResist.value results_Jarvis, output_path = S.execute(run_suffix="Jarvis_docker", run_option = 'docker_develop') ###Output _____no_output_____ ###Markdown 4. Results Recreate the Figure 7 plot from Clark et al., 2015: The total ET for the three different stomatal resistance methods ###Code from pysumma.Plotting import Plotting from jupyterthemes import jtplot import matplotlib.pyplot as plt import pandas as pd import xarray as xr import numpy as np jtplot.figsize(x=10, y=10) ###Output _____no_output_____ ###Markdown 4.1) Create P attribute using Plotting.py and output_path ###Code # create P attribute P = Plotting(output_path) # create Plot attribute with open_netcdf method Plot = P.open_netcdf() ###Output _____no_output_____ ###Markdown 4.2) Explain output variables There are three structure types of variables 1) variable (time, hru or gru) : [example] pptrate, airtemp, basin__SurfaceRunoff, ...2) variable (time, midToto, hru) : [example] mLayerVolFracIce, mLayerVolFracLiq, mLayerVolFracWat, ... - 'mid' are associated with variables that are specified at the mid-point of each layer (or layer-average) - 'Toto indicate snow layers, soil layers, and all layers,3) variable (time, midSoil, hru) : [example] mLayerMatricHead, mLayerLiqFluxSoil 4) variable (time, ifcToto, hru) : [example] iLayerHeight - 'ifc' are associated with variables that are specified at the interfaces between layers including the very top and bottom 5) variable (time, ifcSoil, hru) : [example] iLayerLiqFluxSoil ###Code # explain output variables Plot ###Output _____no_output_____ ###Markdown 4.3) Plot (variable) ###Code # The case of "1) variable (time, hru or gru)" P.plot_1d('pptrate') ###Output /home/hydro/miniconda3/lib/python3.6/site-packages/xarray/plot/utils.py:51: FutureWarning: 'pandas.tseries.converter.register' has been moved and renamed to 'pandas.plotting.register_matplotlib_converters'. converter.register() ###Markdown 4.4) Plot hru (hru_num, variable) ###Code # The case of "1) variable (time, hru or gru) and more than 2 hru P.plot_1d_hru(0,'airtemp') ###Output _____no_output_____ ###Markdown 4.5) Plot layer (variable) ###Code # the case of 2) variable (time, midToto, hru) : [example] mLayerVolFracIce, mLayerVolFracLiq, mLayerVolFracWat, ... # midToto: 13 test = Plot['mLayerVolFracWat'].data dates = Plot['time'].data # convert data array test = np.squeeze(test) # create df attribute using pandas DataFrame df = pd.DataFrame(data = test, index=dates) df.replace(to_replace=-9999.0, value = 0, inplace=True) # midToto is 13, therefore user can change each layer value from 0 to 12 df[12].plot() P.plot_1d_layer('mLayerVolFracWat') # the case of 3) variable (time, midSoil, hru) : [example] mLayerMatricHead, mLayerLiqFluxSoil # midSoil: 8 test = Plot['mLayerLiqFluxSoil'].data dates = Plot['time'].data # convert data array test = np.squeeze(test) # create df attribute using pandas DataFrame df = pd.DataFrame(data = test, index=dates) df.replace(to_replace=-9999.0, value = 0, inplace=True) # midToto is 13, therefore user can change each layer value from 0 to 12 df[0].plot() P.plot_1d_layer('mLayerLiqFluxSoil') # the case of 4) variable (time, ifcToto, hru) : [example] iLayerHeight # midSoil: 14 test = Plot['iLayerHeight'].data dates = Plot['time'].data # convert data array test = np.squeeze(test) # create df attribute using pandas DataFrame df = pd.DataFrame(data = test, index=dates) df.replace(to_replace=-9999.0, value = 0, inplace=True) # midToto is 13, therefore user can change each layer value from 0 to 12 df[0].plot() P.plot_1d_layer('iLayerHeight') # the case of 5) variable (time, ifcSoil, hru) : [example] iLayerLiqFluxSoil # midSoil: 9 test = Plot['iLayerLiqFluxSoil'].data dates = Plot['time'].data # convert data array test = np.squeeze(test) # create df attribute using pandas DataFrame df = pd.DataFrame(data = test, index=dates) df.replace(to_replace=-9999.0, value = 0, inplace=True) # midToto is 13, therefore user can change each layer value from 0 to 12 df[0].plot() P.plot_1d_layer('iLayerLiqFluxSoil') from pysumma.layers import layers ds = xr.open_dataset(output_path).isel(hru=0) layers(ds.isel(time=slice(0,9)), 'mLayerTemp') layers = ds.nLayers.values.astype('int') max_layers = np.amax(layers) max_layers depths = np.empty((max_layers+1, len(ds.time))) depths depths[:] = np.nan depths[:] vals = np.empty((max_layers, len(ds.time))) vals vals[:] = np.nan vals[:] layer_refs = ['Toto', 'Soil'] for ref in layer_refs: test_coord = 'mid{}'.format(ref) if test_coord in ds['mLayerTemp'].dims: ifcStartIdx = ds['ifc{}'.format(ref)].values midStartIdx = ds['mid{}'.format(ref)].values break else: raise ValueError("Dataset provided doesn't appear to have layers!") ifcStartIdx midStartIdx for i in range(len(ds['time'].values)): start_ifc = int(ifcStartIdx[i]) - 1 start_mid = int(midStartIdx[i]) - 1 end_ifc = start_ifc + int(layers[i]) + 1 end_mid = start_mid + int(layers[i]) depths[0:layers[i]+1, i] = -ds['iLayerHeight'][start_ifc:end_ifc] vals[0:layers[i], i] = ds[var][start_mid:end_mid] len(ds['time'].values) start_ifc = int(ifcStartIdx[i]) - 1 start_ifc start_mid = int(midStartIdx[i]) - 1 start_mid end_ifc = start_ifc + int(layers[i]) + 1 end_ifc end_mid = start_mid + int(layers[i]) end_mid int(layers[i]) depths[0:layers[i]+1, i] -ds['iLayerHeight'] ds['mLayerTemp']. ds['midToto'].values ds['time'].isel(time=slice(0,4)) ###Output _____no_output_____
assets/posts/mass-transfer-modes/MassRadius.ipynb
###Markdown Mass-Radius relationship ###Code from astroutils.matplotlibrc import * %pylab inline from roche_q import calc_qr from scipy.interpolate import interp1d from scipy.optimize import brentq rcParams['font.size'] = 28 rcParams['xtick.major.pad']='8' ###Output _____no_output_____ ###Markdown Nuclear timescales (steep ZAMS) ###Code q, r = calc_qr() roche_relationship = interp1d(q, r) X = np.logspace(.45, .7) Y0 = X**3 / 150 Y1 = X**3 / 40 # Find the intersection of the Roche lobe with the later mass-radius relationship Xprime = brentq(lambda x: roche_relationship(x) - x**3 / 40, 1, 10) # Find the initial radius of this star Yprime0 = Xprime**3 / 150 Yprime1 = Xprime**3 / 40 fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.21, 0.15, 0.74, 0.8]) ax.plot(q, r, c='k') ax.set_xlim([.1, 10]) ax.set_ylim([.1, 10]) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'mass ratio') ax.set_ylabel(r'$R$') ax.plot(X, Y0, c='k') ax.plot(X, Y1, c='k', linestyle='--') # Add an arrow going up ax.arrow(Xprime, Yprime0, 0, Yprime1 - Yprime0, color='k', head_width=.2, head_length=.1, length_includes_head=True, linestyle=':'); ax.text(.15, 1.3, 'Roche lobe', fontsize=14, rotation=-50) ax.text(4, .4, 'ZAMS', fontsize=14, rotation=70) plt.savefig('mass_radius1.png', dpi=240, transparent=True) ###Output _____no_output_____ ###Markdown Thermal timescales (shallow ZAMS) ###Code slope = .5 const1 = 10 const2 = 2 X0 = np.logspace(.25, .75) Y0 = X0**slope / const1 X1 = np.logspace(np.log10(.4), .75) Y1 = X1**slope / const2 # Find the intersection of the Roche lobe with the later mass-radius relationship Xprime1 = brentq(lambda x: roche_relationship(x) - x**slope / const2, 1, 10) # Find the initial radius of this star Yprime0 = Xprime1**slope / const1 Yprime1 = Xprime1**slope / const2 # Find the second intersetion of the Roche lobe with the later mass-radius relationship Xprime2 = brentq(lambda x: roche_relationship(x) - x**slope / const2, .1, 1) Yprime2 = Xprime2**slope / const2 fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.21, 0.15, 0.74, 0.8]) ax.plot(q, r, c='k') ax.set_xlim([.1, 10]) ax.set_ylim([.1, 10]) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'mass ratio') ax.set_ylabel(r'$R$') ax.plot(X0, Y0, c='k') ax.plot(X1, Y1, c='k', linestyle='--') ax.scatter(Xprime2, Yprime2, c='k', s=50) # Add an arrow going up ax.arrow(Xprime1, Yprime0, 0, Yprime1 - Yprime0, color='k', head_width=.2, head_length=.1, length_includes_head=True, linestyle=':') # Add an arrow going along the later mass-radius relationship ax.arrow(Xprime1, Yprime1 + .1, Xprime2 - Xprime1, Yprime2 - .05 - Yprime1, color='k', head_width=Yprime2*.1, head_length=Xprime1*.02, length_includes_head=True, linestyle=':') ax.text(.15, 1.3, 'Roche lobe', fontsize=14, rotation=-50) ax.text(2.5, .15, 'ZAMS', fontsize=14, rotation=25) ax.text(1, .7, '?', fontsize=24) plt.savefig('mass_radius2.png', transparent=True) ###Output _____no_output_____
t81_558_class_12_02_qlearningreinforcement.ipynb
###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$ There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into discrete values. # This is often called binning. We divide the range that the state values # might occupy and assign each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also provide a flag to # indicate if the game should be rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it. To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into # discrete values. This is often called binning. We divide # the range that the state values might occupy and assign # each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also # provide a flag to indicate if the game should be # rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low) \ /DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE \ + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count}" +\ " ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation.$ Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:*$Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?*$s_t$ - The current state.*$r_t$ - The last reward received.*$a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into discrete values. # This is often called binning. We divide the range that the state values # might occupy and assign each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also provide a flag to # indicate if the game should be rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it. To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$ There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into # discrete values. This is often called binning. We divide # the range that the state values might occupy and assign # each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also # provide a flag to indicate if the game should be # rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low) \ /DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE \ + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count}" +\ " ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Deep Learning and Security*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module Video MaterialMain video lecture:* Part 12.1: Introduction to the OpenAI Gym** [[Video]](https://www.youtube.com/playlist?list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/playlist?list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/playlist?list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/playlist?list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/playlist?list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-4.34475245e-01 3.41983158e-04], Reward=-1.0 Step 2: State=[-0.43379375 0.00068149], Reward=-1.0 Step 3: State=[-0.43277768 0.00101607], Reward=-1.0 Step 4: State=[-0.43143437 0.00134331], Reward=-1.0 Step 5: State=[-0.42977352 0.00166085], Reward=-1.0 Step 6: State=[-0.4278071 0.00196642], Reward=-1.0 Step 7: State=[-0.42554927 0.00225783], Reward=-1.0 Step 8: State=[-0.42301625 0.00253302], Reward=-1.0 Step 9: State=[-0.42022621 0.00279004], Reward=-1.0 Step 10: State=[-0.4171991 0.00302712], Reward=-1.0 Step 11: State=[-0.4139565 0.0032426], Reward=-1.0 Step 12: State=[-0.41052146 0.00343503], Reward=-1.0 Step 13: State=[-0.40691834 0.00360312], Reward=-1.0 Step 14: State=[-0.40317256 0.00374578], Reward=-1.0 Step 15: State=[-0.39931045 0.00386211], Reward=-1.0 Step 16: State=[-0.39535906 0.00395139], Reward=-1.0 Step 17: State=[-0.39134591 0.00401315], Reward=-1.0 Step 18: State=[-0.38729884 0.00404707], Reward=-1.0 Step 19: State=[-0.38324577 0.00405307], Reward=-1.0 Step 20: State=[-0.37921452 0.00403125], Reward=-1.0 Step 21: State=[-0.37523261 0.00398192], Reward=-1.0 Step 22: State=[-0.37132706 0.00390555], Reward=-1.0 Step 23: State=[-0.36752424 0.00380282], Reward=-1.0 Step 24: State=[-0.36384968 0.00367456], Reward=-1.0 Step 25: State=[-0.36032789 0.00352178], Reward=-1.0 Step 26: State=[-0.35698226 0.00334563], Reward=-1.0 Step 27: State=[-0.35383486 0.0031474 ], Reward=-1.0 Step 28: State=[-0.35090636 0.0029285 ], Reward=-1.0 Step 29: State=[-0.34821588 0.00269048], Reward=-1.0 Step 30: State=[-0.34578092 0.00243496], Reward=-1.0 Step 31: State=[-0.34361724 0.00216368], Reward=-1.0 Step 32: State=[-0.34173878 0.00187846], Reward=-1.0 Step 33: State=[-0.3401576 0.00158118], Reward=-1.0 Step 34: State=[-0.33888383 0.00127377], Reward=-1.0 Step 35: State=[-0.3379256 0.00095823], Reward=-1.0 Step 36: State=[-0.33728902 0.00063658], Reward=-1.0 Step 37: State=[-3.36978131e-01 3.10886054e-04], Reward=-1.0 Step 38: State=[-3.36994918e-01 -1.67869874e-05], Reward=-1.0 Step 39: State=[-0.33733927 -0.00034435], Reward=-1.0 Step 40: State=[-0.338009 -0.00066973], Reward=-1.0 Step 41: State=[-0.33899985 -0.00099085], Reward=-1.0 Step 42: State=[-0.34030549 -0.00130565], Reward=-1.0 Step 43: State=[-0.3419176 -0.00161211], Reward=-1.0 Step 44: State=[-0.34382585 -0.00190825], Reward=-1.0 Step 45: State=[-0.34601798 -0.00219213], Reward=-1.0 Step 46: State=[-0.34847985 -0.00246187], Reward=-1.0 Step 47: State=[-0.35119552 -0.00271567], Reward=-1.0 Step 48: State=[-0.35414734 -0.00295182], Reward=-1.0 Step 49: State=[-0.357316 -0.00316867], Reward=-1.0 Step 50: State=[-0.36068071 -0.0033647 ], Reward=-1.0 Step 51: State=[-0.36421923 -0.00353852], Reward=-1.0 Step 52: State=[-0.36790806 -0.00368884], Reward=-1.0 Step 53: State=[-0.37172259 -0.00381452], Reward=-1.0 Step 54: State=[-0.37563718 -0.00391459], Reward=-1.0 Step 55: State=[-0.37962539 -0.00398822], Reward=-1.0 Step 56: State=[-0.38366015 -0.00403476], Reward=-1.0 Step 57: State=[-0.38771389 -0.00405374], Reward=-1.0 Step 58: State=[-0.39175877 -0.00404488], Reward=-1.0 Step 59: State=[-0.39576687 -0.0040081 ], Reward=-1.0 Step 60: State=[-0.39971038 -0.00394351], Reward=-1.0 Step 61: State=[-0.40356181 -0.00385143], Reward=-1.0 Step 62: State=[-0.40729418 -0.00373237], Reward=-1.0 Step 63: State=[-0.41088125 -0.00358707], Reward=-1.0 Step 64: State=[-0.41429768 -0.00341643], Reward=-1.0 Step 65: State=[-0.41751926 -0.00322158], Reward=-1.0 Step 66: State=[-0.42052307 -0.00300381], Reward=-1.0 Step 67: State=[-0.42328769 -0.00276462], Reward=-1.0 Step 68: State=[-0.42579334 -0.00250565], Reward=-1.0 Step 69: State=[-0.42802204 -0.00222871], Reward=-1.0 Step 70: State=[-0.4299578 -0.00193575], Reward=-1.0 Step 71: State=[-0.43158665 -0.00162886], Reward=-1.0 Step 72: State=[-0.43289687 -0.00131022], Reward=-1.0 Step 73: State=[-0.43387899 -0.00098212], Reward=-1.0 Step 74: State=[-0.43452591 -0.00064692], Reward=-1.0 Step 75: State=[-4.34832960e-01 -3.07046553e-04], Reward=-1.0 Step 76: State=[-4.34797909e-01 3.50504375e-05], Reward=-1.0 Step 77: State=[-4.34421016e-01 3.76893819e-04], Reward=-1.0 Step 78: State=[-0.43370501 0.00071601], Reward=-1.0 Step 79: State=[-0.43265506 0.00104995], Reward=-1.0 Step 80: State=[-0.43127875 0.0013763 ], Reward=-1.0 Step 81: State=[-0.42958603 0.00169272], Reward=-1.0 Step 82: State=[-0.4275891 0.00199694], Reward=-1.0 Step 83: State=[-0.42530232 0.00228678], Reward=-1.0 Step 84: State=[-0.42274213 0.00256019], Reward=-1.0 Step 85: State=[-0.41992687 0.00281526], Reward=-1.0 Step 86: State=[-0.41687668 0.00305019], Reward=-1.0 Step 87: State=[-0.41361329 0.00326338], Reward=-1.0 Step 88: State=[-0.41015992 0.00345338], Reward=-1.0 Step 89: State=[-0.406541 0.00361891], Reward=-1.0 Step 90: State=[-0.40278209 0.00375891], Reward=-1.0 Step 91: State=[-0.39890959 0.0038725 ], Reward=-1.0 Step 92: State=[-0.3949506 0.00395899], Reward=-1.0 Step 93: State=[-0.3909327 0.0040179], Reward=-1.0 Step 94: State=[-0.38688374 0.00404897], Reward=-1.0 Step 95: State=[-0.38283163 0.00405211], Reward=-1.0 Step 96: State=[-0.37880417 0.00402746], Reward=-1.0 Step 97: State=[-0.37482884 0.00397533], Reward=-1.0 Step 98: State=[-0.37093261 0.00389623], Reward=-1.0 Step 99: State=[-0.36714176 0.00379085], Reward=-1.0 Step 100: State=[-0.36348173 0.00366003], Reward=-1.0 Step 101: State=[-0.35997693 0.00350481], Reward=-1.0 Step 102: State=[-0.35665059 0.00332633], Reward=-1.0 Step 103: State=[-0.35352468 0.00312592], Reward=-1.0 Step 104: State=[-0.35061969 0.00290499], Reward=-1.0 Step 105: State=[-0.3479546 0.00266509], Reward=-1.0 Step 106: State=[-0.34554671 0.00240788], Reward=-1.0 Step 107: State=[-0.34341162 0.0021351 ], Reward=-1.0 Step 108: State=[-0.34156307 0.00184855], Reward=-1.0 Step 109: State=[-0.34001293 0.00155014], Reward=-1.0 Step 110: State=[-0.33877112 0.00124181], Reward=-1.0 Step 111: State=[-0.33784557 0.00092555], Reward=-1.0 Step 112: State=[-0.33724218 0.00060339], Reward=-1.0 Step 113: State=[-3.36964779e-01 2.77398044e-04], Reward=-1.0 Step 114: State=[-3.37015139e-01 -5.03598439e-05], Reward=-1.0 Step 115: State=[-0.33739294 -0.0003778 ], Reward=-1.0 Step 116: State=[-0.33809577 -0.00070283], Reward=-1.0 Step 117: State=[-0.33911917 -0.0010234 ], Reward=-1.0 Step 118: State=[-0.3404566 -0.00133744], Reward=-1.0 Step 119: State=[-0.34209954 -0.00164293], Reward=-1.0 Step 120: State=[-0.34403744 -0.0019379 ], Reward=-1.0 Step 121: State=[-0.34625786 -0.00222042], Reward=-1.0 Step 122: State=[-0.34874647 -0.00248861], Reward=-1.0 Step 123: State=[-0.35148716 -0.00274069], Reward=-1.0 Step 124: State=[-0.35446209 -0.00297493], Reward=-1.0 Step 125: State=[-0.3576518 -0.00318972], Reward=-1.0 Step 126: State=[-0.36103534 -0.00338354], Reward=-1.0 Step 127: State=[-0.36459035 -0.00355501], Reward=-1.0 Step 128: State=[-0.36829321 -0.00370285], Reward=-1.0 Step 129: State=[-0.37211916 -0.00382596], Reward=-1.0 Step 130: State=[-0.37604252 -0.00392335], Reward=-1.0 Step 131: State=[-0.38003675 -0.00399424], Reward=-1.0 Step 132: State=[-0.38407472 -0.00403797], Reward=-1.0 Step 133: State=[-0.38812884 -0.00405411], Reward=-1.0 Step 134: State=[-0.39217123 -0.0040424 ], Reward=-1.0 Step 135: State=[-0.396174 -0.00400276], Reward=-1.0 Step 136: State=[-0.40010934 -0.00393534], Reward=-1.0 Step 137: State=[-0.40394981 -0.00384047], Reward=-1.0 Step 138: State=[-0.4076685 -0.00371869], Reward=-1.0 Step 139: State=[-0.41123925 -0.00357075], Reward=-1.0 Step 140: State=[-0.41463682 -0.00339758], Reward=-1.0 Step 141: State=[-0.41783713 -0.00320031], Reward=-1.0 Step 142: State=[-0.42081742 -0.00298028], Reward=-1.0 Step 143: State=[-0.42355641 -0.00273899], Reward=-1.0 Step 144: State=[-0.4260345 -0.00247809], Reward=-1.0 Step 145: State=[-0.42823392 -0.00219942], Reward=-1.0 Step 146: State=[-0.43013886 -0.00190494], Reward=-1.0 Step 147: State=[-0.4317356 -0.00159674], Reward=-1.0 Step 148: State=[-0.43301262 -0.00127703], Reward=-1.0 Step 149: State=[-0.43396072 -0.00094809], Reward=-1.0 Step 150: State=[-0.43457302 -0.0006123 ], Reward=-1.0 Step 151: State=[-4.34845105e-01 -2.72086653e-04], Reward=-1.0 Step 152: State=[-4.34775007e-01 7.00982155e-05], Reward=-1.0 Step 153: State=[-4.34363231e-01 4.11775888e-04], Reward=-1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 1 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-4.64341884e-01 -4.45376842e-04], Reward=-1.0 Step 2: State=[-0.46522935 -0.00088747], Reward=-1.0 Step 3: State=[-0.46655235 -0.001323 ], Reward=-1.0 Step 4: State=[-0.46830112 -0.00174877], Reward=-1.0 Step 5: State=[-0.47046272 -0.0021616 ], Reward=-1.0 Step 6: State=[-0.47302115 -0.00255843], Reward=-1.0 Step 7: State=[-0.47595746 -0.00293631], Reward=-1.0 Step 8: State=[-0.47924987 -0.00329241], Reward=-1.0 Step 9: State=[-0.48287391 -0.00362404], Reward=-1.0 Step 10: State=[-0.48680263 -0.00392872], Reward=-1.0 Step 11: State=[-0.49100676 -0.00420413], Reward=-1.0 Step 12: State=[-0.49545495 -0.00444818], Reward=-1.0 Step 13: State=[-0.50011396 -0.00465901], Reward=-1.0 Step 14: State=[-0.50494896 -0.004835 ], Reward=-1.0 Step 15: State=[-0.50992376 -0.0049748 ], Reward=-1.0 Step 16: State=[-0.51500109 -0.00507733], Reward=-1.0 Step 17: State=[-0.5201429 -0.00514181], Reward=-1.0 Step 18: State=[-0.52531063 -0.00516773], Reward=-1.0 Step 19: State=[-0.53046552 -0.00515489], Reward=-1.0 Step 20: State=[-0.53556891 -0.00510339], Reward=-1.0 Step 21: State=[-0.54058255 -0.00501364], Reward=-1.0 Step 22: State=[-0.54546886 -0.00488631], Reward=-1.0 Step 23: State=[-0.55019127 -0.00472241], Reward=-1.0 Step 24: State=[-0.55471444 -0.00452317], Reward=-1.0 Step 25: State=[-0.55900458 -0.00429014], Reward=-1.0 Step 26: State=[-0.56302968 -0.0040251 ], Reward=-1.0 Step 27: State=[-0.56675974 -0.00373006], Reward=-1.0 Step 28: State=[-0.57016699 -0.00340725], Reward=-1.0 Step 29: State=[-0.57322612 -0.00305913], Reward=-1.0 Step 30: State=[-0.57591442 -0.0026883 ], Reward=-1.0 Step 31: State=[-0.57821195 -0.00229754], Reward=-1.0 Step 32: State=[-0.58010172 -0.00188977], Reward=-1.0 Step 33: State=[-0.58156974 -0.00146802], Reward=-1.0 Step 34: State=[-0.58260517 -0.00103543], Reward=-1.0 Step 35: State=[-0.58320036 -0.00059519], Reward=-1.0 Step 36: State=[-5.83350916e-01 -1.50554466e-04], Reward=-1.0 Step 37: State=[-5.83055725e-01 2.95190429e-04], Reward=-1.0 Step 38: State=[-0.58131697 0.00173876], Reward=-1.0 Step 39: State=[-0.57814749 0.00316948], Reward=-1.0 Step 40: State=[-0.57357071 0.00457677], Reward=-1.0 Step 41: State=[-0.56762055 0.00595016], Reward=-1.0 Step 42: State=[-0.56034118 0.00727937], Reward=-1.0 Step 43: State=[-0.5517868 0.00855438], Reward=-1.0 Step 44: State=[-0.54202127 0.00976554], Reward=-1.0 Step 45: State=[-0.53111764 0.01090363], Reward=-1.0 Step 46: State=[-0.51915762 0.01196002], Reward=-1.0 Step 47: State=[-0.5062309 0.01292671], Reward=-1.0 Step 48: State=[-0.49243439 0.01379651], Reward=-1.0 Step 49: State=[-0.47787127 0.01456312], Reward=-1.0 Step 50: State=[-0.46265003 0.01522124], Reward=-1.0 Step 51: State=[-0.44688337 0.01576667], Reward=-1.0 Step 52: State=[-0.430687 0.01619637], Reward=-1.0 Step 53: State=[-0.41417849 0.01650852], Reward=-1.0 Step 54: State=[-0.39747596 0.01670252], Reward=-1.0 Step 55: State=[-0.38069695 0.01677901], Reward=-1.0 Step 56: State=[-0.36395718 0.01673978], Reward=-1.0 Step 57: State=[-0.34736946 0.01658771], Reward=-1.0 Step 58: State=[-0.33104275 0.01632671], Reward=-1.0 Step 59: State=[-0.31508122 0.01596153], Reward=-1.0 Step 60: State=[-0.29958355 0.01549767], Reward=-1.0 Step 61: State=[-0.28464235 0.0149412 ], Reward=-1.0 Step 62: State=[-0.27034373 0.01429863], Reward=-1.0 Step 63: State=[-0.25676698 0.01357675], Reward=-1.0 Step 64: State=[-0.24398448 0.0127825 ], Reward=-1.0 Step 65: State=[-0.23206166 0.01192282], Reward=-1.0 Step 66: State=[-0.22105707 0.01100459], Reward=-1.0 Step 67: State=[-0.21102259 0.01003448], Reward=-1.0 Step 68: State=[-0.20200366 0.00901894], Reward=-1.0 Step 69: State=[-0.19403954 0.00796412], Reward=-1.0 Step 70: State=[-0.18716367 0.00687587], Reward=-1.0 Step 71: State=[-0.18140396 0.00575971], Reward=-1.0 Step 72: State=[-0.17678308 0.00462087], Reward=-1.0 Step 73: State=[-0.17331878 0.0034643 ], Reward=-1.0 Step 74: State=[-0.17102409 0.0022947 ], Reward=-1.0 Step 75: State=[-0.16990749 0.0011166 ], Reward=-1.0 Step 76: State=[-1.69973098e-01 -6.56048800e-05], Reward=-1.0 Step 77: State=[-0.17222066 -0.00224756], Reward=-1.0 Step 78: State=[-0.17664191 -0.00442125], Reward=-1.0 Step 79: State=[-0.18322027 -0.00657836], Reward=-1.0 Step 80: State=[-0.19193038 -0.00871011], Reward=-1.0 Step 81: State=[-0.2027374 -0.01080702], Reward=-1.0 Step 82: State=[-0.21559609 -0.01285869], Reward=-1.0 Step 83: State=[-0.23044985 -0.01485375], Reward=-1.0 Step 84: State=[-0.24722956 -0.01677972], Reward=-1.0 Step 85: State=[-0.26585261 -0.01862304], Reward=-1.0 Step 86: State=[-0.28622179 -0.02036918], Reward=-1.0 Step 87: State=[-0.30822459 -0.0220028 ], Reward=-1.0 Step 88: State=[-0.33173263 -0.02350804], Reward=-1.0 Step 89: State=[-0.35660151 -0.02486888], Reward=-1.0 Step 90: State=[-0.38267114 -0.02606962], Reward=-1.0 Step 91: State=[-0.40976651 -0.02709537], Reward=-1.0 Step 92: State=[-0.43769913 -0.02793262], Reward=-1.0 Step 93: State=[-0.46626888 -0.02856976], Reward=-1.0 Step 94: State=[-0.4952665 -0.02899761], Reward=-1.0 Step 95: State=[-0.52447635 -0.02920985], Reward=-1.0 Step 96: State=[-0.55367962 -0.02920327], Reward=-1.0 Step 97: State=[-0.58265759 -0.02897797], Reward=-1.0 Step 98: State=[-0.61119493 -0.02853734], Reward=-1.0 Step 99: State=[-0.63908283 -0.02788791], Reward=-1.0 Step 100: State=[-0.66612183 -0.027039 ], Reward=-1.0 Step 101: State=[-0.69212418 -0.02600235], Reward=-1.0 Step 102: State=[-0.71691575 -0.02479157], Reward=-1.0 Step 103: State=[-0.74033736 -0.02342161], Reward=-1.0 Step 104: State=[-0.76224558 -0.02190822], Reward=-1.0 Step 105: State=[-0.78251298 -0.0202674 ], Reward=-1.0 Step 106: State=[-0.80102798 -0.018515 ], Reward=-1.0 Step 107: State=[-0.81769429 -0.01666632], Reward=-1.0 Step 108: State=[-0.83243012 -0.01473583], Reward=-1.0 Step 109: State=[-0.84516716 -0.01273703], Reward=-1.0 Step 110: State=[-0.85584949 -0.01068233], Reward=-1.0 Step 111: State=[-0.86443254 -0.00858305], Reward=-1.0 Step 112: State=[-0.87088206 -0.00644952], Reward=-1.0 Step 113: State=[-0.87517322 -0.00429117], Reward=-1.0 Step 114: State=[-0.87728998 -0.00211676], Reward=-1.0 Step 115: State=[-8.77224540e-01 6.54411254e-05], Reward=-1.0 Step 116: State=[-0.87397714 0.0032474 ], Reward=-1.0 Step 117: State=[-0.86755977 0.00641737], Reward=-1.0 Step 118: State=[-0.85799673 0.00956304], Reward=-1.0 Step 119: State=[-0.84532571 0.01267102], Reward=-1.0 Step 120: State=[-0.82959932 0.0157264 ], Reward=-1.0 Step 121: State=[-0.81088695 0.01871237], Reward=-1.0 Step 122: State=[-0.78927693 0.02161002], Reward=-1.0 Step 123: State=[-0.7648787 0.02439823], Reward=-1.0 Step 124: State=[-0.7378248 0.0270539], Reward=-1.0 Step 125: State=[-0.70827255 0.02955225], Reward=-1.0 Step 126: State=[-0.67640502 0.03186753], Reward=-1.0 Step 127: State=[-0.64243116 0.03397386], Reward=-1.0 Step 128: State=[-0.60658482 0.03584634], Reward=-1.0 Step 129: State=[-0.56912249 0.03746233], Reward=-1.0 Step 130: State=[-0.5303198 0.03880269], Reward=-1.0 Step 131: State=[-0.4904667 0.0398531], Reward=-1.0 Step 132: State=[-0.44986168 0.04060502], Reward=-1.0 Step 133: State=[-0.40880519 0.04105649], Reward=-1.0 Step 134: State=[-0.36759274 0.04121245], Reward=-1.0 Step 135: State=[-0.32650808 0.04108466], Reward=-1.0 Step 136: State=[-0.28581697 0.04069111], Reward=-1.0 Step 137: State=[-0.24576177 0.0400552 ], Reward=-1.0 Step 138: State=[-0.20655732 0.03920446], Reward=-1.0 Step 139: State=[-0.16838803 0.03816928], Reward=-1.0 Step 140: State=[-0.13140649 0.03698154], Reward=-1.0 Step 141: State=[-0.09573318 0.0356733 ], Reward=-1.0 Step 142: State=[-0.06145748 0.0342757 ], Reward=-1.0 Step 143: State=[-0.02863941 0.03281807], Reward=-1.0 Step 144: State=[0.00268788 0.03132729], Reward=-1.0 Step 145: State=[0.03251526 0.02982738], Reward=-1.0 Step 146: State=[0.06085452 0.02833926], Reward=-1.0 Step 147: State=[0.08773532 0.02688081], Reward=-1.0 Step 148: State=[0.11320223 0.0254669 ], Reward=-1.0 Step 149: State=[0.13731192 0.02410969], Reward=-1.0 Step 150: State=[0.16013074 0.02281882], Reward=-1.0 Step 151: State=[0.18173253 0.02160179], Reward=-1.0 Step 152: State=[0.20219675 0.02046422], Reward=-1.0 Step 153: State=[0.22160698 0.01941023], Reward=-1.0 Step 154: State=[0.24004965 0.01844266], Reward=-1.0 Step 155: State=[0.25761304 0.0175634 ], Reward=-1.0 ###Markdown Reinforcement Learning![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined.$ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df DISCRETE_OS_SIZE[0] np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Deep Learning and Security*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.54298351 0.00115394], Reward=-1.0 Step 2: State=[-0.54068426 0.00229925], Reward=-1.0 Step 3: State=[-0.53725693 0.00342733], Reward=-1.0 Step 4: State=[-0.53272719 0.00452974], Reward=-1.0 Step 5: State=[-0.527129 0.00559819], Reward=-1.0 Step 6: State=[-0.52050433 0.00662467], Reward=-1.0 Step 7: State=[-0.51290287 0.00760146], Reward=-1.0 Step 8: State=[-0.50438161 0.00852126], Reward=-1.0 Step 9: State=[-0.4950044 0.00937721], Reward=-1.0 Step 10: State=[-0.48484139 0.01016301], Reward=-1.0 Step 11: State=[-0.47396841 0.01087299], Reward=-1.0 Step 12: State=[-0.46246627 0.01150213], Reward=-1.0 Step 13: State=[-0.45042007 0.0120462 ], Reward=-1.0 Step 14: State=[-0.43791831 0.01250176], Reward=-1.0 Step 15: State=[-0.4250521 0.01286621], Reward=-1.0 Step 16: State=[-0.41191426 0.01313783], Reward=-1.0 Step 17: State=[-0.39859848 0.01331578], Reward=-1.0 Step 18: State=[-0.38519838 0.0134001 ], Reward=-1.0 Step 19: State=[-0.37180672 0.01339166], Reward=-1.0 Step 20: State=[-0.35851456 0.01329216], Reward=-1.0 Step 21: State=[-0.34541053 0.01310403], Reward=-1.0 Step 22: State=[-0.33258017 0.01283036], Reward=-1.0 Step 23: State=[-0.32010531 0.01247486], Reward=-1.0 Step 24: State=[-0.30806361 0.0120417 ], Reward=-1.0 Step 25: State=[-0.29652811 0.0115355 ], Reward=-1.0 Step 26: State=[-0.28556694 0.01096116], Reward=-1.0 Step 27: State=[-0.27524312 0.01032383], Reward=-1.0 Step 28: State=[-0.26561434 0.00962878], Reward=-1.0 Step 29: State=[-0.25673298 0.00888136], Reward=-1.0 Step 30: State=[-0.24864606 0.00808693], Reward=-1.0 Step 31: State=[-0.24139526 0.0072508 ], Reward=-1.0 Step 32: State=[-0.23501706 0.0063782 ], Reward=-1.0 Step 33: State=[-0.22954281 0.00547425], Reward=-1.0 Step 34: State=[-0.22499885 0.00454396], Reward=-1.0 Step 35: State=[-0.22140666 0.00359218], Reward=-1.0 Step 36: State=[-0.21878297 0.00262369], Reward=-1.0 Step 37: State=[-0.21713985 0.00164313], Reward=-1.0 Step 38: State=[-0.21648478 0.00065507], Reward=-1.0 Step 39: State=[-0.21682075 -0.00033597], Reward=-1.0 Step 40: State=[-0.21814623 -0.00132548], Reward=-1.0 Step 41: State=[-0.22045518 -0.00230895], Reward=-1.0 Step 42: State=[-0.22373702 -0.00328184], Reward=-1.0 Step 43: State=[-0.22797653 -0.00423951], Reward=-1.0 Step 44: State=[-0.23315378 -0.00517725], Reward=-1.0 Step 45: State=[-0.239244 -0.00609022], Reward=-1.0 Step 46: State=[-0.24621747 -0.00697347], Reward=-1.0 Step 47: State=[-0.25403939 -0.00782191], Reward=-1.0 Step 48: State=[-0.26266974 -0.00863035], Reward=-1.0 Step 49: State=[-0.27206323 -0.0093935 ], Reward=-1.0 Step 50: State=[-0.28216923 -0.010106 ], Reward=-1.0 Step 51: State=[-0.29293174 -0.01076251], Reward=-1.0 Step 52: State=[-0.30428945 -0.01135771], Reward=-1.0 Step 53: State=[-0.31617585 -0.0118864 ], Reward=-1.0 Step 54: State=[-0.32851945 -0.0123436 ], Reward=-1.0 Step 55: State=[-0.34124405 -0.0127246 ], Reward=-1.0 Step 56: State=[-0.3542691 -0.01302505], Reward=-1.0 Step 57: State=[-0.36751021 -0.01324111], Reward=-1.0 Step 58: State=[-0.38087966 -0.01336945], Reward=-1.0 Step 59: State=[-0.3942871 -0.01340744], Reward=-1.0 Step 60: State=[-0.40764024 -0.01335314], Reward=-1.0 Step 61: State=[-0.42084563 -0.01320539], Reward=-1.0 Step 62: State=[-0.43380952 -0.01296389], Reward=-1.0 Step 63: State=[-0.44643872 -0.0126292 ], Reward=-1.0 Step 64: State=[-0.45864146 -0.01220274], Reward=-1.0 Step 65: State=[-0.47032831 -0.01168684], Reward=-1.0 Step 66: State=[-0.48141298 -0.01108468], Reward=-1.0 Step 67: State=[-0.49181321 -0.01040022], Reward=-1.0 Step 68: State=[-0.50145146 -0.00963826], Reward=-1.0 Step 69: State=[-0.5102557 -0.00880424], Reward=-1.0 Step 70: State=[-0.51815998 -0.00790428], Reward=-1.0 Step 71: State=[-0.52510506 -0.00694507], Reward=-1.0 Step 72: State=[-0.53103883 -0.00593378], Reward=-1.0 Step 73: State=[-0.53591681 -0.00487798], Reward=-1.0 Step 74: State=[-0.53970243 -0.00378562], Reward=-1.0 Step 75: State=[-0.54236732 -0.00266489], Reward=-1.0 Step 76: State=[-0.54389151 -0.0015242 ], Reward=-1.0 Step 77: State=[-5.44263607e-01 -3.72094556e-04], Reward=-1.0 Step 78: State=[-0.54348081 0.00078279], Reward=-1.0 Step 79: State=[-0.541549 0.00193182], Reward=-1.0 Step 80: State=[-0.53848261 0.00306638], Reward=-1.0 Step 81: State=[-0.53430464 0.00417797], Reward=-1.0 Step 82: State=[-0.52904639 0.00525825], Reward=-1.0 Step 83: State=[-0.52274728 0.00629911], Reward=-1.0 Step 84: State=[-0.51545456 0.00729272], Reward=-1.0 Step 85: State=[-0.50722291 0.00823165], Reward=-1.0 Step 86: State=[-0.49811404 0.00910888], Reward=-1.0 Step 87: State=[-0.48819611 0.00991793], Reward=-1.0 Step 88: State=[-0.4775432 0.01065291], Reward=-1.0 Step 89: State=[-0.46623461 0.01130859], Reward=-1.0 Step 90: State=[-0.45435414 0.01188048], Reward=-1.0 Step 91: State=[-0.44198927 0.01236487], Reward=-1.0 Step 92: State=[-0.42923038 0.01275889], Reward=-1.0 Step 93: State=[-0.41616983 0.01306055], Reward=-1.0 Step 94: State=[-0.40290112 0.01326871], Reward=-1.0 Step 95: State=[-0.389518 0.01338313], Reward=-1.0 Step 96: State=[-0.37611358 0.01340442], Reward=-1.0 Step 97: State=[-0.36277956 0.01333402], Reward=-1.0 Step 98: State=[-0.34960543 0.01317413], Reward=-1.0 Step 99: State=[-0.3366778 0.01292763], Reward=-1.0 Step 100: State=[-0.32407975 0.01259805], Reward=-1.0 Step 101: State=[-0.31189033 0.01218942], Reward=-1.0 Step 102: State=[-0.3001841 0.01170623], Reward=-1.0 Step 103: State=[-0.28903082 0.01115328], Reward=-1.0 Step 104: State=[-0.27849515 0.01053567], Reward=-1.0 Step 105: State=[-0.26863652 0.00985862], Reward=-1.0 Step 106: State=[-0.25950904 0.00912749], Reward=-1.0 Step 107: State=[-0.25116142 0.00834761], Reward=-1.0 Step 108: State=[-0.24363708 0.00752434], Reward=-1.0 Step 109: State=[-0.23697416 0.00666292], Reward=-1.0 Step 110: State=[-0.23120564 0.00576852], Reward=-1.0 Step 111: State=[-0.22635946 0.00484618], Reward=-1.0 Step 112: State=[-0.22245866 0.0039008 ], Reward=-1.0 Step 113: State=[-0.21952148 0.00293718], Reward=-1.0 Step 114: State=[-0.21756149 0.00196 ], Reward=-1.0 Step 115: State=[-0.21658763 0.00097386], Reward=-1.0 Step 116: State=[-2.16604342e-01 -1.67115330e-05], Reward=-1.0 Step 117: State=[-0.21761155 -0.0010072 ], Reward=-1.0 Step 118: State=[-0.21960466 -0.00199312], Reward=-1.0 Step 119: State=[-0.22257458 -0.00296991], Reward=-1.0 Step 120: State=[-0.22650757 -0.003933 ], Reward=-1.0 Step 121: State=[-0.23138525 -0.00487768], Reward=-1.0 Step 122: State=[-0.23718442 -0.00579916], Reward=-1.0 Step 123: State=[-0.24387695 -0.00669253], Reward=-1.0 Step 124: State=[-0.2514297 -0.00755275], Reward=-1.0 Step 125: State=[-0.25980435 -0.00837465], Reward=-1.0 Step 126: State=[-0.26895731 -0.00915296], Reward=-1.0 Step 127: State=[-0.27883967 -0.00988236], Reward=-1.0 Step 128: State=[-0.28939716 -0.01055749], Reward=-1.0 Step 129: State=[-0.30057017 -0.01117301], Reward=-1.0 Step 130: State=[-0.31229385 -0.01172368], Reward=-1.0 Step 131: State=[-0.32449829 -0.01220444], Reward=-1.0 Step 132: State=[-0.33710877 -0.01261047], Reward=-1.0 Step 133: State=[-0.35004609 -0.01293732], Reward=-1.0 Step 134: State=[-0.36322703 -0.01318094], Reward=-1.0 Step 135: State=[-0.3765649 -0.01333787], Reward=-1.0 Step 136: State=[-0.3899701 -0.0134052], Reward=-1.0 Step 137: State=[-0.40335089 -0.01338079], Reward=-1.0 Step 138: State=[-0.41661411 -0.01326322], Reward=-1.0 Step 139: State=[-0.429666 -0.0130519], Reward=-1.0 Step 140: State=[-0.44241311 -0.0127471 ], Reward=-1.0 Step 141: State=[-0.4547631 -0.01235 ], Reward=-1.0 Step 142: State=[-0.4666257 -0.0118626], Reward=-1.0 Step 143: State=[-0.47791353 -0.01128782], Reward=-1.0 Step 144: State=[-0.48854292 -0.01062939], Reward=-1.0 Step 145: State=[-0.49843474 -0.00989182], Reward=-1.0 Step 146: State=[-0.50751511 -0.00908037], Reward=-1.0 Step 147: State=[-0.51571607 -0.00820096], Reward=-1.0 Step 148: State=[-0.52297614 -0.00726007], Reward=-1.0 Step 149: State=[-0.52924088 -0.00626474], Reward=-1.0 Step 150: State=[-0.53446331 -0.00522243], Reward=-1.0 Step 151: State=[-0.53860426 -0.00414096], Reward=-1.0 Step 152: State=[-0.54163272 -0.00302845], Reward=-1.0 Step 153: State=[-0.54352598 -0.00189327], Reward=-1.0 Step 154: State=[-0.54426988 -0.0007439 ], Reward=-1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.51431373 -0.00107771], Reward=-1.0 Step 2: State=[-0.51646107 -0.00214734], Reward=-1.0 Step 3: State=[-0.51966193 -0.00320087], Reward=-1.0 Step 4: State=[-0.52389233 -0.00423039], Reward=-1.0 Step 5: State=[-0.52912052 -0.00522819], Reward=-1.0 Step 6: State=[-0.53530729 -0.00618678], Reward=-1.0 Step 7: State=[-0.54240628 -0.00709898], Reward=-1.0 Step 8: State=[-0.55036428 -0.007958 ], Reward=-1.0 Step 9: State=[-0.55912175 -0.00875748], Reward=-1.0 Step 10: State=[-0.56861331 -0.00949156], Reward=-1.0 Step 11: State=[-0.57876828 -0.01015497], Reward=-1.0 Step 12: State=[-0.58951137 -0.01074309], Reward=-1.0 Step 13: State=[-0.60076333 -0.01125196], Reward=-1.0 Step 14: State=[-0.61244171 -0.01167838], Reward=-1.0 Step 15: State=[-0.62446163 -0.01201992], Reward=-1.0 Step 16: State=[-0.63673657 -0.01227494], Reward=-1.0 Step 17: State=[-0.64917917 -0.0124426 ], Reward=-1.0 Step 18: State=[-0.66170205 -0.01252287], Reward=-1.0 Step 19: State=[-0.67421853 -0.01251648], Reward=-1.0 Step 20: State=[-0.68664341 -0.01242488], Reward=-1.0 Step 21: State=[-0.69889363 -0.01225023], Reward=-1.0 Step 22: State=[-0.71088891 -0.01199528], Reward=-1.0 Step 23: State=[-0.72255227 -0.01166336], Reward=-1.0 Step 24: State=[-0.73381051 -0.01125823], Reward=-1.0 Step 25: State=[-0.7445946 -0.01078409], Reward=-1.0 Step 26: State=[-0.75484 -0.0102454], Reward=-1.0 Step 27: State=[-0.76448689 -0.00964689], Reward=-1.0 Step 28: State=[-0.77348032 -0.00899343], Reward=-1.0 Step 29: State=[-0.78177031 -0.00828998], Reward=-1.0 Step 30: State=[-0.78931187 -0.00754156], Reward=-1.0 Step 31: State=[-0.79606502 -0.00675316], Reward=-1.0 Step 32: State=[-0.80199476 -0.00592974], Reward=-1.0 Step 33: State=[-0.80707094 -0.00507618], Reward=-1.0 Step 34: State=[-0.81126824 -0.00419729], Reward=-1.0 Step 35: State=[-0.81456603 -0.00329779], Reward=-1.0 Step 36: State=[-0.81694832 -0.0023823 ], Reward=-1.0 Step 37: State=[-0.81840369 -0.00145537], Reward=-1.0 Step 38: State=[-8.18925204e-01 -5.21510941e-04], Reward=-1.0 Step 39: State=[-8.18510378e-01 4.14826025e-04], Reward=-1.0 Step 40: State=[-0.81516118 0.00334919], Reward=-1.0 Step 41: State=[-0.80889363 0.00626755], Reward=-1.0 Step 42: State=[-0.7997382 0.00915543], Reward=-1.0 Step 43: State=[-0.78774062 0.01199759], Reward=-1.0 Step 44: State=[-0.77296289 0.01477773], Reward=-1.0 Step 45: State=[-0.75548455 0.01747834], Reward=-1.0 Step 46: State=[-0.73540399 0.02008056], Reward=-1.0 Step 47: State=[-0.71283965 0.02256434], Reward=-1.0 Step 48: State=[-0.68793102 0.02490863], Reward=-1.0 Step 49: State=[-0.66083923 0.0270918 ], Reward=-1.0 Step 50: State=[-0.63174696 0.02909226], Reward=-1.0 Step 51: State=[-0.60085774 0.03088922], Reward=-1.0 Step 52: State=[-0.56839425 0.03246349], Reward=-1.0 Step 53: State=[-0.53459581 0.03379844], Reward=-1.0 Step 54: State=[-0.49971491 0.03488091], Reward=-1.0 Step 55: State=[-0.46401297 0.03570193], Reward=-1.0 Step 56: State=[-0.42775556 0.03625741], Reward=-1.0 Step 57: State=[-0.39120711 0.03654845], Reward=-1.0 Step 58: State=[-0.35462569 0.03658142], Reward=-1.0 Step 59: State=[-0.31825799 0.0363677 ], Reward=-1.0 Step 60: State=[-0.28233478 0.03592322], Reward=-1.0 Step 61: State=[-0.24706714 0.03526764], Reward=-1.0 Step 62: State=[-0.21264364 0.0344235 ], Reward=-1.0 Step 63: State=[-0.17922847 0.03341517], Reward=-1.0 Step 64: State=[-0.14696054 0.03226793], Reward=-1.0 Step 65: State=[-0.11595355 0.03100699], Reward=-1.0 Step 66: State=[-0.08629682 0.02965673], Reward=-1.0 Step 67: State=[-0.05805677 0.02824004], Reward=-1.0 Step 68: State=[-0.03127891 0.02677787], Reward=-1.0 Step 69: State=[-0.00599004 0.02528887], Reward=-1.0 Step 70: State=[0.01779923 0.02378927], Reward=-1.0 Step 71: State=[0.04009206 0.02229283], Reward=-1.0 Step 72: State=[0.06090295 0.02081089], Reward=-1.0 Step 73: State=[0.08025546 0.01935251], Reward=-1.0 Step 74: State=[0.09818008 0.01792462], Reward=-1.0 Step 75: State=[0.11471236 0.01653228], Reward=-1.0 Step 76: State=[0.12989122 0.01517886], Reward=-1.0 Step 77: State=[0.14375749 0.01386628], Reward=-1.0 Step 78: State=[0.15635269 0.01259519], Reward=-1.0 Step 79: State=[0.16771789 0.01136521], Reward=-1.0 Step 80: State=[0.17789293 0.01017504], Reward=-1.0 Step 81: State=[0.18691562 0.00902269], Reward=-1.0 Step 82: State=[0.19482116 0.00790554], Reward=-1.0 Step 83: State=[0.20164168 0.00682052], Reward=-1.0 Step 84: State=[0.20740583 0.00576416], Reward=-1.0 Step 85: State=[0.21213852 0.00473269], Reward=-1.0 Step 86: State=[0.21586063 0.00372211], Reward=-1.0 Step 87: State=[0.21858888 0.00272825], Reward=-1.0 Step 88: State=[0.22033568 0.0017468 ], Reward=-1.0 Step 89: State=[0.22110904 0.00077336], Reward=-1.0 Step 90: State=[ 2.20912527e-01 -1.96509754e-04], Reward=-1.0 Step 91: State=[ 0.21774524 -0.00316729], Reward=-1.0 Step 92: State=[ 0.21159265 -0.00615259], Reward=-1.0 Step 93: State=[ 0.20242705 -0.0091656 ], Reward=-1.0 Step 94: State=[ 0.19020845 -0.01221861], Reward=-1.0 Step 95: State=[ 0.17488593 -0.01532251], Reward=-1.0 Step 96: State=[ 0.15639968 -0.01848625], Reward=-1.0 Step 97: State=[ 0.1346836 -0.02171608], Reward=-1.0 Step 98: State=[ 0.10966883 -0.02501477], Reward=-1.0 Step 99: State=[ 0.08128815 -0.02838068], Reward=-1.0 Step 100: State=[ 0.04948145 -0.03180671], Reward=-1.0 Step 101: State=[ 0.01420223 -0.03527921], Reward=-1.0 Step 102: State=[-0.02457471 -0.03877695], Reward=-1.0 Step 103: State=[-0.06684487 -0.04227015], Reward=-1.0 Step 104: State=[-0.11256492 -0.04572006], Reward=-1.0 Step 105: State=[-0.16164378 -0.04907886], Reward=-1.0 Step 106: State=[-0.21393441 -0.05229063], Reward=-1.0 Step 107: State=[-0.26922758 -0.05529317], Reward=-1.0 Step 108: State=[-0.32724868 -0.05802111], Reward=-1.0 Step 109: State=[-0.38765872 -0.06041004], Reward=-1.0 Step 110: State=[-0.45006028 -0.06240156], Reward=-1.0 Step 111: State=[-0.51400891 -0.06394863], Reward=-1.0 Step 112: State=[-0.57902946 -0.06502055], Reward=-1.0 Step 113: State=[-0.64463619 -0.06560673], Reward=-1.0 Step 114: State=[-0.71035496 -0.06571877], Reward=-1.0 Step 115: State=[-0.77574519 -0.06539023], Reward=-1.0 Step 116: State=[-0.84041959 -0.06467439], Reward=-1.0 Step 117: State=[-0.90405977 -0.06364018], Reward=-1.0 Step 118: State=[-0.96642693 -0.06236716], Reward=-1.0 Step 119: State=[-1.02736712 -0.06094019], Reward=-1.0 Step 120: State=[-1.08681173 -0.05944462], Reward=-1.0 Step 121: State=[-1.14477398 -0.05796225], Reward=-1.0 Step 122: State=[-1.2 0. ], Reward=-1.0 Step 123: State=[-1.1987581 0.0012419], Reward=-1.0 Step 124: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 125: State=[-1.18652173 0.00774848], Reward=-1.0 Step 126: State=[-1.17548846 0.01103326], Reward=-1.0 Step 127: State=[-1.16113808 0.01435038], Reward=-1.0 Step 128: State=[-1.14343234 0.01770574], Reward=-1.0 Step 129: State=[-1.12233007 0.02110228], Reward=-1.0 Step 130: State=[-1.09779103 0.02453904], Reward=-1.0 Step 131: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 132: State=[-1.03827616 0.03150456], Reward=-1.0 Step 133: State=[-1.0032725 0.03500367], Reward=-1.0 Step 134: State=[-0.9647905 0.03848199], Reward=-1.0 Step 135: State=[-0.92288452 0.04190598], Reward=-1.0 Step 136: State=[-0.87765038 0.04523414], Reward=-1.0 Step 137: State=[-0.82923273 0.04841765], Reward=-1.0 Step 138: State=[-0.77783078 0.05140195], Reward=-1.0 Step 139: State=[-0.72370164 0.05412914], Reward=-1.0 Step 140: State=[-0.66716026 0.05654138], Reward=-1.0 Step 141: State=[-0.60857514 0.05858511], Reward=-1.0 Step 142: State=[-0.54835959 0.06021555], Reward=-1.0 Step 143: State=[-0.4869585 0.06140109], Reward=-1.0 Step 144: State=[-0.42483166 0.06212684], Reward=-1.0 Step 145: State=[-0.36243478 0.06239688], Reward=-1.0 Step 146: State=[-0.30020009 0.06223469], Reward=-1.0 Step 147: State=[-0.23851824 0.06168185], Reward=-1.0 Step 148: State=[-0.17772322 0.06079502], Reward=-1.0 Step 149: State=[-0.1180812 0.05964202], Reward=-1.0 Step 150: State=[-0.05978395 0.05829725], Reward=-1.0 Step 151: State=[-0.0029466 0.05683735], Reward=-1.0 Step 152: State=[0.05239085 0.05533745], Reward=-1.0 ###Markdown Reinforcement Learning![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined. $ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False # HIDE OUTPUT if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q gym !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents !pip install -q pygame ###Output Reading package lists... Done Building dependency tree Reading state information... Done ffmpeg is already the newest version (7:3.4.8-0ubuntu0.2). Suggested packages: mesa-utils The following NEW packages will be installed: libxxf86dga1 x11-utils xvfb 0 upgraded, 3 newly installed, 0 to remove and 39 not upgraded. Need to get 993 kB of archives. After this operation, 2,982 kB of additional disk space will be used. Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxxf86dga1 amd64 2:1.1.4-1 [13.7 kB] Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11-utils amd64 7.7+3build1 [196 kB] Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 xvfb amd64 2:1.19.6-1ubuntu4.10 [784 kB] Fetched 993 kB in 1s (1,252 kB/s) debconf: unable to initialize frontend: Dialog debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 3.) debconf: falling back to frontend: Readline debconf: unable to initialize frontend: Readline debconf: (This frontend requires a controlling tty.) debconf: falling back to frontend: Teletype dpkg-preconfigure: unable to re-open stdin: Selecting previously unselected package libxxf86dga1:amd64. (Reading database ... 156210 files and directories currently installed.) Preparing to unpack .../libxxf86dga1_2%3a1.1.4-1_amd64.deb ... Unpacking libxxf86dga1:amd64 (2:1.1.4-1) ... Selecting previously unselected package x11-utils. Preparing to unpack .../x11-utils_7.7+3build1_amd64.deb ... Unpacking x11-utils (7.7+3build1) ... Selecting previously unselected package xvfb. Preparing to unpack .../xvfb_2%3a1.19.6-1ubuntu4.10_amd64.deb ... Unpacking xvfb (2:1.19.6-1ubuntu4.10) ... Setting up xvfb (2:1.19.6-1ubuntu4.10) ... Setting up libxxf86dga1:amd64 (2:1.1.4-1) ... Setting up x11-utils (7.7+3build1) ... Processing triggers for man-db (2.8.3-2ubuntu0.1) ... Processing triggers for libc-bin (2.27-3ubuntu1.3) ... /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link  |████████████████████████████████| 3.3 MB 5.1 MB/s [?25h Building wheel for imageio (setup.py) ... [?25l[?25hdone ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.  |████████████████████████████████| 1.0 MB 5.2 MB/s ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. gym 0.17.3 requires pyglet<=1.5.0,>=1.4.0, but you have pyglet 1.3.2 which is incompatible.  |████████████████████████████████| 1.3 MB 5.0 MB/s  |████████████████████████████████| 1.0 MB 29.8 MB/s  |████████████████████████████████| 21.8 MB 1.2 MB/s [?25h ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technology upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the agent's actions.* **Actions** - Steps that the agent can perform to alter the environment * **Step** - A step occurs when the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. A terminal state occurs when the agent has one, lost, or the environment exceeds the maximum number of steps in many environments.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can range from released to fully engaged. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Researchers have developed clever tricks to allow Q-Learning to accommodate continuous actions.Deep neural networks can help solve the problems of continuous environments and action spaces. In the next section, we will learn more about deep reinforcement learning. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, it cannot merely accelerate up the steep slope even with full throttle. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, TF-Agents is just used to render the mountain care environment for now. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe cart is not strong enough. It will need to use potential energy from the mountain behind it. The following code shows an agent that applies full throttle to climb the hill. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it. To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env ###Output _____no_output_____ ###Markdown We are now ready to train the agent. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.50905189 0.00089766], Reward=-1.0 Step 2: State=[-0.50726329 0.00178859], Reward=-1.0 Step 3: State=[-0.50459717 0.00266613], Reward=-1.0 Step 4: State=[-0.50107348 0.00352369], Reward=-1.0 Step 5: State=[-0.4967186 0.00435488], Reward=-1.0 Step 6: State=[-0.4915651 0.0051535], Reward=-1.0 Step 7: State=[-0.48565149 0.00591361], Reward=-1.0 Step 8: State=[-0.47902187 0.00662962], Reward=-1.0 Step 9: State=[-0.47172557 0.00729629], Reward=-1.0 Step 10: State=[-0.46381676 0.00790881], Reward=-1.0 Step 11: State=[-0.45535392 0.00846285], Reward=-1.0 Step 12: State=[-0.44639934 0.00895458], Reward=-1.0 Step 13: State=[-0.4370186 0.00938074], Reward=-1.0 Step 14: State=[-0.42727993 0.00973867], Reward=-1.0 Step 15: State=[-0.41725364 0.01002629], Reward=-1.0 Step 16: State=[-0.40701147 0.01024216], Reward=-1.0 Step 17: State=[-0.396626 0.01038548], Reward=-1.0 Step 18: State=[-0.38616995 0.01045604], Reward=-1.0 Step 19: State=[-0.37571567 0.01045428], Reward=-1.0 Step 20: State=[-0.36533449 0.01038118], Reward=-1.0 Step 21: State=[-0.35509619 0.0102383 ], Reward=-1.0 Step 22: State=[-0.34506852 0.01002767], Reward=-1.0 Step 23: State=[-0.33531672 0.0097518 ], Reward=-1.0 Step 24: State=[-0.32590314 0.00941358], Reward=-1.0 Step 25: State=[-0.31688687 0.00901627], Reward=-1.0 Step 26: State=[-0.30832346 0.00856341], Reward=-1.0 Step 27: State=[-0.30026469 0.00805876], Reward=-1.0 Step 28: State=[-0.2927584 0.00750629], Reward=-1.0 Step 29: State=[-0.2858483 0.0069101], Reward=-1.0 Step 30: State=[-0.27957395 0.00627436], Reward=-1.0 Step 31: State=[-0.27397063 0.00560332], Reward=-1.0 Step 32: State=[-0.26906936 0.00490127], Reward=-1.0 Step 33: State=[-0.26489689 0.00417247], Reward=-1.0 Step 34: State=[-0.26147568 0.00342121], Reward=-1.0 Step 35: State=[-0.25882396 0.00265172], Reward=-1.0 Step 36: State=[-0.25695571 0.00186825], Reward=-1.0 Step 37: State=[-0.25588073 0.00107498], Reward=-1.0 Step 38: State=[-0.25560462 0.00027611], Reward=-1.0 Step 39: State=[-0.25612883 -0.00052421], Reward=-1.0 Step 40: State=[-0.25745062 -0.00132179], Reward=-1.0 Step 41: State=[-0.25956309 -0.00211247], Reward=-1.0 Step 42: State=[-0.26245514 -0.00289205], Reward=-1.0 Step 43: State=[-0.26611148 -0.00365634], Reward=-1.0 Step 44: State=[-0.27051257 -0.00440109], Reward=-1.0 Step 45: State=[-0.27563463 -0.00512205], Reward=-1.0 Step 46: State=[-0.28144957 -0.00581494], Reward=-1.0 Step 47: State=[-0.28792506 -0.00647549], Reward=-1.0 Step 48: State=[-0.29502448 -0.00709942], Reward=-1.0 Step 49: State=[-0.30270698 -0.0076825 ], Reward=-1.0 Step 50: State=[-0.31092755 -0.00822057], Reward=-1.0 Step 51: State=[-0.31963713 -0.00870957], Reward=-1.0 Step 52: State=[-0.32878273 -0.0091456 ], Reward=-1.0 Step 53: State=[-0.33830768 -0.00952495], Reward=-1.0 Step 54: State=[-0.34815185 -0.00984416], Reward=-1.0 Step 55: State=[-0.35825194 -0.0101001 ], Reward=-1.0 Step 56: State=[-0.36854191 -0.01028996], Reward=-1.0 Step 57: State=[-0.37895331 -0.0104114 ], Reward=-1.0 Step 58: State=[-0.38941582 -0.01046252], Reward=-1.0 Step 59: State=[-0.39985775 -0.01044193], Reward=-1.0 Step 60: State=[-0.41020657 -0.01034882], Reward=-1.0 Step 61: State=[-0.42038952 -0.01018295], Reward=-1.0 Step 62: State=[-0.43033423 -0.00994471], Reward=-1.0 Step 63: State=[-0.43996933 -0.0096351 ], Reward=-1.0 Step 64: State=[-0.4492251 -0.00925577], Reward=-1.0 Step 65: State=[-0.45803405 -0.00880895], Reward=-1.0 Step 66: State=[-0.46633157 -0.00829752], Reward=-1.0 Step 67: State=[-0.47405649 -0.00772492], Reward=-1.0 Step 68: State=[-0.48115161 -0.00709512], Reward=-1.0 Step 69: State=[-0.48756422 -0.00641261], Reward=-1.0 Step 70: State=[-0.49324656 -0.00568234], Reward=-1.0 Step 71: State=[-0.49815623 -0.00490967], Reward=-1.0 Step 72: State=[-0.50225654 -0.00410031], Reward=-1.0 Step 73: State=[-0.5055168 -0.00326026], Reward=-1.0 Step 74: State=[-0.50791261 -0.00239581], Reward=-1.0 Step 75: State=[-0.50942603 -0.00151341], Reward=-1.0 Step 76: State=[-0.5100457 -0.00061968], Reward=-1.0 Step 77: State=[-5.09767002e-01 2.78702550e-04], Reward=-1.0 Step 78: State=[-0.50859201 0.00117499], Reward=-1.0 Step 79: State=[-0.50652953 0.00206248], Reward=-1.0 Step 80: State=[-0.50359501 0.00293452], Reward=-1.0 Step 81: State=[-0.49981043 0.00378458], Reward=-1.0 Step 82: State=[-0.49520411 0.00460632], Reward=-1.0 Step 83: State=[-0.48981049 0.00539362], Reward=-1.0 Step 84: State=[-0.48366986 0.00614064], Reward=-1.0 Step 85: State=[-0.47682797 0.00684189], Reward=-1.0 Step 86: State=[-0.46933572 0.00749226], Reward=-1.0 Step 87: State=[-0.46124864 0.00808708], Reward=-1.0 Step 88: State=[-0.45262646 0.00862217], Reward=-1.0 Step 89: State=[-0.44353257 0.00909389], Reward=-1.0 Step 90: State=[-0.43403342 0.00949915], Reward=-1.0 Step 91: State=[-0.42419795 0.00983547], Reward=-1.0 Step 92: State=[-0.41409699 0.01010096], Reward=-1.0 Step 93: State=[-0.40380259 0.01029439], Reward=-1.0 Step 94: State=[-0.39338746 0.01041514], Reward=-1.0 Step 95: State=[-0.38292426 0.0104632 ], Reward=-1.0 Step 96: State=[-0.37248508 0.01043918], Reward=-1.0 Step 97: State=[-0.36214083 0.01034425], Reward=-1.0 Step 98: State=[-0.35196071 0.01018012], Reward=-1.0 Step 99: State=[-0.34201175 0.00994897], Reward=-1.0 Step 100: State=[-0.33235831 0.00965343], Reward=-1.0 Step 101: State=[-0.32306179 0.00929653], Reward=-1.0 Step 102: State=[-0.31418019 0.0088816 ], Reward=-1.0 Step 103: State=[-0.30576792 0.00841226], Reward=-1.0 Step 104: State=[-0.29787557 0.00789236], Reward=-1.0 Step 105: State=[-0.29054969 0.00732588], Reward=-1.0 Step 106: State=[-0.28383272 0.00671697], Reward=-1.0 Step 107: State=[-0.27776289 0.00606983], Reward=-1.0 Step 108: State=[-0.27237418 0.00538871], Reward=-1.0 Step 109: State=[-0.26769627 0.00467791], Reward=-1.0 Step 110: State=[-0.26375458 0.00394169], Reward=-1.0 Step 111: State=[-0.26057026 0.00318432], Reward=-1.0 Step 112: State=[-0.25816021 0.00241005], Reward=-1.0 Step 113: State=[-0.25653713 0.00162309], Reward=-1.0 Step 114: State=[-0.25570949 0.00082763], Reward=-1.0 Step 115: State=[-2.55681628e-01 2.78670044e-05], Reward=-1.0 Step 116: State=[-0.25645367 -0.00077204], Reward=-1.0 Step 117: State=[-0.25802161 -0.00156793], Reward=-1.0 Step 118: State=[-0.26037723 -0.00235562], Reward=-1.0 Step 119: State=[-0.26350814 -0.00313091], Reward=-1.0 Step 120: State=[-0.26739774 -0.0038896 ], Reward=-1.0 Step 121: State=[-0.27202516 -0.00462742], Reward=-1.0 Step 122: State=[-0.2773653 -0.00534014], Reward=-1.0 Step 123: State=[-0.28338876 -0.00602346], Reward=-1.0 Step 124: State=[-0.29006186 -0.0066731 ], Reward=-1.0 Step 125: State=[-0.29734667 -0.00728481], Reward=-1.0 Step 126: State=[-0.30520105 -0.00785438], Reward=-1.0 Step 127: State=[-0.31357871 -0.00837766], Reward=-1.0 Step 128: State=[-0.32242935 -0.00885064], Reward=-1.0 Step 129: State=[-0.33169883 -0.00926948], Reward=-1.0 Step 130: State=[-0.34132937 -0.00963053], Reward=-1.0 Step 131: State=[-0.35125981 -0.00993044], Reward=-1.0 Step 132: State=[-0.36142598 -0.01016617], Reward=-1.0 Step 133: State=[-0.37176102 -0.01033504], Reward=-1.0 Step 134: State=[-0.38219587 -0.01043485], Reward=-1.0 Step 135: State=[-0.39265972 -0.01046385], Reward=-1.0 Step 136: State=[-0.40308055 -0.01042083], Reward=-1.0 Step 137: State=[-0.41338571 -0.01030515], Reward=-1.0 Step 138: State=[-0.42350248 -0.01011677], Reward=-1.0 Step 139: State=[-0.43335875 -0.00985626], Reward=-1.0 Step 140: State=[-0.44288357 -0.00952483], Reward=-1.0 Step 141: State=[-0.45200787 -0.00912429], Reward=-1.0 Step 142: State=[-0.46066497 -0.00865711], Reward=-1.0 Step 143: State=[-0.46879128 -0.00812631], Reward=-1.0 Step 144: State=[-0.4763268 -0.00753552], Reward=-1.0 Step 145: State=[-0.48321567 -0.00688887], Reward=-1.0 Step 146: State=[-0.48940667 -0.006191 ], Reward=-1.0 Step 147: State=[-0.49485367 -0.00544699], Reward=-1.0 Step 148: State=[-0.49951598 -0.00466232], Reward=-1.0 Step 149: State=[-0.50335876 -0.00384278], Reward=-1.0 Step 150: State=[-0.50635325 -0.00299449], Reward=-1.0 Step 151: State=[-0.50847702 -0.00212377], Reward=-1.0 Step 152: State=[-0.50971416 -0.00123714], Reward=-1.0 Step 153: State=[-5.10055410e-01 -3.41248589e-04], Reward=-1.0 Step 154: State=[-0.50949821 0.0005572 ], Reward=-1.0 Step 155: State=[-0.50804672 0.00145148], Reward=-1.0 Step 156: State=[-0.50571184 0.00233488], Reward=-1.0 Step 157: State=[-0.50251105 0.0032008 ], Reward=-1.0 Step 158: State=[-0.4984683 0.00404274], Reward=-1.0 Step 159: State=[-0.49361386 0.00485444], Reward=-1.0 Step 160: State=[-0.487984 0.00562986], Reward=-1.0 Step 161: State=[-0.48162074 0.00636326], Reward=-1.0 Step 162: State=[-0.47457149 0.00704925], Reward=-1.0 Step 163: State=[-0.46688862 0.00768287], Reward=-1.0 Step 164: State=[-0.45862902 0.0082596 ], Reward=-1.0 Step 165: State=[-0.44985362 0.0087754 ], Reward=-1.0 Step 166: State=[-0.44062681 0.00922681], Reward=-1.0 Step 167: State=[-0.43101588 0.00961093], Reward=-1.0 Step 168: State=[-0.42109043 0.00992545], Reward=-1.0 Step 169: State=[-0.41092173 0.0101687 ], Reward=-1.0 Step 170: State=[-0.4005821 0.01033962], Reward=-1.0 Step 171: State=[-0.3901443 0.0104378], Reward=-1.0 Step 172: State=[-0.37968088 0.01046342], Reward=-1.0 Step 173: State=[-0.36926363 0.01041726], Reward=-1.0 Step 174: State=[-0.35896297 0.01030066], Reward=-1.0 Step 175: State=[-0.34884748 0.01011548], Reward=-1.0 Step 176: State=[-0.33898342 0.00986407], Reward=-1.0 Step 177: State=[-0.32943426 0.00954916], Reward=-1.0 Step 178: State=[-0.32026037 0.00917389], Reward=-1.0 Step 179: State=[-0.31151868 0.00874169], Reward=-1.0 Step 180: State=[-0.30326242 0.00825625], Reward=-1.0 Step 181: State=[-0.29554096 0.00772147], Reward=-1.0 Step 182: State=[-0.28839957 0.00714139], Reward=-1.0 Step 183: State=[-0.28187941 0.00652016], Reward=-1.0 Step 184: State=[-0.27601738 0.00586203], Reward=-1.0 Step 185: State=[-0.27084613 0.00517125], Reward=-1.0 Step 186: State=[-0.26639402 0.00445211], Reward=-1.0 Step 187: State=[-0.26268515 0.00370887], Reward=-1.0 Step 188: State=[-0.25973934 0.00294581], Reward=-1.0 Step 189: State=[-0.25757219 0.00216715], Reward=-1.0 Step 190: State=[-0.25619508 0.00137711], Reward=-1.0 Step 191: State=[-0.25561521 0.00057987], Reward=-1.0 Step 192: State=[-2.55835595e-01 -2.20385847e-04], Reward=-1.0 Step 193: State=[-0.25685509 -0.0010195 ], Reward=-1.0 Step 194: State=[-0.25866838 -0.00181329], Reward=-1.0 Step 195: State=[-0.26126596 -0.00259758], Reward=-1.0 Step 196: State=[-0.26463414 -0.00336818], Reward=-1.0 Step 197: State=[-0.26875498 -0.00412085], Reward=-1.0 Step 198: State=[-0.27360632 -0.00485134], Reward=-1.0 Step 199: State=[-0.27916172 -0.0055554 ], Reward=-1.0 Step 200: State=[-0.28539045 -0.00622873], Reward=-1.0 ###Markdown It helps to visualize the car. The following code shows a video of the car when run from a notebook. ###Code # HIDE OUTPUT show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force in one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward, force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-5.84581471e-01 -5.49227966e-04], Reward=-1.0 Step 2: State=[-0.58567588 -0.0010944 ], Reward=-1.0 Step 3: State=[-0.58730739 -0.00163151], Reward=-1.0 Step 4: State=[-0.58946399 -0.0021566 ], Reward=-1.0 Step 5: State=[-0.59212981 -0.00266582], Reward=-1.0 Step 6: State=[-0.59528526 -0.00315545], Reward=-1.0 Step 7: State=[-0.5989072 -0.00362194], Reward=-1.0 Step 8: State=[-0.60296912 -0.00406192], Reward=-1.0 Step 9: State=[-0.60744137 -0.00447225], Reward=-1.0 Step 10: State=[-0.61229141 -0.00485004], Reward=-1.0 Step 11: State=[-0.61748407 -0.00519267], Reward=-1.0 Step 12: State=[-0.62298187 -0.0054978 ], Reward=-1.0 Step 13: State=[-0.62874529 -0.00576342], Reward=-1.0 Step 14: State=[-0.63473313 -0.00598783], Reward=-1.0 Step 15: State=[-0.64090281 -0.00616968], Reward=-1.0 Step 16: State=[-0.64721076 -0.00630795], Reward=-1.0 Step 17: State=[-0.65361272 -0.00640196], Reward=-1.0 Step 18: State=[-0.66006412 -0.00645139], Reward=-1.0 Step 19: State=[-0.66652037 -0.00645626], Reward=-1.0 Step 20: State=[-0.67293726 -0.00641689], Reward=-1.0 Step 21: State=[-0.6792712 -0.00633394], Reward=-1.0 Step 22: State=[-0.68547958 -0.00620838], Reward=-1.0 Step 23: State=[-0.69152102 -0.00604144], Reward=-1.0 Step 24: State=[-0.69735564 -0.00583462], Reward=-1.0 Step 25: State=[-0.7029453 -0.00558966], Reward=-1.0 Step 26: State=[-0.70825383 -0.00530853], Reward=-1.0 Step 27: State=[-0.7132472 -0.00499337], Reward=-1.0 Step 28: State=[-0.71789372 -0.00464651], Reward=-1.0 Step 29: State=[-0.72216414 -0.00427042], Reward=-1.0 Step 30: State=[-0.72603185 -0.00386771], Reward=-1.0 Step 31: State=[-0.72947294 -0.00344108], Reward=-1.0 Step 32: State=[-0.73246627 -0.00299334], Reward=-1.0 Step 33: State=[-0.73499362 -0.00252735], Reward=-1.0 Step 34: State=[-0.73703966 -0.00204604], Reward=-1.0 Step 35: State=[-0.73859207 -0.00155241], Reward=-1.0 Step 36: State=[-0.73964152 -0.00104945], Reward=-1.0 Step 37: State=[-7.40181738e-01 -5.40214614e-04], Reward=-1.0 Step 38: State=[-7.40209487e-01 -2.77484127e-05], Reward=-1.0 Step 39: State=[-7.39724603e-01 4.84883491e-04], Reward=-1.0 Step 40: State=[-0.73672998 0.00299462], Reward=-1.0 Step 41: State=[-0.73124359 0.00548639], Reward=-1.0 Step 42: State=[-0.72329865 0.00794494], Reward=-1.0 Step 43: State=[-0.71294396 0.01035469], Reward=-1.0 Step 44: State=[-0.70024433 0.01269963], Reward=-1.0 Step 45: State=[-0.685281 0.01496333], Reward=-1.0 Step 46: State=[-0.66815204 0.01712895], Reward=-1.0 Step 47: State=[-0.6489726 0.01917944], Reward=-1.0 Step 48: State=[-0.62787487 0.02109773], Reward=-1.0 Step 49: State=[-0.60500776 0.02286711], Reward=-1.0 Step 50: State=[-0.58053614 0.02447162], Reward=-1.0 Step 51: State=[-0.55463956 0.02589658], Reward=-1.0 Step 52: State=[-0.52751051 0.02712905], Reward=-1.0 Step 53: State=[-0.49935212 0.02815839], Reward=-1.0 Step 54: State=[-0.47037542 0.0289767 ], Reward=-1.0 Step 55: State=[-0.44079621 0.02957922], Reward=-1.0 Step 56: State=[-0.41083164 0.02996456], Reward=-1.0 Step 57: State=[-0.38069679 0.03013485], Reward=-1.0 Step 58: State=[-0.35060117 0.03009562], Reward=-1.0 Step 59: State=[-0.32074557 0.0298556 ], Reward=-1.0 Step 60: State=[-0.29131919 0.02942639], Reward=-1.0 Step 61: State=[-0.26249729 0.02882189], Reward=-1.0 Step 62: State=[-0.23443946 0.02805783], Reward=-1.0 Step 63: State=[-0.20728838 0.02715108], Reward=-1.0 Step 64: State=[-0.18116928 0.0261191 ], Reward=-1.0 Step 65: State=[-0.15618993 0.02497935], Reward=-1.0 Step 66: State=[-0.13244112 0.02374881], Reward=-1.0 Step 67: State=[-0.10999756 0.02244356], Reward=-1.0 Step 68: State=[-0.08891911 0.02107845], Reward=-1.0 Step 69: State=[-0.06925224 0.01966687], Reward=-1.0 Step 70: State=[-0.05103161 0.01822063], Reward=-1.0 Step 71: State=[-0.03428174 0.01674987], Reward=-1.0 Step 72: State=[-0.01901866 0.01526308], Reward=-1.0 Step 73: State=[-0.00525151 0.01376715], Reward=-1.0 Step 74: State=[0.00701595 0.01226746], Reward=-1.0 Step 75: State=[0.01778397 0.01076801], Reward=-1.0 Step 76: State=[0.02705554 0.00927157], Reward=-1.0 Step 77: State=[0.03483534 0.0077798 ], Reward=-1.0 Step 78: State=[0.04112878 0.00629344], Reward=-1.0 Step 79: State=[0.04594123 0.00481245], Reward=-1.0 Step 80: State=[0.04927738 0.00333615], Reward=-1.0 Step 81: State=[0.05114081 0.00186342], Reward=-1.0 Step 82: State=[0.05153359 0.00039279], Reward=-1.0 Step 83: State=[ 0.0504562 -0.0010774], Reward=-1.0 Step 84: State=[ 0.04590739 -0.00454881], Reward=-1.0 Step 85: State=[ 0.03788225 -0.00802514], Reward=-1.0 Step 86: State=[ 0.02637324 -0.01150901], Reward=-1.0 Step 87: State=[ 0.01137205 -0.01500119], Reward=-1.0 Step 88: State=[-0.00712768 -0.01849973], Reward=-1.0 Step 89: State=[-0.02912685 -0.02199916], Reward=-1.0 Step 90: State=[-0.05461647 -0.02548963], Reward=-1.0 Step 91: State=[-0.08357261 -0.02895614], Reward=-1.0 Step 92: State=[-0.11595059 -0.03237798], Reward=-1.0 Step 93: State=[-0.15167884 -0.03572825], Reward=-1.0 Step 94: State=[-0.1906527 -0.03897386], Reward=-1.0 Step 95: State=[-0.23272866 -0.04207597], Reward=-1.0 Step 96: State=[-0.27771965 -0.04499099], Reward=-1.0 Step 97: State=[-0.32539199 -0.04767234], Reward=-1.0 Step 98: State=[-0.37546482 -0.05007283], Reward=-1.0 Step 99: State=[-0.42761244 -0.05214762], Reward=-1.0 Step 100: State=[-0.48147006 -0.05385761], Reward=-1.0 Step 101: State=[-0.5366428 -0.05517274], Reward=-1.0 Step 102: State=[-0.59271773 -0.05607493], Reward=-1.0 Step 103: State=[-0.64927797 -0.05656025], Reward=-1.0 Step 104: State=[-0.7059178 -0.05663983], Reward=-1.0 Step 105: State=[-0.7622574 -0.0563396], Reward=-1.0 Step 106: State=[-0.81795612 -0.05569872], Reward=-1.0 Step 107: State=[-0.8727231 -0.05476698], Reward=-1.0 Step 108: State=[-0.92632481 -0.0536017 ], Reward=-1.0 Step 109: State=[-0.97858908 -0.05226427], Reward=-1.0 Step 110: State=[-1.02940612 -0.05081704], Reward=-1.0 Step 111: State=[-1.07872672 -0.0493206 ], Reward=-1.0 Step 112: State=[-1.1265585 -0.04783178], Reward=-1.0 Step 113: State=[-1.1729608 -0.0464023], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code # HIDE OUTPUT show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value-driven action is governed by the epsilon ($\epsilon$) parameter, the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference in the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum Q-values from the resulting state when the client takes this action. Adding the maximum of action Q-values for the new state is essential because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into # discrete values. This is often called binning. We divide # the range that the state values might occupy and assign # each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(int)) # Run one game. The q_table to use is provided. We also # provide a flag to indicate if the game should be # rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% on the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each continuous state variable. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB, we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low) \ /DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE \ + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB, we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation # at SHOW_EVERY intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count}" +\ f" {(float(success_count)/SHOW_EVERY)}") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 0.0 Current episode: 2000, success: 0 0.0 Current episode: 3000, success: 0 0.0 Current episode: 4000, success: 31 0.031 Current episode: 5000, success: 321 0.321 Current episode: 6000, success: 602 0.602 Current episode: 7000, success: 620 0.62 Current episode: 8000, success: 821 0.821 Current episode: 9000, success: 707 0.707 Current episode: 10000, success: 714 0.714 Current episode: 11000, success: 574 0.574 Current episode: 12000, success: 443 0.443 Current episode: 13000, success: 480 0.48 Current episode: 14000, success: 458 0.458 Current episode: 15000, success: 327 0.327 Current episode: 16000, success: 323 0.323 Current episode: 17000, success: 295 0.295 Current episode: 18000, success: 314 0.314 Current episode: 19000, success: 362 0.362 Current episode: 20000, success: 488 0.488 Current episode: 21000, success: 566 0.566 Current episode: 22000, success: 591 0.591 Current episode: 23000, success: 441 0.441 Current episode: 24000, success: 385 0.385 Current episode: 25000, success: 1000 1.0 Current episode: 26000, success: 1000 1.0 Current episode: 27000, success: 993 0.993 Current episode: 28000, success: 67 0.067 Current episode: 29000, success: 0 0.0 Current episode: 30000, success: 39 0.039 Current episode: 31000, success: 204 0.204 Current episode: 32000, success: 429 0.429 Current episode: 33000, success: 345 0.345 Current episode: 34000, success: 970 0.97 Current episode: 35000, success: 583 0.583 Current episode: 36000, success: 752 0.752 Current episode: 37000, success: 955 0.955 Current episode: 38000, success: 997 0.997 Current episode: 39000, success: 1000 1.0 Current episode: 40000, success: 1000 1.0 Current episode: 41000, success: 1000 1.0 Current episode: 42000, success: 1000 1.0 Current episode: 43000, success: 1000 1.0 Current episode: 44000, success: 1000 1.0 Current episode: 45000, success: 1000 1.0 Current episode: 46000, success: 1000 1.0 Current episode: 47000, success: 1000 1.0 Current episode: 48000, success: 1000 1.0 Current episode: 49000, success: 1000 1.0 Current episode: 50000, success: 1000 1.0 True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. It might be safe to stop training once you observe that the agent has gotten 100% for several update intervals. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code # HIDE OUTPUT run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Deep Learning and Security*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False ###Output _____no_output_____ ###Markdown Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.54298351 0.00115394], Reward=-1.0 Step 2: State=[-0.54068426 0.00229925], Reward=-1.0 Step 3: State=[-0.53725693 0.00342733], Reward=-1.0 Step 4: State=[-0.53272719 0.00452974], Reward=-1.0 Step 5: State=[-0.527129 0.00559819], Reward=-1.0 Step 6: State=[-0.52050433 0.00662467], Reward=-1.0 Step 7: State=[-0.51290287 0.00760146], Reward=-1.0 Step 8: State=[-0.50438161 0.00852126], Reward=-1.0 Step 9: State=[-0.4950044 0.00937721], Reward=-1.0 Step 10: State=[-0.48484139 0.01016301], Reward=-1.0 Step 11: State=[-0.47396841 0.01087299], Reward=-1.0 Step 12: State=[-0.46246627 0.01150213], Reward=-1.0 Step 13: State=[-0.45042007 0.0120462 ], Reward=-1.0 Step 14: State=[-0.43791831 0.01250176], Reward=-1.0 Step 15: State=[-0.4250521 0.01286621], Reward=-1.0 Step 16: State=[-0.41191426 0.01313783], Reward=-1.0 Step 17: State=[-0.39859848 0.01331578], Reward=-1.0 Step 18: State=[-0.38519838 0.0134001 ], Reward=-1.0 Step 19: State=[-0.37180672 0.01339166], Reward=-1.0 Step 20: State=[-0.35851456 0.01329216], Reward=-1.0 Step 21: State=[-0.34541053 0.01310403], Reward=-1.0 Step 22: State=[-0.33258017 0.01283036], Reward=-1.0 Step 23: State=[-0.32010531 0.01247486], Reward=-1.0 Step 24: State=[-0.30806361 0.0120417 ], Reward=-1.0 Step 25: State=[-0.29652811 0.0115355 ], Reward=-1.0 Step 26: State=[-0.28556694 0.01096116], Reward=-1.0 Step 27: State=[-0.27524312 0.01032383], Reward=-1.0 Step 28: State=[-0.26561434 0.00962878], Reward=-1.0 Step 29: State=[-0.25673298 0.00888136], Reward=-1.0 Step 30: State=[-0.24864606 0.00808693], Reward=-1.0 Step 31: State=[-0.24139526 0.0072508 ], Reward=-1.0 Step 32: State=[-0.23501706 0.0063782 ], Reward=-1.0 Step 33: State=[-0.22954281 0.00547425], Reward=-1.0 Step 34: State=[-0.22499885 0.00454396], Reward=-1.0 Step 35: State=[-0.22140666 0.00359218], Reward=-1.0 Step 36: State=[-0.21878297 0.00262369], Reward=-1.0 Step 37: State=[-0.21713985 0.00164313], Reward=-1.0 Step 38: State=[-0.21648478 0.00065507], Reward=-1.0 Step 39: State=[-0.21682075 -0.00033597], Reward=-1.0 Step 40: State=[-0.21814623 -0.00132548], Reward=-1.0 Step 41: State=[-0.22045518 -0.00230895], Reward=-1.0 Step 42: State=[-0.22373702 -0.00328184], Reward=-1.0 Step 43: State=[-0.22797653 -0.00423951], Reward=-1.0 Step 44: State=[-0.23315378 -0.00517725], Reward=-1.0 Step 45: State=[-0.239244 -0.00609022], Reward=-1.0 Step 46: State=[-0.24621747 -0.00697347], Reward=-1.0 Step 47: State=[-0.25403939 -0.00782191], Reward=-1.0 Step 48: State=[-0.26266974 -0.00863035], Reward=-1.0 Step 49: State=[-0.27206323 -0.0093935 ], Reward=-1.0 Step 50: State=[-0.28216923 -0.010106 ], Reward=-1.0 Step 51: State=[-0.29293174 -0.01076251], Reward=-1.0 Step 52: State=[-0.30428945 -0.01135771], Reward=-1.0 Step 53: State=[-0.31617585 -0.0118864 ], Reward=-1.0 Step 54: State=[-0.32851945 -0.0123436 ], Reward=-1.0 Step 55: State=[-0.34124405 -0.0127246 ], Reward=-1.0 Step 56: State=[-0.3542691 -0.01302505], Reward=-1.0 Step 57: State=[-0.36751021 -0.01324111], Reward=-1.0 Step 58: State=[-0.38087966 -0.01336945], Reward=-1.0 Step 59: State=[-0.3942871 -0.01340744], Reward=-1.0 Step 60: State=[-0.40764024 -0.01335314], Reward=-1.0 Step 61: State=[-0.42084563 -0.01320539], Reward=-1.0 Step 62: State=[-0.43380952 -0.01296389], Reward=-1.0 Step 63: State=[-0.44643872 -0.0126292 ], Reward=-1.0 Step 64: State=[-0.45864146 -0.01220274], Reward=-1.0 Step 65: State=[-0.47032831 -0.01168684], Reward=-1.0 Step 66: State=[-0.48141298 -0.01108468], Reward=-1.0 Step 67: State=[-0.49181321 -0.01040022], Reward=-1.0 Step 68: State=[-0.50145146 -0.00963826], Reward=-1.0 Step 69: State=[-0.5102557 -0.00880424], Reward=-1.0 Step 70: State=[-0.51815998 -0.00790428], Reward=-1.0 Step 71: State=[-0.52510506 -0.00694507], Reward=-1.0 Step 72: State=[-0.53103883 -0.00593378], Reward=-1.0 Step 73: State=[-0.53591681 -0.00487798], Reward=-1.0 Step 74: State=[-0.53970243 -0.00378562], Reward=-1.0 Step 75: State=[-0.54236732 -0.00266489], Reward=-1.0 Step 76: State=[-0.54389151 -0.0015242 ], Reward=-1.0 Step 77: State=[-5.44263607e-01 -3.72094556e-04], Reward=-1.0 Step 78: State=[-0.54348081 0.00078279], Reward=-1.0 Step 79: State=[-0.541549 0.00193182], Reward=-1.0 Step 80: State=[-0.53848261 0.00306638], Reward=-1.0 Step 81: State=[-0.53430464 0.00417797], Reward=-1.0 Step 82: State=[-0.52904639 0.00525825], Reward=-1.0 Step 83: State=[-0.52274728 0.00629911], Reward=-1.0 Step 84: State=[-0.51545456 0.00729272], Reward=-1.0 Step 85: State=[-0.50722291 0.00823165], Reward=-1.0 Step 86: State=[-0.49811404 0.00910888], Reward=-1.0 Step 87: State=[-0.48819611 0.00991793], Reward=-1.0 Step 88: State=[-0.4775432 0.01065291], Reward=-1.0 Step 89: State=[-0.46623461 0.01130859], Reward=-1.0 Step 90: State=[-0.45435414 0.01188048], Reward=-1.0 Step 91: State=[-0.44198927 0.01236487], Reward=-1.0 Step 92: State=[-0.42923038 0.01275889], Reward=-1.0 Step 93: State=[-0.41616983 0.01306055], Reward=-1.0 Step 94: State=[-0.40290112 0.01326871], Reward=-1.0 Step 95: State=[-0.389518 0.01338313], Reward=-1.0 Step 96: State=[-0.37611358 0.01340442], Reward=-1.0 Step 97: State=[-0.36277956 0.01333402], Reward=-1.0 Step 98: State=[-0.34960543 0.01317413], Reward=-1.0 Step 99: State=[-0.3366778 0.01292763], Reward=-1.0 Step 100: State=[-0.32407975 0.01259805], Reward=-1.0 Step 101: State=[-0.31189033 0.01218942], Reward=-1.0 Step 102: State=[-0.3001841 0.01170623], Reward=-1.0 Step 103: State=[-0.28903082 0.01115328], Reward=-1.0 Step 104: State=[-0.27849515 0.01053567], Reward=-1.0 Step 105: State=[-0.26863652 0.00985862], Reward=-1.0 Step 106: State=[-0.25950904 0.00912749], Reward=-1.0 Step 107: State=[-0.25116142 0.00834761], Reward=-1.0 Step 108: State=[-0.24363708 0.00752434], Reward=-1.0 Step 109: State=[-0.23697416 0.00666292], Reward=-1.0 Step 110: State=[-0.23120564 0.00576852], Reward=-1.0 Step 111: State=[-0.22635946 0.00484618], Reward=-1.0 Step 112: State=[-0.22245866 0.0039008 ], Reward=-1.0 Step 113: State=[-0.21952148 0.00293718], Reward=-1.0 Step 114: State=[-0.21756149 0.00196 ], Reward=-1.0 Step 115: State=[-0.21658763 0.00097386], Reward=-1.0 Step 116: State=[-2.16604342e-01 -1.67115330e-05], Reward=-1.0 Step 117: State=[-0.21761155 -0.0010072 ], Reward=-1.0 Step 118: State=[-0.21960466 -0.00199312], Reward=-1.0 Step 119: State=[-0.22257458 -0.00296991], Reward=-1.0 Step 120: State=[-0.22650757 -0.003933 ], Reward=-1.0 Step 121: State=[-0.23138525 -0.00487768], Reward=-1.0 Step 122: State=[-0.23718442 -0.00579916], Reward=-1.0 Step 123: State=[-0.24387695 -0.00669253], Reward=-1.0 Step 124: State=[-0.2514297 -0.00755275], Reward=-1.0 Step 125: State=[-0.25980435 -0.00837465], Reward=-1.0 Step 126: State=[-0.26895731 -0.00915296], Reward=-1.0 Step 127: State=[-0.27883967 -0.00988236], Reward=-1.0 Step 128: State=[-0.28939716 -0.01055749], Reward=-1.0 Step 129: State=[-0.30057017 -0.01117301], Reward=-1.0 Step 130: State=[-0.31229385 -0.01172368], Reward=-1.0 Step 131: State=[-0.32449829 -0.01220444], Reward=-1.0 Step 132: State=[-0.33710877 -0.01261047], Reward=-1.0 Step 133: State=[-0.35004609 -0.01293732], Reward=-1.0 Step 134: State=[-0.36322703 -0.01318094], Reward=-1.0 Step 135: State=[-0.3765649 -0.01333787], Reward=-1.0 Step 136: State=[-0.3899701 -0.0134052], Reward=-1.0 Step 137: State=[-0.40335089 -0.01338079], Reward=-1.0 Step 138: State=[-0.41661411 -0.01326322], Reward=-1.0 Step 139: State=[-0.429666 -0.0130519], Reward=-1.0 Step 140: State=[-0.44241311 -0.0127471 ], Reward=-1.0 Step 141: State=[-0.4547631 -0.01235 ], Reward=-1.0 Step 142: State=[-0.4666257 -0.0118626], Reward=-1.0 Step 143: State=[-0.47791353 -0.01128782], Reward=-1.0 Step 144: State=[-0.48854292 -0.01062939], Reward=-1.0 Step 145: State=[-0.49843474 -0.00989182], Reward=-1.0 Step 146: State=[-0.50751511 -0.00908037], Reward=-1.0 Step 147: State=[-0.51571607 -0.00820096], Reward=-1.0 Step 148: State=[-0.52297614 -0.00726007], Reward=-1.0 Step 149: State=[-0.52924088 -0.00626474], Reward=-1.0 Step 150: State=[-0.53446331 -0.00522243], Reward=-1.0 Step 151: State=[-0.53860426 -0.00414096], Reward=-1.0 Step 152: State=[-0.54163272 -0.00302845], Reward=-1.0 Step 153: State=[-0.54352598 -0.00189327], Reward=-1.0 Step 154: State=[-0.54426988 -0.0007439 ], Reward=-1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.51431373 -0.00107771], Reward=-1.0 Step 2: State=[-0.51646107 -0.00214734], Reward=-1.0 Step 3: State=[-0.51966193 -0.00320087], Reward=-1.0 Step 4: State=[-0.52389233 -0.00423039], Reward=-1.0 Step 5: State=[-0.52912052 -0.00522819], Reward=-1.0 Step 6: State=[-0.53530729 -0.00618678], Reward=-1.0 Step 7: State=[-0.54240628 -0.00709898], Reward=-1.0 Step 8: State=[-0.55036428 -0.007958 ], Reward=-1.0 Step 9: State=[-0.55912175 -0.00875748], Reward=-1.0 Step 10: State=[-0.56861331 -0.00949156], Reward=-1.0 Step 11: State=[-0.57876828 -0.01015497], Reward=-1.0 Step 12: State=[-0.58951137 -0.01074309], Reward=-1.0 Step 13: State=[-0.60076333 -0.01125196], Reward=-1.0 Step 14: State=[-0.61244171 -0.01167838], Reward=-1.0 Step 15: State=[-0.62446163 -0.01201992], Reward=-1.0 Step 16: State=[-0.63673657 -0.01227494], Reward=-1.0 Step 17: State=[-0.64917917 -0.0124426 ], Reward=-1.0 Step 18: State=[-0.66170205 -0.01252287], Reward=-1.0 Step 19: State=[-0.67421853 -0.01251648], Reward=-1.0 Step 20: State=[-0.68664341 -0.01242488], Reward=-1.0 Step 21: State=[-0.69889363 -0.01225023], Reward=-1.0 Step 22: State=[-0.71088891 -0.01199528], Reward=-1.0 Step 23: State=[-0.72255227 -0.01166336], Reward=-1.0 Step 24: State=[-0.73381051 -0.01125823], Reward=-1.0 Step 25: State=[-0.7445946 -0.01078409], Reward=-1.0 Step 26: State=[-0.75484 -0.0102454], Reward=-1.0 Step 27: State=[-0.76448689 -0.00964689], Reward=-1.0 Step 28: State=[-0.77348032 -0.00899343], Reward=-1.0 Step 29: State=[-0.78177031 -0.00828998], Reward=-1.0 Step 30: State=[-0.78931187 -0.00754156], Reward=-1.0 Step 31: State=[-0.79606502 -0.00675316], Reward=-1.0 Step 32: State=[-0.80199476 -0.00592974], Reward=-1.0 Step 33: State=[-0.80707094 -0.00507618], Reward=-1.0 Step 34: State=[-0.81126824 -0.00419729], Reward=-1.0 Step 35: State=[-0.81456603 -0.00329779], Reward=-1.0 Step 36: State=[-0.81694832 -0.0023823 ], Reward=-1.0 Step 37: State=[-0.81840369 -0.00145537], Reward=-1.0 Step 38: State=[-8.18925204e-01 -5.21510941e-04], Reward=-1.0 Step 39: State=[-8.18510378e-01 4.14826025e-04], Reward=-1.0 Step 40: State=[-0.81516118 0.00334919], Reward=-1.0 Step 41: State=[-0.80889363 0.00626755], Reward=-1.0 Step 42: State=[-0.7997382 0.00915543], Reward=-1.0 Step 43: State=[-0.78774062 0.01199759], Reward=-1.0 Step 44: State=[-0.77296289 0.01477773], Reward=-1.0 Step 45: State=[-0.75548455 0.01747834], Reward=-1.0 Step 46: State=[-0.73540399 0.02008056], Reward=-1.0 Step 47: State=[-0.71283965 0.02256434], Reward=-1.0 Step 48: State=[-0.68793102 0.02490863], Reward=-1.0 Step 49: State=[-0.66083923 0.0270918 ], Reward=-1.0 Step 50: State=[-0.63174696 0.02909226], Reward=-1.0 Step 51: State=[-0.60085774 0.03088922], Reward=-1.0 Step 52: State=[-0.56839425 0.03246349], Reward=-1.0 Step 53: State=[-0.53459581 0.03379844], Reward=-1.0 Step 54: State=[-0.49971491 0.03488091], Reward=-1.0 Step 55: State=[-0.46401297 0.03570193], Reward=-1.0 Step 56: State=[-0.42775556 0.03625741], Reward=-1.0 Step 57: State=[-0.39120711 0.03654845], Reward=-1.0 Step 58: State=[-0.35462569 0.03658142], Reward=-1.0 Step 59: State=[-0.31825799 0.0363677 ], Reward=-1.0 Step 60: State=[-0.28233478 0.03592322], Reward=-1.0 Step 61: State=[-0.24706714 0.03526764], Reward=-1.0 Step 62: State=[-0.21264364 0.0344235 ], Reward=-1.0 Step 63: State=[-0.17922847 0.03341517], Reward=-1.0 Step 64: State=[-0.14696054 0.03226793], Reward=-1.0 Step 65: State=[-0.11595355 0.03100699], Reward=-1.0 Step 66: State=[-0.08629682 0.02965673], Reward=-1.0 Step 67: State=[-0.05805677 0.02824004], Reward=-1.0 Step 68: State=[-0.03127891 0.02677787], Reward=-1.0 Step 69: State=[-0.00599004 0.02528887], Reward=-1.0 Step 70: State=[0.01779923 0.02378927], Reward=-1.0 Step 71: State=[0.04009206 0.02229283], Reward=-1.0 Step 72: State=[0.06090295 0.02081089], Reward=-1.0 Step 73: State=[0.08025546 0.01935251], Reward=-1.0 Step 74: State=[0.09818008 0.01792462], Reward=-1.0 Step 75: State=[0.11471236 0.01653228], Reward=-1.0 Step 76: State=[0.12989122 0.01517886], Reward=-1.0 Step 77: State=[0.14375749 0.01386628], Reward=-1.0 Step 78: State=[0.15635269 0.01259519], Reward=-1.0 Step 79: State=[0.16771789 0.01136521], Reward=-1.0 Step 80: State=[0.17789293 0.01017504], Reward=-1.0 Step 81: State=[0.18691562 0.00902269], Reward=-1.0 Step 82: State=[0.19482116 0.00790554], Reward=-1.0 Step 83: State=[0.20164168 0.00682052], Reward=-1.0 Step 84: State=[0.20740583 0.00576416], Reward=-1.0 Step 85: State=[0.21213852 0.00473269], Reward=-1.0 Step 86: State=[0.21586063 0.00372211], Reward=-1.0 Step 87: State=[0.21858888 0.00272825], Reward=-1.0 Step 88: State=[0.22033568 0.0017468 ], Reward=-1.0 Step 89: State=[0.22110904 0.00077336], Reward=-1.0 Step 90: State=[ 2.20912527e-01 -1.96509754e-04], Reward=-1.0 Step 91: State=[ 0.21774524 -0.00316729], Reward=-1.0 Step 92: State=[ 0.21159265 -0.00615259], Reward=-1.0 Step 93: State=[ 0.20242705 -0.0091656 ], Reward=-1.0 Step 94: State=[ 0.19020845 -0.01221861], Reward=-1.0 Step 95: State=[ 0.17488593 -0.01532251], Reward=-1.0 Step 96: State=[ 0.15639968 -0.01848625], Reward=-1.0 Step 97: State=[ 0.1346836 -0.02171608], Reward=-1.0 Step 98: State=[ 0.10966883 -0.02501477], Reward=-1.0 Step 99: State=[ 0.08128815 -0.02838068], Reward=-1.0 Step 100: State=[ 0.04948145 -0.03180671], Reward=-1.0 Step 101: State=[ 0.01420223 -0.03527921], Reward=-1.0 Step 102: State=[-0.02457471 -0.03877695], Reward=-1.0 Step 103: State=[-0.06684487 -0.04227015], Reward=-1.0 Step 104: State=[-0.11256492 -0.04572006], Reward=-1.0 Step 105: State=[-0.16164378 -0.04907886], Reward=-1.0 Step 106: State=[-0.21393441 -0.05229063], Reward=-1.0 Step 107: State=[-0.26922758 -0.05529317], Reward=-1.0 Step 108: State=[-0.32724868 -0.05802111], Reward=-1.0 Step 109: State=[-0.38765872 -0.06041004], Reward=-1.0 Step 110: State=[-0.45006028 -0.06240156], Reward=-1.0 Step 111: State=[-0.51400891 -0.06394863], Reward=-1.0 Step 112: State=[-0.57902946 -0.06502055], Reward=-1.0 Step 113: State=[-0.64463619 -0.06560673], Reward=-1.0 Step 114: State=[-0.71035496 -0.06571877], Reward=-1.0 Step 115: State=[-0.77574519 -0.06539023], Reward=-1.0 Step 116: State=[-0.84041959 -0.06467439], Reward=-1.0 Step 117: State=[-0.90405977 -0.06364018], Reward=-1.0 Step 118: State=[-0.96642693 -0.06236716], Reward=-1.0 Step 119: State=[-1.02736712 -0.06094019], Reward=-1.0 Step 120: State=[-1.08681173 -0.05944462], Reward=-1.0 Step 121: State=[-1.14477398 -0.05796225], Reward=-1.0 Step 122: State=[-1.2 0. ], Reward=-1.0 Step 123: State=[-1.1987581 0.0012419], Reward=-1.0 Step 124: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 125: State=[-1.18652173 0.00774848], Reward=-1.0 Step 126: State=[-1.17548846 0.01103326], Reward=-1.0 Step 127: State=[-1.16113808 0.01435038], Reward=-1.0 Step 128: State=[-1.14343234 0.01770574], Reward=-1.0 Step 129: State=[-1.12233007 0.02110228], Reward=-1.0 Step 130: State=[-1.09779103 0.02453904], Reward=-1.0 Step 131: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 132: State=[-1.03827616 0.03150456], Reward=-1.0 Step 133: State=[-1.0032725 0.03500367], Reward=-1.0 Step 134: State=[-0.9647905 0.03848199], Reward=-1.0 Step 135: State=[-0.92288452 0.04190598], Reward=-1.0 Step 136: State=[-0.87765038 0.04523414], Reward=-1.0 Step 137: State=[-0.82923273 0.04841765], Reward=-1.0 Step 138: State=[-0.77783078 0.05140195], Reward=-1.0 Step 139: State=[-0.72370164 0.05412914], Reward=-1.0 Step 140: State=[-0.66716026 0.05654138], Reward=-1.0 Step 141: State=[-0.60857514 0.05858511], Reward=-1.0 Step 142: State=[-0.54835959 0.06021555], Reward=-1.0 Step 143: State=[-0.4869585 0.06140109], Reward=-1.0 Step 144: State=[-0.42483166 0.06212684], Reward=-1.0 Step 145: State=[-0.36243478 0.06239688], Reward=-1.0 Step 146: State=[-0.30020009 0.06223469], Reward=-1.0 Step 147: State=[-0.23851824 0.06168185], Reward=-1.0 Step 148: State=[-0.17772322 0.06079502], Reward=-1.0 Step 149: State=[-0.1180812 0.05964202], Reward=-1.0 Step 150: State=[-0.05978395 0.05829725], Reward=-1.0 Step 151: State=[-0.0029466 0.05683735], Reward=-1.0 Step 152: State=[0.05239085 0.05533745], Reward=-1.0 ###Markdown Reinforcement LearningFigure 12.REINF provides a high level overview of Reinforcement, or Q Learning.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined. $ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() #print(f"Step {i}: State={state}, Reward={reward}") print("Step: {0}, State: {1}, Reward = {2}".format(i, state,reward)) env.close() ###Output Step: 1, State: [-0.47707696 0.0006571 ], Reward = -1.0 Step: 2, State: [-0.47576764 0.00130932], Reward = -1.0 Step: 3, State: [-0.47381583 0.00195181], Reward = -1.0 Step: 4, State: [-0.471236 0.00257983], Reward = -1.0 Step: 5, State: [-0.46804728 0.00318872], Reward = -1.0 Step: 6, State: [-0.46427327 0.00377401], Reward = -1.0 Step: 7, State: [-0.45994186 0.00433141], Reward = -1.0 Step: 8, State: [-0.45508497 0.00485688], Reward = -1.0 Step: 9, State: [-0.44973833 0.00534664], Reward = -1.0 Step: 10, State: [-0.44394112 0.00579721], Reward = -1.0 Step: 11, State: [-0.43773568 0.00620545], Reward = -1.0 Step: 12, State: [-0.43116711 0.00656857], Reward = -1.0 Step: 13, State: [-0.42428292 0.00688418], Reward = -1.0 Step: 14, State: [-0.41713263 0.00715029], Reward = -1.0 Step: 15, State: [-0.40976734 0.0073653 ], Reward = -1.0 Step: 16, State: [-0.40223928 0.00752806], Reward = -1.0 Step: 17, State: [-0.39460144 0.00763784], Reward = -1.0 Step: 18, State: [-0.38690711 0.00769433], Reward = -1.0 Step: 19, State: [-0.37920948 0.00769763], Reward = -1.0 Step: 20, State: [-0.37156122 0.00764826], Reward = -1.0 Step: 21, State: [-0.36401411 0.00754711], Reward = -1.0 Step: 22, State: [-0.35661869 0.00739542], Reward = -1.0 Step: 23, State: [-0.34942389 0.0071948 ], Reward = -1.0 Step: 24, State: [-0.34247677 0.00694712], Reward = -1.0 Step: 25, State: [-0.33582219 0.00665457], Reward = -1.0 Step: 26, State: [-0.32950263 0.00631956], Reward = -1.0 Step: 27, State: [-0.32355791 0.00594472], Reward = -1.0 Step: 28, State: [-0.31802505 0.00553286], Reward = -1.0 Step: 29, State: [-0.3129381 0.00508695], Reward = -1.0 Step: 30, State: [-0.30832801 0.00461009], Reward = -1.0 Step: 31, State: [-0.30422253 0.00410547], Reward = -1.0 Step: 32, State: [-0.30064616 0.00357638], Reward = -1.0 Step: 33, State: [-0.29762001 0.00302615], Reward = -1.0 Step: 34, State: [-0.29516182 0.00245818], Reward = -1.0 Step: 35, State: [-0.29328592 0.0018759 ], Reward = -1.0 Step: 36, State: [-0.29200317 0.00128275], Reward = -1.0 Step: 37, State: [-0.29132098 0.00068219], Reward = -1.0 Step: 38, State: [-2.91243266e-01 7.77126097e-05], Reward = -1.0 Step: 39, State: [-0.29177048 -0.00052722], Reward = -1.0 Step: 40, State: [-0.29289959 -0.00112911], Reward = -1.0 Step: 41, State: [-0.29462409 -0.00172449], Reward = -1.0 Step: 42, State: [-0.29693398 -0.0023099 ], Reward = -1.0 Step: 43, State: [-0.29981585 -0.00288187], Reward = -1.0 Step: 44, State: [-0.30325283 -0.00343698], Reward = -1.0 Step: 45, State: [-0.30722465 -0.00397182], Reward = -1.0 Step: 46, State: [-0.31170769 -0.00448304], Reward = -1.0 Step: 47, State: [-0.31667502 -0.00496733], Reward = -1.0 Step: 48, State: [-0.32209651 -0.00542149], Reward = -1.0 Step: 49, State: [-0.32793889 -0.00584238], Reward = -1.0 Step: 50, State: [-0.3341659 -0.006227 ], Reward = -1.0 Step: 51, State: [-0.3407384 -0.0065725], Reward = -1.0 Step: 52, State: [-0.34761459 -0.00687619], Reward = -1.0 Step: 53, State: [-0.3547502 -0.00713561], Reward = -1.0 Step: 54, State: [-0.36209871 -0.00734851], Reward = -1.0 Step: 55, State: [-0.36961163 -0.00751292], Reward = -1.0 Step: 56, State: [-0.37723882 -0.00762719], Reward = -1.0 Step: 57, State: [-0.38492877 -0.00768995], Reward = -1.0 Step: 58, State: [-0.39262901 -0.00770024], Reward = -1.0 Step: 59, State: [-0.40028644 -0.00765743], Reward = -1.0 Step: 60, State: [-0.40784776 -0.00756132], Reward = -1.0 Step: 61, State: [-0.41525988 -0.00741211], Reward = -1.0 Step: 62, State: [-0.4224703 -0.00721042], Reward = -1.0 Step: 63, State: [-0.42942761 -0.00695731], Reward = -1.0 Step: 64, State: [-0.43608184 -0.00665423], Reward = -1.0 Step: 65, State: [-0.44238493 -0.00630309], Reward = -1.0 Step: 66, State: [-0.44829112 -0.00590619], Reward = -1.0 Step: 67, State: [-0.45375733 -0.0054662 ], Reward = -1.0 Step: 68, State: [-0.45874352 -0.00498619], Reward = -1.0 Step: 69, State: [-0.46321306 -0.00446954], Reward = -1.0 Step: 70, State: [-0.46713303 -0.00391996], Reward = -1.0 Step: 71, State: [-0.47047446 -0.00334143], Reward = -1.0 Step: 72, State: [-0.47321264 -0.00273818], Reward = -1.0 Step: 73, State: [-0.47532728 -0.00211464], Reward = -1.0 Step: 74, State: [-0.47680269 -0.00147541], Reward = -1.0 Step: 75, State: [-0.47762792 -0.00082523], Reward = -1.0 Step: 76, State: [-4.77796842e-01 -1.68920140e-04], Reward = -1.0 Step: 77, State: [-0.4773082 0.00048865], Reward = -1.0 Step: 78, State: [-0.47616562 0.00114258], Reward = -1.0 Step: 79, State: [-0.47437758 0.00178803], Reward = -1.0 Step: 80, State: [-0.47195737 0.00242021], Reward = -1.0 Step: 81, State: [-0.46892292 0.00303445], Reward = -1.0 Step: 82, State: [-0.46529671 0.00362622], Reward = -1.0 Step: 83, State: [-0.46110553 0.00419118], Reward = -1.0 Step: 84, State: [-0.45638031 0.00472522], Reward = -1.0 Step: 85, State: [-0.45115582 0.00522449], Reward = -1.0 Step: 86, State: [-0.44547038 0.00568544], Reward = -1.0 Step: 87, State: [-0.43936556 0.00610482], Reward = -1.0 Step: 88, State: [-0.43288578 0.00647978], Reward = -1.0 Step: 89, State: [-0.42607799 0.00680779], Reward = -1.0 Step: 90, State: [-0.41899121 0.00708678], Reward = -1.0 Step: 91, State: [-0.41167618 0.00731504], Reward = -1.0 Step: 92, State: [-0.40418487 0.0074913 ], Reward = -1.0 Step: 93, State: [-0.39657014 0.00761473], Reward = -1.0 Step: 94, State: [-0.38888524 0.00768491], Reward = -1.0 Step: 95, State: [-0.3811834 0.00770184], Reward = -1.0 Step: 96, State: [-0.37351748 0.00766592], Reward = -1.0 Step: 97, State: [-0.36593952 0.00757796], Reward = -1.0 Step: 98, State: [-0.35850041 0.00743911], Reward = -1.0 Step: 99, State: [-0.35124952 0.00725088], Reward = -1.0 Step: 100, State: [-0.34423443 0.00701509], Reward = -1.0 Step: 101, State: [-0.33750059 0.00673384], Reward = -1.0 Step: 102, State: [-0.33109109 0.00640949], Reward = -1.0 Step: 103, State: [-0.32504648 0.00604462], Reward = -1.0 Step: 104, State: [-0.31940449 0.00564199], Reward = -1.0 Step: 105, State: [-0.31419996 0.00520453], Reward = -1.0 Step: 106, State: [-0.30946465 0.00473531], Reward = -1.0 Step: 107, State: [-0.30522714 0.00423751], Reward = -1.0 Step: 108, State: [-0.30151275 0.00371439], Reward = -1.0 Step: 109, State: [-0.29834349 0.00316926], Reward = -1.0 Step: 110, State: [-0.29573796 0.00260553], Reward = -1.0 Step: 111, State: [-0.29371138 0.00202659], Reward = -1.0 Step: 112, State: [-0.29227548 0.0014359 ], Reward = -1.0 Step: 113, State: [-0.29143856 0.00083691], Reward = -1.0 Step: 114, State: [-2.91205456e-01 2.33108360e-04], Reward = -1.0 Step: 115, State: [-0.29157749 -0.00037204], Reward = -1.0 Step: 116, State: [-0.29255254 -0.00097504], Reward = -1.0 Step: 117, State: [-0.29412497 -0.00157243], Reward = -1.0 Step: 118, State: [-0.29628569 -0.00216073], Reward = -1.0 Step: 119, State: [-0.29902217 -0.00273648], Reward = -1.0 Step: 120, State: [-0.30231841 -0.00329624], Reward = -1.0 Step: 121, State: [-0.30615501 -0.00383661], Reward = -1.0 Step: 122, State: [-0.31050922 -0.00435421], Reward = -1.0 Step: 123, State: [-0.31535495 -0.00484573], Reward = -1.0 Step: 124, State: [-0.32066288 -0.00530793], Reward = -1.0 Step: 125, State: [-0.32640053 -0.00573765], Reward = -1.0 Step: 126, State: [-0.3325324 -0.00613187], Reward = -1.0 Step: 127, State: [-0.33902007 -0.00648767], Reward = -1.0 Step: 128, State: [-0.34582242 -0.00680234], Reward = -1.0 Step: 129, State: [-0.35289577 -0.00707335], Reward = -1.0 Step: 130, State: [-0.36019416 -0.00729839], Reward = -1.0 Step: 131, State: [-0.36766959 -0.00747543], Reward = -1.0 Step: 132, State: [-0.3752723 -0.00760271], Reward = -1.0 Step: 133, State: [-0.38295111 -0.00767881], Reward = -1.0 Step: 134, State: [-0.39065376 -0.00770264], Reward = -1.0 Step: 135, State: [-0.39832726 -0.00767351], Reward = -1.0 Step: 136, State: [-0.40591835 -0.00759108], Reward = -1.0 Step: 137, State: [-0.41337381 -0.00745547], Reward = -1.0 Step: 138, State: [-0.42064098 -0.00726717], Reward = -1.0 Step: 139, State: [-0.42766812 -0.00702713], Reward = -1.0 Step: 140, State: [-0.43440484 -0.00673672], Reward = -1.0 Step: 141, State: [-0.44080256 -0.00639772], Reward = -1.0 Step: 142, State: [-0.44681489 -0.00601233], Reward = -1.0 Step: 143, State: [-0.45239802 -0.00558313], Reward = -1.0 Step: 144, State: [-0.4575111 -0.00511308], Reward = -1.0 Step: 145, State: [-0.4621166 -0.0046055], Reward = -1.0 Step: 146, State: [-0.46618061 -0.00406401], Reward = -1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() #print(f"Step {i}: State={state}, Reward={reward}") print("Step: {0}, State: {1}, Reward = {2}".format(i, state,reward)) env.close() ###Output Step: 1, State: [-0.441596 -0.00162062], Reward = -1.0 Step: 2, State: [-0.44482546 -0.00322945], Reward = -1.0 Step: 3, State: [-0.44964022 -0.00481477], Reward = -1.0 Step: 4, State: [-0.45600514 -0.00636492], Reward = -1.0 Step: 5, State: [-0.46387355 -0.0078684 ], Reward = -1.0 Step: 6, State: [-0.4731875 -0.00931395], Reward = -1.0 Step: 7, State: [-0.48387809 -0.0106906 ], Reward = -1.0 Step: 8, State: [-0.49586589 -0.0119878 ], Reward = -1.0 Step: 9, State: [-0.50906144 -0.01319555], Reward = -1.0 Step: 10, State: [-0.52336599 -0.01430455], Reward = -1.0 Step: 11, State: [-0.53867228 -0.01530629], Reward = -1.0 Step: 12, State: [-0.55486556 -0.01619328], Reward = -1.0 Step: 13, State: [-0.57182469 -0.01695912], Reward = -1.0 Step: 14, State: [-0.58942338 -0.01759869], Reward = -1.0 Step: 15, State: [-0.60753159 -0.01810821], Reward = -1.0 Step: 16, State: [-0.62601693 -0.01848534], Reward = -1.0 Step: 17, State: [-0.64474616 -0.01872924], Reward = -1.0 Step: 18, State: [-0.66358667 -0.0188405 ], Reward = -1.0 Step: 19, State: [-0.68240785 -0.01882118], Reward = -1.0 Step: 20, State: [-0.70108251 -0.01867467], Reward = -1.0 Step: 21, State: [-0.71948806 -0.01840555], Reward = -1.0 Step: 22, State: [-0.73750756 -0.01801949], Reward = -1.0 Step: 23, State: [-0.7550306 -0.01752305], Reward = -1.0 Step: 24, State: [-0.77195404 -0.01692344], Reward = -1.0 Step: 25, State: [-0.78818243 -0.01622839], Reward = -1.0 Step: 26, State: [-0.80362834 -0.01544591], Reward = -1.0 Step: 27, State: [-0.8182125 -0.01458416], Reward = -1.0 Step: 28, State: [-0.83186371 -0.01365121], Reward = -1.0 Step: 29, State: [-0.84451867 -0.01265496], Reward = -1.0 Step: 30, State: [-0.85612171 -0.01160304], Reward = -1.0 Step: 31, State: [-0.86662435 -0.01050265], Reward = -1.0 Step: 32, State: [-0.87598495 -0.00936059], Reward = -1.0 Step: 33, State: [-0.88416813 -0.00818318], Reward = -1.0 Step: 34, State: [-0.89114441 -0.00697628], Reward = -1.0 Step: 35, State: [-0.89688969 -0.00574528], Reward = -1.0 Step: 36, State: [-0.90138485 -0.00449517], Reward = -1.0 Step: 37, State: [-0.90461542 -0.00323057], Reward = -1.0 Step: 38, State: [-0.90657123 -0.00195581], Reward = -1.0 Step: 39, State: [-9.07246235e-01 -6.75006284e-04], Reward = -1.0 Step: 40, State: [-9.06638370e-01 6.07864927e-04], Reward = -1.0 Step: 41, State: [-0.9027495 0.00388887], Reward = -1.0 Step: 42, State: [-0.89559171 0.00715779], Reward = -1.0 Step: 43, State: [-0.88518806 0.01040364], Reward = -1.0 Step: 44, State: [-0.87157393 0.01361413], Reward = -1.0 Step: 45, State: [-0.85479884 0.01677509], Reward = -1.0 Step: 46, State: [-0.83492876 0.01987008], Reward = -1.0 Step: 47, State: [-0.81204868 0.02288008], Reward = -1.0 Step: 48, State: [-0.78626529 0.02578338], Reward = -1.0 Step: 49, State: [-0.75770955 0.02855574], Reward = -1.0 Step: 50, State: [-0.7265388 0.03117074], Reward = -1.0 Step: 51, State: [-0.69293831 0.03360049], Reward = -1.0 Step: 52, State: [-0.6571217 0.03581661], Reward = -1.0 Step: 53, State: [-0.61933023 0.03779147], Reward = -1.0 Step: 54, State: [-0.57983061 0.03949962], Reward = -1.0 Step: 55, State: [-0.53891124 0.04091936], Reward = -1.0 Step: 56, State: [-0.49687707 0.04203417], Reward = -1.0 Step: 57, State: [-0.45404311 0.04283397], Reward = -1.0 Step: 58, State: [-0.41072703 0.04331608], Reward = -1.0 Step: 59, State: [-0.3672414 0.04348563], Reward = -1.0 Step: 60, State: [-0.32388592 0.04335548], Reward = -1.0 Step: 61, State: [-0.28094027 0.04294565], Reward = -1.0 Step: 62, State: [-0.23865802 0.04228225], Reward = -1.0 Step: 63, State: [-0.1972619 0.04139612], Reward = -1.0 Step: 64, State: [-0.15694065 0.04032125], Reward = -1.0 Step: 65, State: [-0.11784739 0.03909326], Reward = -1.0 Step: 66, State: [-0.08009951 0.03774788], Reward = -1.0 Step: 67, State: [-0.04377979 0.03631971], Reward = -1.0 Step: 68, State: [-0.00893855 0.03484125], Reward = -1.0 Step: 69, State: [0.0244036 0.03334214], Reward = -1.0 Step: 70, State: [0.05625244 0.03184884], Reward = -1.0 Step: 71, State: [0.0866368 0.03038436], Reward = -1.0 Step: 72, State: [0.11560512 0.02896832], Reward = -1.0 Step: 73, State: [0.14322229 0.02761717], Reward = -1.0 Step: 74, State: [0.1695667 0.02634441], Reward = -1.0 Step: 75, State: [0.19472767 0.02516097], Reward = -1.0 Step: 76, State: [0.21880323 0.02407556], Reward = -1.0 Step: 77, State: [0.24189832 0.02309509], Reward = -1.0 Step: 78, State: [0.26412331 0.02222499], Reward = -1.0 Step: 79, State: [0.2855929 0.02146959], Reward = -1.0 Step: 80, State: [0.3064253 0.0208324], Reward = -1.0 Step: 81, State: [0.32674172 0.02031641], Reward = -1.0 Step: 82, State: [0.34666604 0.01992432], Reward = -1.0 Step: 83, State: [0.36632481 0.01965877], Reward = -1.0 Step: 84, State: [0.38584731 0.0195225 ], Reward = -1.0 Step: 85, State: [0.40536582 0.01951852], Reward = -1.0 Step: 86, State: [0.42501607 0.01965025], Reward = -1.0 Step: 87, State: [0.44493767 0.01992161], Reward = -1.0 Step: 88, State: [0.46527478 0.02033711], Reward = -1.0 Step: 89, State: [0.48617669 0.02090191], Reward = -1.0 Step: 90, State: [0.50779852 0.02162183], Reward = -1.0 ###Markdown Reinforcement Learning![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined.$ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 200 SHOW_EVERY = 40 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: #print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") print("Current episode: {0}, success: {1}".format(episode, success_count,float(success_count)/SHOW_EVERY)) success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) env.close() #end the process import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = ['v-{0}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = ['p-{1}' for x in range(DISCRETE_GRID_SIZE[1])] df np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it. To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into # discrete values. This is often called binning. We divide # the range that the state values might occupy and assign # each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also # provide a flag to indicate if the game should be # rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low) \ /DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE \ + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count}" +\ " ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Deep Learning and Security*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.54298351 0.00115394], Reward=-1.0 Step 2: State=[-0.54068426 0.00229925], Reward=-1.0 Step 3: State=[-0.53725693 0.00342733], Reward=-1.0 Step 4: State=[-0.53272719 0.00452974], Reward=-1.0 Step 5: State=[-0.527129 0.00559819], Reward=-1.0 Step 6: State=[-0.52050433 0.00662467], Reward=-1.0 Step 7: State=[-0.51290287 0.00760146], Reward=-1.0 Step 8: State=[-0.50438161 0.00852126], Reward=-1.0 Step 9: State=[-0.4950044 0.00937721], Reward=-1.0 Step 10: State=[-0.48484139 0.01016301], Reward=-1.0 Step 11: State=[-0.47396841 0.01087299], Reward=-1.0 Step 12: State=[-0.46246627 0.01150213], Reward=-1.0 Step 13: State=[-0.45042007 0.0120462 ], Reward=-1.0 Step 14: State=[-0.43791831 0.01250176], Reward=-1.0 Step 15: State=[-0.4250521 0.01286621], Reward=-1.0 Step 16: State=[-0.41191426 0.01313783], Reward=-1.0 Step 17: State=[-0.39859848 0.01331578], Reward=-1.0 Step 18: State=[-0.38519838 0.0134001 ], Reward=-1.0 Step 19: State=[-0.37180672 0.01339166], Reward=-1.0 Step 20: State=[-0.35851456 0.01329216], Reward=-1.0 Step 21: State=[-0.34541053 0.01310403], Reward=-1.0 Step 22: State=[-0.33258017 0.01283036], Reward=-1.0 Step 23: State=[-0.32010531 0.01247486], Reward=-1.0 Step 24: State=[-0.30806361 0.0120417 ], Reward=-1.0 Step 25: State=[-0.29652811 0.0115355 ], Reward=-1.0 Step 26: State=[-0.28556694 0.01096116], Reward=-1.0 Step 27: State=[-0.27524312 0.01032383], Reward=-1.0 Step 28: State=[-0.26561434 0.00962878], Reward=-1.0 Step 29: State=[-0.25673298 0.00888136], Reward=-1.0 Step 30: State=[-0.24864606 0.00808693], Reward=-1.0 Step 31: State=[-0.24139526 0.0072508 ], Reward=-1.0 Step 32: State=[-0.23501706 0.0063782 ], Reward=-1.0 Step 33: State=[-0.22954281 0.00547425], Reward=-1.0 Step 34: State=[-0.22499885 0.00454396], Reward=-1.0 Step 35: State=[-0.22140666 0.00359218], Reward=-1.0 Step 36: State=[-0.21878297 0.00262369], Reward=-1.0 Step 37: State=[-0.21713985 0.00164313], Reward=-1.0 Step 38: State=[-0.21648478 0.00065507], Reward=-1.0 Step 39: State=[-0.21682075 -0.00033597], Reward=-1.0 Step 40: State=[-0.21814623 -0.00132548], Reward=-1.0 Step 41: State=[-0.22045518 -0.00230895], Reward=-1.0 Step 42: State=[-0.22373702 -0.00328184], Reward=-1.0 Step 43: State=[-0.22797653 -0.00423951], Reward=-1.0 Step 44: State=[-0.23315378 -0.00517725], Reward=-1.0 Step 45: State=[-0.239244 -0.00609022], Reward=-1.0 Step 46: State=[-0.24621747 -0.00697347], Reward=-1.0 Step 47: State=[-0.25403939 -0.00782191], Reward=-1.0 Step 48: State=[-0.26266974 -0.00863035], Reward=-1.0 Step 49: State=[-0.27206323 -0.0093935 ], Reward=-1.0 Step 50: State=[-0.28216923 -0.010106 ], Reward=-1.0 Step 51: State=[-0.29293174 -0.01076251], Reward=-1.0 Step 52: State=[-0.30428945 -0.01135771], Reward=-1.0 Step 53: State=[-0.31617585 -0.0118864 ], Reward=-1.0 Step 54: State=[-0.32851945 -0.0123436 ], Reward=-1.0 Step 55: State=[-0.34124405 -0.0127246 ], Reward=-1.0 Step 56: State=[-0.3542691 -0.01302505], Reward=-1.0 Step 57: State=[-0.36751021 -0.01324111], Reward=-1.0 Step 58: State=[-0.38087966 -0.01336945], Reward=-1.0 Step 59: State=[-0.3942871 -0.01340744], Reward=-1.0 Step 60: State=[-0.40764024 -0.01335314], Reward=-1.0 Step 61: State=[-0.42084563 -0.01320539], Reward=-1.0 Step 62: State=[-0.43380952 -0.01296389], Reward=-1.0 Step 63: State=[-0.44643872 -0.0126292 ], Reward=-1.0 Step 64: State=[-0.45864146 -0.01220274], Reward=-1.0 Step 65: State=[-0.47032831 -0.01168684], Reward=-1.0 Step 66: State=[-0.48141298 -0.01108468], Reward=-1.0 Step 67: State=[-0.49181321 -0.01040022], Reward=-1.0 Step 68: State=[-0.50145146 -0.00963826], Reward=-1.0 Step 69: State=[-0.5102557 -0.00880424], Reward=-1.0 Step 70: State=[-0.51815998 -0.00790428], Reward=-1.0 Step 71: State=[-0.52510506 -0.00694507], Reward=-1.0 Step 72: State=[-0.53103883 -0.00593378], Reward=-1.0 Step 73: State=[-0.53591681 -0.00487798], Reward=-1.0 Step 74: State=[-0.53970243 -0.00378562], Reward=-1.0 Step 75: State=[-0.54236732 -0.00266489], Reward=-1.0 Step 76: State=[-0.54389151 -0.0015242 ], Reward=-1.0 Step 77: State=[-5.44263607e-01 -3.72094556e-04], Reward=-1.0 Step 78: State=[-0.54348081 0.00078279], Reward=-1.0 Step 79: State=[-0.541549 0.00193182], Reward=-1.0 Step 80: State=[-0.53848261 0.00306638], Reward=-1.0 Step 81: State=[-0.53430464 0.00417797], Reward=-1.0 Step 82: State=[-0.52904639 0.00525825], Reward=-1.0 Step 83: State=[-0.52274728 0.00629911], Reward=-1.0 Step 84: State=[-0.51545456 0.00729272], Reward=-1.0 Step 85: State=[-0.50722291 0.00823165], Reward=-1.0 Step 86: State=[-0.49811404 0.00910888], Reward=-1.0 Step 87: State=[-0.48819611 0.00991793], Reward=-1.0 Step 88: State=[-0.4775432 0.01065291], Reward=-1.0 Step 89: State=[-0.46623461 0.01130859], Reward=-1.0 Step 90: State=[-0.45435414 0.01188048], Reward=-1.0 Step 91: State=[-0.44198927 0.01236487], Reward=-1.0 Step 92: State=[-0.42923038 0.01275889], Reward=-1.0 Step 93: State=[-0.41616983 0.01306055], Reward=-1.0 Step 94: State=[-0.40290112 0.01326871], Reward=-1.0 Step 95: State=[-0.389518 0.01338313], Reward=-1.0 Step 96: State=[-0.37611358 0.01340442], Reward=-1.0 Step 97: State=[-0.36277956 0.01333402], Reward=-1.0 Step 98: State=[-0.34960543 0.01317413], Reward=-1.0 Step 99: State=[-0.3366778 0.01292763], Reward=-1.0 Step 100: State=[-0.32407975 0.01259805], Reward=-1.0 Step 101: State=[-0.31189033 0.01218942], Reward=-1.0 Step 102: State=[-0.3001841 0.01170623], Reward=-1.0 Step 103: State=[-0.28903082 0.01115328], Reward=-1.0 Step 104: State=[-0.27849515 0.01053567], Reward=-1.0 Step 105: State=[-0.26863652 0.00985862], Reward=-1.0 Step 106: State=[-0.25950904 0.00912749], Reward=-1.0 Step 107: State=[-0.25116142 0.00834761], Reward=-1.0 Step 108: State=[-0.24363708 0.00752434], Reward=-1.0 Step 109: State=[-0.23697416 0.00666292], Reward=-1.0 Step 110: State=[-0.23120564 0.00576852], Reward=-1.0 Step 111: State=[-0.22635946 0.00484618], Reward=-1.0 Step 112: State=[-0.22245866 0.0039008 ], Reward=-1.0 Step 113: State=[-0.21952148 0.00293718], Reward=-1.0 Step 114: State=[-0.21756149 0.00196 ], Reward=-1.0 Step 115: State=[-0.21658763 0.00097386], Reward=-1.0 Step 116: State=[-2.16604342e-01 -1.67115330e-05], Reward=-1.0 Step 117: State=[-0.21761155 -0.0010072 ], Reward=-1.0 Step 118: State=[-0.21960466 -0.00199312], Reward=-1.0 Step 119: State=[-0.22257458 -0.00296991], Reward=-1.0 Step 120: State=[-0.22650757 -0.003933 ], Reward=-1.0 Step 121: State=[-0.23138525 -0.00487768], Reward=-1.0 Step 122: State=[-0.23718442 -0.00579916], Reward=-1.0 Step 123: State=[-0.24387695 -0.00669253], Reward=-1.0 Step 124: State=[-0.2514297 -0.00755275], Reward=-1.0 Step 125: State=[-0.25980435 -0.00837465], Reward=-1.0 Step 126: State=[-0.26895731 -0.00915296], Reward=-1.0 Step 127: State=[-0.27883967 -0.00988236], Reward=-1.0 Step 128: State=[-0.28939716 -0.01055749], Reward=-1.0 Step 129: State=[-0.30057017 -0.01117301], Reward=-1.0 Step 130: State=[-0.31229385 -0.01172368], Reward=-1.0 Step 131: State=[-0.32449829 -0.01220444], Reward=-1.0 Step 132: State=[-0.33710877 -0.01261047], Reward=-1.0 Step 133: State=[-0.35004609 -0.01293732], Reward=-1.0 Step 134: State=[-0.36322703 -0.01318094], Reward=-1.0 Step 135: State=[-0.3765649 -0.01333787], Reward=-1.0 Step 136: State=[-0.3899701 -0.0134052], Reward=-1.0 Step 137: State=[-0.40335089 -0.01338079], Reward=-1.0 Step 138: State=[-0.41661411 -0.01326322], Reward=-1.0 Step 139: State=[-0.429666 -0.0130519], Reward=-1.0 Step 140: State=[-0.44241311 -0.0127471 ], Reward=-1.0 Step 141: State=[-0.4547631 -0.01235 ], Reward=-1.0 Step 142: State=[-0.4666257 -0.0118626], Reward=-1.0 Step 143: State=[-0.47791353 -0.01128782], Reward=-1.0 Step 144: State=[-0.48854292 -0.01062939], Reward=-1.0 Step 145: State=[-0.49843474 -0.00989182], Reward=-1.0 Step 146: State=[-0.50751511 -0.00908037], Reward=-1.0 Step 147: State=[-0.51571607 -0.00820096], Reward=-1.0 Step 148: State=[-0.52297614 -0.00726007], Reward=-1.0 Step 149: State=[-0.52924088 -0.00626474], Reward=-1.0 Step 150: State=[-0.53446331 -0.00522243], Reward=-1.0 Step 151: State=[-0.53860426 -0.00414096], Reward=-1.0 Step 152: State=[-0.54163272 -0.00302845], Reward=-1.0 Step 153: State=[-0.54352598 -0.00189327], Reward=-1.0 Step 154: State=[-0.54426988 -0.0007439 ], Reward=-1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.51431373 -0.00107771], Reward=-1.0 Step 2: State=[-0.51646107 -0.00214734], Reward=-1.0 Step 3: State=[-0.51966193 -0.00320087], Reward=-1.0 Step 4: State=[-0.52389233 -0.00423039], Reward=-1.0 Step 5: State=[-0.52912052 -0.00522819], Reward=-1.0 Step 6: State=[-0.53530729 -0.00618678], Reward=-1.0 Step 7: State=[-0.54240628 -0.00709898], Reward=-1.0 Step 8: State=[-0.55036428 -0.007958 ], Reward=-1.0 Step 9: State=[-0.55912175 -0.00875748], Reward=-1.0 Step 10: State=[-0.56861331 -0.00949156], Reward=-1.0 Step 11: State=[-0.57876828 -0.01015497], Reward=-1.0 Step 12: State=[-0.58951137 -0.01074309], Reward=-1.0 Step 13: State=[-0.60076333 -0.01125196], Reward=-1.0 Step 14: State=[-0.61244171 -0.01167838], Reward=-1.0 Step 15: State=[-0.62446163 -0.01201992], Reward=-1.0 Step 16: State=[-0.63673657 -0.01227494], Reward=-1.0 Step 17: State=[-0.64917917 -0.0124426 ], Reward=-1.0 Step 18: State=[-0.66170205 -0.01252287], Reward=-1.0 Step 19: State=[-0.67421853 -0.01251648], Reward=-1.0 Step 20: State=[-0.68664341 -0.01242488], Reward=-1.0 Step 21: State=[-0.69889363 -0.01225023], Reward=-1.0 Step 22: State=[-0.71088891 -0.01199528], Reward=-1.0 Step 23: State=[-0.72255227 -0.01166336], Reward=-1.0 Step 24: State=[-0.73381051 -0.01125823], Reward=-1.0 Step 25: State=[-0.7445946 -0.01078409], Reward=-1.0 Step 26: State=[-0.75484 -0.0102454], Reward=-1.0 Step 27: State=[-0.76448689 -0.00964689], Reward=-1.0 Step 28: State=[-0.77348032 -0.00899343], Reward=-1.0 Step 29: State=[-0.78177031 -0.00828998], Reward=-1.0 Step 30: State=[-0.78931187 -0.00754156], Reward=-1.0 Step 31: State=[-0.79606502 -0.00675316], Reward=-1.0 Step 32: State=[-0.80199476 -0.00592974], Reward=-1.0 Step 33: State=[-0.80707094 -0.00507618], Reward=-1.0 Step 34: State=[-0.81126824 -0.00419729], Reward=-1.0 Step 35: State=[-0.81456603 -0.00329779], Reward=-1.0 Step 36: State=[-0.81694832 -0.0023823 ], Reward=-1.0 Step 37: State=[-0.81840369 -0.00145537], Reward=-1.0 Step 38: State=[-8.18925204e-01 -5.21510941e-04], Reward=-1.0 Step 39: State=[-8.18510378e-01 4.14826025e-04], Reward=-1.0 Step 40: State=[-0.81516118 0.00334919], Reward=-1.0 Step 41: State=[-0.80889363 0.00626755], Reward=-1.0 Step 42: State=[-0.7997382 0.00915543], Reward=-1.0 Step 43: State=[-0.78774062 0.01199759], Reward=-1.0 Step 44: State=[-0.77296289 0.01477773], Reward=-1.0 Step 45: State=[-0.75548455 0.01747834], Reward=-1.0 Step 46: State=[-0.73540399 0.02008056], Reward=-1.0 Step 47: State=[-0.71283965 0.02256434], Reward=-1.0 Step 48: State=[-0.68793102 0.02490863], Reward=-1.0 Step 49: State=[-0.66083923 0.0270918 ], Reward=-1.0 Step 50: State=[-0.63174696 0.02909226], Reward=-1.0 Step 51: State=[-0.60085774 0.03088922], Reward=-1.0 Step 52: State=[-0.56839425 0.03246349], Reward=-1.0 Step 53: State=[-0.53459581 0.03379844], Reward=-1.0 Step 54: State=[-0.49971491 0.03488091], Reward=-1.0 Step 55: State=[-0.46401297 0.03570193], Reward=-1.0 Step 56: State=[-0.42775556 0.03625741], Reward=-1.0 Step 57: State=[-0.39120711 0.03654845], Reward=-1.0 Step 58: State=[-0.35462569 0.03658142], Reward=-1.0 Step 59: State=[-0.31825799 0.0363677 ], Reward=-1.0 Step 60: State=[-0.28233478 0.03592322], Reward=-1.0 Step 61: State=[-0.24706714 0.03526764], Reward=-1.0 Step 62: State=[-0.21264364 0.0344235 ], Reward=-1.0 Step 63: State=[-0.17922847 0.03341517], Reward=-1.0 Step 64: State=[-0.14696054 0.03226793], Reward=-1.0 Step 65: State=[-0.11595355 0.03100699], Reward=-1.0 Step 66: State=[-0.08629682 0.02965673], Reward=-1.0 Step 67: State=[-0.05805677 0.02824004], Reward=-1.0 Step 68: State=[-0.03127891 0.02677787], Reward=-1.0 Step 69: State=[-0.00599004 0.02528887], Reward=-1.0 Step 70: State=[0.01779923 0.02378927], Reward=-1.0 Step 71: State=[0.04009206 0.02229283], Reward=-1.0 Step 72: State=[0.06090295 0.02081089], Reward=-1.0 Step 73: State=[0.08025546 0.01935251], Reward=-1.0 Step 74: State=[0.09818008 0.01792462], Reward=-1.0 Step 75: State=[0.11471236 0.01653228], Reward=-1.0 Step 76: State=[0.12989122 0.01517886], Reward=-1.0 Step 77: State=[0.14375749 0.01386628], Reward=-1.0 Step 78: State=[0.15635269 0.01259519], Reward=-1.0 Step 79: State=[0.16771789 0.01136521], Reward=-1.0 Step 80: State=[0.17789293 0.01017504], Reward=-1.0 Step 81: State=[0.18691562 0.00902269], Reward=-1.0 Step 82: State=[0.19482116 0.00790554], Reward=-1.0 Step 83: State=[0.20164168 0.00682052], Reward=-1.0 Step 84: State=[0.20740583 0.00576416], Reward=-1.0 Step 85: State=[0.21213852 0.00473269], Reward=-1.0 Step 86: State=[0.21586063 0.00372211], Reward=-1.0 Step 87: State=[0.21858888 0.00272825], Reward=-1.0 Step 88: State=[0.22033568 0.0017468 ], Reward=-1.0 Step 89: State=[0.22110904 0.00077336], Reward=-1.0 Step 90: State=[ 2.20912527e-01 -1.96509754e-04], Reward=-1.0 Step 91: State=[ 0.21774524 -0.00316729], Reward=-1.0 Step 92: State=[ 0.21159265 -0.00615259], Reward=-1.0 Step 93: State=[ 0.20242705 -0.0091656 ], Reward=-1.0 Step 94: State=[ 0.19020845 -0.01221861], Reward=-1.0 Step 95: State=[ 0.17488593 -0.01532251], Reward=-1.0 Step 96: State=[ 0.15639968 -0.01848625], Reward=-1.0 Step 97: State=[ 0.1346836 -0.02171608], Reward=-1.0 Step 98: State=[ 0.10966883 -0.02501477], Reward=-1.0 Step 99: State=[ 0.08128815 -0.02838068], Reward=-1.0 Step 100: State=[ 0.04948145 -0.03180671], Reward=-1.0 Step 101: State=[ 0.01420223 -0.03527921], Reward=-1.0 Step 102: State=[-0.02457471 -0.03877695], Reward=-1.0 Step 103: State=[-0.06684487 -0.04227015], Reward=-1.0 Step 104: State=[-0.11256492 -0.04572006], Reward=-1.0 Step 105: State=[-0.16164378 -0.04907886], Reward=-1.0 Step 106: State=[-0.21393441 -0.05229063], Reward=-1.0 Step 107: State=[-0.26922758 -0.05529317], Reward=-1.0 Step 108: State=[-0.32724868 -0.05802111], Reward=-1.0 Step 109: State=[-0.38765872 -0.06041004], Reward=-1.0 Step 110: State=[-0.45006028 -0.06240156], Reward=-1.0 Step 111: State=[-0.51400891 -0.06394863], Reward=-1.0 Step 112: State=[-0.57902946 -0.06502055], Reward=-1.0 Step 113: State=[-0.64463619 -0.06560673], Reward=-1.0 Step 114: State=[-0.71035496 -0.06571877], Reward=-1.0 Step 115: State=[-0.77574519 -0.06539023], Reward=-1.0 Step 116: State=[-0.84041959 -0.06467439], Reward=-1.0 Step 117: State=[-0.90405977 -0.06364018], Reward=-1.0 Step 118: State=[-0.96642693 -0.06236716], Reward=-1.0 Step 119: State=[-1.02736712 -0.06094019], Reward=-1.0 Step 120: State=[-1.08681173 -0.05944462], Reward=-1.0 Step 121: State=[-1.14477398 -0.05796225], Reward=-1.0 Step 122: State=[-1.2 0. ], Reward=-1.0 Step 123: State=[-1.1987581 0.0012419], Reward=-1.0 Step 124: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 125: State=[-1.18652173 0.00774848], Reward=-1.0 Step 126: State=[-1.17548846 0.01103326], Reward=-1.0 Step 127: State=[-1.16113808 0.01435038], Reward=-1.0 Step 128: State=[-1.14343234 0.01770574], Reward=-1.0 Step 129: State=[-1.12233007 0.02110228], Reward=-1.0 Step 130: State=[-1.09779103 0.02453904], Reward=-1.0 Step 131: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 132: State=[-1.03827616 0.03150456], Reward=-1.0 Step 133: State=[-1.0032725 0.03500367], Reward=-1.0 Step 134: State=[-0.9647905 0.03848199], Reward=-1.0 Step 135: State=[-0.92288452 0.04190598], Reward=-1.0 Step 136: State=[-0.87765038 0.04523414], Reward=-1.0 Step 137: State=[-0.82923273 0.04841765], Reward=-1.0 Step 138: State=[-0.77783078 0.05140195], Reward=-1.0 Step 139: State=[-0.72370164 0.05412914], Reward=-1.0 Step 140: State=[-0.66716026 0.05654138], Reward=-1.0 Step 141: State=[-0.60857514 0.05858511], Reward=-1.0 Step 142: State=[-0.54835959 0.06021555], Reward=-1.0 Step 143: State=[-0.4869585 0.06140109], Reward=-1.0 Step 144: State=[-0.42483166 0.06212684], Reward=-1.0 Step 145: State=[-0.36243478 0.06239688], Reward=-1.0 Step 146: State=[-0.30020009 0.06223469], Reward=-1.0 Step 147: State=[-0.23851824 0.06168185], Reward=-1.0 Step 148: State=[-0.17772322 0.06079502], Reward=-1.0 Step 149: State=[-0.1180812 0.05964202], Reward=-1.0 Step 150: State=[-0.05978395 0.05829725], Reward=-1.0 Step 151: State=[-0.0029466 0.05683735], Reward=-1.0 Step 152: State=[0.05239085 0.05533745], Reward=-1.0 ###Markdown Reinforcement Learning![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined.$ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q 'gym==0.10.11' !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents ###Output Reading package lists... Done Building dependency tree Reading state information... Done x11-utils is already the newest version (7.7+3build1). ffmpeg is already the newest version (7:3.4.6-0ubuntu0.18.04.1). xvfb is already the newest version (2:1.19.6-1ubuntu4.4). 0 upgraded, 0 newly installed, 0 to remove and 31 not upgraded. ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technique upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the actions of the agent.* **Actions** - Steps that can be performed by the agent to alter the environment * **Step** - A step occurs each time that the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. In many environments, a terminal state occurs when the agent has one, lost, or the environment exceeding the maximum number of steps.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can be in a range of positions from released to fully engaged. Researchers have come up with clever tricks to allow Q-Learning to accommodate continuous actions.In the next chapter, we will learn more about deep reinforcement learning. Deep neural networks can help to solve the problems of continuous environments and action spaces. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, even with full throttle, it cannot merely accelerate up the steep slope. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, for now, TF-Agents is just used to render the mountain care environment. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe following code shows an agent that applies full throttle to climb the hill. The cart is not strong enough. It will need to use potential energy from the mountain behind it. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() """ Utility functions to enable video recording of gym environment and displaying it To enable video, just do "env = wrap_env(env)"" """ def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force to one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.57730941 -0.00060338], Reward=-1.0 Step 2: State=[-0.5785117 -0.00120229], Reward=-1.0 Step 3: State=[-0.580304 -0.0017923], Reward=-1.0 Step 4: State=[-0.58267307 -0.00236906], Reward=-1.0 Step 5: State=[-0.58560139 -0.00292832], Reward=-1.0 Step 6: State=[-0.58906736 -0.00346598], Reward=-1.0 Step 7: State=[-0.59304548 -0.00397811], Reward=-1.0 Step 8: State=[-0.5975065 -0.00446102], Reward=-1.0 Step 9: State=[-0.60241775 -0.00491125], Reward=-1.0 Step 10: State=[-0.60774335 -0.0053256 ], Reward=-1.0 Step 11: State=[-0.61344454 -0.00570119], Reward=-1.0 Step 12: State=[-0.61948002 -0.00603548], Reward=-1.0 Step 13: State=[-0.62580627 -0.00632625], Reward=-1.0 Step 14: State=[-0.63237791 -0.00657165], Reward=-1.0 Step 15: State=[-0.63914812 -0.00677021], Reward=-1.0 Step 16: State=[-0.64606896 -0.00692084], Reward=-1.0 Step 17: State=[-0.65309179 -0.00702284], Reward=-1.0 Step 18: State=[-0.66016768 -0.00707588], Reward=-1.0 Step 19: State=[-0.66724771 -0.00708003], Reward=-1.0 Step 20: State=[-0.67428342 -0.00703571], Reward=-1.0 Step 21: State=[-0.68122709 -0.00694367], Reward=-1.0 Step 22: State=[-0.68803212 -0.00680503], Reward=-1.0 Step 23: State=[-0.69465331 -0.00662119], Reward=-1.0 Step 24: State=[-0.70104716 -0.00639385], Reward=-1.0 Step 25: State=[-0.70717213 -0.00612496], Reward=-1.0 Step 26: State=[-0.71298884 -0.00581671], Reward=-1.0 Step 27: State=[-0.71846032 -0.00547148], Reward=-1.0 Step 28: State=[-0.72355218 -0.00509185], Reward=-1.0 Step 29: State=[-0.72823271 -0.00468053], Reward=-1.0 Step 30: State=[-0.73247309 -0.00424038], Reward=-1.0 Step 31: State=[-0.73624744 -0.00377435], Reward=-1.0 Step 32: State=[-0.73953293 -0.00328548], Reward=-1.0 Step 33: State=[-0.74230982 -0.00277689], Reward=-1.0 Step 34: State=[-0.74456157 -0.00225175], Reward=-1.0 Step 35: State=[-0.74627483 -0.00171326], Reward=-1.0 Step 36: State=[-0.7474395 -0.00116466], Reward=-1.0 Step 37: State=[-7.48048712e-01 -6.09216585e-04], Reward=-1.0 Step 38: State=[-7.48098908e-01 -5.01962094e-05], Reward=-1.0 Step 39: State=[-7.47589789e-01 5.09118450e-04], Reward=-1.0 Step 40: State=[-0.74452434 0.00306545], Reward=-1.0 Step 41: State=[-0.73892063 0.00560372], Reward=-1.0 Step 42: State=[-0.73081198 0.00810864], Reward=-1.0 Step 43: State=[-0.72024742 0.01056456], Reward=-1.0 Step 44: State=[-0.70729207 0.01295535], Reward=-1.0 Step 45: State=[-0.6920277 0.01526437], Reward=-1.0 Step 46: State=[-0.67455318 0.01747452], Reward=-1.0 Step 47: State=[-0.6549848 0.01956837], Reward=-1.0 Step 48: State=[-0.63345635 0.02152845], Reward=-1.0 Step 49: State=[-0.61011881 0.02333755], Reward=-1.0 Step 50: State=[-0.58513962 0.02497919], Reward=-1.0 Step 51: State=[-0.5587015 0.02643812], Reward=-1.0 Step 52: State=[-0.53100059 0.02770091], Reward=-1.0 Step 53: State=[-0.50224417 0.02875642], Reward=-1.0 Step 54: State=[-0.4726478 0.02959637], Reward=-1.0 Step 55: State=[-0.44243208 0.03021572], Reward=-1.0 Step 56: State=[-0.41181911 0.03061297], Reward=-1.0 Step 57: State=[-0.38102886 0.03079025], Reward=-1.0 Step 58: State=[-0.35027559 0.03075328], Reward=-1.0 Step 59: State=[-0.31976445 0.03051114], Reward=-1.0 Step 60: State=[-0.28968855 0.0300759 ], Reward=-1.0 Step 61: State=[-0.26022651 0.02946204], Reward=-1.0 Step 62: State=[-0.23154055 0.02868596], Reward=-1.0 Step 63: State=[-0.20377533 0.02776522], Reward=-1.0 Step 64: State=[-0.17705734 0.026718 ], Reward=-1.0 Step 65: State=[-0.15149488 0.02556246], Reward=-1.0 Step 66: State=[-0.12717863 0.02431624], Reward=-1.0 Step 67: State=[-0.10418263 0.02299601], Reward=-1.0 Step 68: State=[-0.0825655 0.02161713], Reward=-1.0 Step 69: State=[-0.06237207 0.02019343], Reward=-1.0 Step 70: State=[-0.04363501 0.01873706], Reward=-1.0 Step 71: State=[-0.02637656 0.01725845], Reward=-1.0 Step 72: State=[-0.01061028 0.01576628], Reward=-1.0 Step 73: State=[0.00365726 0.01426754], Reward=-1.0 Step 74: State=[0.01642496 0.01276769], Reward=-1.0 Step 75: State=[0.02769568 0.01127073], Reward=-1.0 Step 76: State=[0.03747504 0.00977935], Reward=-1.0 Step 77: State=[0.04577017 0.00829513], Reward=-1.0 Step 78: State=[0.05258884 0.00681867], Reward=-1.0 Step 79: State=[0.05793855 0.00534971], Reward=-1.0 Step 80: State=[0.06182593 0.00388738], Reward=-1.0 Step 81: State=[0.0642562 0.00243026], Reward=-1.0 Step 82: State=[0.06523276 0.00097657], Reward=-1.0 Step 83: State=[ 0.06475705 -0.00047571], Reward=-1.0 Step 84: State=[ 0.06082837 -0.00392868], Reward=-1.0 Step 85: State=[ 0.0534412 -0.00738717], Reward=-1.0 Step 86: State=[ 0.04258609 -0.01085511], Reward=-1.0 Step 87: State=[ 0.02825135 -0.01433474], Reward=-1.0 Step 88: State=[ 0.01042559 -0.01782576], Reward=-1.0 Step 89: State=[-0.01089895 -0.02132454], Reward=-1.0 Step 90: State=[-0.03572216 -0.0248232 ], Reward=-1.0 Step 91: State=[-0.06403102 -0.02830886], Reward=-1.0 Step 92: State=[-0.0957939 -0.03176288], Reward=-1.0 Step 93: State=[-0.13095425 -0.03516035], Reward=-1.0 Step 94: State=[-0.16942414 -0.03846989], Reward=-1.0 Step 95: State=[-0.21107801 -0.04165386], Reward=-1.0 Step 96: State=[-0.25574716 -0.04466916], Reward=-1.0 Step 97: State=[-0.30321589 -0.04746873], Reward=-1.0 Step 98: State=[-0.35321967 -0.05000379], Reward=-1.0 Step 99: State=[-0.40544638 -0.05222671], Reward=-1.0 Step 100: State=[-0.4595408 -0.05409441], Reward=-1.0 Step 101: State=[-0.51511269 -0.0555719 ], Reward=-1.0 Step 102: State=[-0.57174823 -0.05663553], Reward=-1.0 Step 103: State=[-0.6290239 -0.05727567], Reward=-1.0 Step 104: State=[-0.68652199 -0.0574981 ], Reward=-1.0 Step 105: State=[-0.74384624 -0.05732425], Reward=-1.0 Step 106: State=[-0.80063623 -0.05678999], Reward=-1.0 Step 107: State=[-0.85657951 -0.05594328], Reward=-1.0 Step 108: State=[-0.91142055 -0.05484104], Reward=-1.0 Step 109: State=[-0.96496613 -0.05354558], Reward=-1.0 Step 110: State=[-1.0170874 -0.05212127], Reward=-1.0 Step 111: State=[-1.06771887 -0.05063146], Reward=-1.0 Step 112: State=[-1.11685507 -0.0491362 ], Reward=-1.0 Step 113: State=[-1.16454566 -0.04769059], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through a series of episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value driven action is governed by the epsilon ($\epsilon$) parameter, which is the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation.$ Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:*$Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?*$s_t$ - The current state.*$r_t$ - The last reward received.*$a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha) scales this delta. A learning rate of 1.0 would fully implement the temporal difference to the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount that we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum of the Q-values from the resulting state when the client takes this action. It is essential to add the maximum of action Q-values for the new state because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into discrete values. # This is often called binning. We divide the range that the state values # might occupy and assign each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) # Run one game. The q_table to use is provided. We also provide a flag to # indicate if the game should be rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% to the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each of the continuous state variables. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB then we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode<EPISODES: episode+=1 done = False # Run the game. If we are local, display render animation at SHOW_EVERY # intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 (0.0) Current episode: 2000, success: 0 (0.0) Current episode: 3000, success: 0 (0.0) Current episode: 4000, success: 29 (0.029) Current episode: 5000, success: 345 (0.345) Current episode: 6000, success: 834 (0.834) Current episode: 7000, success: 797 (0.797) Current episode: 8000, success: 679 (0.679) Current episode: 9000, success: 600 (0.6) Current episode: 10000, success: 728 (0.728) Current episode: 11000, success: 205 (0.205) Current episode: 12000, success: 612 (0.612) Current episode: 13000, success: 733 (0.733) Current episode: 14000, success: 1000 (1.0) Current episode: 15000, success: 998 (0.998) Current episode: 16000, success: 879 (0.879) Current episode: 17000, success: 510 (0.51) Current episode: 18000, success: 615 (0.615) Current episode: 19000, success: 220 (0.22) Current episode: 20000, success: 445 (0.445) Current episode: 21000, success: 627 (0.627) Current episode: 22000, success: 597 (0.597) Current episode: 23000, success: 827 (0.827) Current episode: 24000, success: 862 (0.862) Current episode: 25000, success: 322 (0.322) Current episode: 26000, success: 632 (0.632) Current episode: 27000, success: 613 (0.613) Current episode: 28000, success: 409 (0.409) Current episode: 29000, success: 379 (0.379) Current episode: 30000, success: 320 (0.32) Current episode: 31000, success: 327 (0.327) Current episode: 32000, success: 302 (0.302) Current episode: 33000, success: 308 (0.308) Current episode: 34000, success: 336 (0.336) Current episode: 35000, success: 274 (0.274) Current episode: 36000, success: 281 (0.281) Current episode: 37000, success: 301 (0.301) Current episode: 38000, success: 322 (0.322) Current episode: 39000, success: 292 (0.292) Current episode: 40000, success: 299 (0.299) Current episode: 41000, success: 281 (0.281) Current episode: 42000, success: 233 (0.233) Current episode: 43000, success: 380 (0.38) Current episode: 44000, success: 598 (0.598) Current episode: 45000, success: 933 (0.933) Current episode: 46000, success: 986 (0.986) Current episode: 47000, success: 1000 (1.0) Current episode: 48000, success: 1000 (1.0) Current episode: 49000, success: 1000 (1.0) Current episode: 50000, success: 1000 (1.0) True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time that we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. Once you observe that the agent has gotten 100% for several update intervals, it might be safe to stop training. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the action that the agent would perform for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that directions do arise, as seen by calculating the means of rows and columns. The actions seem consistent at upper and lower halves of both velocity and position. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Deep Learning and Security*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)* Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False ###Output _____no_output_____ ###Markdown Part 12.2: Introduction to Q-Learning Single Action CartMountain car actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceState values:* state[0] - Position * state[1] - VelocityThe following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it. ###Code import gym env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.54298351 0.00115394], Reward=-1.0 Step 2: State=[-0.54068426 0.00229925], Reward=-1.0 Step 3: State=[-0.53725693 0.00342733], Reward=-1.0 Step 4: State=[-0.53272719 0.00452974], Reward=-1.0 Step 5: State=[-0.527129 0.00559819], Reward=-1.0 Step 6: State=[-0.52050433 0.00662467], Reward=-1.0 Step 7: State=[-0.51290287 0.00760146], Reward=-1.0 Step 8: State=[-0.50438161 0.00852126], Reward=-1.0 Step 9: State=[-0.4950044 0.00937721], Reward=-1.0 Step 10: State=[-0.48484139 0.01016301], Reward=-1.0 Step 11: State=[-0.47396841 0.01087299], Reward=-1.0 Step 12: State=[-0.46246627 0.01150213], Reward=-1.0 Step 13: State=[-0.45042007 0.0120462 ], Reward=-1.0 Step 14: State=[-0.43791831 0.01250176], Reward=-1.0 Step 15: State=[-0.4250521 0.01286621], Reward=-1.0 Step 16: State=[-0.41191426 0.01313783], Reward=-1.0 Step 17: State=[-0.39859848 0.01331578], Reward=-1.0 Step 18: State=[-0.38519838 0.0134001 ], Reward=-1.0 Step 19: State=[-0.37180672 0.01339166], Reward=-1.0 Step 20: State=[-0.35851456 0.01329216], Reward=-1.0 Step 21: State=[-0.34541053 0.01310403], Reward=-1.0 Step 22: State=[-0.33258017 0.01283036], Reward=-1.0 Step 23: State=[-0.32010531 0.01247486], Reward=-1.0 Step 24: State=[-0.30806361 0.0120417 ], Reward=-1.0 Step 25: State=[-0.29652811 0.0115355 ], Reward=-1.0 Step 26: State=[-0.28556694 0.01096116], Reward=-1.0 Step 27: State=[-0.27524312 0.01032383], Reward=-1.0 Step 28: State=[-0.26561434 0.00962878], Reward=-1.0 Step 29: State=[-0.25673298 0.00888136], Reward=-1.0 Step 30: State=[-0.24864606 0.00808693], Reward=-1.0 Step 31: State=[-0.24139526 0.0072508 ], Reward=-1.0 Step 32: State=[-0.23501706 0.0063782 ], Reward=-1.0 Step 33: State=[-0.22954281 0.00547425], Reward=-1.0 Step 34: State=[-0.22499885 0.00454396], Reward=-1.0 Step 35: State=[-0.22140666 0.00359218], Reward=-1.0 Step 36: State=[-0.21878297 0.00262369], Reward=-1.0 Step 37: State=[-0.21713985 0.00164313], Reward=-1.0 Step 38: State=[-0.21648478 0.00065507], Reward=-1.0 Step 39: State=[-0.21682075 -0.00033597], Reward=-1.0 Step 40: State=[-0.21814623 -0.00132548], Reward=-1.0 Step 41: State=[-0.22045518 -0.00230895], Reward=-1.0 Step 42: State=[-0.22373702 -0.00328184], Reward=-1.0 Step 43: State=[-0.22797653 -0.00423951], Reward=-1.0 Step 44: State=[-0.23315378 -0.00517725], Reward=-1.0 Step 45: State=[-0.239244 -0.00609022], Reward=-1.0 Step 46: State=[-0.24621747 -0.00697347], Reward=-1.0 Step 47: State=[-0.25403939 -0.00782191], Reward=-1.0 Step 48: State=[-0.26266974 -0.00863035], Reward=-1.0 Step 49: State=[-0.27206323 -0.0093935 ], Reward=-1.0 Step 50: State=[-0.28216923 -0.010106 ], Reward=-1.0 Step 51: State=[-0.29293174 -0.01076251], Reward=-1.0 Step 52: State=[-0.30428945 -0.01135771], Reward=-1.0 Step 53: State=[-0.31617585 -0.0118864 ], Reward=-1.0 Step 54: State=[-0.32851945 -0.0123436 ], Reward=-1.0 Step 55: State=[-0.34124405 -0.0127246 ], Reward=-1.0 Step 56: State=[-0.3542691 -0.01302505], Reward=-1.0 Step 57: State=[-0.36751021 -0.01324111], Reward=-1.0 Step 58: State=[-0.38087966 -0.01336945], Reward=-1.0 Step 59: State=[-0.3942871 -0.01340744], Reward=-1.0 Step 60: State=[-0.40764024 -0.01335314], Reward=-1.0 Step 61: State=[-0.42084563 -0.01320539], Reward=-1.0 Step 62: State=[-0.43380952 -0.01296389], Reward=-1.0 Step 63: State=[-0.44643872 -0.0126292 ], Reward=-1.0 Step 64: State=[-0.45864146 -0.01220274], Reward=-1.0 Step 65: State=[-0.47032831 -0.01168684], Reward=-1.0 Step 66: State=[-0.48141298 -0.01108468], Reward=-1.0 Step 67: State=[-0.49181321 -0.01040022], Reward=-1.0 Step 68: State=[-0.50145146 -0.00963826], Reward=-1.0 Step 69: State=[-0.5102557 -0.00880424], Reward=-1.0 Step 70: State=[-0.51815998 -0.00790428], Reward=-1.0 Step 71: State=[-0.52510506 -0.00694507], Reward=-1.0 Step 72: State=[-0.53103883 -0.00593378], Reward=-1.0 Step 73: State=[-0.53591681 -0.00487798], Reward=-1.0 Step 74: State=[-0.53970243 -0.00378562], Reward=-1.0 Step 75: State=[-0.54236732 -0.00266489], Reward=-1.0 Step 76: State=[-0.54389151 -0.0015242 ], Reward=-1.0 Step 77: State=[-5.44263607e-01 -3.72094556e-04], Reward=-1.0 Step 78: State=[-0.54348081 0.00078279], Reward=-1.0 Step 79: State=[-0.541549 0.00193182], Reward=-1.0 Step 80: State=[-0.53848261 0.00306638], Reward=-1.0 Step 81: State=[-0.53430464 0.00417797], Reward=-1.0 Step 82: State=[-0.52904639 0.00525825], Reward=-1.0 Step 83: State=[-0.52274728 0.00629911], Reward=-1.0 Step 84: State=[-0.51545456 0.00729272], Reward=-1.0 Step 85: State=[-0.50722291 0.00823165], Reward=-1.0 Step 86: State=[-0.49811404 0.00910888], Reward=-1.0 Step 87: State=[-0.48819611 0.00991793], Reward=-1.0 Step 88: State=[-0.4775432 0.01065291], Reward=-1.0 Step 89: State=[-0.46623461 0.01130859], Reward=-1.0 Step 90: State=[-0.45435414 0.01188048], Reward=-1.0 Step 91: State=[-0.44198927 0.01236487], Reward=-1.0 Step 92: State=[-0.42923038 0.01275889], Reward=-1.0 Step 93: State=[-0.41616983 0.01306055], Reward=-1.0 Step 94: State=[-0.40290112 0.01326871], Reward=-1.0 Step 95: State=[-0.389518 0.01338313], Reward=-1.0 Step 96: State=[-0.37611358 0.01340442], Reward=-1.0 Step 97: State=[-0.36277956 0.01333402], Reward=-1.0 Step 98: State=[-0.34960543 0.01317413], Reward=-1.0 Step 99: State=[-0.3366778 0.01292763], Reward=-1.0 Step 100: State=[-0.32407975 0.01259805], Reward=-1.0 Step 101: State=[-0.31189033 0.01218942], Reward=-1.0 Step 102: State=[-0.3001841 0.01170623], Reward=-1.0 Step 103: State=[-0.28903082 0.01115328], Reward=-1.0 Step 104: State=[-0.27849515 0.01053567], Reward=-1.0 Step 105: State=[-0.26863652 0.00985862], Reward=-1.0 Step 106: State=[-0.25950904 0.00912749], Reward=-1.0 Step 107: State=[-0.25116142 0.00834761], Reward=-1.0 Step 108: State=[-0.24363708 0.00752434], Reward=-1.0 Step 109: State=[-0.23697416 0.00666292], Reward=-1.0 Step 110: State=[-0.23120564 0.00576852], Reward=-1.0 Step 111: State=[-0.22635946 0.00484618], Reward=-1.0 Step 112: State=[-0.22245866 0.0039008 ], Reward=-1.0 Step 113: State=[-0.21952148 0.00293718], Reward=-1.0 Step 114: State=[-0.21756149 0.00196 ], Reward=-1.0 Step 115: State=[-0.21658763 0.00097386], Reward=-1.0 Step 116: State=[-2.16604342e-01 -1.67115330e-05], Reward=-1.0 Step 117: State=[-0.21761155 -0.0010072 ], Reward=-1.0 Step 118: State=[-0.21960466 -0.00199312], Reward=-1.0 Step 119: State=[-0.22257458 -0.00296991], Reward=-1.0 Step 120: State=[-0.22650757 -0.003933 ], Reward=-1.0 Step 121: State=[-0.23138525 -0.00487768], Reward=-1.0 Step 122: State=[-0.23718442 -0.00579916], Reward=-1.0 Step 123: State=[-0.24387695 -0.00669253], Reward=-1.0 Step 124: State=[-0.2514297 -0.00755275], Reward=-1.0 Step 125: State=[-0.25980435 -0.00837465], Reward=-1.0 Step 126: State=[-0.26895731 -0.00915296], Reward=-1.0 Step 127: State=[-0.27883967 -0.00988236], Reward=-1.0 Step 128: State=[-0.28939716 -0.01055749], Reward=-1.0 Step 129: State=[-0.30057017 -0.01117301], Reward=-1.0 Step 130: State=[-0.31229385 -0.01172368], Reward=-1.0 Step 131: State=[-0.32449829 -0.01220444], Reward=-1.0 Step 132: State=[-0.33710877 -0.01261047], Reward=-1.0 Step 133: State=[-0.35004609 -0.01293732], Reward=-1.0 Step 134: State=[-0.36322703 -0.01318094], Reward=-1.0 Step 135: State=[-0.3765649 -0.01333787], Reward=-1.0 Step 136: State=[-0.3899701 -0.0134052], Reward=-1.0 Step 137: State=[-0.40335089 -0.01338079], Reward=-1.0 Step 138: State=[-0.41661411 -0.01326322], Reward=-1.0 Step 139: State=[-0.429666 -0.0130519], Reward=-1.0 Step 140: State=[-0.44241311 -0.0127471 ], Reward=-1.0 Step 141: State=[-0.4547631 -0.01235 ], Reward=-1.0 Step 142: State=[-0.4666257 -0.0118626], Reward=-1.0 Step 143: State=[-0.47791353 -0.01128782], Reward=-1.0 Step 144: State=[-0.48854292 -0.01062939], Reward=-1.0 Step 145: State=[-0.49843474 -0.00989182], Reward=-1.0 Step 146: State=[-0.50751511 -0.00908037], Reward=-1.0 Step 147: State=[-0.51571607 -0.00820096], Reward=-1.0 Step 148: State=[-0.52297614 -0.00726007], Reward=-1.0 Step 149: State=[-0.52924088 -0.00626474], Reward=-1.0 Step 150: State=[-0.53446331 -0.00522243], Reward=-1.0 Step 151: State=[-0.53860426 -0.00414096], Reward=-1.0 Step 152: State=[-0.54163272 -0.00302845], Reward=-1.0 Step 153: State=[-0.54352598 -0.00189327], Reward=-1.0 Step 154: State=[-0.54426988 -0.0007439 ], Reward=-1.0 ###Markdown Programmed CarThis is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction. ###Code import gym env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1]>0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.51431373 -0.00107771], Reward=-1.0 Step 2: State=[-0.51646107 -0.00214734], Reward=-1.0 Step 3: State=[-0.51966193 -0.00320087], Reward=-1.0 Step 4: State=[-0.52389233 -0.00423039], Reward=-1.0 Step 5: State=[-0.52912052 -0.00522819], Reward=-1.0 Step 6: State=[-0.53530729 -0.00618678], Reward=-1.0 Step 7: State=[-0.54240628 -0.00709898], Reward=-1.0 Step 8: State=[-0.55036428 -0.007958 ], Reward=-1.0 Step 9: State=[-0.55912175 -0.00875748], Reward=-1.0 Step 10: State=[-0.56861331 -0.00949156], Reward=-1.0 Step 11: State=[-0.57876828 -0.01015497], Reward=-1.0 Step 12: State=[-0.58951137 -0.01074309], Reward=-1.0 Step 13: State=[-0.60076333 -0.01125196], Reward=-1.0 Step 14: State=[-0.61244171 -0.01167838], Reward=-1.0 Step 15: State=[-0.62446163 -0.01201992], Reward=-1.0 Step 16: State=[-0.63673657 -0.01227494], Reward=-1.0 Step 17: State=[-0.64917917 -0.0124426 ], Reward=-1.0 Step 18: State=[-0.66170205 -0.01252287], Reward=-1.0 Step 19: State=[-0.67421853 -0.01251648], Reward=-1.0 Step 20: State=[-0.68664341 -0.01242488], Reward=-1.0 Step 21: State=[-0.69889363 -0.01225023], Reward=-1.0 Step 22: State=[-0.71088891 -0.01199528], Reward=-1.0 Step 23: State=[-0.72255227 -0.01166336], Reward=-1.0 Step 24: State=[-0.73381051 -0.01125823], Reward=-1.0 Step 25: State=[-0.7445946 -0.01078409], Reward=-1.0 Step 26: State=[-0.75484 -0.0102454], Reward=-1.0 Step 27: State=[-0.76448689 -0.00964689], Reward=-1.0 Step 28: State=[-0.77348032 -0.00899343], Reward=-1.0 Step 29: State=[-0.78177031 -0.00828998], Reward=-1.0 Step 30: State=[-0.78931187 -0.00754156], Reward=-1.0 Step 31: State=[-0.79606502 -0.00675316], Reward=-1.0 Step 32: State=[-0.80199476 -0.00592974], Reward=-1.0 Step 33: State=[-0.80707094 -0.00507618], Reward=-1.0 Step 34: State=[-0.81126824 -0.00419729], Reward=-1.0 Step 35: State=[-0.81456603 -0.00329779], Reward=-1.0 Step 36: State=[-0.81694832 -0.0023823 ], Reward=-1.0 Step 37: State=[-0.81840369 -0.00145537], Reward=-1.0 Step 38: State=[-8.18925204e-01 -5.21510941e-04], Reward=-1.0 Step 39: State=[-8.18510378e-01 4.14826025e-04], Reward=-1.0 Step 40: State=[-0.81516118 0.00334919], Reward=-1.0 Step 41: State=[-0.80889363 0.00626755], Reward=-1.0 Step 42: State=[-0.7997382 0.00915543], Reward=-1.0 Step 43: State=[-0.78774062 0.01199759], Reward=-1.0 Step 44: State=[-0.77296289 0.01477773], Reward=-1.0 Step 45: State=[-0.75548455 0.01747834], Reward=-1.0 Step 46: State=[-0.73540399 0.02008056], Reward=-1.0 Step 47: State=[-0.71283965 0.02256434], Reward=-1.0 Step 48: State=[-0.68793102 0.02490863], Reward=-1.0 Step 49: State=[-0.66083923 0.0270918 ], Reward=-1.0 Step 50: State=[-0.63174696 0.02909226], Reward=-1.0 Step 51: State=[-0.60085774 0.03088922], Reward=-1.0 Step 52: State=[-0.56839425 0.03246349], Reward=-1.0 Step 53: State=[-0.53459581 0.03379844], Reward=-1.0 Step 54: State=[-0.49971491 0.03488091], Reward=-1.0 Step 55: State=[-0.46401297 0.03570193], Reward=-1.0 Step 56: State=[-0.42775556 0.03625741], Reward=-1.0 Step 57: State=[-0.39120711 0.03654845], Reward=-1.0 Step 58: State=[-0.35462569 0.03658142], Reward=-1.0 Step 59: State=[-0.31825799 0.0363677 ], Reward=-1.0 Step 60: State=[-0.28233478 0.03592322], Reward=-1.0 Step 61: State=[-0.24706714 0.03526764], Reward=-1.0 Step 62: State=[-0.21264364 0.0344235 ], Reward=-1.0 Step 63: State=[-0.17922847 0.03341517], Reward=-1.0 Step 64: State=[-0.14696054 0.03226793], Reward=-1.0 Step 65: State=[-0.11595355 0.03100699], Reward=-1.0 Step 66: State=[-0.08629682 0.02965673], Reward=-1.0 Step 67: State=[-0.05805677 0.02824004], Reward=-1.0 Step 68: State=[-0.03127891 0.02677787], Reward=-1.0 Step 69: State=[-0.00599004 0.02528887], Reward=-1.0 Step 70: State=[0.01779923 0.02378927], Reward=-1.0 Step 71: State=[0.04009206 0.02229283], Reward=-1.0 Step 72: State=[0.06090295 0.02081089], Reward=-1.0 Step 73: State=[0.08025546 0.01935251], Reward=-1.0 Step 74: State=[0.09818008 0.01792462], Reward=-1.0 Step 75: State=[0.11471236 0.01653228], Reward=-1.0 Step 76: State=[0.12989122 0.01517886], Reward=-1.0 Step 77: State=[0.14375749 0.01386628], Reward=-1.0 Step 78: State=[0.15635269 0.01259519], Reward=-1.0 Step 79: State=[0.16771789 0.01136521], Reward=-1.0 Step 80: State=[0.17789293 0.01017504], Reward=-1.0 Step 81: State=[0.18691562 0.00902269], Reward=-1.0 Step 82: State=[0.19482116 0.00790554], Reward=-1.0 Step 83: State=[0.20164168 0.00682052], Reward=-1.0 Step 84: State=[0.20740583 0.00576416], Reward=-1.0 Step 85: State=[0.21213852 0.00473269], Reward=-1.0 Step 86: State=[0.21586063 0.00372211], Reward=-1.0 Step 87: State=[0.21858888 0.00272825], Reward=-1.0 Step 88: State=[0.22033568 0.0017468 ], Reward=-1.0 Step 89: State=[0.22110904 0.00077336], Reward=-1.0 Step 90: State=[ 2.20912527e-01 -1.96509754e-04], Reward=-1.0 Step 91: State=[ 0.21774524 -0.00316729], Reward=-1.0 Step 92: State=[ 0.21159265 -0.00615259], Reward=-1.0 Step 93: State=[ 0.20242705 -0.0091656 ], Reward=-1.0 Step 94: State=[ 0.19020845 -0.01221861], Reward=-1.0 Step 95: State=[ 0.17488593 -0.01532251], Reward=-1.0 Step 96: State=[ 0.15639968 -0.01848625], Reward=-1.0 Step 97: State=[ 0.1346836 -0.02171608], Reward=-1.0 Step 98: State=[ 0.10966883 -0.02501477], Reward=-1.0 Step 99: State=[ 0.08128815 -0.02838068], Reward=-1.0 Step 100: State=[ 0.04948145 -0.03180671], Reward=-1.0 Step 101: State=[ 0.01420223 -0.03527921], Reward=-1.0 Step 102: State=[-0.02457471 -0.03877695], Reward=-1.0 Step 103: State=[-0.06684487 -0.04227015], Reward=-1.0 Step 104: State=[-0.11256492 -0.04572006], Reward=-1.0 Step 105: State=[-0.16164378 -0.04907886], Reward=-1.0 Step 106: State=[-0.21393441 -0.05229063], Reward=-1.0 Step 107: State=[-0.26922758 -0.05529317], Reward=-1.0 Step 108: State=[-0.32724868 -0.05802111], Reward=-1.0 Step 109: State=[-0.38765872 -0.06041004], Reward=-1.0 Step 110: State=[-0.45006028 -0.06240156], Reward=-1.0 Step 111: State=[-0.51400891 -0.06394863], Reward=-1.0 Step 112: State=[-0.57902946 -0.06502055], Reward=-1.0 Step 113: State=[-0.64463619 -0.06560673], Reward=-1.0 Step 114: State=[-0.71035496 -0.06571877], Reward=-1.0 Step 115: State=[-0.77574519 -0.06539023], Reward=-1.0 Step 116: State=[-0.84041959 -0.06467439], Reward=-1.0 Step 117: State=[-0.90405977 -0.06364018], Reward=-1.0 Step 118: State=[-0.96642693 -0.06236716], Reward=-1.0 Step 119: State=[-1.02736712 -0.06094019], Reward=-1.0 Step 120: State=[-1.08681173 -0.05944462], Reward=-1.0 Step 121: State=[-1.14477398 -0.05796225], Reward=-1.0 Step 122: State=[-1.2 0. ], Reward=-1.0 Step 123: State=[-1.1987581 0.0012419], Reward=-1.0 Step 124: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 125: State=[-1.18652173 0.00774848], Reward=-1.0 Step 126: State=[-1.17548846 0.01103326], Reward=-1.0 Step 127: State=[-1.16113808 0.01435038], Reward=-1.0 Step 128: State=[-1.14343234 0.01770574], Reward=-1.0 Step 129: State=[-1.12233007 0.02110228], Reward=-1.0 Step 130: State=[-1.09779103 0.02453904], Reward=-1.0 Step 131: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 132: State=[-1.03827616 0.03150456], Reward=-1.0 Step 133: State=[-1.0032725 0.03500367], Reward=-1.0 Step 134: State=[-0.9647905 0.03848199], Reward=-1.0 Step 135: State=[-0.92288452 0.04190598], Reward=-1.0 Step 136: State=[-0.87765038 0.04523414], Reward=-1.0 Step 137: State=[-0.82923273 0.04841765], Reward=-1.0 Step 138: State=[-0.77783078 0.05140195], Reward=-1.0 Step 139: State=[-0.72370164 0.05412914], Reward=-1.0 Step 140: State=[-0.66716026 0.05654138], Reward=-1.0 Step 141: State=[-0.60857514 0.05858511], Reward=-1.0 Step 142: State=[-0.54835959 0.06021555], Reward=-1.0 Step 143: State=[-0.4869585 0.06140109], Reward=-1.0 Step 144: State=[-0.42483166 0.06212684], Reward=-1.0 Step 145: State=[-0.36243478 0.06239688], Reward=-1.0 Step 146: State=[-0.30020009 0.06223469], Reward=-1.0 Step 147: State=[-0.23851824 0.06168185], Reward=-1.0 Step 148: State=[-0.17772322 0.06079502], Reward=-1.0 Step 149: State=[-0.1180812 0.05964202], Reward=-1.0 Step 150: State=[-0.05978395 0.05829725], Reward=-1.0 Step 151: State=[-0.0029466 0.05683735], Reward=-1.0 Step 152: State=[0.05239085 0.05533745], Reward=-1.0 ###Markdown Reinforcement Learning![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning") Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla! Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined. $ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $ ###Code import gym import numpy as np def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(np.int)) def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # new_state_disc = calc_discrete_state(new_state) # if new_state[0] >= env.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 10000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 1 END_EPSILON_DECAYING = EPISODES//2 env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False episode = 0 success_count = 0 while episode<EPISODES: episode+=1 done = False if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon -= epsilon_change print(success) run_game(q_table, True, False) import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df np.argmax(q_table[(2,0)]) ###Output _____no_output_____ ###Markdown T81-558: Applications of Deep Neural Networks**Module 12: Reinforcement Learning*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). Module 12 Video Material* Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_01_ai_gym.ipynb)* **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=A3sYFcJY3lA&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_02_qlearningreinforcement.ipynb)* Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=qy1SJmsRhvM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_03_keras_reinforce.ipynb)* Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=co0SwPWoZh0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_04_atari.ipynb)* Part 12.5: Application of Reinforcement Learning [[Video]](https://www.youtube.com/watch?v=1jQPP3RfwMI&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_12_05_apply_rl.ipynb) Google CoLab InstructionsThe following code ensures that Google CoLab is running the correct version of TensorFlow. ###Code try: from google.colab import drive %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False # HIDE OUTPUT if COLAB: !sudo apt-get install -y xvfb ffmpeg x11-utils !pip install -q gym !pip install -q 'imageio==2.4.0' !pip install -q PILLOW !pip install -q 'pyglet==1.3.2' !pip install -q pyvirtualdisplay !pip install -q tf-agents !pip install -q pygame ###Output Reading package lists... Done Building dependency tree Reading state information... Done ffmpeg is already the newest version (7:3.4.8-0ubuntu0.2). Suggested packages: mesa-utils The following NEW packages will be installed: libxxf86dga1 x11-utils xvfb 0 upgraded, 3 newly installed, 0 to remove and 39 not upgraded. Need to get 993 kB of archives. After this operation, 2,982 kB of additional disk space will be used. Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxxf86dga1 amd64 2:1.1.4-1 [13.7 kB] Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11-utils amd64 7.7+3build1 [196 kB] Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 xvfb amd64 2:1.19.6-1ubuntu4.10 [784 kB] Fetched 993 kB in 1s (1,252 kB/s) debconf: unable to initialize frontend: Dialog debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 3.) debconf: falling back to frontend: Readline debconf: unable to initialize frontend: Readline debconf: (This frontend requires a controlling tty.) debconf: falling back to frontend: Teletype dpkg-preconfigure: unable to re-open stdin: Selecting previously unselected package libxxf86dga1:amd64. (Reading database ... 156210 files and directories currently installed.) Preparing to unpack .../libxxf86dga1_2%3a1.1.4-1_amd64.deb ... Unpacking libxxf86dga1:amd64 (2:1.1.4-1) ... Selecting previously unselected package x11-utils. Preparing to unpack .../x11-utils_7.7+3build1_amd64.deb ... Unpacking x11-utils (7.7+3build1) ... Selecting previously unselected package xvfb. Preparing to unpack .../xvfb_2%3a1.19.6-1ubuntu4.10_amd64.deb ... Unpacking xvfb (2:1.19.6-1ubuntu4.10) ... Setting up xvfb (2:1.19.6-1ubuntu4.10) ... Setting up libxxf86dga1:amd64 (2:1.1.4-1) ... Setting up x11-utils (7.7+3build1) ... Processing triggers for man-db (2.8.3-2ubuntu0.1) ... Processing triggers for libc-bin (2.27-3ubuntu1.3) ... /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link  |████████████████████████████████| 3.3 MB 5.1 MB/s [?25h Building wheel for imageio (setup.py) ... [?25l[?25hdone ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. albumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.  |████████████████████████████████| 1.0 MB 5.2 MB/s ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. gym 0.17.3 requires pyglet<=1.5.0,>=1.4.0, but you have pyglet 1.3.2 which is incompatible.  |████████████████████████████████| 1.3 MB 5.0 MB/s  |████████████████████████████████| 1.0 MB 29.8 MB/s  |████████████████████████████████| 21.8 MB 1.2 MB/s [?25h ###Markdown Part 12.2: Introduction to Q-LearningQ-Learning is a foundational technology upon which deep reinforcement learning is based. Before we explore deep reinforcement learning, it is essential to understand Q-Learning. Several components make up any Q-Learning system.* **Agent** - The agent is an entity that exists in an environment that takes actions to affect the state of the environment, to receive rewards.* **Environment** - The environment is the universe that the agent exists in. The environment is always in a specific state that is changed by the agent's actions.* **Actions** - Steps that the agent can perform to alter the environment * **Step** - A step occurs when the agent performs an action and potentially changes the environment state.* **Episode** - A chain of steps that ultimately culminates in the environment entering a terminal state.* **Epoch** - A training iteration of the agent that contains some number of episodes.* **Terminal State** - A state in which further actions do not make sense. A terminal state occurs when the agent has one, lost, or the environment exceeds the maximum number of steps in many environments.Q-Learning works by building a table that suggests an action for every possible state. This approach runs into several problems. First, the environment is usually composed of several continuous numbers, resulting in an infinite number of states. Q-Learning handles continuous states by binning these numeric values into ranges. Out of the box, Q-Learning does not deal with continuous inputs, such as a car's accelerator that can range from released to fully engaged. Additionally, Q-Learning primarily deals with discrete actions, such as pressing a joystick up or down. Researchers have developed clever tricks to allow Q-Learning to accommodate continuous actions.Deep neural networks can help solve the problems of continuous environments and action spaces. In the next section, we will learn more about deep reinforcement learning. For now, we will apply regular Q-Learning to the Mountain Car problem from OpenAI Gym. Introducing the Mountain CarThis section will demonstrate how Q-Learning can create a solution to the mountain car gym environment. The Mountain car is an environment where a car must climb a mountain. Because gravity is stronger than the car's engine, it cannot merely accelerate up the steep slope even with full throttle. The vehicle is situated in a valley and must learn to utilize potential energy by driving up the opposite hill before the car can make it to the goal at the top of the rightmost hill.First, it might be helpful to visualize the mountain car environment. The following code shows this environment. This code makes use of TF-Agents to perform this render. Usually, we use TF-Agents for the type of deep reinforcement learning that we will see in the next module. However, TF-Agents is just used to render the mountain care environment for now. ###Code import tf_agents from tf_agents.environments import suite_gym import PIL.Image import pyvirtualdisplay display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start() env_name = 'MountainCar-v0' env = suite_gym.load(env_name) env.reset() PIL.Image.fromarray(env.render()) ###Output _____no_output_____ ###Markdown The mountain car environment provides the following discrete actions:* 0 - Apply left force* 1 - Apply no force* 2 - Apply right forceThe mountain car environment is made up of the following continuous values:* state[0] - Position * state[1] - VelocityThe cart is not strong enough. It will need to use potential energy from the mountain behind it. The following code shows an agent that applies full throttle to climb the hill. ###Code import gym from gym.wrappers import Monitor import glob import io import base64 from IPython.display import HTML from pyvirtualdisplay import Display from IPython import display as ipythondisplay display = Display(visible=0, size=(1400, 900)) display.start() def show_video(): mp4list = glob.glob('video/*.mp4') if len(mp4list) > 0: mp4 = mp4list[0] video = io.open(mp4, 'r+b').read() encoded = base64.b64encode(video) ipythondisplay.display(HTML(data='''<video alt="test" autoplay loop controls style="height: 400px;"> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))) else: print("Could not find video") def wrap_env(env): env = Monitor(env, './video', force=True) return env ###Output _____no_output_____ ###Markdown We are now ready to train the agent. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") env.reset() done = False i = 0 while not done: i += 1 state, reward, done, _ = env.step(2) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-0.50905189 0.00089766], Reward=-1.0 Step 2: State=[-0.50726329 0.00178859], Reward=-1.0 Step 3: State=[-0.50459717 0.00266613], Reward=-1.0 Step 4: State=[-0.50107348 0.00352369], Reward=-1.0 Step 5: State=[-0.4967186 0.00435488], Reward=-1.0 Step 6: State=[-0.4915651 0.0051535], Reward=-1.0 Step 7: State=[-0.48565149 0.00591361], Reward=-1.0 Step 8: State=[-0.47902187 0.00662962], Reward=-1.0 Step 9: State=[-0.47172557 0.00729629], Reward=-1.0 Step 10: State=[-0.46381676 0.00790881], Reward=-1.0 Step 11: State=[-0.45535392 0.00846285], Reward=-1.0 Step 12: State=[-0.44639934 0.00895458], Reward=-1.0 Step 13: State=[-0.4370186 0.00938074], Reward=-1.0 Step 14: State=[-0.42727993 0.00973867], Reward=-1.0 Step 15: State=[-0.41725364 0.01002629], Reward=-1.0 Step 16: State=[-0.40701147 0.01024216], Reward=-1.0 Step 17: State=[-0.396626 0.01038548], Reward=-1.0 Step 18: State=[-0.38616995 0.01045604], Reward=-1.0 Step 19: State=[-0.37571567 0.01045428], Reward=-1.0 Step 20: State=[-0.36533449 0.01038118], Reward=-1.0 Step 21: State=[-0.35509619 0.0102383 ], Reward=-1.0 Step 22: State=[-0.34506852 0.01002767], Reward=-1.0 Step 23: State=[-0.33531672 0.0097518 ], Reward=-1.0 Step 24: State=[-0.32590314 0.00941358], Reward=-1.0 Step 25: State=[-0.31688687 0.00901627], Reward=-1.0 Step 26: State=[-0.30832346 0.00856341], Reward=-1.0 Step 27: State=[-0.30026469 0.00805876], Reward=-1.0 Step 28: State=[-0.2927584 0.00750629], Reward=-1.0 Step 29: State=[-0.2858483 0.0069101], Reward=-1.0 Step 30: State=[-0.27957395 0.00627436], Reward=-1.0 Step 31: State=[-0.27397063 0.00560332], Reward=-1.0 Step 32: State=[-0.26906936 0.00490127], Reward=-1.0 Step 33: State=[-0.26489689 0.00417247], Reward=-1.0 Step 34: State=[-0.26147568 0.00342121], Reward=-1.0 Step 35: State=[-0.25882396 0.00265172], Reward=-1.0 Step 36: State=[-0.25695571 0.00186825], Reward=-1.0 Step 37: State=[-0.25588073 0.00107498], Reward=-1.0 Step 38: State=[-0.25560462 0.00027611], Reward=-1.0 Step 39: State=[-0.25612883 -0.00052421], Reward=-1.0 Step 40: State=[-0.25745062 -0.00132179], Reward=-1.0 Step 41: State=[-0.25956309 -0.00211247], Reward=-1.0 Step 42: State=[-0.26245514 -0.00289205], Reward=-1.0 Step 43: State=[-0.26611148 -0.00365634], Reward=-1.0 Step 44: State=[-0.27051257 -0.00440109], Reward=-1.0 Step 45: State=[-0.27563463 -0.00512205], Reward=-1.0 Step 46: State=[-0.28144957 -0.00581494], Reward=-1.0 Step 47: State=[-0.28792506 -0.00647549], Reward=-1.0 Step 48: State=[-0.29502448 -0.00709942], Reward=-1.0 Step 49: State=[-0.30270698 -0.0076825 ], Reward=-1.0 Step 50: State=[-0.31092755 -0.00822057], Reward=-1.0 Step 51: State=[-0.31963713 -0.00870957], Reward=-1.0 Step 52: State=[-0.32878273 -0.0091456 ], Reward=-1.0 Step 53: State=[-0.33830768 -0.00952495], Reward=-1.0 Step 54: State=[-0.34815185 -0.00984416], Reward=-1.0 Step 55: State=[-0.35825194 -0.0101001 ], Reward=-1.0 Step 56: State=[-0.36854191 -0.01028996], Reward=-1.0 Step 57: State=[-0.37895331 -0.0104114 ], Reward=-1.0 Step 58: State=[-0.38941582 -0.01046252], Reward=-1.0 Step 59: State=[-0.39985775 -0.01044193], Reward=-1.0 Step 60: State=[-0.41020657 -0.01034882], Reward=-1.0 Step 61: State=[-0.42038952 -0.01018295], Reward=-1.0 Step 62: State=[-0.43033423 -0.00994471], Reward=-1.0 Step 63: State=[-0.43996933 -0.0096351 ], Reward=-1.0 Step 64: State=[-0.4492251 -0.00925577], Reward=-1.0 Step 65: State=[-0.45803405 -0.00880895], Reward=-1.0 Step 66: State=[-0.46633157 -0.00829752], Reward=-1.0 Step 67: State=[-0.47405649 -0.00772492], Reward=-1.0 Step 68: State=[-0.48115161 -0.00709512], Reward=-1.0 Step 69: State=[-0.48756422 -0.00641261], Reward=-1.0 Step 70: State=[-0.49324656 -0.00568234], Reward=-1.0 Step 71: State=[-0.49815623 -0.00490967], Reward=-1.0 Step 72: State=[-0.50225654 -0.00410031], Reward=-1.0 Step 73: State=[-0.5055168 -0.00326026], Reward=-1.0 Step 74: State=[-0.50791261 -0.00239581], Reward=-1.0 Step 75: State=[-0.50942603 -0.00151341], Reward=-1.0 Step 76: State=[-0.5100457 -0.00061968], Reward=-1.0 Step 77: State=[-5.09767002e-01 2.78702550e-04], Reward=-1.0 Step 78: State=[-0.50859201 0.00117499], Reward=-1.0 Step 79: State=[-0.50652953 0.00206248], Reward=-1.0 Step 80: State=[-0.50359501 0.00293452], Reward=-1.0 Step 81: State=[-0.49981043 0.00378458], Reward=-1.0 Step 82: State=[-0.49520411 0.00460632], Reward=-1.0 Step 83: State=[-0.48981049 0.00539362], Reward=-1.0 Step 84: State=[-0.48366986 0.00614064], Reward=-1.0 Step 85: State=[-0.47682797 0.00684189], Reward=-1.0 Step 86: State=[-0.46933572 0.00749226], Reward=-1.0 Step 87: State=[-0.46124864 0.00808708], Reward=-1.0 Step 88: State=[-0.45262646 0.00862217], Reward=-1.0 Step 89: State=[-0.44353257 0.00909389], Reward=-1.0 Step 90: State=[-0.43403342 0.00949915], Reward=-1.0 Step 91: State=[-0.42419795 0.00983547], Reward=-1.0 Step 92: State=[-0.41409699 0.01010096], Reward=-1.0 Step 93: State=[-0.40380259 0.01029439], Reward=-1.0 Step 94: State=[-0.39338746 0.01041514], Reward=-1.0 Step 95: State=[-0.38292426 0.0104632 ], Reward=-1.0 Step 96: State=[-0.37248508 0.01043918], Reward=-1.0 Step 97: State=[-0.36214083 0.01034425], Reward=-1.0 Step 98: State=[-0.35196071 0.01018012], Reward=-1.0 Step 99: State=[-0.34201175 0.00994897], Reward=-1.0 Step 100: State=[-0.33235831 0.00965343], Reward=-1.0 Step 101: State=[-0.32306179 0.00929653], Reward=-1.0 Step 102: State=[-0.31418019 0.0088816 ], Reward=-1.0 Step 103: State=[-0.30576792 0.00841226], Reward=-1.0 Step 104: State=[-0.29787557 0.00789236], Reward=-1.0 Step 105: State=[-0.29054969 0.00732588], Reward=-1.0 Step 106: State=[-0.28383272 0.00671697], Reward=-1.0 Step 107: State=[-0.27776289 0.00606983], Reward=-1.0 Step 108: State=[-0.27237418 0.00538871], Reward=-1.0 Step 109: State=[-0.26769627 0.00467791], Reward=-1.0 Step 110: State=[-0.26375458 0.00394169], Reward=-1.0 Step 111: State=[-0.26057026 0.00318432], Reward=-1.0 Step 112: State=[-0.25816021 0.00241005], Reward=-1.0 Step 113: State=[-0.25653713 0.00162309], Reward=-1.0 Step 114: State=[-0.25570949 0.00082763], Reward=-1.0 Step 115: State=[-2.55681628e-01 2.78670044e-05], Reward=-1.0 Step 116: State=[-0.25645367 -0.00077204], Reward=-1.0 Step 117: State=[-0.25802161 -0.00156793], Reward=-1.0 Step 118: State=[-0.26037723 -0.00235562], Reward=-1.0 Step 119: State=[-0.26350814 -0.00313091], Reward=-1.0 Step 120: State=[-0.26739774 -0.0038896 ], Reward=-1.0 Step 121: State=[-0.27202516 -0.00462742], Reward=-1.0 Step 122: State=[-0.2773653 -0.00534014], Reward=-1.0 Step 123: State=[-0.28338876 -0.00602346], Reward=-1.0 Step 124: State=[-0.29006186 -0.0066731 ], Reward=-1.0 Step 125: State=[-0.29734667 -0.00728481], Reward=-1.0 Step 126: State=[-0.30520105 -0.00785438], Reward=-1.0 Step 127: State=[-0.31357871 -0.00837766], Reward=-1.0 Step 128: State=[-0.32242935 -0.00885064], Reward=-1.0 Step 129: State=[-0.33169883 -0.00926948], Reward=-1.0 Step 130: State=[-0.34132937 -0.00963053], Reward=-1.0 Step 131: State=[-0.35125981 -0.00993044], Reward=-1.0 Step 132: State=[-0.36142598 -0.01016617], Reward=-1.0 Step 133: State=[-0.37176102 -0.01033504], Reward=-1.0 Step 134: State=[-0.38219587 -0.01043485], Reward=-1.0 Step 135: State=[-0.39265972 -0.01046385], Reward=-1.0 Step 136: State=[-0.40308055 -0.01042083], Reward=-1.0 Step 137: State=[-0.41338571 -0.01030515], Reward=-1.0 Step 138: State=[-0.42350248 -0.01011677], Reward=-1.0 Step 139: State=[-0.43335875 -0.00985626], Reward=-1.0 Step 140: State=[-0.44288357 -0.00952483], Reward=-1.0 Step 141: State=[-0.45200787 -0.00912429], Reward=-1.0 Step 142: State=[-0.46066497 -0.00865711], Reward=-1.0 Step 143: State=[-0.46879128 -0.00812631], Reward=-1.0 Step 144: State=[-0.4763268 -0.00753552], Reward=-1.0 Step 145: State=[-0.48321567 -0.00688887], Reward=-1.0 Step 146: State=[-0.48940667 -0.006191 ], Reward=-1.0 Step 147: State=[-0.49485367 -0.00544699], Reward=-1.0 Step 148: State=[-0.49951598 -0.00466232], Reward=-1.0 Step 149: State=[-0.50335876 -0.00384278], Reward=-1.0 Step 150: State=[-0.50635325 -0.00299449], Reward=-1.0 Step 151: State=[-0.50847702 -0.00212377], Reward=-1.0 Step 152: State=[-0.50971416 -0.00123714], Reward=-1.0 Step 153: State=[-5.10055410e-01 -3.41248589e-04], Reward=-1.0 Step 154: State=[-0.50949821 0.0005572 ], Reward=-1.0 Step 155: State=[-0.50804672 0.00145148], Reward=-1.0 Step 156: State=[-0.50571184 0.00233488], Reward=-1.0 Step 157: State=[-0.50251105 0.0032008 ], Reward=-1.0 Step 158: State=[-0.4984683 0.00404274], Reward=-1.0 Step 159: State=[-0.49361386 0.00485444], Reward=-1.0 Step 160: State=[-0.487984 0.00562986], Reward=-1.0 Step 161: State=[-0.48162074 0.00636326], Reward=-1.0 Step 162: State=[-0.47457149 0.00704925], Reward=-1.0 Step 163: State=[-0.46688862 0.00768287], Reward=-1.0 Step 164: State=[-0.45862902 0.0082596 ], Reward=-1.0 Step 165: State=[-0.44985362 0.0087754 ], Reward=-1.0 Step 166: State=[-0.44062681 0.00922681], Reward=-1.0 Step 167: State=[-0.43101588 0.00961093], Reward=-1.0 Step 168: State=[-0.42109043 0.00992545], Reward=-1.0 Step 169: State=[-0.41092173 0.0101687 ], Reward=-1.0 Step 170: State=[-0.4005821 0.01033962], Reward=-1.0 Step 171: State=[-0.3901443 0.0104378], Reward=-1.0 Step 172: State=[-0.37968088 0.01046342], Reward=-1.0 Step 173: State=[-0.36926363 0.01041726], Reward=-1.0 Step 174: State=[-0.35896297 0.01030066], Reward=-1.0 Step 175: State=[-0.34884748 0.01011548], Reward=-1.0 Step 176: State=[-0.33898342 0.00986407], Reward=-1.0 Step 177: State=[-0.32943426 0.00954916], Reward=-1.0 Step 178: State=[-0.32026037 0.00917389], Reward=-1.0 Step 179: State=[-0.31151868 0.00874169], Reward=-1.0 Step 180: State=[-0.30326242 0.00825625], Reward=-1.0 Step 181: State=[-0.29554096 0.00772147], Reward=-1.0 Step 182: State=[-0.28839957 0.00714139], Reward=-1.0 Step 183: State=[-0.28187941 0.00652016], Reward=-1.0 Step 184: State=[-0.27601738 0.00586203], Reward=-1.0 Step 185: State=[-0.27084613 0.00517125], Reward=-1.0 Step 186: State=[-0.26639402 0.00445211], Reward=-1.0 Step 187: State=[-0.26268515 0.00370887], Reward=-1.0 Step 188: State=[-0.25973934 0.00294581], Reward=-1.0 Step 189: State=[-0.25757219 0.00216715], Reward=-1.0 Step 190: State=[-0.25619508 0.00137711], Reward=-1.0 Step 191: State=[-0.25561521 0.00057987], Reward=-1.0 Step 192: State=[-2.55835595e-01 -2.20385847e-04], Reward=-1.0 Step 193: State=[-0.25685509 -0.0010195 ], Reward=-1.0 Step 194: State=[-0.25866838 -0.00181329], Reward=-1.0 Step 195: State=[-0.26126596 -0.00259758], Reward=-1.0 Step 196: State=[-0.26463414 -0.00336818], Reward=-1.0 Step 197: State=[-0.26875498 -0.00412085], Reward=-1.0 Step 198: State=[-0.27360632 -0.00485134], Reward=-1.0 Step 199: State=[-0.27916172 -0.0055554 ], Reward=-1.0 Step 200: State=[-0.28539045 -0.00622873], Reward=-1.0 ###Markdown It helps to visualize the car. The following code shows a video of the car when run from a notebook. ###Code # HIDE OUTPUT show_video() ###Output _____no_output_____ ###Markdown Programmed CarNow we will look at a car that I hand-programmed. This car is straightforward; however, it solves the problem. The programmed car always applies force in one direction or another. It does not break. Whatever direction the vehicle is currently rolling, the agent uses power in that direction. Therefore, the car begins to climb a hill, is overpowered, and turns backward. However, once it starts to roll backward, force is immediately applied in this new direction.The following code implements this preprogrammed car. ###Code import gym if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") state = env.reset() done = False i = 0 while not done: i += 1 if state[1] > 0: action = 2 else: action = 0 state, reward, done, _ = env.step(action) env.render() print(f"Step {i}: State={state}, Reward={reward}") env.close() ###Output Step 1: State=[-5.84581471e-01 -5.49227966e-04], Reward=-1.0 Step 2: State=[-0.58567588 -0.0010944 ], Reward=-1.0 Step 3: State=[-0.58730739 -0.00163151], Reward=-1.0 Step 4: State=[-0.58946399 -0.0021566 ], Reward=-1.0 Step 5: State=[-0.59212981 -0.00266582], Reward=-1.0 Step 6: State=[-0.59528526 -0.00315545], Reward=-1.0 Step 7: State=[-0.5989072 -0.00362194], Reward=-1.0 Step 8: State=[-0.60296912 -0.00406192], Reward=-1.0 Step 9: State=[-0.60744137 -0.00447225], Reward=-1.0 Step 10: State=[-0.61229141 -0.00485004], Reward=-1.0 Step 11: State=[-0.61748407 -0.00519267], Reward=-1.0 Step 12: State=[-0.62298187 -0.0054978 ], Reward=-1.0 Step 13: State=[-0.62874529 -0.00576342], Reward=-1.0 Step 14: State=[-0.63473313 -0.00598783], Reward=-1.0 Step 15: State=[-0.64090281 -0.00616968], Reward=-1.0 Step 16: State=[-0.64721076 -0.00630795], Reward=-1.0 Step 17: State=[-0.65361272 -0.00640196], Reward=-1.0 Step 18: State=[-0.66006412 -0.00645139], Reward=-1.0 Step 19: State=[-0.66652037 -0.00645626], Reward=-1.0 Step 20: State=[-0.67293726 -0.00641689], Reward=-1.0 Step 21: State=[-0.6792712 -0.00633394], Reward=-1.0 Step 22: State=[-0.68547958 -0.00620838], Reward=-1.0 Step 23: State=[-0.69152102 -0.00604144], Reward=-1.0 Step 24: State=[-0.69735564 -0.00583462], Reward=-1.0 Step 25: State=[-0.7029453 -0.00558966], Reward=-1.0 Step 26: State=[-0.70825383 -0.00530853], Reward=-1.0 Step 27: State=[-0.7132472 -0.00499337], Reward=-1.0 Step 28: State=[-0.71789372 -0.00464651], Reward=-1.0 Step 29: State=[-0.72216414 -0.00427042], Reward=-1.0 Step 30: State=[-0.72603185 -0.00386771], Reward=-1.0 Step 31: State=[-0.72947294 -0.00344108], Reward=-1.0 Step 32: State=[-0.73246627 -0.00299334], Reward=-1.0 Step 33: State=[-0.73499362 -0.00252735], Reward=-1.0 Step 34: State=[-0.73703966 -0.00204604], Reward=-1.0 Step 35: State=[-0.73859207 -0.00155241], Reward=-1.0 Step 36: State=[-0.73964152 -0.00104945], Reward=-1.0 Step 37: State=[-7.40181738e-01 -5.40214614e-04], Reward=-1.0 Step 38: State=[-7.40209487e-01 -2.77484127e-05], Reward=-1.0 Step 39: State=[-7.39724603e-01 4.84883491e-04], Reward=-1.0 Step 40: State=[-0.73672998 0.00299462], Reward=-1.0 Step 41: State=[-0.73124359 0.00548639], Reward=-1.0 Step 42: State=[-0.72329865 0.00794494], Reward=-1.0 Step 43: State=[-0.71294396 0.01035469], Reward=-1.0 Step 44: State=[-0.70024433 0.01269963], Reward=-1.0 Step 45: State=[-0.685281 0.01496333], Reward=-1.0 Step 46: State=[-0.66815204 0.01712895], Reward=-1.0 Step 47: State=[-0.6489726 0.01917944], Reward=-1.0 Step 48: State=[-0.62787487 0.02109773], Reward=-1.0 Step 49: State=[-0.60500776 0.02286711], Reward=-1.0 Step 50: State=[-0.58053614 0.02447162], Reward=-1.0 Step 51: State=[-0.55463956 0.02589658], Reward=-1.0 Step 52: State=[-0.52751051 0.02712905], Reward=-1.0 Step 53: State=[-0.49935212 0.02815839], Reward=-1.0 Step 54: State=[-0.47037542 0.0289767 ], Reward=-1.0 Step 55: State=[-0.44079621 0.02957922], Reward=-1.0 Step 56: State=[-0.41083164 0.02996456], Reward=-1.0 Step 57: State=[-0.38069679 0.03013485], Reward=-1.0 Step 58: State=[-0.35060117 0.03009562], Reward=-1.0 Step 59: State=[-0.32074557 0.0298556 ], Reward=-1.0 Step 60: State=[-0.29131919 0.02942639], Reward=-1.0 Step 61: State=[-0.26249729 0.02882189], Reward=-1.0 Step 62: State=[-0.23443946 0.02805783], Reward=-1.0 Step 63: State=[-0.20728838 0.02715108], Reward=-1.0 Step 64: State=[-0.18116928 0.0261191 ], Reward=-1.0 Step 65: State=[-0.15618993 0.02497935], Reward=-1.0 Step 66: State=[-0.13244112 0.02374881], Reward=-1.0 Step 67: State=[-0.10999756 0.02244356], Reward=-1.0 Step 68: State=[-0.08891911 0.02107845], Reward=-1.0 Step 69: State=[-0.06925224 0.01966687], Reward=-1.0 Step 70: State=[-0.05103161 0.01822063], Reward=-1.0 Step 71: State=[-0.03428174 0.01674987], Reward=-1.0 Step 72: State=[-0.01901866 0.01526308], Reward=-1.0 Step 73: State=[-0.00525151 0.01376715], Reward=-1.0 Step 74: State=[0.00701595 0.01226746], Reward=-1.0 Step 75: State=[0.01778397 0.01076801], Reward=-1.0 Step 76: State=[0.02705554 0.00927157], Reward=-1.0 Step 77: State=[0.03483534 0.0077798 ], Reward=-1.0 Step 78: State=[0.04112878 0.00629344], Reward=-1.0 Step 79: State=[0.04594123 0.00481245], Reward=-1.0 Step 80: State=[0.04927738 0.00333615], Reward=-1.0 Step 81: State=[0.05114081 0.00186342], Reward=-1.0 Step 82: State=[0.05153359 0.00039279], Reward=-1.0 Step 83: State=[ 0.0504562 -0.0010774], Reward=-1.0 Step 84: State=[ 0.04590739 -0.00454881], Reward=-1.0 Step 85: State=[ 0.03788225 -0.00802514], Reward=-1.0 Step 86: State=[ 0.02637324 -0.01150901], Reward=-1.0 Step 87: State=[ 0.01137205 -0.01500119], Reward=-1.0 Step 88: State=[-0.00712768 -0.01849973], Reward=-1.0 Step 89: State=[-0.02912685 -0.02199916], Reward=-1.0 Step 90: State=[-0.05461647 -0.02548963], Reward=-1.0 Step 91: State=[-0.08357261 -0.02895614], Reward=-1.0 Step 92: State=[-0.11595059 -0.03237798], Reward=-1.0 Step 93: State=[-0.15167884 -0.03572825], Reward=-1.0 Step 94: State=[-0.1906527 -0.03897386], Reward=-1.0 Step 95: State=[-0.23272866 -0.04207597], Reward=-1.0 Step 96: State=[-0.27771965 -0.04499099], Reward=-1.0 Step 97: State=[-0.32539199 -0.04767234], Reward=-1.0 Step 98: State=[-0.37546482 -0.05007283], Reward=-1.0 Step 99: State=[-0.42761244 -0.05214762], Reward=-1.0 Step 100: State=[-0.48147006 -0.05385761], Reward=-1.0 Step 101: State=[-0.5366428 -0.05517274], Reward=-1.0 Step 102: State=[-0.59271773 -0.05607493], Reward=-1.0 Step 103: State=[-0.64927797 -0.05656025], Reward=-1.0 Step 104: State=[-0.7059178 -0.05663983], Reward=-1.0 Step 105: State=[-0.7622574 -0.0563396], Reward=-1.0 Step 106: State=[-0.81795612 -0.05569872], Reward=-1.0 Step 107: State=[-0.8727231 -0.05476698], Reward=-1.0 Step 108: State=[-0.92632481 -0.0536017 ], Reward=-1.0 Step 109: State=[-0.97858908 -0.05226427], Reward=-1.0 Step 110: State=[-1.02940612 -0.05081704], Reward=-1.0 Step 111: State=[-1.07872672 -0.0493206 ], Reward=-1.0 Step 112: State=[-1.1265585 -0.04783178], Reward=-1.0 Step 113: State=[-1.1729608 -0.0464023], Reward=-1.0 Step 114: State=[-1.2 0. ], Reward=-1.0 Step 115: State=[-1.1987581 0.0012419], Reward=-1.0 Step 116: State=[-1.19427021 0.0044879 ], Reward=-1.0 Step 117: State=[-1.18652173 0.00774848], Reward=-1.0 Step 118: State=[-1.17548846 0.01103326], Reward=-1.0 Step 119: State=[-1.16113808 0.01435038], Reward=-1.0 Step 120: State=[-1.14343234 0.01770574], Reward=-1.0 Step 121: State=[-1.12233007 0.02110228], Reward=-1.0 Step 122: State=[-1.09779103 0.02453904], Reward=-1.0 Step 123: State=[-1.06978073 0.0280103 ], Reward=-1.0 Step 124: State=[-1.03827616 0.03150456], Reward=-1.0 Step 125: State=[-1.0032725 0.03500367], Reward=-1.0 Step 126: State=[-0.9647905 0.03848199], Reward=-1.0 Step 127: State=[-0.92288452 0.04190598], Reward=-1.0 Step 128: State=[-0.87765038 0.04523414], Reward=-1.0 Step 129: State=[-0.82923273 0.04841765], Reward=-1.0 Step 130: State=[-0.77783078 0.05140195], Reward=-1.0 Step 131: State=[-0.72370164 0.05412914], Reward=-1.0 Step 132: State=[-0.66716026 0.05654138], Reward=-1.0 Step 133: State=[-0.60857514 0.05858511], Reward=-1.0 Step 134: State=[-0.54835959 0.06021555], Reward=-1.0 Step 135: State=[-0.4869585 0.06140109], Reward=-1.0 Step 136: State=[-0.42483166 0.06212684], Reward=-1.0 Step 137: State=[-0.36243478 0.06239688], Reward=-1.0 Step 138: State=[-0.30020009 0.06223469], Reward=-1.0 Step 139: State=[-0.23851824 0.06168185], Reward=-1.0 Step 140: State=[-0.17772322 0.06079502], Reward=-1.0 Step 141: State=[-0.1180812 0.05964202], Reward=-1.0 Step 142: State=[-0.05978395 0.05829725], Reward=-1.0 Step 143: State=[-0.0029466 0.05683735], Reward=-1.0 Step 144: State=[0.05239085 0.05533745], Reward=-1.0 Step 145: State=[0.10625911 0.05386826], Reward=-1.0 Step 146: State=[0.15875332 0.05249421], Reward=-1.0 Step 147: State=[0.21002575 0.05127242], Reward=-1.0 Step 148: State=[0.26027822 0.05025247], Reward=-1.0 Step 149: State=[0.30975487 0.04947665], Reward=-1.0 Step 150: State=[0.35873547 0.0489806 ], Reward=-1.0 Step 151: State=[0.40752939 0.04879392], Reward=-1.0 Step 152: State=[0.45647027 0.04894088], Reward=-1.0 Step 153: State=[0.50591109 0.04944082], Reward=-1.0 ###Markdown We now visualize the preprogrammed car solving the problem. ###Code # HIDE OUTPUT show_video() ###Output _____no_output_____ ###Markdown Reinforcement LearningQ-Learning is a system of rewards that the algorithm gives an agent for successfully moving the environment into a state considered successful. These rewards are the Q-values from which this algorithm takes its name. The final output from the Q-Learning algorithm is a table of Q-values that indicate the reward value of every action that the agent can take, given every possible environment state. The agent must bin continuous state values into a fixed finite number of columns.Learning occurs when the algorithm runs the agent and environment through episodes and updates the Q-values based on the rewards received from actions taken; Figure 12.REINF provides a high-level overview of this reinforcement or Q-Learning loop.**Figure 12.REINF:Reinforcement/Q Learning**![Reinforcement Learning](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/images/reinforcement.png "Reinforcement Learning")The Q-values can dictate action by selecting the action column with the highest Q-value for the current environment state. The choice between choosing a random action and a Q-value-driven action is governed by the epsilon ($\epsilon$) parameter, the probability of random action.Each time through the training loop, the training algorithm updates the Q-values according to the following equation. $Q^{new}(s_{t},a_{t}) \leftarrow \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{\underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}}}_{\text{new value (temporal difference target)}} - \underbrace{Q(s_{t},a_{t})}_{\text{old value}} \bigg) }^{\text{temporal difference}}$There are several parameters in this equation:* alpha ($\alpha$) - The learning rate, how much should the current step cause the Q-values to be updated.* lambda ($\lambda$) - The discount factor is the percentage of future reward that the algorithm should consider in this update.This equation modifies several values:* $Q(s_t,a_t)$ - The Q-table. For each combination of states, what reward would the agent likely receive for performing each action?* $s_t$ - The current state.* $r_t$ - The last reward received.* $a_t$ - The action that the agent will perform.The equation works by calculating a delta (temporal difference) that the equation should apply to the old state. This learning rate ($\alpha$) scales this delta. A learning rate of 1.0 would fully implement the temporal difference in the Q-values each iteration and would likely be very chaotic.There are two parts to the temporal difference: the new and old values. The new value is subtracted from the old value to provide a delta; the full amount we would change the Q-value by if the learning rate did not scale this value. The new value is a summation of the reward received from the last action and the maximum Q-values from the resulting state when the client takes this action. Adding the maximum of action Q-values for the new state is essential because it estimates the optimal future values from proceeding with this action. Q-Learning CarWe will now use Q-Learning to produce a car that learns to drive itself. Look out, Tesla! We begin by defining two essential functions. ###Code import gym import numpy as np # This function converts the floating point state values into # discrete values. This is often called binning. We divide # the range that the state values might occupy and assign # each region to a bucket. def calc_discrete_state(state): discrete_state = (state - env.observation_space.low)/buckets return tuple(discrete_state.astype(int)) # Run one game. The q_table to use is provided. We also # provide a flag to indicate if the game should be # rendered/animated. Finally, we also provide # a flag to indicate if the q_table should be updated. def run_game(q_table, render, should_update): done = False discrete_state = calc_discrete_state(env.reset()) success = False while not done: # Exploit or explore if np.random.random() > epsilon: # Exploit - use q-table to take current best action # (and probably refine) action = np.argmax(q_table[discrete_state]) else: # Explore - t action = np.random.randint(0, env.action_space.n) # Run simulation step new_state, reward, done, _ = env.step(action) # Convert continuous state to discrete new_state_disc = calc_discrete_state(new_state) # Have we reached the goal position (have we won?)? if new_state[0] >= env.unwrapped.goal_position: success = True # Update q-table if should_update: max_future_q = np.max(q_table[new_state_disc]) current_q = q_table[discrete_state + (action,)] new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * \ (reward + DISCOUNT * max_future_q) q_table[discrete_state + (action,)] = new_q discrete_state = new_state_disc if render: env.render() return success ###Output _____no_output_____ ###Markdown Several hyperparameters are very important for Q-Learning. These parameters will likely need adjustment as you apply Q-Learning to other problems. Because of this, it is crucial to understand the role of each parameter.* **LEARNING_RATE** The rate at which previous Q-values are updated based on new episodes run during training. * **DISCOUNT** The amount of significance to give estimates of future rewards when added to the reward for the current action taken. A value of 0.95 would indicate a discount of 5% on the future reward estimates. * **EPISODES** The number of episodes to train over. Increase this for more complex problems; however, training time also increases.* **SHOW_EVERY** How many episodes to allow to elapse before showing an update.* **DISCRETE_GRID_SIZE** How many buckets to use when converting each continuous state variable. For example, [10, 10] indicates that the algorithm should use ten buckets for the first and second state variables.* **START_EPSILON_DECAYING** Epsilon is the probability that the agent will select a random action over what the Q-Table suggests. This value determines the starting probability of randomness.* **END_EPSILON_DECAYING** How many episodes should elapse before epsilon goes to zero and no random actions are permitted. For example, EPISODES//10 means only the first 1/10th of the episodes might have random actions. ###Code LEARNING_RATE = 0.1 DISCOUNT = 0.95 EPISODES = 50000 SHOW_EVERY = 1000 DISCRETE_GRID_SIZE = [10, 10] START_EPSILON_DECAYING = 0.5 END_EPSILON_DECAYING = EPISODES//10 ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB, we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code if COLAB: env = wrap_env(gym.make("MountainCar-v0")) else: env = gym.make("MountainCar-v0") epsilon = 1 epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING) buckets = (env.observation_space.high - env.observation_space.low) \ / DISCRETE_GRID_SIZE q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n])) success = False ###Output _____no_output_____ ###Markdown We can now make the environment. If we are running in Google COLAB, we wrap the environment to be displayed inside the web browser. Next, create the discrete buckets for state and build Q-table. ###Code episode = 0 success_count = 0 # Loop through the required number of episodes while episode < EPISODES: episode += 1 done = False # Run the game. If we are local, display render animation # at SHOW_EVERY intervals. if episode % SHOW_EVERY == 0: print(f"Current episode: {episode}, success: {success_count}" + f" {(float(success_count)/SHOW_EVERY)}") success = run_game(q_table, True, False) success_count = 0 else: success = run_game(q_table, False, True) # Count successes if success: success_count += 1 # Move epsilon towards its ending value, if it still needs to move if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING: epsilon = max(0, epsilon - epsilon_change) print(success) ###Output Current episode: 1000, success: 0 0.0 Current episode: 2000, success: 0 0.0 Current episode: 3000, success: 0 0.0 Current episode: 4000, success: 31 0.031 Current episode: 5000, success: 321 0.321 Current episode: 6000, success: 602 0.602 Current episode: 7000, success: 620 0.62 Current episode: 8000, success: 821 0.821 Current episode: 9000, success: 707 0.707 Current episode: 10000, success: 714 0.714 Current episode: 11000, success: 574 0.574 Current episode: 12000, success: 443 0.443 Current episode: 13000, success: 480 0.48 Current episode: 14000, success: 458 0.458 Current episode: 15000, success: 327 0.327 Current episode: 16000, success: 323 0.323 Current episode: 17000, success: 295 0.295 Current episode: 18000, success: 314 0.314 Current episode: 19000, success: 362 0.362 Current episode: 20000, success: 488 0.488 Current episode: 21000, success: 566 0.566 Current episode: 22000, success: 591 0.591 Current episode: 23000, success: 441 0.441 Current episode: 24000, success: 385 0.385 Current episode: 25000, success: 1000 1.0 Current episode: 26000, success: 1000 1.0 Current episode: 27000, success: 993 0.993 Current episode: 28000, success: 67 0.067 Current episode: 29000, success: 0 0.0 Current episode: 30000, success: 39 0.039 Current episode: 31000, success: 204 0.204 Current episode: 32000, success: 429 0.429 Current episode: 33000, success: 345 0.345 Current episode: 34000, success: 970 0.97 Current episode: 35000, success: 583 0.583 Current episode: 36000, success: 752 0.752 Current episode: 37000, success: 955 0.955 Current episode: 38000, success: 997 0.997 Current episode: 39000, success: 1000 1.0 Current episode: 40000, success: 1000 1.0 Current episode: 41000, success: 1000 1.0 Current episode: 42000, success: 1000 1.0 Current episode: 43000, success: 1000 1.0 Current episode: 44000, success: 1000 1.0 Current episode: 45000, success: 1000 1.0 Current episode: 46000, success: 1000 1.0 Current episode: 47000, success: 1000 1.0 Current episode: 48000, success: 1000 1.0 Current episode: 49000, success: 1000 1.0 Current episode: 50000, success: 1000 1.0 True ###Markdown As you can see, the number of successful episodes generally increases as training progresses. It is not advisable to stop the first time we observe 100% success over 1,000 episodes. There is a randomness to most games, so it is not likely that an agent would retain its 100% success rate with a new run. It might be safe to stop training once you observe that the agent has gotten 100% for several update intervals. Running and Observing the AgentNow that the algorithm has trained the agent, we can observe the agent in action. You can use the following code to see the agent in action. ###Code # HIDE OUTPUT run_game(q_table, True, False) show_video() ###Output _____no_output_____ ###Markdown Inspecting the Q-TableWe can also display the Q-table. The following code shows the agent's action for each environment state. As the weights of a neural network, this table is not straightforward to interpret. Some patterns do emerge in that direction, as seen by calculating the means of rows and columns. The actions seem consistent at both velocity and position's upper and lower halves. ###Code import pandas as pd df = pd.DataFrame(q_table.argmax(axis=2)) df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])] df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])] df df.mean(axis=0) df.mean(axis=1) ###Output _____no_output_____
Day1/.ipynb_checkpoints/Python-ABC-checkpoint.ipynb
###Markdown Hands-On Lab My Dear Student! **Let me tell you the best way to learn python is, practice!**Let's do this small hands-on exercise together with me to understand Python essentials All the best! The fate of the mission is in your hands now. Why you will learn in this hands-on exercise?Python's power. You will learn how the cocepts of Python, you will be applying the following concepts:- variable - rules for gud coding style- Data types(number, string, boolean, float) - Most used complex types: - list - Access Element - Looping - List comprehension - Adding item - Removing item - dictionary - Access Element - Looping - dic comprehension - Adding item - Removing item - touple - Conditional statements - if - elif - else- loop - for - while- Functions - inbuilt - user defined ###Code #Declare a Variable #Assign value to a variable #Talk about dynamic types #print #talk about number, string, float #string operations #loop #declre a list #list operations #declare a dictionary #dictionay operation #declare a touple #touple operations #moving back a pice of code to a function and calling it ###Output _____no_output_____ ###Markdown Task 1**A college is maintaining operations of a college (IET-North Engineering College) through a software. This software captures and maintain college_name, year_of_establishment, address, courses and degrees, pincode.With respect to area pincode college has different facilities to engage the students** Instructions:* write down the variables the software program will use * Initialize the variables with required set of data * print the college name and year of establishment ###Code #Sometimes there are multiple ways of viewing problem statements #Sometimes it is importnat to understand the futuristic changes ###Output _____no_output_____ ###Markdown Task 2**College management has decided to crate a new holdings to show all courses offered by college. So, for this let's print all courses offered by college** ###Code #Sometimes we need to club different items in one #Sometimes we need to find Index Of a item #sometimes we need to check the type of item #Sometimes we need to put logical conditions to make sure we are dealing with right item ###Output _____no_output_____ ###Markdown Task 3**Add a new recently added facility `digital library` to area with pin code 201302** ###Code #Can a List Item be accessed using index? #Can a List Item be accessed using value? ###Output _____no_output_____ ###Markdown Task 4**One of the degree course is closed by college in year 2020-21 in all colleges. Remove that degree from list of degree courses.** **Add one degree course which is newly introduced** ###Code #What probing you may do while solving this task #Which Degree is added? #Which Degree is removed? #Will this change for all colleges or for a specific area? ###Output _____no_output_____ ###Markdown Task 5**One interesting thing about college is, for security reasons, there are 3 gates in college with even pin codes but the name of each gate is the square the number from 1 to 3** Instructions:* explanation: the names of Gate(1,2,3) are Gate1, Gate4, Gate9 repectively* print all Gates name ###Code #What probing you may do while solving this task? #Can there be more than one colleges in future with even Pin Code? #Can there be more than 3 gates in a college? ###Output _____no_output_____ ###Markdown Task 6**Check if the name of the College is less than 10 characters or equal, take first word as college name for any print media** ###Code #What probing you may do while solving this task #Can First World of college be more than 10 characters, what should be done in that case? #What does print media means? #What if Name is B.G.Reddy Campus Of Engineering? ###Output _____no_output_____
vision/vision_multiplexing.ipynb
###Markdown Convolutional Models of Multiplexing ###Code import torch import torch.nn as nn import torch.optim as optim from torch.nn import functional import torchvision import numpy as np import matplotlib.pyplot as plt import time from IPython import display # grayscale and inline plotting %matplotlib inline plt.rcParams['image.cmap'] = 'gray' ###Output _____no_output_____ ###Markdown Visualization ###Code def plot_image(image): nr, nc = image.shape extent = [-0.5, nc - 0.5, nr - 0.5, -0.5] plt.imshow(image, extent=extent, origin='upper', interpolation='nearest') def visualize(t, loss, errcl, out, x0): loss_avg = np.divide( np.cumsum(loss[: t + 1]), range(1, t + 2) ) errcl_avg = np.divide( np.cumsum(errcl[: t + 1]), range(1, t + 2) ) n_last_batches = np.min([20, t]) k = np.ones(n_last_batches * 2 + 1) / (n_last_batches + 1) k[:n_last_batches] = 0 errcl_sm = np.convolve(np.pad(errcl, mode="edge", pad_width=n_last_batches), k, mode="valid") errcl_sm = errcl_sm[: len(errcl_avg)] loss_sm = np.convolve(np.pad(loss, mode="edge", pad_width=n_last_batches), k, mode="valid") loss_sm = loss_sm[: len(loss)] display.clear_output(wait=True) plt.subplot(1, 4, 1) plt.plot(loss, label="loss") plt.plot(loss_sm, label="smothed loss") plt.plot(loss_avg, label="avg loss") plt.legend() plt.ylim(0, np.max(loss)*1.05) plt.title("loss: avg - %.4f,\nsmoothed - %.4f,\ncurrent - %.4f" % (loss_avg[t], loss_sm[t], loss[t])) plt.subplot(1, 4, 2) plt.plot(errcl, label="cl err") plt.plot(errcl_sm, label="smothed cl err") plt.plot(errcl_avg, label="avg cl err") plt.legend() plt.ylim(0, np.max(errcl)*1.05) plt.title("cl error: avg - %.4f,\nsmoothed - %.4f,\ncurrent - %.4f" % (errcl_avg[t], errcl_sm[t], errcl[t])) plt.subplot(1, 4, 3) plot_image(x0) plt.title("input image") plt.subplot(1, 4, 4) plt.bar(range(len(out)), out) plt.title("class confidences") plt.subplots_adjust(wspace=1.5) plt.subplots_adjust(hspace=1.5) plt.gcf().set_size_inches(24.5, 5.5) display.display(plt.gcf()) ###Output _____no_output_____ ###Markdown Data Preparation ###Code device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") mnist = torchvision.datasets.MNIST(root='data', train=True, download=True) # train data only trainimages = mnist.data trainlabels = mnist.targets mnist = torchvision.datasets.MNIST(root='data', train=False, download=True) # test data only testimages = mnist.data testlabels = mnist.targets # check training data shape print("Training Data shape is: ", list(trainimages.size())) print("Training Target shape is: ", list(trainlabels.size())) print("Training Data shape is: ", list(testimages.size())) print("Training Target shape is: ", list(testlabels.size())) tempimg = np.zeros((20,20)) # crop images into 20 x 20 trainimages = trainimages[:, 4:-4, 4:-4] testimages = testimages[:, 4:-4, 4:-4] tempimg[5:10,0:5] = trainimages[0][0::4,0::4] plt.imshow(tempimg) plt.imshow(trainimages[0]) %%time def auto_cov(X): X = X / 255.0 X = (X.T - X.mean(1)).T return X.T.dot(X)/X.shape[0] Cov = auto_cov(trainimages.contiguous().view(trainimages.size(0), -1).numpy()) eigvals, eigvecs = np.linalg.eig(Cov) plt.plot(np.arange(len(eigvals)), eigvals) plt.ylabel("eigenvalues") plt.show() print("{:.2f}% variance explained by top 50 PCs".format(100*eigvals[:50].sum()/eigvals.sum())) print("{:.2f}% variance explained by top 80 PCs".format(100*eigvals[:80].sum()/eigvals.sum())) ###Output 86.54% variance explained by top 50 PCs 92.08% variance explained by top 80 PCs ###Markdown Single Instance Architecture ###Code class LeNet(nn.Module): # definition of each neural network layer def __init__(self): super(LeNet, self).__init__() self.C1 = nn.Conv2d(1, 6, kernel_size=(3, 3)) self.S2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) self.C3 = nn.Conv2d(6, 16, kernel_size=(4, 4)) self.S4 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) self.C5 = nn.Conv2d(16, 120, kernel_size=(3, 3)) self.F6 = nn.Linear(120, 84) self.OL = nn.Linear(84, 10) # definition of the forward pass def forward(self, x): x = torch.tanh(self.C1(x)) x = self.S2(x) x = torch.tanh(self.C3(x)) x = self.S4(x) x = torch.tanh(self.C5(x)) x = x.view(x.size(0), -1) x = torch.tanh(self.F6(x)) x = torch.tanh(self.OL(x)) return x ###Output _____no_output_____ ###Markdown Training ###Code # %%time ntrain = trainimages.shape[0]; # number of training examples nepoch = 10; # number of epochs through training set disp_freq = 200 # display frequency batchsize = 32 # minibatch size errs = [] losses = [] cnn = LeNet().to(device) # use SGD optimizer, set learning rate parameter as 0.1 optimizer = optim.SGD(cnn.parameters(), lr=0.1) t_start = time.time() for iepoch in range(nepoch): for t in range(int(ntrain / batchsize)): batchindices = np.random.choice(ntrain, batchsize, replace=False) trainlabels_iter = trainlabels[batchindices] # label 1 for the correct digit and -1 for the incorrect digits y = torch.ones(10, batchsize) * (-1) y[trainlabels_iter, torch.arange(batchsize, dtype=torch.int64)] = 1 # normalize input images imgs = trainimages[batchindices].float() / 255. optimizer.zero_grad() out = cnn(imgs.view(len(batchindices), 1, 20, 20).to(device)) loss = torch.mean(0.5*(y.to(device) - out.t())**2) loss.backward() optimizer.step() # calculate error rate and loss for plot pred = torch.argmax(out, dim=1) err = torch.mean((pred != trainlabels_iter.to(device)).float()) errs.append(err.detach().cpu().numpy()) losses.append(loss.detach().cpu().numpy()) # plots if (t + 1) % disp_freq == 0: plt.gcf().clear() visualize(len(errs) - 1, losses, errs, out[0,:].detach().cpu(), imgs[0].detach().cpu()) print(str(time.time() - t_start) + " seconds per " + str(disp_freq) + " iterations") t_start = time.time() time.sleep(0.01) %%time ntest = testimages.shape[0] imgs = testimages.float() / 255. out = cnn(imgs.view(ntest, 1, 20, 20).to(device)) pred = torch.argmax(out, dim=1) err = torch.mean((pred != testlabels.to(device)).float()) print("Test Acc {:.2f}%".format(100 * (1-err))) ###Output Test Acc 97.61% CPU times: user 39.5 ms, sys: 19.3 ms, total: 58.8 ms Wall time: 108 ms ###Markdown Multiple Instance Architecture ###Code from scipy.stats import ortho_group, special_ortho_group from scipy import ndimage class MuxLeNet(nn.Module): # definition of each neural network layer def __init__(self, K, mod='Gaussian'): super(MuxLeNet, self).__init__() self.K = K self.C1 = nn.Conv2d(1, 10, kernel_size=(3, 3)) self.S2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) self.C3 = nn.Conv2d(10, 16, kernel_size=(4, 4)) self.S4 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) self.C5 = nn.Conv2d(16, 120, kernel_size=(3, 3)) self.F6 = nn.Linear(120, 84) self.DCs = nn.ModuleList([nn.Linear(84, 84) for _ in range(self.K)]) self.OL = nn.Linear(84, 10) self.mod = mod if mod == 'Gaussian': self.rop = [torch.randn([1,1,3,3], requires_grad=False).to(device) for _ in range(K)] elif mod == 'graded': # identity projections, fixed self.rop = [(g+1) * torch.ones([1,1,3,3], requires_grad=False).to(device) for g in range(K)] elif mod == 'identity': # identity projections, fixed self.rop = [torch.ones([1,1,3,3], requires_grad=False).to(device) for _ in range(K)] elif mod == 'learnable': self.register_parameter(name='rop', param=torch.nn.Parameter(torch.randn([K,1,1,3,3]))) elif mod == 'SO(N)': self.rop = [torch.Tensor(special_ortho_group.rvs(dim=400)).to(device) for _ in range(self.K)] elif mod == 'learnable-W': self.register_parameter(name='rop', param=torch.nn.Parameter(torch.randn([K,400,400]))) elif mod == 'nonlinear': self.register_parameter(name='rop', param=torch.nn.Parameter(torch.randn([K,16,1,3,3]))) self.register_parameter(name='rop2', param=torch.nn.Parameter(torch.randn([K,1,16,3,3]))) elif mod == 'nonlinear-expand': # self.expand_factor = 4 self.expand_factor = 8 self.register_parameter(name='rop', param=torch.nn.Parameter(torch.randn([K,16,1,3,3]))) self.register_parameter(name='rop2', param=torch.nn.Parameter( torch.randn([K,self.expand_factor,16,3,3]))) self.C1 = nn.Conv2d(self.expand_factor, 10, kernel_size=(3, 3)) elif mod == 'rotation': self.rop = [360 / K * i for i in range(K)] elif mod == 'remap': self.rop = [i for i in range(K)] def proj(self, imgs): comp_imgs = torch.zeros(imgs.shape[1], imgs.shape[2], imgs.shape[3], imgs.shape[4]).to(device) if self.mod == 'rotation': for i, r in enumerate(self.rop): comp_imgs += torch.from_numpy((1-2*i) * ndimage.rotate(imgs[i].cpu().numpy(), angle=r, axes=(2,3), reshape=False)).to(device) elif self.mod == 'remap': for i, r in enumerate(self.rop): row = r % 4 col = r // 4 comp_imgs[:, 5*row:5*(row+1), 5*col:5*(col+1)] += imgs[i][:,::4,::4] elif self.mod in ['SO(N)', 'learnable-W']: for i, r in enumerate(self.rop): comp_imgs += imgs[i].view(-1, 400).mm(r).view(imgs.shape[1], -1, 20, 20) elif self.mod == 'nonlinear': for i, r in enumerate(self.rop): tmp_imgs = nn.functional.conv2d(imgs[i], weight=r, padding=1) tmp_imgs = torch.tanh(tmp_imgs) tmp_imgs = nn.functional.conv2d(tmp_imgs, weight=self.rop2[i], padding=1) comp_imgs += torch.tanh(tmp_imgs) elif self.mod == 'nonlinear-expand': comp_imgs = torch.zeros(imgs.shape[1], self.expand_factor * imgs.shape[2], imgs.shape[3], imgs.shape[4]).to(device) for i, r in enumerate(self.rop): tmp_imgs = nn.functional.conv2d(imgs[i], weight=r, padding=1) tmp_imgs = torch.tanh(tmp_imgs) tmp_imgs = nn.functional.conv2d(tmp_imgs, weight=self.rop2[i], padding=1) comp_imgs += torch.tanh(tmp_imgs) else: for i, r in enumerate(self.rop): comp_imgs += nn.functional.conv2d(imgs[i], weight=r, padding=1) return comp_imgs # definition of the forward pass def forward(self, x): x = torch.tanh(self.C1(x)) x = self.S2(x) x = torch.tanh(self.C3(x)) x = self.S4(x) x = torch.tanh(self.C5(x)) x = x.view(x.size(0), -1) x = torch.tanh(self.F6(x)) out = [torch.tanh(self.OL(torch.tanh(dc(x)))) for dc in self.DCs] return out for i, (r, r2) in enumerate(zip([1,2], [3,4])): print(r, r2) ###Output 1 3 2 4 ###Markdown Sanity Check, K = 1 ###Code # %%time ntrain = trainimages.shape[0]; # number of training examples nepoch = 12 # number of epochs through training set disp_freq = 200 # display frequency batchsize = 32 # minibatch size K = 1 # multiplex errs = [] losses = [] muxcnn = MuxLeNet(K, 'rotation').to(device) # use SGD optimizer, set learning rate parameter as 0.1 optimizer = optim.SGD(muxcnn.parameters(), lr=0.1) t_start = time.time() for iepoch in range(nepoch): for t in range(int(ntrain / batchsize)): batchindices = np.random.choice(ntrain, batchsize * K, replace=False) trainlabels_iter = trainlabels[batchindices] trainlabels_iter_sep = trainlabels_iter.view(K, batchsize) # label 1 for the correct digit and -1 for the incorrect digits ys = torch.ones(10, batchsize * K) * (-1) ys[trainlabels_iter, torch.arange(batchsize * K, dtype=torch.int64)] = 1 ys = ys.view(-1, K, batchsize) # normalize input images imgs = trainimages[batchindices].float() / 255. comp_imgs = muxcnn.proj(imgs.view(K, batchsize, 1, 20, 20).to(device)) optimizer.zero_grad() outs = muxcnn(comp_imgs) loss = 0 for i, out in enumerate(outs): loss += torch.mean(0.5*(ys[:,i,:].to(device) - out.t())**2) loss.backward() optimizer.step() # calculate error rate and loss for plot for i, out in enumerate(outs): pred = torch.argmax(out, dim=1) err = torch.mean((pred != trainlabels_iter_sep[i].to(device)).float()) errs.append(err.detach().cpu().numpy()) losses.append(loss.detach().cpu().numpy()) # plots if (t + 1) % disp_freq == 0: plt.gcf().clear() visualize(len(errs) - 1, losses, errs, out[0,:].detach().cpu(), imgs.view(K, batchsize, 20, 20)[i, 0].detach().cpu()) print(str(time.time() - t_start) + " seconds per " + str(disp_freq) + " iterations") t_start = time.time() time.sleep(0.01) %%time ntest = testimages.shape[0] imgs = testimages.float() / 255. comp_imgs = muxcnn.proj(imgs.view(K, ntest//K, 1, 20, 20).to(device)) outs = muxcnn(comp_imgs) for i, out in enumerate(outs): pred = torch.argmax(out, dim=1) err = torch.mean((pred != testlabels.view(K, ntest//K)[i].to(device)).float()) print("Test Acc {:.2f}%".format(100 * (1-err))) ###Output Test Acc 97.95% CPU times: user 1.11 s, sys: 19 ms, total: 1.13 s Wall time: 1.13 s ###Markdown Sanity Check, K=2 ###Code # %%time ntrain = trainimages.shape[0]; # number of training examples nepoch = 15; # number of epochs through training set disp_freq = 200 # display frequency batchsize = 32 # minibatch size K = 2 # multiplex errs = {i:[] for i in range(K)} losses = [] muxcnn = MuxLeNet(K, 'nonlinear').to(device) # use SGD optimizer, set learning rate parameter as 0.1 optimizer = optim.SGD(muxcnn.parameters(), lr=0.1) t_start = time.time() for iepoch in range(nepoch): for t in range(int(ntrain / batchsize)): batchindices = np.random.choice(ntrain, batchsize * K, replace=False) trainlabels_iter = trainlabels[batchindices] trainlabels_iter_sep = trainlabels_iter.view(K, batchsize) # label 1 for the correct digit and -1 for the incorrect digits ys = torch.ones(10, batchsize * K) * (-1) ys[trainlabels_iter, torch.arange(batchsize * K, dtype=torch.int64)] = 1 ys = ys.view(-1, K, batchsize).to(device) # normalize input images imgs = trainimages[batchindices].float() / 255. comp_imgs = muxcnn.proj(imgs.view(K, batchsize, 1, 20, 20).to(device)) optimizer.zero_grad() outs = muxcnn(comp_imgs) loss = 0 for i, out in enumerate(outs): loss += torch.mean(0.5*(ys[:,i,:].t() - out)**2) loss.backward() optimizer.step() # calculate error rate and loss for plot for i, out in enumerate(outs): pred = torch.argmax(out, dim=1) err = torch.mean((pred != trainlabels_iter_sep[i].to(device)).float()) errs[i].append(err.detach().cpu().numpy()) if i == 0: losses.append(loss.detach().cpu().numpy()) # plots if (t + 1) % disp_freq == 0: plt.gcf().clear() visualize(len(errs[i]) - 1, losses, errs[i], out[0,:].detach().cpu(), imgs.view(K, batchsize, 20, 20)[i, 0].detach().cpu()) print(torch.argmax(ys[:, i, 0])) print(str(time.time() - t_start) + " seconds per " + str(disp_freq) + " iterations") t_start = time.time() time.sleep(0.01) %%time ntest = testimages.shape[0] imgs = testimages.float() / 255. comp_imgs = muxcnn.proj(imgs.view(K, ntest//K, 1, 20, 20).to(device)) outs = muxcnn(comp_imgs) for i, out in enumerate(outs): pred = torch.argmax(out, dim=1) err = torch.mean((pred != testlabels.view(K, ntest//K)[i].to(device)).float()) print("Test Acc {:.2f}%".format(100 * (1-err))) ###Output Test Acc 91.58% Test Acc 95.56% CPU times: user 124 ms, sys: 11.1 ms, total: 135 ms Wall time: 137 ms ###Markdown Number of Images vs Testing Accuracy ###Code %%time ntrain = trainimages.shape[0]; # number of training examples nepoch = 15; # number of epochs through training set batchsize = 32 # minibatch size Ks = [1,2,4,8,16] # multiplex muxcnns = [MuxLeNet(K, 'nonlinear-expand').to(device) for K in Ks] for mi, K in enumerate(Ks): print("training a model with {} inputs".format(K)) optimizer = optim.SGD(muxcnns[mi].parameters(), lr=0.1) t_start = time.time() for iepoch in range(nepoch): for t in range(int(ntrain / batchsize)): batchindices = np.random.choice(ntrain, batchsize * K, replace=False) trainlabels_iter = trainlabels[batchindices] trainlabels_iter_sep = trainlabels_iter.view(K, batchsize) # label 1 for the correct digit and -1 for the incorrect digits ys = torch.ones(10, batchsize * K) * (-1) ys[trainlabels_iter, torch.arange(batchsize * K, dtype=torch.int64)] = 1 ys = ys.view(-1, K, batchsize).to(device) # normalize input images imgs = trainimages[batchindices].float() / 255. comp_imgs = muxcnns[mi].proj(imgs.view(K, batchsize, 1, 20, 20).to(device)) optimizer.zero_grad() outs = muxcnns[mi](comp_imgs) loss = 0 for i, out in enumerate(outs): loss += torch.mean(0.5*(ys[:,i,:].t() - out)**2) loss.backward() optimizer.step() %%time ntest = testimages.shape[0] ## from learnable mean_test_acc = [] for mi, K in enumerate(Ks): imgs = testimages.float() / 255. comp_imgs = muxcnns[mi].proj(imgs.view(K, ntest//K, 1, 20, 20).to(device)) outs = muxcnns[mi](comp_imgs) print("----K={}----".format(K)) errs = [] for i, out in enumerate(outs): pred = torch.argmax(out, dim=1) err = torch.mean((pred != testlabels.view(K, ntest//K)[i].to(device)).float()) errs.append(err.cpu().numpy()) print("Test Acc {:.2f}%".format(100 * (1-err))) mean_test_acc.append(1-np.mean(errs)) nl_exp8_mean_test_acc = mean_test_acc plt.plot(Ks, nl_exp8_mean_test_acc, 'o-') plt.xlabel('number of inputs') plt.ylabel('accuracy') plt.show() ###Output _____no_output_____
cvnd/CVND_Exercises/1_1_Image_Representation/6_4. Classification.ipynb
###Markdown Day and Night Image Classifier---The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images.We'd like to build a classifier that can accurately label these images as day or night, and that relies on finding distinguishing features between the two types of images!*Note: All images come from the [AMOS dataset](http://cs.uky.edu/~jacobs/datasets/amos/) (Archive of Many Outdoor Scenes).* Import resourcesBefore you get started on the project code, import the libraries and resources that you'll need. ###Code import cv2 # computer vision library import helpers import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline ###Output _____no_output_____ ###Markdown Training and Testing DataThe 200 day/night images are separated into training and testing datasets. * 60% of these images are training images, for you to use as you create a classifier.* 40% are test images, which will be used to test the accuracy of your classifier.First, we set some variables to keep track of some where our images are stored: image_dir_training: the directory where our training image data is stored image_dir_test: the directory where our test image data is stored ###Code # Image data directories image_dir_training = "day_night_images/training/" image_dir_test = "day_night_images/test/" ###Output _____no_output_____ ###Markdown Load the datasetsThese first few lines of code will load the training day/night images and store all of them in a variable, `IMAGE_LIST`. This list contains the images and their associated label ("day" or "night"). For example, the first image-label pair in `IMAGE_LIST` can be accessed by index: ``` IMAGE_LIST[0][:]```. ###Code # Using the load_dataset function in helpers.py # Load training data IMAGE_LIST = helpers.load_dataset(image_dir_training) ###Output _____no_output_____ ###Markdown Construct a `STANDARDIZED_LIST` of input images and output labels.This function takes in a list of image-label pairs and outputs a **standardized** list of resized images and numerical labels. ###Code # Standardize all training images STANDARDIZED_LIST = helpers.standardize(IMAGE_LIST) ###Output _____no_output_____ ###Markdown Visualize the standardized dataDisplay a standardized image from STANDARDIZED_LIST. ###Code # Display a standardized image and its label # Select an image by index image_num = 0 selected_image = STANDARDIZED_LIST[image_num][0] selected_label = STANDARDIZED_LIST[image_num][1] # Display image and data about it plt.imshow(selected_image) print("Shape: "+str(selected_image.shape)) print("Label [1 = day, 0 = night]: " + str(selected_label)) ###Output Shape: (600, 1100, 3) Label [1 = day, 0 = night]: 1 ###Markdown Feature ExtractionCreate a feature that represents the brightness in an image. We'll be extracting the **average brightness** using HSV colorspace. Specifically, we'll use the V channel (a measure of brightness), add up the pixel values in the V channel, then divide that sum by the area of the image to get the average Value of the image. --- Find the average brightness using the V channelThis function takes in a **standardized** RGB image and returns a feature (a single value) that represent the average level of brightness in the image. We'll use this value to classify the image as day or night. ###Code # Find the average Value or brightness of an image def avg_brightness(rgb_image): # Convert image to HSV hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) # Add up all the pixel values in the V channel sum_brightness = np.sum(hsv[:,:,2]) area = 600*1100.0 # pixels # find the avg avg = sum_brightness/area return avg # Testing average brightness levels # Look at a number of different day and night images and think about # what average brightness value separates the two types of images # As an example, a "night" image is loaded in and its avg brightness is displayed image_num = 190 test_im_night = STANDARDIZED_LIST[image_num][0] avg = avg_brightness(test_im_night) print('Night - Avg brightness: ' + str(avg)) image_num = 10 test_im_day = STANDARDIZED_LIST[image_num][0] avg = avg_brightness(test_im_day) print('Day - Avg brightness: ' + str(avg)) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.imshow(test_im_night) ax2.imshow(test_im_day) ###Output Night - Avg brightness: 24.52624393939394 Day - Avg brightness: 157.08083484848484 ###Markdown Classification and Visualizing ErrorIn this section, we'll turn our average brightness feature into a classifier that takes in a standardized image and returns a `predicted_label` for that image. This `estimate_label` function should return a value: 0 or 1 (night or day, respectively). --- TODO: Build a complete classifier Set a threshold that you think will separate the day and night images by average brightness. ###Code # This function should take in RGB image input def estimate_label(rgb_image, threshold = 100): ## TODO: extract average brightness feature from an RGB image # Use the avg brightness feature to predict a label (0, 1) predicted_label = 0 ## TODO: set the value of a threshold that will separate day and night images ## TODO: Return the predicted_label (0 or 1) based on whether the avg is # above or below the threshold if avg_brightness(rgb_image) > threshold: predicted_label = 1 # day return predicted_label ## Test out your code by calling the above function and seeing # how some of your training data is classified incorrect = [] for img_num in range(len(STANDARDIZED_LIST)): test_img = STANDARDIZED_LIST[image_num][0] true_label = STANDARDIZED_LIST[image_num][1] if true_label != estimate_label(test_img, 130): incorrect.append([img_num, true_label]) print(len(STANDARDIZED_LIST)) print(len(incorrect)) ###Output 240 0
SegmentingandClusteringPart2.ipynb
###Markdown Peer-graded Assignment: Segmenting and Clustering Neighborhoods in Toronto Part 2 ###Code import pandas as pd ###Output _____no_output_____ ###Markdown Get the dataframe from first task ###Code # read data from html url = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M' read_table = pd.read_html(url,header=[0]) df1 = read_table[0] # rename columns' name df1 = df1.rename(index=str, columns={'Postcode':'PostalCode','Neighbourhood':'Neighborhood'}) # Ignore cells with a borough that is Not assigned df1 = df1[df1.Borough !='Not assigned'] df1.reset_index(drop=True,inplace=True) # groupby df1 = df1.groupby('PostalCode',as_index=False).agg(lambda x: ','.join(set(x.dropna()))) # If a cell has a borough but a Not assigned neighborhood, #then the neighborhood will be the same as the borough df1.loc[df1['Neighborhood'] == 'Not assigned','Neighborhood'] = df1['Borough'] df1.head() ###Output _____no_output_____ ###Markdown Read csv file with geographical coordinates ###Code df2 = pd.read_csv('http://cocl.us/Geospatial_data') df2.head() ###Output _____no_output_____ ###Markdown Rename column name ###Code df2.columns = ['PostalCode','Latitude','Longitude'] df2.head() ###Output _____no_output_____ ###Markdown Checking the shape of two dataframes ###Code print(df1.shape[0]) print(df2.shape[0]) ###Output 103 103 ###Markdown Merge two dataframes ###Code df_merge = pd.merge(left=df1,right=df2,on='PostalCode') df_merge.head(15) ###Output _____no_output_____
examples/input_tranformer/spam-classification.ipynb
###Markdown Spam Classification Model (Sklearn) - Wrap a ML model for use as a prediction microservice in seldon-core- Run locally on Docker to test- Deploy on seldon-core running on k8s cluster Train Locally ###Code import numpy as np import pandas as pd from sklearn.externals import joblib from pathlib import Path import string from nltk.stem import SnowballStemmer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split import pickle from sklearn.svm import SVC from sklearn.metrics import accuracy_score model_path: Path=Path('./') data = pd.read_csv("spam.csv",encoding='latin-1') data = data.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1) data = data.rename(columns={"v1":"class", "v2":"text"}) data.head() def pre_process(text): text = text.translate(str.maketrans('', '', string.punctuation)) text = [word for word in text.split() if word.lower() not in stopwords.words('english')] words = "" for i in text: stemmer = SnowballStemmer("english") words += (stemmer.stem(i))+" " return words features = data['text'].copy() features = features.apply(pre_process) vectorizer = TfidfVectorizer("english") _features = vectorizer.fit_transform(features) with open('Spam-Classifier/model/vectorizer.pkl', 'wb') as vect: pickle.dump(vectorizer, vect) vectorizer = joblib.load(model_path.joinpath('Spam-Classifier/model/vectorizer.pkl')) train_x, test_x, train_y, test_y = train_test_split(_features, data['class'], test_size=0.3, random_state=0) svc = SVC(kernel='sigmoid', gamma=1.0, probability=True) svc.fit(train_x,train_y) # save the model to disk filename = 'Spam-Classifier/model/model.pkl' pickle.dump(svc, open(filename, 'wb')) clf = joblib.load(model_path.joinpath(filename)) prediction = clf.predict(test_x) accuracy_score(test_y,prediction) message = np.array(['click here to win the price']) data = vectorizer.transform(message).todense() probas = clf.predict_proba(data) probas clf.classes_ ###Output _____no_output_____ ###Markdown wrap each model component using s2i ###Code !s2i build Spam-Classifier/ seldonio/seldon-core-s2i-python3:1.2.2-dev spam-classifier:1.0.0.1 !docker run --name "spam-classifier" -d --rm -p 5000:5000 spam-classifier:1.0.0.1 !curl -g http://localhost:5000/predict --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["click here to win the price"]}}' !docker rm spam-classifier --force !s2i build Translator/ seldonio/seldon-core-s2i-python3:1.2.2-dev translator:1.0.0.1 !docker run --name "eng-translator" -d --rm -p 5000:5000 translator:1.0.0.1 !curl -g http://localhost:5000/transform-input --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["Wie läuft dein Tag"]}}' !docker rm eng-translator --force ###Output eng-translator ###Markdown Spam Classification Model (Sklearn) - Wrap a ML model for use as a prediction microservice in seldon-core- Run locally on Docker to test- Deploy on seldon-core running on k8s cluster Train Locally ###Code import numpy as np import pandas as pd from sklearn.externals import joblib from pathlib import Path import string from nltk.stem import SnowballStemmer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split import pickle from sklearn.svm import SVC from sklearn.metrics import accuracy_score model_path: Path=Path('./') data = pd.read_csv("spam.csv",encoding='latin-1') data = data.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1) data = data.rename(columns={"v1":"class", "v2":"text"}) data.head() def pre_process(text): text = text.translate(str.maketrans('', '', string.punctuation)) text = [word for word in text.split() if word.lower() not in stopwords.words('english')] words = "" for i in text: stemmer = SnowballStemmer("english") words += (stemmer.stem(i))+" " return words features = data['text'].copy() features = features.apply(pre_process) vectorizer = TfidfVectorizer("english") _features = vectorizer.fit_transform(features) with open('Spam-Classifier/model/vectorizer.pkl', 'wb') as vect: pickle.dump(vectorizer, vect) vectorizer = joblib.load(model_path.joinpath('Spam-Classifier/model/vectorizer.pkl')) train_x, test_x, train_y, test_y = train_test_split(_features, data['class'], test_size=0.3, random_state=0) svc = SVC(kernel='sigmoid', gamma=1.0, probability=True) svc.fit(train_x,train_y) # save the model to disk filename = 'Spam-Classifier/model/model.pkl' pickle.dump(svc, open(filename, 'wb')) clf = joblib.load(model_path.joinpath(filename)) prediction = clf.predict(test_x) accuracy_score(test_y,prediction) message = np.array(['click here to win the price']) data = vectorizer.transform(message).todense() probas = clf.predict_proba(data) probas clf.classes_ ###Output _____no_output_____ ###Markdown wrap each model component using s2i ###Code !s2i build Spam-Classifier/ seldonio/seldon-core-s2i-python3:0.7 spam-classifier:1.0.0.1 !docker run --name "spam-classifier" -d --rm -p 5000:5000 spam-classifier:1.0.0.1 !curl -g http://localhost:5000/predict --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["click here to win the price"]}}' !docker rm spam-classifier --force !s2i build Translator/ seldonio/seldon-core-s2i-python3:0.7 translator:1.0.0.1 !docker run --name "eng-translator" -d --rm -p 5000:5000 translator:1.0.0.1 !curl -g http://localhost:5000/transform-input --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["Wie läuft dein Tag"]}}' !docker rm eng-translator --force ###Output eng-translator ###Markdown Spam Classification Model (Sklearn) - Wrap a ML model for use as a prediction microservice in seldon-core- Run locally on Docker to test- Deploy on seldon-core running on k8s cluster Train Locally ###Code import numpy as np import pandas as pd from sklearn.externals import joblib from pathlib import Path import string from nltk.stem import SnowballStemmer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split import pickle from sklearn.svm import SVC from sklearn.metrics import accuracy_score model_path: Path=Path('./') data = pd.read_csv("spam.csv",encoding='latin-1') data = data.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1) data = data.rename(columns={"v1":"class", "v2":"text"}) data.head() def pre_process(text): text = text.translate(str.maketrans('', '', string.punctuation)) text = [word for word in text.split() if word.lower() not in stopwords.words('english')] words = "" for i in text: stemmer = SnowballStemmer("english") words += (stemmer.stem(i))+" " return words features = data['text'].copy() features = features.apply(pre_process) vectorizer = TfidfVectorizer("english") _features = vectorizer.fit_transform(features) with open('Spam-Classifier/model/vectorizer.pkl', 'wb') as vect: pickle.dump(vectorizer, vect) vectorizer = joblib.load(model_path.joinpath('Spam-Classifier/model/vectorizer.pkl')) train_x, test_x, train_y, test_y = train_test_split(_features, data['class'], test_size=0.3, random_state=0) svc = SVC(kernel='sigmoid', gamma=1.0, probability=True) svc.fit(train_x,train_y) # save the model to disk filename = 'Spam-Classifier/model/model.pkl' pickle.dump(svc, open(filename, 'wb')) clf = joblib.load(model_path.joinpath(filename)) prediction = clf.predict(test_x) accuracy_score(test_y,prediction) message = np.array(['click here to win the price']) data = vectorizer.transform(message).todense() probas = clf.predict_proba(data) probas clf.classes_ ###Output _____no_output_____ ###Markdown wrap each model component using s2i ###Code !s2i build Spam-Classifier/ seldonio/seldon-core-s2i-python3:1.1.1-rc spam-classifier:1.0.0.1 !docker run --name "spam-classifier" -d --rm -p 5000:5000 spam-classifier:1.0.0.1 !curl -g http://localhost:5000/predict --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["click here to win the price"]}}' !docker rm spam-classifier --force !s2i build Translator/ seldonio/seldon-core-s2i-python3:1.1.1-rc translator:1.0.0.1 !docker run --name "eng-translator" -d --rm -p 5000:5000 translator:1.0.0.1 !curl -g http://localhost:5000/transform-input --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["Wie läuft dein Tag"]}}' !docker rm eng-translator --force ###Output eng-translator ###Markdown Spam Classification Model (Sklearn) - Wrap a ML model for use as a prediction microservice in seldon-core- Run locally on Docker to test- Deploy on seldon-core running on k8s cluster Train Locally ###Code import numpy as np import pandas as pd from sklearn.externals import joblib from pathlib import Path import string from nltk.stem import SnowballStemmer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split import pickle from sklearn.svm import SVC from sklearn.metrics import accuracy_score model_path: Path=Path('./') data = pd.read_csv("spam.csv",encoding='latin-1') data = data.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1) data = data.rename(columns={"v1":"class", "v2":"text"}) data.head() def pre_process(text): text = text.translate(str.maketrans('', '', string.punctuation)) text = [word for word in text.split() if word.lower() not in stopwords.words('english')] words = "" for i in text: stemmer = SnowballStemmer("english") words += (stemmer.stem(i))+" " return words features = data['text'].copy() features = features.apply(pre_process) vectorizer = TfidfVectorizer("english") _features = vectorizer.fit_transform(features) with open('Spam-Classifier/model/vectorizer.pkl', 'wb') as vect: pickle.dump(vectorizer, vect) vectorizer = joblib.load(model_path.joinpath('Spam-Classifier/model/vectorizer.pkl')) train_x, test_x, train_y, test_y = train_test_split(_features, data['class'], test_size=0.3, random_state=0) svc = SVC(kernel='sigmoid', gamma=1.0, probability=True) svc.fit(train_x,train_y) # save the model to disk filename = 'Spam-Classifier/model/model.pkl' pickle.dump(svc, open(filename, 'wb')) clf = joblib.load(model_path.joinpath(filename)) prediction = clf.predict(test_x) accuracy_score(test_y,prediction) message = np.array(['click here to win the price']) data = vectorizer.transform(message).todense() probas = clf.predict_proba(data) probas clf.classes_ ###Output _____no_output_____ ###Markdown wrap each model component using s2i ###Code !s2i build Spam-Classifier/ seldonio/seldon-core-s2i-python3:1.2.1-dev spam-classifier:1.0.0.1 !docker run --name "spam-classifier" -d --rm -p 5000:5000 spam-classifier:1.0.0.1 !curl -g http://localhost:5000/predict --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["click here to win the price"]}}' !docker rm spam-classifier --force !s2i build Translator/ seldonio/seldon-core-s2i-python3:1.2.1-dev translator:1.0.0.1 !docker run --name "eng-translator" -d --rm -p 5000:5000 translator:1.0.0.1 !curl -g http://localhost:5000/transform-input --data-urlencode 'json={"data": {"names": ["message"], "ndarray": ["Wie läuft dein Tag"]}}' !docker rm eng-translator --force ###Output eng-translator
poldergemaal.ipynb
###Markdown Polder pumping station - machine learning tutorial Polder pumping stationBecause a polder closely resembles a bath tub, it will slowly fill with water because of rainfall if it's not emptied by a pump. ![Polder](https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/images/polder1.png)This is done by a polder pumping station - or _poldergemaal_ in Dutch. This is a small building with a big pump that can remove water from the polder to canals that eventually transfer it to sea.If the polder is emptied too much, the land in the polder has too little water for nature and farmers. Therefore, an ideal water level is determined by the water board. The pumping station is managed in such way, that this level is followed as closely as possible, by turning the pumps on and off. This resembles the working of for example an oven or central heating in a house._This is what a polder pumping station looks like, although it comes in many shapes and sizes._![Gemaal 1](https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/images/gemaal1.jpg)_Schematic pumping station._![Gemaal 2](https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/images/gemaal2.png)In this tutorial, you will create a control system which tries to follow this ideal water level as closely as possible, while it's raining in the polder. This rain is generated randomly. The water level we're aiming at is 0.5 m. (Deep) Reinforcement learningWe'll be using a technique called deep reinforcement learning. Based on simulations, the method tries to decide what is the best action it can do. It uses so-called neural networks, which are originally based on the workings of human brains. These kinds of models have been used to create the best chess robots in the world and for the first time beat the best human in the game of Go. _A Neural Network_![nn](https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/images/nn.png)The model consists of a number of parts: - Environment: the world the agent interacts with- Agent: the model that alters the environment- State: the state the world (environment) is in at a moment- Reward: this is important; in order to learn to do what we want, the system should deliver rewards. These should be high when the model does what we want it to do, and low when it's doing things that we don't want it to do.![reinforcement learning](https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/images/reinforcementlearning.png) RewardIn this tutorial, the first question you will try to solve, is the reward function. You will try to make a function that is high when the water level is around the level we want (so 0.5 m) and low when the water level is away from that number. In this example, we'll flip this and make a penalty: the further away from 0.5, the higher the penalty and the more negative the reward becomes. PythonThe programming is done in the programming called Python. This is a relatively easy programming language and is widely used by data scientist.We're using a so-called Notebook to run the Python code in the browser. Press the play button or press `shift`+`enter` to run a cell. You can basically run all cells after one another, but there's one cell which you'll have to alter before running. HintsThere is a number of hints near the first question. Run a cell with the hint to see the hint.Below is the first hint, but first run the cell below: ###Code import requests path_json = r"https://raw.githubusercontent.com/SGnoddeHHDelfland/PolderGemaalBesturing/main/hints.json" response = requests.get(path_json) hints = response.json() def print_hints(number): print(hints['hints'][number]) ###Output _____no_output_____ ###Markdown This will be your first hint, which we've basically already talked about. ###Code print_hints(0) ###Output _____no_output_____ ###Markdown Run this cell to install the model we're using. This is installed on Google, not on your pc. Don't mind all the text that will show up below it. ###Code !pip install tensorforce ###Output _____no_output_____ ###Markdown Just run the cell below ###Code from tensorforce.environments import Environment from tensorforce.agents import Agent import numpy as np import plotly.express as px import pandas as pd from random import uniform ###Output _____no_output_____ ###Markdown Question 1Create a penalty function behind the `penalty = `. This should be a function of the water level (`water_level`).Note: if you want to use a power (tot de macht), this is written as `**` in Python, instead of `^` for example. ###Code def calculate_penalty(water_level): penalty = ... return penalty ###Output _____no_output_____ ###Markdown Hint 2 ###Code print_hints(1) ###Output _____no_output_____ ###Markdown Hint 3 ###Code print_hints(2) ###Output _____no_output_____ ###Markdown Hint 4 ###Code print_hints(3) ###Output _____no_output_____ ###Markdown Run the cell below, this will define the environment and agent. ###Code class PolderEnvironment(Environment): """Simple polder environment. It is a polder with a single pump attached to it. If the pump is activated, the waterlevel in the polder will lower. Rainfall will cause the waterlevel in the polder to rise. The amount of rainfall is random. The goal will be to keep the waterlevel between 0.0 and 1.0m NAP and to keep this up for at least 100 timesteps. """ def __init__(self): super().__init__() self.water_level = np.random.uniform(low=0.0, high=1.0, size=(1,)) def states(self): return dict(type='float', shape=(1,), min_value=0.0, max_value=1.0) def actions(self): return dict(type='int', num_values=2) # Optional, should only be defined if environment has a natural maximum # episode length def max_episode_timesteps(self): return 500 # Optional def close(self): super().close() def reset(self): """Reset state.""" self.timestep = 0 self.water_level = np.random.uniform(low=0.0, high=1.0, size=(1,)) return self.water_level def response(self, action): """Respond to an action.""" return self.water_level - (action * 0.2) def reward_compute(self): penalty = calculate_penalty(self.water_level) return -penalty # TODO 0 weghalen def rain(self): return uniform(0.0,0.25) # back-up def terminal(self): if self.water_level > 1.0 or self.water_level < 0.0: return True return False def execute(self, actions): ## Check the action is either 0 or 1 -- pump on or off. assert actions == 0 or actions == 1 ## Increment timestamp self.timestep += 1 ## Update the current_temp self.water_level = self.response(actions) self.water_level += self.rain() ## Compute the reward reward = self.reward_compute()[0] ## The only way to go terminal is to exceed max_episode_timestamp. ## terminal == False means episode is not done ## terminal == True means it is done. terminal = self.terminal() return self.water_level, terminal, reward ###Output _____no_output_____ ###Markdown Create the environment and agent (just run these cells) ###Code environment = environment = Environment.create( environment=PolderEnvironment, max_episode_timesteps=500) agent = Agent.create( agent='tensorforce', environment=environment, update=64, optimizer=dict(optimizer='adam', learning_rate=1e-3), objective='policy_gradient', reward_estimation=dict(horizon=1) ) ###Output _____no_output_____ ###Markdown This is the actual training, so it can take a while ###Code for _ in range(200): states = environment.reset() terminal = False while not terminal: actions = agent.act(states=states) states, terminal, reward = environment.execute(actions=actions) agent.observe(terminal=terminal, reward=reward) ###Output _____no_output_____ ###Markdown Run this cell to see whether it worked and see the results. If it didn't work, you'll have to change you penalty function and you'll have to rerun all the cells from the changed cell onwards. ###Code ### Initialize environment.reset() environment.water_level = np.random.uniform(low=0.0, high=1.0, size=(1,)) states = environment.water_level internals = agent.initial_internals() terminal = False ### Run an episode temp = [environment.water_level[0]] while not terminal: actions, internals = agent.act(states=states, internals=internals, independent=True) states, terminal, reward = environment.execute(actions=actions) temp += [states[0]] fig = px.line(df, x=df.index, y='water level', title='Reinforcement learning poldergemaal: water level over time', labels={ "index": "Time"}) ### Plot the run df = pd.Series(temp).rename('water level') fig.update_yaxes(range = [0,1]) fig.show() ###Output _____no_output_____ ###Markdown Bonus questionsYou'll have to do these questions in the code above. Question 2Change the target water level from 0.5 to 0.6. Hint question 2 - 1 ###Code print_hints(5) ###Output _____no_output_____ ###Markdown Hint question 2 - 2 ###Code print_hints(6) ###Output _____no_output_____
Day 4/KalpanaLabs_Day4.ipynb
###Markdown Strings 🧵What are strings?When Python 🐍 wants to store text, it creates a variable called _string_. A string's sole purpose is to hold text for the programming. It can hold anything - from nothing at all ('') to enough to fill up all the memory on your computer. Create a stringA string is declared in the following way.**variableName = "{value}"**OR**variableName = '{value}'** ###Code # declaring your name, age, birthdate, and birthYear as variables yourName = "Aditya" # ENTER CODE HERE age = "21" # ENTER CODE HERE birthDate = "30 November" # ENTER CODE HERE birthYear = "1999" # ENTER CODE HERE ###Output _____no_output_____ ###Markdown Now a little bit of magic! ###Code print("My name is " + yourName + "! ") print("My age is " + age + ".") print("I was born on " + birthDate + ".") print("The year was " + birthYear + ".") ###Output My name is Aditya! My age is 21. I was born on 30 November. The year was 1999. ###Markdown Analysis of the code. What does the print statement here do? ###Code ###Output _____no_output_____ ###Markdown String-Formatting Methods---|Method|Description|Example||------|-----------|-------||.upper()|Converts all letters to capital letters|'HELLO WORLD'||.lower()|Converts all letters to lower case|'hello world'||.capitalize()|Converts first letter in a string to uppercase and converts the rest layers to lowercase|'Hello world'||.title()|Converts the first letter, and every letter after a punctuation or space, to uppercase. The other letters are converted to lowercase|'Hello World'| Apply the methodsWe are going to apply the methods on a very famous line from the movie, Harry Potter and the Chamber of Secrets.The line is below👇 ###Code line = "It is our choices, Harry, that show what we truly are, far more than our abilities." ###Output _____no_output_____ ###Markdown Now print the line ###Code # ENTER CODE HERE ###Output _____no_output_____ ###Markdown .upper() methodApplying the **.upper()** method on the string ###Code lineUpper = line.upper() ###Output _____no_output_____ ###Markdown Now print the new variable ###Code # ENTER CODE HERE ###Output _____no_output_____ ###Markdown .lower() methodApplying the **.lower()** method on the string ###Code lineLower = line.lower() ###Output _____no_output_____ ###Markdown Now print the new variable ###Code # ENTER CODE HERE ###Output _____no_output_____ ###Markdown .capitalize() methodApplying the **.capitalize()** method on the string ###Code lineCapitalize = line.capitalize() ###Output _____no_output_____ ###Markdown Now print the new variable ###Code # ENTER CODE HERE ###Output _____no_output_____ ###Markdown .title() methodApplying the **.title()** method on the string ###Code lineTitle = line.title() ###Output _____no_output_____ ###Markdown Now print the new variable ###Code # ENTER CODE HERE ###Output _____no_output_____ ###Markdown Try it yourself!Seems that we have seen some of the basic string methods in Python!Now create a string variable of your own and apply these methods on them! ###Code ###Output _____no_output_____
notebooks/09.0-clusterability/make-clusterability-plot-convex-hull-indvs-final.ipynb
###Markdown Save for paper ###Code clusterability_df[:3] ensure_dir(DATA_DIR / "paper_data" / "hopkins_species_comparison" ) clusterability_df.to_pickle(DATA_DIR / "paper_data" / "hopkins_species_comparison" / "all_species.pickle") pd.__version__ ###Output _____no_output_____
Model backlog/Train/9-melanoma-3fold-resnet18-label-smoothing-2.ipynb
###Markdown Dependencies ###Code # !pip install --quiet efficientnet !pip install --quiet image-classifiers import warnings, json, re from scripts_step_lr_schedulers import * from melanoma_utility_scripts import * from kaggle_datasets import KaggleDatasets from sklearn.model_selection import KFold import tensorflow.keras.layers as L import tensorflow.keras.backend as K from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from tensorflow.keras import optimizers, layers, metrics, losses, Model # import efficientnet.tfkeras as efn from classification_models.tfkeras import Classifiers SEED = 0 seed_everything(SEED) warnings.filterwarnings("ignore") ###Output _____no_output_____ ###Markdown TPU configuration ###Code strategy, tpu = set_up_strategy() print("REPLICAS: ", strategy.num_replicas_in_sync) AUTO = tf.data.experimental.AUTOTUNE ###Output REPLICAS: 1 ###Markdown Model parameters ###Code base_model_path = '/kaggle/input/efficientnet/' dataset_path = 'melanoma-256x256' config = { "HEIGHT": 256, "WIDTH": 256, "CHANNELS": 3, "BATCH_SIZE": 64, "EPOCHS": 15, "LEARNING_RATE": 3e-4, "ES_PATIENCE": 5, "N_FOLDS": 3, "BASE_MODEL_PATH": base_model_path + 'efficientnet-b3_weights_tf_dim_ordering_tf_kernels_autoaugment_notop.h5', "DATASET_PATH": dataset_path } with open('config.json', 'w') as json_file: json.dump(json.loads(json.dumps(config)), json_file) config ###Output _____no_output_____ ###Markdown Load data ###Code database_base_path = '/kaggle/input/siim-isic-melanoma-classification/' k_fold = pd.read_csv(database_base_path + 'train.csv') print('Train samples: %d' % len(k_fold)) display(k_fold.head()) GCS_PATH = KaggleDatasets().get_gcs_path(dataset_path) TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec') ###Output Train samples: 33126 ###Markdown Auxiliary functions ###Code # Datasets utility functions def read_labeled_tfrecord(example, height=config['HEIGHT'], width=config['WIDTH'], channels=config['CHANNELS']): example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image'], height, width, channels) label = tf.cast(example['target'], tf.float32) # meta features data = {} data['patient_id'] = tf.cast(example['patient_id'], tf.int32) data['sex'] = tf.cast(example['sex'], tf.int32) data['age_approx'] = tf.cast(example['age_approx'], tf.int32) data['anatom_site_general_challenge'] = tf.cast(tf.one_hot(example['anatom_site_general_challenge'], 7), tf.int32) data['diagnosis'] = tf.cast(tf.one_hot(example['diagnosis'], 10), tf.int32) return {'input_image': image, 'input_meta': data}, label # returns a dataset of (image, data, label) def read_labeled_tfrecord_eval(example, height=config['HEIGHT'], width=config['WIDTH'], channels=config['CHANNELS']): example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) image = decode_image(example['image'], height, width, channels) label = tf.cast(example['target'], tf.float32) image_name = example['image_name'] # meta features data = {} data['patient_id'] = tf.cast(example['patient_id'], tf.int32) data['sex'] = tf.cast(example['sex'], tf.int32) data['age_approx'] = tf.cast(example['age_approx'], tf.int32) data['anatom_site_general_challenge'] = tf.cast(tf.one_hot(example['anatom_site_general_challenge'], 7), tf.int32) data['diagnosis'] = tf.cast(tf.one_hot(example['diagnosis'], 10), tf.int32) return {'input_image': image, 'input_meta': data}, label, image_name # returns a dataset of (image, data, label, image_name) def data_augment(image, label): p_spatial = tf.random.uniform([1], minval=0, maxval=1, dtype='float32', seed=SEED) p_rotate = tf.random.uniform([1], minval=0, maxval=1, dtype='float32', seed=SEED) ### Spatial-level transforms if p_spatial >= .2: # flips image['input_image'] = tf.image.random_flip_left_right(image['input_image'], seed=SEED) image['input_image'] = tf.image.random_flip_up_down(image['input_image'], seed=SEED) if p_spatial >= .7: image['input_image'] = tf.image.transpose(image['input_image']) if p_rotate >= .8: # rotate 270 image['input_image'] = tf.image.rot90(image['input_image'], k=3) elif p_rotate >= .6: # rotate 180 image['input_image'] = tf.image.rot90(image['input_image'], k=2) elif p_rotate >= .4: # rotate 90 image['input_image'] = tf.image.rot90(image['input_image'], k=1) return image, label def load_dataset(filenames, ordered=False, buffer_size=-1): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False # disable order, increase speed dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=buffer_size) # automatically interleaves reads from multiple files dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order dataset = dataset.map(read_labeled_tfrecord, num_parallel_calls=buffer_size) return dataset # returns a dataset of (image, data, label) def load_dataset_eval(filenames, buffer_size=-1): dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=buffer_size) # automatically interleaves reads from multiple files dataset = dataset.map(read_labeled_tfrecord_eval, num_parallel_calls=buffer_size) return dataset # returns a dataset of (image, data, label, image_name) def get_training_dataset(filenames, batch_size, buffer_size=-1): dataset = load_dataset(filenames, ordered=False, buffer_size=buffer_size) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.repeat() # the training dataset must repeat for several epochs dataset = dataset.shuffle(2048) dataset = dataset.batch(batch_size, drop_remainder=True) # slighly faster with fixed tensor sizes dataset = dataset.prefetch(buffer_size) # prefetch next batch while training (autotune prefetch buffer size) return dataset def get_validation_dataset(filenames, ordered=True, repeated=False, batch_size=32, buffer_size=-1): dataset = load_dataset(filenames, ordered=ordered, buffer_size=buffer_size) if repeated: dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(batch_size, drop_remainder=repeated) dataset = dataset.prefetch(buffer_size) return dataset def get_eval_dataset(filenames, batch_size=32, buffer_size=-1): dataset = load_dataset_eval(filenames, buffer_size=buffer_size) dataset = dataset.batch(batch_size, drop_remainder=False) dataset = dataset.prefetch(buffer_size) return dataset ###Output _____no_output_____ ###Markdown Learning rate scheduler ###Code lr_min = 1e-6 lr_start = 0 lr_max = config['LEARNING_RATE'] step_size = 26880 // config['BATCH_SIZE'] #(len(k_fold[k_fold[f'fold_{fold_n}'] == 'train']) * 2) // config['BATCH_SIZE'] total_steps = config['EPOCHS'] * step_size hold_max_steps = 0 warmup_steps = step_size * 5 rng = [i for i in range(0, total_steps, step_size)] y = [linear_schedule_with_warmup(tf.cast(x, tf.float32), total_steps=total_steps, warmup_steps=warmup_steps, hold_max_steps=hold_max_steps, lr_start=lr_start, lr_max=lr_max, lr_min=lr_min) for x in rng] sns.set(style="whitegrid") fig, ax = plt.subplots(figsize=(20, 6)) plt.plot(rng, y) print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1])) ###Output Learning rate schedule: 0 to 0.0003 to 3e-05 ###Markdown Model ###Code def model_fn(input_shape): input_image = L.Input(shape=input_shape, name='input_image') ResNet18, preprocess_input = Classifiers.get('resnet18') base_model = ResNet18(input_shape=input_shape, weights='imagenet', include_top=False) x = base_model(input_image) x = L.GlobalAveragePooling2D()(x) output = L.Dense(1, activation='sigmoid')(x) model = Model(inputs=input_image, outputs=output) return model ###Output _____no_output_____ ###Markdown Training ###Code eval_dataset = get_eval_dataset(TRAINING_FILENAMES, batch_size=config['BATCH_SIZE'], buffer_size=AUTO) image_names = next(iter(eval_dataset.unbatch().map(lambda data, label, image_name: image_name).batch(len(k_fold)))).numpy().astype('U') image_data = eval_dataset.map(lambda data, label, image_name: data) history_list = [] kfold = KFold(config['N_FOLDS'], shuffle=True, random_state=SEED) for n_fold, (trn_idx, val_idx) in enumerate(kfold.split(TRAINING_FILENAMES)): n_fold +=1 print('\nFOLD: %d' % (n_fold)) # tf.tpu.experimental.initialize_tpu_system(tpu) K.clear_session() ### Data train_filenames = np.array(TRAINING_FILENAMES)[trn_idx] valid_filenames = np.array(TRAINING_FILENAMES)[val_idx] train_size = count_data_items(train_filenames) step_size = train_size // config['BATCH_SIZE'] # Train model model_path = 'model_fold_%d.h5' % (n_fold) es = EarlyStopping(monitor='val_loss', mode='min', patience=config['ES_PATIENCE'], restore_best_weights=True, verbose=1) checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True, save_weights_only=True) with strategy.scope(): model = model_fn((config['HEIGHT'], config['WIDTH'], config['CHANNELS'])) lr = lambda: linear_schedule_with_warmup(tf.cast(optimizer.iterations, tf.float32), total_steps=total_steps, warmup_steps=warmup_steps, hold_max_steps=hold_max_steps, lr_start=lr_start, lr_max=lr_max, lr_min=lr_min) optimizer = optimizers.Adam(learning_rate=lr) model.compile(optimizer, loss=losses.BinaryCrossentropy(label_smoothing=0.2), metrics=[metrics.AUC()]) history = model.fit(get_training_dataset(train_filenames, batch_size=config['BATCH_SIZE'], buffer_size=AUTO), validation_data=get_validation_dataset(valid_filenames, ordered=True, repeated=False, batch_size=config['BATCH_SIZE'], buffer_size=AUTO), epochs=config['EPOCHS'], steps_per_epoch=step_size, callbacks=[checkpoint, es], verbose=2).history history_list.append(history) # Make predictions preds = model.predict(image_data) name_preds = dict(zip(image_names, preds.reshape(len(preds)))) k_fold[f'pred_fold_{n_fold}'] = k_fold.apply(lambda x: name_preds[x['image_name']], axis=1) valid_filenames = np.array(TRAINING_FILENAMES)[val_idx] valid_dataset = get_eval_dataset(valid_filenames, batch_size=config['BATCH_SIZE'], buffer_size=AUTO) valid_image_names = next(iter(valid_dataset.unbatch().map(lambda data, label, image_name: image_name).batch(count_data_items(valid_filenames)))).numpy().astype('U') k_fold[f'fold_{n_fold}'] = k_fold.apply(lambda x: 'validation' if x['image_name'] in valid_image_names else 'train', axis=1) ###Output FOLD: 1 Downloading data from https://github.com/qubvel/classification_models/releases/download/0.0.1/resnet18_imagenet_1000_no_top.h5 44924928/44920640 [==============================] - 1s 0us/step Epoch 1/15 323/323 - 100s - loss: 0.4816 - auc: 0.5787 - val_loss: 0.5415 - val_auc: 0.4169 Epoch 2/15 323/323 - 99s - loss: 0.3569 - auc: 0.7896 - val_loss: 0.3607 - val_auc: 0.3586 Epoch 3/15 323/323 - 99s - loss: 0.3548 - auc: 0.8373 - val_loss: 0.3547 - val_auc: 0.6742 Epoch 4/15 323/323 - 98s - loss: 0.3536 - auc: 0.8521 - val_loss: 0.3588 - val_auc: 0.7807 Epoch 5/15 323/323 - 98s - loss: 0.3523 - auc: 0.8741 - val_loss: 0.3572 - val_auc: 0.5639 Epoch 6/15 323/323 - 99s - loss: 0.3510 - auc: 0.8814 - val_loss: 0.3545 - val_auc: 0.8495 Epoch 7/15 323/323 - 98s - loss: 0.3513 - auc: 0.8610 - val_loss: 0.3524 - val_auc: 0.7736 Epoch 8/15 323/323 - 98s - loss: 0.3507 - auc: 0.8900 - val_loss: 0.3560 - val_auc: 0.8347 Epoch 9/15 323/323 - 98s - loss: 0.3508 - auc: 0.8809 - val_loss: 0.3508 - val_auc: 0.8493 Epoch 10/15 323/323 - 98s - loss: 0.3484 - auc: 0.9018 - val_loss: 0.3532 - val_auc: 0.7983 Epoch 11/15 323/323 - 98s - loss: 0.3480 - auc: 0.9026 - val_loss: 0.4033 - val_auc: 0.8126 Epoch 12/15 323/323 - 97s - loss: 0.3481 - auc: 0.9153 - val_loss: 0.3535 - val_auc: 0.6917 Epoch 13/15 323/323 - 98s - loss: 0.3453 - auc: 0.9247 - val_loss: 0.3520 - val_auc: 0.8287 Epoch 14/15 Restoring model weights from the end of the best epoch. 323/323 - 98s - loss: 0.3438 - auc: 0.9315 - val_loss: 0.3522 - val_auc: 0.7845 Epoch 00014: early stopping FOLD: 2 Epoch 1/15 355/355 - 105s - loss: 0.6695 - auc: 0.5560 - val_loss: 0.4204 - val_auc: 0.5254 Epoch 2/15 355/355 - 103s - loss: 0.3547 - auc: 0.7830 - val_loss: 0.3614 - val_auc: 0.4937 Epoch 3/15 355/355 - 103s - loss: 0.3531 - auc: 0.8343 - val_loss: 0.3556 - val_auc: 0.7799 Epoch 4/15 355/355 - 104s - loss: 0.3521 - auc: 0.8580 - val_loss: 0.3558 - val_auc: 0.8301 Epoch 5/15 355/355 - 102s - loss: 0.3509 - auc: 0.8500 - val_loss: 0.3558 - val_auc: 0.7802 Epoch 6/15 355/355 - 103s - loss: 0.3507 - auc: 0.8639 - val_loss: 0.3554 - val_auc: 0.7613 Epoch 7/15 355/355 - 103s - loss: 0.3516 - auc: 0.8759 - val_loss: 0.3540 - val_auc: 0.8386 Epoch 8/15 355/355 - 104s - loss: 0.3495 - auc: 0.8836 - val_loss: 0.3550 - val_auc: 0.8129 Epoch 9/15 355/355 - 103s - loss: 0.3490 - auc: 0.8906 - val_loss: 0.3570 - val_auc: 0.7035 Epoch 10/15 355/355 - 103s - loss: 0.3482 - auc: 0.9058 - val_loss: 0.3545 - val_auc: 0.8012 Epoch 11/15 355/355 - 103s - loss: 0.3478 - auc: 0.9094 - val_loss: 0.3557 - val_auc: 0.8358 Epoch 12/15 Restoring model weights from the end of the best epoch. 355/355 - 103s - loss: 0.3462 - auc: 0.9320 - val_loss: 0.3540 - val_auc: 0.8204 Epoch 00012: early stopping FOLD: 3 Epoch 1/15 355/355 - 103s - loss: 0.5140 - auc: 0.5757 - val_loss: 0.5987 - val_auc: 0.4712 Epoch 2/15 355/355 - 103s - loss: 0.3560 - auc: 0.7785 - val_loss: 0.3566 - val_auc: 0.5732 Epoch 3/15 355/355 - 104s - loss: 0.3534 - auc: 0.8306 - val_loss: 0.3536 - val_auc: 0.8342 Epoch 4/15 355/355 - 102s - loss: 0.3528 - auc: 0.8550 - val_loss: 0.3565 - val_auc: 0.8392 Epoch 5/15 355/355 - 103s - loss: 0.3520 - auc: 0.8590 - val_loss: 0.3724 - val_auc: 0.6665 Epoch 6/15 355/355 - 103s - loss: 0.3516 - auc: 0.8450 - val_loss: 0.3542 - val_auc: 0.8008 Epoch 7/15 355/355 - 103s - loss: 0.3514 - auc: 0.8601 - val_loss: 0.3634 - val_auc: 0.8204 Epoch 8/15 355/355 - 103s - loss: 0.3502 - auc: 0.8809 - val_loss: 0.3526 - val_auc: 0.8352 Epoch 9/15 355/355 - 104s - loss: 0.3496 - auc: 0.8971 - val_loss: 0.3554 - val_auc: 0.8296 Epoch 10/15 355/355 - 103s - loss: 0.3489 - auc: 0.9048 - val_loss: 0.3522 - val_auc: 0.8266 Epoch 11/15 355/355 - 102s - loss: 0.3476 - auc: 0.9148 - val_loss: 0.3531 - val_auc: 0.8037 Epoch 12/15 355/355 - 103s - loss: 0.3462 - auc: 0.9181 - val_loss: 0.3526 - val_auc: 0.8311 Epoch 13/15 355/355 - 103s - loss: 0.3448 - auc: 0.9315 - val_loss: 0.3540 - val_auc: 0.8472 Epoch 14/15 355/355 - 103s - loss: 0.3428 - auc: 0.9425 - val_loss: 0.3528 - val_auc: 0.7810 Epoch 15/15 Restoring model weights from the end of the best epoch. 355/355 - 103s - loss: 0.3397 - auc: 0.9628 - val_loss: 0.3534 - val_auc: 0.7865 Epoch 00015: early stopping ###Markdown Model loss graph ###Code for n_fold in range(config['N_FOLDS']): print(f'Fold: {n_fold}') plot_metrics(history_list[n_fold]) ###Output Fold: 0 ###Markdown Model loss graph aggregated ###Code plot_metrics_agg(history_list, config['N_FOLDS']) ###Output _____no_output_____ ###Markdown Model evaluation ###Code display(evaluate_model(k_fold, config['N_FOLDS']).style.applymap(color_map)) ###Output _____no_output_____ ###Markdown Model evaluation by Subset ###Code display(evaluate_model_Subset(k_fold, config['N_FOLDS']).style.applymap(color_map)) ###Output _____no_output_____ ###Markdown Confusion matrix ###Code for n_fold in range(config['N_FOLDS']): n_fold += 1 pred_col = f'pred_fold_{n_fold}' train_set = k_fold[k_fold[f'fold_{n_fold}'] == 'train'] valid_set = k_fold[k_fold[f'fold_{n_fold}'] == 'validation'] print(f'Fold: {n_fold}') plot_confusion_matrix(train_set['target'], np.round(train_set[pred_col]), valid_set['target'], np.round(valid_set[pred_col])) ###Output Fold: 1 ###Markdown Visualize predictions ###Code k_fold['pred'] = 0 for n_fold in range(config['N_FOLDS']): n_fold +=1 k_fold['pred'] += k_fold[f'pred_fold_{n_fold}'] / config['N_FOLDS'] print('Top 10 samples') display(k_fold[['image_name', 'sex', 'age_approx','anatom_site_general_challenge', 'diagnosis', 'target', 'pred'] + [c for c in k_fold.columns if (c.startswith('pred_fold'))]].head(10)) print('Top 10 positive samples') display(k_fold[['image_name', 'sex', 'age_approx','anatom_site_general_challenge', 'diagnosis', 'target', 'pred'] + [c for c in k_fold.columns if (c.startswith('pred_fold'))]].query('target == 1').head(10)) print('Top 10 predicted positive samples') display(k_fold[['image_name', 'sex', 'age_approx','anatom_site_general_challenge', 'diagnosis', 'target', 'pred'] + [c for c in k_fold.columns if (c.startswith('pred_fold'))]].query('pred >= .5').head(10)) print('Label/prediction distribution') print(f"Train positive labels: {len(k_fold[k_fold['target'] >= .5])}") print(f"Train positive predictions: {len(k_fold[k_fold['pred'] >= .5])}") ###Output Top 10 samples
demos/1_time_correlation/Multi_tau_one_time_correlation_example.ipynb
###Markdown One Time Correlation Example for NIPA_GEL 250K¶ ###Code import numpy as np from matplotlib.ticker import MaxNLocator from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import matplotlib.patches as mp %matplotlib notebook import skxray.core.correlation as corr import skxray.core.roi as roi ###Output _____no_output_____ ###Markdown One Time Correlation¶ Multi-tau Scheme ###Code # it would be great to have a link to what this multi-tau scheme is! num_levels = 7 num_bufs = 8 # load the data img_stack = np.load("100_500_NIPA_GEL.npy") # plot the first image to make sure the data loaded correctly plt.imshow(img_stack[0]) plt.title("NIPA_GEL_250K") plt.show() ###Output _____no_output_____ ###Markdown Get the Reqiured ROI's Call skxray.diff_roi_choice.roi_rings_step ###Code # define the ROIs roi_start = 65 # in pixels roi_width = 9 # in pixels roi_spacing = (5.0, 4.0) x_center = 7. # in pixels y_center = (129.) # in pixels num_rings = 3 # get the edges of the rings edges = roi.ring_edges(roi_start, width=roi_width, spacing=roi_spacing, num_rings=num_rings) # get the label array from the ring shaped 3 region of interests(ROI's) labeled_roi_array = roi.rings( edges, (y_center, x_center), img_stack.shape[1:]) # extarct the ROI's lables and pixel indices corresponding to those labels roi_indices, pixel_list = corr.extract_label_indices(labeled_roi_array) ###Output _____no_output_____ ###Markdown Plot the Reqiured ROI's ###Code def overlay_rois(ax, inds, pix_list, img_dim, image): """ This will plot the reqiured roi's on the image """ tt = np.zeros(img_dim).ravel() * np.nan tt[pix_list] = inds im = ax.imshow(image, interpolation='none', norm=LogNorm()) im = ax.imshow(tt.reshape(*img_dim), cmap='Paired', interpolation='nearest') roi_names = ['gray', 'orange', 'brown'] tt = np.zeros(img_stack.shape[1:]).ravel() tt[pixel_list] = roi_indices fig, ax = plt.subplots() plt.title("NIPA_GEL_250K") overlay_rois(ax, roi_indices, pixel_list, img_stack.shape[1:], img_stack[0]) plt.show() ###Output _____no_output_____ ###Markdown Call the skxray.corr.multi_tau_corr ###Code # g2 one time correlation results for 3 ROI's g2, lag_steps = corr.multi_tau_auto_corr( num_levels, num_bufs, labeled_roi_array, img_stack) # lag_staps are delays for multiple tau analysis lag_time = 0.001 lag_step = lag_steps[:g2.shape[0]] lags = lag_step*lag_time ###Output _____no_output_____ ###Markdown Plot the one time correlation functions ###Code fig, axes = plt.subplots(num_rings, sharex=True, figsize=(5,10)) axes[num_rings-1].set_xlabel("lags") for i, roi_color in zip(range(num_rings), roi_names): axes[i].set_ylabel("g2") axes[i].semilogx(lags, g2[:, i], 'o', markerfacecolor=roi_color, markersize=10) axes[i].set_ylim(bottom=1, top=np.max(g2[1:, i])) plt.show() ###Output _____no_output_____
Python Fundamentals/Module_1.2_Required_Code_Python_Fundamentals.ipynb
###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC) # [] copy and paste in edX assignment page ###Output _____no_output_____ ###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC) # [] copy and paste in edX assignment page quote = input("Quote: ") word = "" for item in quote: if item.isalpha(): word += item elif word.lower() >= "h": print(word.upper()) word = "" else: word = "" if word.lower() >= "h": print(word.upper()) ###Output WHERESOEVER YOU WITH YOUR HEART ###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC) # [] copy and paste in edX assignment page quote = input("Enter a quote: ").lower() word = "" for character in quote: if character.isalpha(): word += character else: if (word > "h"): print(word.upper()) word = "" else: word = "" if word.lower() > "h": print(word.upper()) ###Output WAR IS ON ###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code quote=input('Enter a 1 sentence quote, non-alpha separate words: ') for word in quote.split(): cleaned_word='' for letter in word: if letter.isalpha(): cleaned_word+=letter else: break if cleaned_word[0]>'g': print(cleaned_word.lower()) ###Output Enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with all your heart you with your heart ###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC) # [] copy and paste in edX assignment page quote = input("enter a 1 sentence quote, non-alpha seperate words: ") word = '' for letter in quote: if letter.isalpha(): word += letter elif word.lower() >= 'h': print(word.upper()) word = '' else: word = '' if word.lower() >= "h": print(word.upper()) ###Output _____no_output_____ ###Markdown Module 1 Required Coding Activity Be sure to complete the tutorials and practice prior to attempting this activity. | Important Assignment Requirements | |:-------------------------------| | **NOTE:** This program **requires** **`print`** output and using code syntax used in module 1 such as keywords **`for`**/**`in`** (iteration), **`input`**, **`if`**, **`else`**, **`.isalpha()`** method, **`.lower()`** or **`.upper()`** method | Program: Words after "G"/"g"Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-zSample input: `enter a 1 sentence quote, non-alpha separate words:` **`Wheresoever you go, go with all your heart`** Sample output:```WHERESOEVERYOUWITHYOURHEART``` ![words_after_g flowchart](https://ofl1zq-ch3302.files.1drv.com/y4msZuRt9FLMg2HrIVri9ozb5zM0Z9cwrgFg0OanRG3wThbKGRTjxf6vEmvDgiQzAthvLq4KDpiOfd5S74i-vsCDYha-Ea5B1d4MJD5tx6obEpFj3Slks3bCFbjltvV_BYQ8mlbmyoAhujPM6nHRbOxNeO2Lb6dvmW0EbS-D3QXR7lRb-whNWwquwwzO4znPMmQ4Jkf4ujqTlSpjGuaKzwTSQ?width=608&height=371&cropmode=none) - split the words by building a placeholder variable: **`word`** - loop each character in the input string - check if character is a letter - add a letter to **`word`** each loop until a non-alpha char is encountered - **if** character is alpha - add character to **`word`** - non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to **`else`** - **`else`** - check **`if`** word is greater than "g" alphabetically - print word - set word = empty string - or **else** - set word = empty string and build the next word Hint: use `.lower()`Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation? ###Code # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC) # [] copy and paste in edX assignment page word = "" quote = input("Enter a quote: ")+" " for character in quote: if character.isalpha(): word += character else: if word.lower() >= "h": print(word.upper()) word = "" else: word = "" ###Output Enter a quote: Wheresoever you go, go with all your heart WHERESOEVER YOU WITH YOUR HEART
docs/tutorials/kafka.ipynb
###Markdown Copyright 2020 The TensorFlow IO Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Robust machine learning on streaming data using Kafka and Tensorflow-IO View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis tutorial focuses on streaming data from a [Kafka](https://kafka.apache.org/quickstart) cluster into a `tf.data.Dataset` which is then used in conjunction with `tf.keras` for training and inference.Kafka is primarily a distributed event-streaming platform which provides scalable and fault-tolerant streaming data across data pipelines. It is an essential technical component of a plethora of major enterprises where mission-critical data delivery is a primary requirement.**NOTE:** A basic understanding of the [kafka components](https://kafka.apache.org/documentation/intro_concepts_and_terms) will help you in following the tutorial with ease.**NOTE:** A Java runtime environment is required to run this tutorial. Setup Install the required tensorflow-io and kafka packages ###Code !pip install tensorflow-io !pip install kafka-python ###Output Collecting tensorflow-io Downloading tensorflow_io-0.20.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (22.7 MB)  |████████████████████████████████| 22.7 MB 16 kB/s [?25hCollecting tensorflow-io-gcs-filesystem==0.20.0 Downloading tensorflow_io_gcs_filesystem-0.20.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.3 MB)  |████████████████████████████████| 2.3 MB 36.1 MB/s [?25hRequirement already satisfied: tensorflow<2.7.0,>=2.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-io) (2.6.0) Requirement already satisfied: keras-preprocessing~=1.1.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.1.2) Requirement already satisfied: wheel~=0.35 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.37.0) Requirement already satisfied: numpy~=1.19.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.19.5) Requirement already satisfied: astunparse~=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.6.3) Requirement already satisfied: typing-extensions~=3.7.4 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.7.4.3) Requirement already satisfied: absl-py~=0.10 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.12.0) Requirement already satisfied: google-pasta~=0.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.2.0) Requirement already satisfied: termcolor~=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.1.0) Requirement already satisfied: flatbuffers~=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.12) Requirement already satisfied: tensorflow-estimator~=2.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2.6.0) Requirement already satisfied: gast==0.4.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.4.0) Requirement already satisfied: tensorboard~=2.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2.6.0) Requirement already satisfied: wrapt~=1.12.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.12.1) Requirement already satisfied: clang~=5.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (5.0) Requirement already satisfied: opt-einsum~=3.3.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.3.0) Requirement already satisfied: keras~=2.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2.6.0) Requirement already satisfied: h5py~=3.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.1.0) Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.17.3) Requirement already satisfied: grpcio<2.0,>=1.37.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.39.0) Requirement already satisfied: six~=1.15.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.15.0) Requirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py~=3.1.0->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.5.2) Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (57.4.0) Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.4.5) Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2.23.0) Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.6.1) Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.8.0) Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.0.1) Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.3.4) Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.34.0) Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (4.2.2) Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (4.7.2) Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.2.8) Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.3.0) Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (4.6.4) Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (0.4.8) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (1.24.3) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2021.5.30) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.0.4) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (2.10) Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.1.1) Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard~=2.6->tensorflow<2.7.0,>=2.6.0->tensorflow-io) (3.5.0) Installing collected packages: tensorflow-io-gcs-filesystem, tensorflow-io Successfully installed tensorflow-io-0.20.0 tensorflow-io-gcs-filesystem-0.20.0 Collecting kafka-python Downloading kafka_python-2.0.2-py2.py3-none-any.whl (246 kB)  |████████████████████████████████| 246 kB 12.0 MB/s [?25hInstalling collected packages: kafka-python Successfully installed kafka-python-2.0.2 ###Markdown Import packages ###Code import os from datetime import datetime import time import threading import json from kafka import KafkaProducer from kafka.errors import KafkaError from sklearn.model_selection import train_test_split import pandas as pd import tensorflow as tf import tensorflow_io as tfio ###Output _____no_output_____ ###Markdown Validate tf and tfio imports ###Code print("tensorflow-io version: {}".format(tfio.__version__)) print("tensorflow version: {}".format(tf.__version__)) ###Output tensorflow-io version: 0.20.0 tensorflow version: 2.6.0 ###Markdown Download and setup Kafka and Zookeeper instancesFor demo purposes, the following instances are setup locally:- Kafka (Brokers: 127.0.0.1:9092)- Zookeeper (Node: 127.0.0.1:2181) ###Code !curl -sSOL https://downloads.apache.org/kafka/2.7.0/kafka_2.13-2.7.0.tgz !tar -xzf kafka_2.13-2.7.0.tgz ###Output _____no_output_____ ###Markdown Using the default configurations (provided by Apache Kafka) for spinning up the instances. ###Code !./kafka_2.13-2.7.0/bin/kafka-topics.sh --bootstrap-server "ec2-13-229-46-113.ap-southeast-1.compute.amazonaws.com:9092" --list !./kafka_2.13-2.7.0/bin/zookeeper-server-start.sh -daemon ./kafka_2.13-2.7.0/config/zookeeper.properties !./kafka_2.13-2.7.0/bin/kafka-server-start.sh -daemon ./kafka_2.13-2.7.0/config/server.properties !echo "Waiting for 10 secs until kafka and zookeeper services are up and running" !sleep 10 ###Output _____no_output_____ ###Markdown Once the instances are started as daemon processes, grep for `kafka` in the processes list. The two java processes correspond to zookeeper and the kafka instances. ###Code !ps -ef | grep kafka ###Output _____no_output_____ ###Markdown Create the kafka topics with the following specs:- susy-train: partitions=1, replication-factor=1 - susy-test: partitions=2, replication-factor=1 ###Code !./kafka_2.13-2.7.0/bin/kafka-topics.sh --create --bootstrap-server 127.0.0.1:9092 --replication-factor 1 --partitions 1 --topic susy-train !./kafka_2.13-2.7.0/bin/kafka-topics.sh --create --bootstrap-server 127.0.0.1:9092 --replication-factor 1 --partitions 2 --topic susy-test ###Output _____no_output_____ ###Markdown Describe the topic for details on the configuration ###Code !./kafka_2.13-2.7.0/bin/kafka-topics.sh --describe --bootstrap-server 127.0.0.1:9092 --topic susy-train !./kafka_2.13-2.7.0/bin/kafka-topics.sh --describe --bootstrap-server 127.0.0.1:9092 --topic susy-test ###Output _____no_output_____ ###Markdown The replication factor 1 indicates that the data is not being replicated. This is due to the presence of a single broker in our kafka setup.In production systems, the number of bootstrap servers can be in the range of 100's of nodes. That is where the fault-tolerance using replication comes into picture.Please refer to the [docs](https://kafka.apache.org/documentation/replication) for more details. SUSY DatasetKafka being an event streaming platform, enables data from various sources to be written into it. For instance:- Web traffic logs- Astronomical measurements- IoT sensor data- Product reviews and many more.For the purpose of this tutorial, lets download the [SUSY](https://archive.ics.uci.edu/ml/datasets/SUSY) dataset and feed the data into kafka manually. The goal of this classification problem is to distinguish between a signal process which produces supersymmetric particles and a background process which does not. ###Code !curl -sSOL https://archive.ics.uci.edu/ml/machine-learning-databases/00279/SUSY.csv.gz ###Output _____no_output_____ ###Markdown Explore the dataset The first column is the class label (1 for signal, 0 for background), followed by the 18 features (8 low-level features then 10 high-level features).The first 8 features are kinematic properties measured by the particle detectors in the accelerator. The last 10 features are functions of the first 8 features. These are high-level features derived by physicists to help discriminate between the two classes. ###Code COLUMNS = [ # labels 'class', # low-level features 'lepton_1_pT', 'lepton_1_eta', 'lepton_1_phi', 'lepton_2_pT', 'lepton_2_eta', 'lepton_2_phi', 'missing_energy_magnitude', 'missing_energy_phi', # high-level derived features 'MET_rel', 'axial_MET', 'M_R', 'M_TR_2', 'R', 'MT2', 'S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)' ] ###Output _____no_output_____ ###Markdown The entire dataset consists of 5 million rows. However, for the purpose of this tutorial, let's consider only a fraction of the dataset (100,000 rows) so that less time is spent on the moving the data and more time on understanding the functionality of the api. ###Code susy_iterator = pd.read_csv('SUSY.csv.gz', header=None, names=COLUMNS, chunksize=100000) susy_df = next(susy_iterator) susy_df.head() # Number of datapoints and columns len(susy_df), len(susy_df.columns) # Number of datapoints belonging to each class (0: background noise, 1: signal) len(susy_df[susy_df["class"]==0]), len(susy_df[susy_df["class"]==1]) ###Output _____no_output_____ ###Markdown Split the dataset ###Code train_df, test_df = train_test_split(susy_df, test_size=0.4, shuffle=True) print("Number of training samples: ",len(train_df)) print("Number of testing sample: ",len(test_df)) x_train_df = train_df.drop(["class"], axis=1) y_train_df = train_df["class"] x_test_df = test_df.drop(["class"], axis=1) y_test_df = test_df["class"] # The labels are set as the kafka message keys so as to store data # in multiple-partitions. Thus, enabling efficient data retrieval # using the consumer groups. x_train = list(filter(None, x_train_df.to_csv(index=False).split("\n")[1:])) y_train = list(filter(None, y_train_df.to_csv(index=False).split("\n")[1:])) x_test = list(filter(None, x_test_df.to_csv(index=False).split("\n")[1:])) y_test = list(filter(None, y_test_df.to_csv(index=False).split("\n")[1:])) NUM_COLUMNS = len(x_train_df.columns) len(x_train), len(y_train), len(x_test), len(y_test) ###Output _____no_output_____ ###Markdown Store the train and test data in kafkaStoring the data in kafka simulates an environment for continuous remote data retrieval for training and inference purposes. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka(topic_name, items): count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8')).add_errback(error_callback) count+=1 producer.flush() print("Wrote {0} messages into topic: {1}".format(count, topic_name)) write_to_kafka("susy-train", zip(x_train, y_train)) write_to_kafka("susy-test", zip(x_test, y_test)) ###Output _____no_output_____ ###Markdown Define the tfio train datasetThe `IODataset` class is utilized for streaming data from kafka into tensorflow. The class inherits from `tf.data.Dataset` and thus has all the useful functionalities of `tf.data.Dataset` out of the box. ###Code def decode_kafka_item(item): message = tf.io.decode_csv(item.message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(item.key) return (message, key) BATCH_SIZE=64 SHUFFLE_BUFFER_SIZE=64 train_ds = tfio.IODataset.from_kafka('susy-train', partition=0, offset=0) train_ds = train_ds.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE) train_ds = train_ds.map(decode_kafka_item) train_ds = train_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Build and train the model ###Code # Set the parameters OPTIMIZER="adam" LOSS=tf.keras.losses.BinaryCrossentropy(from_logits=True) METRICS=['accuracy'] EPOCHS=10 # design/build the model model = tf.keras.Sequential([ tf.keras.layers.Input(shape=(NUM_COLUMNS,)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(1, activation='sigmoid') ]) print(model.summary()) # compile the model model.compile(optimizer=OPTIMIZER, loss=LOSS, metrics=METRICS) # fit the model model.fit(train_ds, epochs=EPOCHS) ###Output _____no_output_____ ###Markdown Note: Please do not confuse the training step with online training. It's an entirely different paradigm which will be covered in a later section.Since only a fraction of the dataset is being utilized, our accuracy is limited to ~78% during the training phase. However, please feel free to store additional data in kafka for a better model performance. Also, since the goal was to just demonstrate the functionality of the tfio kafka datasets, a smaller and less-complicated neural network was used. However, one can increase the complexity of the model, modify the learning strategy, tune hyper-parameters etc for exploration purposes. For a baseline approach, please refer to this [article](https://www.nature.com/articles/ncomms5308Sec11). Infer on the test dataTo infer on the test data by adhering to the 'exactly-once' semantics along with fault-tolerance, the `streaming.KafkaGroupIODataset` can be utilized. Define the tfio test datasetThe `stream_timeout` parameter blocks for the given duration for new data points to be streamed into the topic. This removes the need for creating new datasets if the data is being streamed into the topic in an intermittent fashion. ###Code test_ds = tfio.experimental.streaming.KafkaGroupIODataset( topics=["susy-test"], group_id="testcg", servers="127.0.0.1:9092", stream_timeout=10000, configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) def decode_kafka_test_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) test_ds = test_ds.map(decode_kafka_test_item) test_ds = test_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Though this class can be used for training purposes, there are caveats which need to be addressed. Once all the messages are read from kafka and the latest offsets are committed using the `streaming.KafkaGroupIODataset`, the consumer doesn't restart reading the messages from the beginning. Thus, while training, it is possible only to train for a single epoch with the data continuously flowing in. This kind of a functionality has limited use cases during the training phase wherein, once a datapoint has been consumed by the model it is no longer required and can be discarded.However, this functionality shines when it comes to robust inference with exactly-once semantics. evaluate the performance on the test data ###Code res = model.evaluate(test_ds) print("test loss, test acc:", res) ###Output _____no_output_____ ###Markdown Since the inference is based on 'exactly-once' semantics, the evaluation on the test set can be run only once. In order to run the inference again on the test data, a new consumer group should be used. Track the offset lag of the `testcg` consumer group ###Code !./kafka_2.13-2.7.0/bin/kafka-consumer-groups.sh --bootstrap-server 127.0.0.1:9092 --describe --group testcg ###Output _____no_output_____ ###Markdown Once the `current-offset` matches the `log-end-offset` for all the partitions, it indicates that the consumer(s) have completed fetching all the messages from the kafka topic. Online learningThe online machine learning paradigm is a bit different from the traditional/conventional way of training machine learning models. In the former case, the model continues to incrementally learn/update it's parameters as soon as the new data points are available and this process is expected to continue indefinitely. This is unlike the latter approaches where the dataset is fixed and the model iterates over it `n` number of times. In online learning, the data once consumed by the model may not be available for training again.By utilizing the `streaming.KafkaBatchIODataset`, it is now possible to train the models in this fashion. Let's continue to use our SUSY dataset for demonstrating this functionality. The tfio training dataset for online learningThe `streaming.KafkaBatchIODataset` is similar to the `streaming.KafkaGroupIODataset` in it's API. Additionally, it is recommended to utilize the `stream_timeout` parameter to configure the duration for which the dataset will block for new messages before timing out. In the instance below, the dataset is configured with a `stream_timeout` of `10000` milliseconds. This implies that, after all the messages from the topic have been consumed, the dataset will wait for an additional 10 seconds before timing out and disconnecting from the kafka cluster. If new messages are streamed into the topic before timing out, the data consumption and model training resumes for those newly consumed data points. To block indefinitely, set it to `-1`. ###Code online_train_ds = tfio.experimental.streaming.KafkaBatchIODataset( topics=["susy-train"], group_id="cgonline", servers="127.0.0.1:9092", stream_timeout=10000, # in milliseconds, to block indefinitely, set it to -1. configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) ###Output _____no_output_____ ###Markdown Every item that the `online_train_ds` generates is a `tf.data.Dataset` in itself. Thus, all the standard transformations can be applied as usual. ###Code def decode_kafka_online_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) for mini_ds in online_train_ds: mini_ds = mini_ds.shuffle(buffer_size=32) mini_ds = mini_ds.map(decode_kafka_online_item) mini_ds = mini_ds.batch(32) model.fit(mini_ds, epochs=3) ###Output _____no_output_____ ###Markdown Copyright 2020 The TensorFlow IO Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Robust machine learning on streaming data using Kafka and Tensorflow-IO View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis tutorial focuses on streaming data from a [Kafka](https://docs.confluent.io/current/getting-started.html) cluster into a `tf.data.Dataset` which is then used in conjunction with `tf.keras` for training and inference.Kafka is primarily a distributed event-streaming platform which provides scalable and fault-tolerant streaming data across data pipelines. It is an essential technical component of a plethora of major enterprises where mission-critical data delivery is a primary requirement.**NOTE:** A basic understanding of the [kafka components](https://docs.confluent.io/current/kafka/introduction.html) will help you in following the tutorial with ease. Setup Install the required tensorflow-io and kafka packages ###Code !pip install tensorflow-io !pip install kafka-python ###Output _____no_output_____ ###Markdown Import packages ###Code import os from datetime import datetime import time import threading import json from kafka import KafkaProducer from kafka.errors import KafkaError from sklearn.model_selection import train_test_split import pandas as pd import tensorflow as tf import tensorflow_io as tfio ###Output _____no_output_____ ###Markdown Validate tf and tfio imports ###Code print("tensorflow-io version: {}".format(tfio.__version__)) print("tensorflow version: {}".format(tf.__version__)) ###Output _____no_output_____ ###Markdown Download and setup Kafka and Zookeeper instancesFor demo purposes, the following instances are setup locally:- Kafka (Brokers: 127.0.0.1:9092)- Zookeeper (Node: 127.0.0.1:2181) ###Code !curl -sSOL http://packages.confluent.io/archive/5.4/confluent-community-5.4.1-2.12.tar.gz !tar -xzf confluent-community-5.4.1-2.12.tar.gz ###Output _____no_output_____ ###Markdown Using the default configurations (provided by the confluent package) for spinning up the instances. ###Code !cd confluent-5.4.1 && bin/zookeeper-server-start -daemon etc/kafka/zookeeper.properties !cd confluent-5.4.1 && bin/kafka-server-start -daemon etc/kafka/server.properties !echo "Waiting for 10 secs until kafka and zookeeper services are up and running" !sleep 10 ###Output _____no_output_____ ###Markdown Once the instances are started as daemon processes, grep for `kafka` in the processes list. The two java processes correspond to zookeeper and the kafka instances. ###Code !ps -ef | grep kafka ###Output _____no_output_____ ###Markdown Create the kafka topics with the following specs:- susy-train: partitions=1, replication-factor=1 - susy-test: partitions=2, replication-factor=1 ###Code !confluent-5.4.1/bin/kafka-topics --create --zookeeper 127.0.0.1:2181 --replication-factor 1 --partitions 1 --topic susy-train !confluent-5.4.1/bin/kafka-topics --create --zookeeper 127.0.0.1:2181 --replication-factor 1 --partitions 2 --topic susy-test ###Output _____no_output_____ ###Markdown Describe the topic for details on the configuration ###Code !confluent-5.4.1/bin/kafka-topics --bootstrap-server 127.0.0.1:9092 --describe --topic susy-train !confluent-5.4.1/bin/kafka-topics --bootstrap-server 127.0.0.1:9092 --describe --topic susy-test ###Output _____no_output_____ ###Markdown The replication factor 1 indicates that the data is not being replicated. This is due to the presence of a single broker in our kafka setup.In production systems, the number of bootstrap servers can be in the range of 100's of nodes. That is where the fault-tolerance using replication comes into picture.Please refer to the [docs](https://kafka.apache.org/documentation/replication) for more details. SUSY DatasetKafka being an event streaming platform, enables data from various sources to be written into it. For instance:- Web traffic logs- Astronomical measurements- IoT sensor data- Product reviews and many more.For the purpose of this tutorial, lets download the [SUSY](https://archive.ics.uci.edu/ml/datasets/SUSY) dataset and feed the data into kafka manually. The goal of this classification problem is to distinguish between a signal process which produces supersymmetric particles and a background process which does not. ###Code !curl -sSOL https://archive.ics.uci.edu/ml/machine-learning-databases/00279/SUSY.csv.gz ###Output _____no_output_____ ###Markdown Explore the dataset The first column is the class label (1 for signal, 0 for background), followed by the 18 features (8 low-level features then 10 high-level features).The first 8 features are kinematic properties measured by the particle detectors in the accelerator. The last 10 features are functions of the first 8 features. These are high-level features derived by physicists to help discriminate between the two classes. ###Code COLUMNS = [ # labels 'class', # low-level features 'lepton_1_pT', 'lepton_1_eta', 'lepton_1_phi', 'lepton_2_pT', 'lepton_2_eta', 'lepton_2_phi', 'missing_energy_magnitude', 'missing_energy_phi', # high-level derived features 'MET_rel', 'axial_MET', 'M_R', 'M_TR_2', 'R', 'MT2', 'S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)' ] ###Output _____no_output_____ ###Markdown The entire dataset consists of 5 million rows. However, for the purpose of this tutorial, let's consider only a fraction of the dataset (100,000 rows) so that less time is spent on the moving the data and more time on understanding the functionality of the api. ###Code susy_iterator = pd.read_csv('SUSY.csv.gz', header=None, names=COLUMNS, chunksize=100000) susy_df = next(susy_iterator) susy_df.head() # Number of datapoints and columns len(susy_df), len(susy_df.columns) # Number of datapoints belonging to each class (0: background noise, 1: signal) len(susy_df[susy_df["class"]==0]), len(susy_df[susy_df["class"]==1]) ###Output _____no_output_____ ###Markdown Split the dataset ###Code train_df, test_df = train_test_split(susy_df, test_size=0.4, shuffle=True) print("Number of training samples: ",len(train_df)) print("Number of testing sample: ",len(test_df)) x_train_df = train_df.drop(["class"], axis=1) y_train_df = train_df["class"] x_test_df = test_df.drop(["class"], axis=1) y_test_df = test_df["class"] # The labels are set as the kafka message keys so as to store data # in multiple-partitions. Thus, enabling efficient data retrieval # using the consumer groups. x_train = list(filter(None, x_train_df.to_csv(index=False).split("\n")[1:])) y_train = list(filter(None, y_train_df.to_csv(index=False).split("\n")[1:])) x_test = list(filter(None, x_test_df.to_csv(index=False).split("\n")[1:])) y_test = list(filter(None, y_test_df.to_csv(index=False).split("\n")[1:])) NUM_COLUMNS = len(x_train_df.columns) len(x_train), len(y_train), len(x_test), len(y_test) ###Output _____no_output_____ ###Markdown Store the train and test data in kafkaStoring the data in kafka simulates an environment for continuous remote data retrieval for training and inference purposes. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka(topic_name, items): count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8')).add_errback(error_callback) count+=1 producer.flush() print("Wrote {0} messages into topic: {1}".format(count, topic_name)) write_to_kafka("susy-train", zip(x_train, y_train)) write_to_kafka("susy-test", zip(x_test, y_test)) ###Output _____no_output_____ ###Markdown Define the tfio train datasetThe `IODataset` class is utilized for streaming data from kafka into tensorflow. The class inherits from `tf.data.Dataset` and thus has all the useful functionalities of `tf.data.Dataset` out of the box. ###Code def decode_kafka_item(item): message = tf.io.decode_csv(item.message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(item.key) return (message, key) BATCH_SIZE=64 SHUFFLE_BUFFER_SIZE=64 train_ds = tfio.IODataset.from_kafka('susy-train', partition=0, offset=0) train_ds = train_ds.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE) train_ds = train_ds.map(decode_kafka_item) train_ds = train_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Build and train the model ###Code # Set the parameters OPTIMIZER="adam" LOSS=tf.keras.losses.BinaryCrossentropy(from_logits=True) METRICS=['accuracy'] EPOCHS=20 # design/build the model model = tf.keras.Sequential([ tf.keras.layers.Input(shape=(NUM_COLUMNS,)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(1, activation='sigmoid') ]) print(model.summary()) # compile the model model.compile(optimizer=OPTIMIZER, loss=LOSS, metrics=METRICS) # fit the model model.fit(train_ds, epochs=10) ###Output _____no_output_____ ###Markdown Note: Please do not confuse the training step with online training. It's an entirely different paradigm which will be covered in a later section.Since only a fraction of the dataset is being utilized, our accuracy is limited to ~78% during the training phase. However, please feel free to store additional data in kafka for better a model performance. Also, since the goal was to just demonstrate the functionality of the tfio kafka datasets, a smaller and less-complicated neural network was used. However, one can increase the complexity of the model, modify the learning strategy, tune hyper-parameters etc for exploration purposes. For a baseline approach, please refer to this [article](https://www.nature.com/articles/ncomms5308Sec11). Infer on the test dataTo infer on the test data by adhering to the 'exactly-once' semantics along with fault-tolerance, the `streaming.KafkaGroupIODataset` can be utilized. Define the tfio test datasetThe `stream_timeout` parameter blocks for the given duration for new data points to be streamed into the topic. This removes the need for creating new datasets if the data is being streamed into the topic in an intermittent fashion. ###Code test_ds = tfio.experimental.streaming.KafkaGroupIODataset( topics=["susy-test"], group_id="testcg", servers="127.0.0.1:9092", stream_timeout=10000, configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) def decode_kafka_test_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) test_ds = test_ds.map(decode_kafka_test_item) test_ds = test_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Though this class can be used for training purposes, there are caveats which need to be addressed. Once all the messages are read from kafka and the latest offsets are committed using the `streaming.KafkaGroupIODataset`, the consumer doesn't restart reading the messages from the beginning. Thus, while training, it is possible only to train for a single epoch with the data continuously flowing in. This kind of a functionality has limited use cases during the training phase wherein, once a datapoint has been consumed by the model it is no longer required and can be discarded.However, this functionality shines when it comes to robust inference with exactly-once semantics. evaluate the performance on the test data ###Code res = model.evaluate(test_ds) print("test loss, test acc:", res) ###Output _____no_output_____ ###Markdown Since the inference is based on 'exactly-once' semantics, the evaluation on the test set can be run only once. In order to run the inference again on the test data, a new consumer group should be used. Track the offset lag of the `testcg` consumer group ###Code !confluent-5.4.1/bin/kafka-consumer-groups --bootstrap-server 127.0.0.1:9092 --describe --group testcg ###Output _____no_output_____ ###Markdown Once the `current-offset` matches the `log-end-offset` for all the partitions, it indicates that the consumer(s) have completed fetching all the messages from the kafka topic. Online learningThe online machine learning paradigm is a bit different from the traditional/conventional way of training machine learning models. In the former case, the model continues to incrementally learn/update it's parameters as soon as the new data points are available and this process is expected to continue indefinitely. This is unlike the latter approaches where the dataset is fixed and the model iterates over it `n` number of times. In online learning, the data once consumed by the model may not be available for training again.By utilizing the `streaming.KafkaBatchIODataset`, it is now possible to train the models in this fashion. Let's continue to use our SUSY dataset for demonstrating this functionality. The tfio training dataset for online learningThe `streaming.KafkaBatchIODataset` is similar to the `streaming.KafkaGroupIODataset` in it's API. Additionally, it is recommended to utilize the `stream_timeout` parameter to configure the duration for which the dataset will block for new messages before timing out. In the instance below, the dataset is configured with a `stream_timeout` of `30000` milliseconds. This implies that, after all the messages from the topic have been consumed, the dataset will wait for an additional 30 seconds before timing out and disconnecting from the kafka cluster. If new messages are streamed into the topic before timing out, the data consumption and model training resumes for those newly consumed data points. To block indefinitely, set it to `-1`. ###Code online_train_ds = tfio.experimental.streaming.KafkaBatchIODataset( topics=["susy-train"], group_id="cgonline", servers="127.0.0.1:9092", stream_timeout=30000, # in milliseconds, to block indefinitely, set it to -1. configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) ###Output _____no_output_____ ###Markdown In addition to training the model on existing data, a background thread will be started, which will start streaming additional data into the `susy-train` topic after a sleep duration of 30 seconds. This demonstrates the functionality of resuming the training as soons as new data is fed into the topic without the need for building the dataset over and over again. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka_after_sleep(topic_name, items): time.sleep(30) print("#"*100) print("Writing messages into topic: {0} after a nice sleep !".format(topic_name)) print("#"*100) count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8') ).add_errback(error_callback) count+=1 producer.flush() print("#"*100) print("Wrote {0} messages into topic: {1}".format(count, topic_name)) print("#"*100) def decode_kafka_online_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) ###Output _____no_output_____ ###Markdown Every item that the `online_train_ds` generates is a `tf.data.Dataset` in itself. Thus, all the standard transformations can be applied as usual. ###Code thread = threading.Thread(target=write_to_kafka_after_sleep, args=("susy-train", zip(x_train, y_train))) thread.daemon = True thread.start() for mini_ds in online_train_ds: mini_ds = mini_ds.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE) mini_ds = mini_ds.map(decode_kafka_online_item) mini_ds = mini_ds.batch(BATCH_SIZE) model.fit(mini_ds, epochs=3) ###Output _____no_output_____ ###Markdown Copyright 2020 The TensorFlow IO Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Robust machine learning on streaming data using Kafka and Tensorflow-IO View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis tutorial focuses on streaming data from a [Kafka](https://docs.confluent.io/current/getting-started.html) cluster into a `tf.data.Dataset` which is then used in conjunction with `tf.keras` for training and inference.Kafka is primarily a distributed event-streaming platform which provides scalable and fault-tolerant streaming data across data pipelines. It is an essential technical component of a plethora of major enterprises where mission-critical data delivery is a primary requirement.**NOTE:** A basic understanding of the [kafka components](https://docs.confluent.io/current/kafka/introduction.html) will help you in following the tutorial with ease. Setup Install the required tensorflow-io and kafka packages ###Code !pip install tensorflow-io !pip install kafka-python ###Output _____no_output_____ ###Markdown Import packages ###Code import os from datetime import datetime import time import threading import json from kafka import KafkaProducer from kafka.errors import KafkaError from sklearn.model_selection import train_test_split import pandas as pd import tensorflow as tf import tensorflow_io as tfio ###Output _____no_output_____ ###Markdown Validate tf and tfio imports ###Code print("tensorflow-io version: {}".format(tfio.__version__)) print("tensorflow version: {}".format(tf.__version__)) ###Output _____no_output_____ ###Markdown Download and setup Kafka and Zookeeper instancesFor demo purposes, the following instances are setup locally:- Kafka (Brokers: 127.0.0.1:9092)- Zookeeper (Node: 127.0.0.1:2181) ###Code !curl -sSOL http://packages.confluent.io/archive/5.4/confluent-community-5.4.1-2.12.tar.gz !tar -xzf confluent-community-5.4.1-2.12.tar.gz ###Output _____no_output_____ ###Markdown Using the default configurations (provided by the confluent package) for spinning up the instances. ###Code !cd confluent-5.4.1 && bin/zookeeper-server-start -daemon etc/kafka/zookeeper.properties !cd confluent-5.4.1 && bin/kafka-server-start -daemon etc/kafka/server.properties !echo "Waiting for 10 secs until kafka and zookeeper services are up and running" !sleep 10 ###Output _____no_output_____ ###Markdown Once the instances are started as daemon processes, grep for `kafka` in the processes list. The two java processes correspond to zookeeper and the kafka instances. ###Code !ps -ef | grep kafka ###Output _____no_output_____ ###Markdown Create the kafka topics with the following specs:- susy-train: partitions=1, replication-factor=1 - susy-test: partitions=2, replication-factor=1 ###Code !confluent-5.4.1/bin/kafka-topics --create --zookeeper 127.0.0.1:2181 --replication-factor 1 --partitions 1 --topic susy-train !confluent-5.4.1/bin/kafka-topics --create --zookeeper 127.0.0.1:2181 --replication-factor 1 --partitions 2 --topic susy-test ###Output _____no_output_____ ###Markdown Describe the topic for details on the configuration ###Code !confluent-5.4.1/bin/kafka-topics --bootstrap-server 127.0.0.1:9092 --describe --topic susy-train !confluent-5.4.1/bin/kafka-topics --bootstrap-server 127.0.0.1:9092 --describe --topic susy-test ###Output _____no_output_____ ###Markdown The replication factor 1 indicates that the data is not being replicated. This is due to the presence of a single broker in our kafka setup.In production systems, the number of bootstrap servers can be in the range of 100's of nodes. That is where the fault-tolerance using replication comes into picture.Please refer to the [docs](https://kafka.apache.org/documentation/replication) for more details. SUSY DatasetKafka being an event streaming platform, enables data from various sources to be written into it. For instance:- Web traffic logs- Astronomical measurements- IoT sensor data- Product reviews and many more.For the purpose of this tutorial, lets download the [SUSY](https://archive.ics.uci.edu/ml/datasets/SUSY) dataset and feed the data into kafka manually. The goal of this classification problem is to distinguish between a signal process which produces supersymmetric particles and a background process which does not. ###Code !curl -sSOL https://archive.ics.uci.edu/ml/machine-learning-databases/00279/SUSY.csv.gz ###Output _____no_output_____ ###Markdown Explore the dataset The first column is the class label (1 for signal, 0 for background), followed by the 18 features (8 low-level features then 10 high-level features).The first 8 features are kinematic properties measured by the particle detectors in the accelerator. The last 10 features are functions of the first 8 features. These are high-level features derived by physicists to help discriminate between the two classes. ###Code COLUMNS = [ # labels 'class', # low-level features 'lepton_1_pT', 'lepton_1_eta', 'lepton_1_phi', 'lepton_2_pT', 'lepton_2_eta', 'lepton_2_phi', 'missing_energy_magnitude', 'missing_energy_phi', # high-level derived features 'MET_rel', 'axial_MET', 'M_R', 'M_TR_2', 'R', 'MT2', 'S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)' ] ###Output _____no_output_____ ###Markdown The entire dataset consists of 5 million rows. However, for the purpose of this tutorial, let's consider only a fraction of the dataset (100,000 rows) so that less time is spent on the moving the data and more time on understanding the functionality of the api. ###Code susy_iterator = pd.read_csv('SUSY.csv.gz', header=None, names=COLUMNS, chunksize=100000) susy_df = next(susy_iterator) susy_df.head() # Number of datapoints and columns len(susy_df), len(susy_df.columns) # Number of datapoints belonging to each class (0: background noise, 1: signal) len(susy_df[susy_df["class"]==0]), len(susy_df[susy_df["class"]==1]) ###Output _____no_output_____ ###Markdown Split the dataset ###Code train_df, test_df = train_test_split(susy_df, test_size=0.4, shuffle=True) print("Number of training samples: ",len(train_df)) print("Number of testing sample: ",len(test_df)) x_train_df = train_df.drop(["class"], axis=1) y_train_df = train_df["class"] x_test_df = test_df.drop(["class"], axis=1) y_test_df = test_df["class"] # The labels are set as the kafka message keys so as to store data # in multiple-partitions. Thus, enabling efficient data retrieval # using the consumer groups. x_train = list(filter(None, x_train_df.to_csv(index=False).split("\n")[1:])) y_train = list(filter(None, y_train_df.to_csv(index=False).split("\n")[1:])) x_test = list(filter(None, x_test_df.to_csv(index=False).split("\n")[1:])) y_test = list(filter(None, y_test_df.to_csv(index=False).split("\n")[1:])) NUM_COLUMNS = len(x_train_df.columns) len(x_train), len(y_train), len(x_test), len(y_test) ###Output _____no_output_____ ###Markdown Store the train and test data in kafkaStoring the data in kafka simulates an environment for continuous remote data retrieval for training and inference purposes. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka(topic_name, items): count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8')).add_errback(error_callback) count+=1 producer.flush() print("Wrote {0} messages into topic: {1}".format(count, topic_name)) write_to_kafka("susy-train", zip(x_train, y_train)) write_to_kafka("susy-test", zip(x_test, y_test)) ###Output _____no_output_____ ###Markdown Define the tfio train datasetThe `IODataset` class is utilized for streaming data from kafka into tensorflow. The class inherits from `tf.data.Dataset` and thus has all the useful functionalities of `tf.data.Dataset` out of the box. ###Code def decode_kafka_item(item): message = tf.io.decode_csv(item.message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(item.key) return (message, key) BATCH_SIZE=64 SHUFFLE_BUFFER_SIZE=64 train_ds = tfio.IODataset.from_kafka('susy-train', partition=0, offset=0) train_ds = train_ds.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE) train_ds = train_ds.map(decode_kafka_item) train_ds = train_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Build and train the model ###Code # Set the parameters OPTIMIZER="adam" LOSS=tf.keras.losses.BinaryCrossentropy(from_logits=True) METRICS=['accuracy'] EPOCHS=10 # design/build the model model = tf.keras.Sequential([ tf.keras.layers.Input(shape=(NUM_COLUMNS,)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(1, activation='sigmoid') ]) print(model.summary()) # compile the model model.compile(optimizer=OPTIMIZER, loss=LOSS, metrics=METRICS) # fit the model model.fit(train_ds, epochs=EPOCHS) ###Output _____no_output_____ ###Markdown Note: Please do not confuse the training step with online training. It's an entirely different paradigm which will be covered in a later section.Since only a fraction of the dataset is being utilized, our accuracy is limited to ~78% during the training phase. However, please feel free to store additional data in kafka for a better model performance. Also, since the goal was to just demonstrate the functionality of the tfio kafka datasets, a smaller and less-complicated neural network was used. However, one can increase the complexity of the model, modify the learning strategy, tune hyper-parameters etc for exploration purposes. For a baseline approach, please refer to this [article](https://www.nature.com/articles/ncomms5308Sec11). Infer on the test dataTo infer on the test data by adhering to the 'exactly-once' semantics along with fault-tolerance, the `streaming.KafkaGroupIODataset` can be utilized. Define the tfio test datasetThe `stream_timeout` parameter blocks for the given duration for new data points to be streamed into the topic. This removes the need for creating new datasets if the data is being streamed into the topic in an intermittent fashion. ###Code test_ds = tfio.experimental.streaming.KafkaGroupIODataset( topics=["susy-test"], group_id="testcg", servers="127.0.0.1:9092", stream_timeout=10000, configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) def decode_kafka_test_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) test_ds = test_ds.map(decode_kafka_test_item) test_ds = test_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Though this class can be used for training purposes, there are caveats which need to be addressed. Once all the messages are read from kafka and the latest offsets are committed using the `streaming.KafkaGroupIODataset`, the consumer doesn't restart reading the messages from the beginning. Thus, while training, it is possible only to train for a single epoch with the data continuously flowing in. This kind of a functionality has limited use cases during the training phase wherein, once a datapoint has been consumed by the model it is no longer required and can be discarded.However, this functionality shines when it comes to robust inference with exactly-once semantics. evaluate the performance on the test data ###Code res = model.evaluate(test_ds) print("test loss, test acc:", res) ###Output _____no_output_____ ###Markdown Since the inference is based on 'exactly-once' semantics, the evaluation on the test set can be run only once. In order to run the inference again on the test data, a new consumer group should be used. Track the offset lag of the `testcg` consumer group ###Code !confluent-5.4.1/bin/kafka-consumer-groups --bootstrap-server 127.0.0.1:9092 --describe --group testcg ###Output _____no_output_____ ###Markdown Once the `current-offset` matches the `log-end-offset` for all the partitions, it indicates that the consumer(s) have completed fetching all the messages from the kafka topic. Online learningThe online machine learning paradigm is a bit different from the traditional/conventional way of training machine learning models. In the former case, the model continues to incrementally learn/update it's parameters as soon as the new data points are available and this process is expected to continue indefinitely. This is unlike the latter approaches where the dataset is fixed and the model iterates over it `n` number of times. In online learning, the data once consumed by the model may not be available for training again.By utilizing the `streaming.KafkaBatchIODataset`, it is now possible to train the models in this fashion. Let's continue to use our SUSY dataset for demonstrating this functionality. The tfio training dataset for online learningThe `streaming.KafkaBatchIODataset` is similar to the `streaming.KafkaGroupIODataset` in it's API. Additionally, it is recommended to utilize the `stream_timeout` parameter to configure the duration for which the dataset will block for new messages before timing out. In the instance below, the dataset is configured with a `stream_timeout` of `30000` milliseconds. This implies that, after all the messages from the topic have been consumed, the dataset will wait for an additional 30 seconds before timing out and disconnecting from the kafka cluster. If new messages are streamed into the topic before timing out, the data consumption and model training resumes for those newly consumed data points. To block indefinitely, set it to `-1`. ###Code online_train_ds = tfio.experimental.streaming.KafkaBatchIODataset( topics=["susy-train"], group_id="cgonline", servers="127.0.0.1:9092", stream_timeout=30000, # in milliseconds, to block indefinitely, set it to -1. configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) ###Output _____no_output_____ ###Markdown In addition to training the model on existing data, a background thread will be started, which will start streaming additional data into the `susy-train` topic after a sleep duration of 30 seconds. This demonstrates the functionality of resuming the training as soons as new data is fed into the topic without the need for building the dataset over and over again. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka_after_sleep(topic_name, items): time.sleep(30) print("#"*100) print("Writing messages into topic: {0} after a nice sleep !".format(topic_name)) print("#"*100) count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8') ).add_errback(error_callback) count+=1 producer.flush() print("#"*100) print("Wrote {0} messages into topic: {1}".format(count, topic_name)) print("#"*100) def decode_kafka_online_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) ###Output _____no_output_____ ###Markdown Every item that the `online_train_ds` generates is a `tf.data.Dataset` in itself. Thus, all the standard transformations can be applied as usual. ###Code thread = threading.Thread(target=write_to_kafka_after_sleep, args=("susy-train", zip(x_train, y_train))) thread.daemon = True thread.start() for mini_ds in online_train_ds: mini_ds = mini_ds.shuffle(buffer_size=32) mini_ds = mini_ds.map(decode_kafka_online_item) mini_ds = mini_ds.batch(32) model.fit(mini_ds, epochs=3) ###Output _____no_output_____ ###Markdown Copyright 2020 The TensorFlow IO Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Robust machine learning on streaming data using Kafka and Tensorflow-IO View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis tutorial focuses on streaming data from a [Kafka](https://kafka.apache.org/quickstart) cluster into a `tf.data.Dataset` which is then used in conjunction with `tf.keras` for training and inference.Kafka is primarily a distributed event-streaming platform which provides scalable and fault-tolerant streaming data across data pipelines. It is an essential technical component of a plethora of major enterprises where mission-critical data delivery is a primary requirement.**NOTE:** A basic understanding of the [kafka components](https://kafka.apache.org/documentation/intro_concepts_and_terms) will help you in following the tutorial with ease.**NOTE:** A Java runtime environment is required to run this tutorial. Setup Install the required tensorflow-io and kafka packages ###Code !pip install tensorflow-io !pip install kafka-python ###Output _____no_output_____ ###Markdown Import packages ###Code import os from datetime import datetime import time import threading import json from kafka import KafkaProducer from kafka.errors import KafkaError from sklearn.model_selection import train_test_split import pandas as pd import tensorflow as tf import tensorflow_io as tfio ###Output _____no_output_____ ###Markdown Validate tf and tfio imports ###Code print("tensorflow-io version: {}".format(tfio.__version__)) print("tensorflow version: {}".format(tf.__version__)) ###Output _____no_output_____ ###Markdown Download and setup Kafka and Zookeeper instancesFor demo purposes, the following instances are setup locally:- Kafka (Brokers: 127.0.0.1:9092)- Zookeeper (Node: 127.0.0.1:2181) ###Code !curl -sSOL https://downloads.apache.org/kafka/2.7.0/kafka_2.13-2.7.0.tgz !tar -xzf kafka_2.13-2.7.0.tgz ###Output _____no_output_____ ###Markdown Using the default configurations (provided by Apache Kafka) for spinning up the instances. ###Code !./kafka_2.13-2.7.0/bin/zookeeper-server-start.sh -daemon ./kafka_2.13-2.7.0/config/zookeeper.properties !./kafka_2.13-2.7.0/bin/kafka-server-start.sh -daemon ./kafka_2.13-2.7.0/config/server.properties !echo "Waiting for 10 secs until kafka and zookeeper services are up and running" !sleep 10 ###Output _____no_output_____ ###Markdown Once the instances are started as daemon processes, grep for `kafka` in the processes list. The two java processes correspond to zookeeper and the kafka instances. ###Code !ps -ef | grep kafka ###Output _____no_output_____ ###Markdown Create the kafka topics with the following specs:- susy-train: partitions=1, replication-factor=1 - susy-test: partitions=2, replication-factor=1 ###Code !./kafka_2.13-2.7.0/bin/kafka-topics.sh --create --bootstrap-server 127.0.0.1:9092 --replication-factor 1 --partitions 1 --topic susy-train !./kafka_2.13-2.7.0/bin/kafka-topics.sh --create --bootstrap-server 127.0.0.1:9092 --replication-factor 1 --partitions 2 --topic susy-test ###Output _____no_output_____ ###Markdown Describe the topic for details on the configuration ###Code !./kafka_2.13-2.7.0/bin/kafka-topics.sh --describe --bootstrap-server 127.0.0.1:9092 --topic susy-train !./kafka_2.13-2.7.0/bin/kafka-topics.sh --describe --bootstrap-server 127.0.0.1:9092 --topic susy-test ###Output _____no_output_____ ###Markdown The replication factor 1 indicates that the data is not being replicated. This is due to the presence of a single broker in our kafka setup.In production systems, the number of bootstrap servers can be in the range of 100's of nodes. That is where the fault-tolerance using replication comes into picture.Please refer to the [docs](https://kafka.apache.org/documentation/replication) for more details. SUSY DatasetKafka being an event streaming platform, enables data from various sources to be written into it. For instance:- Web traffic logs- Astronomical measurements- IoT sensor data- Product reviews and many more.For the purpose of this tutorial, lets download the [SUSY](https://archive.ics.uci.edu/ml/datasets/SUSY) dataset and feed the data into kafka manually. The goal of this classification problem is to distinguish between a signal process which produces supersymmetric particles and a background process which does not. ###Code !curl -sSOL https://archive.ics.uci.edu/ml/machine-learning-databases/00279/SUSY.csv.gz ###Output _____no_output_____ ###Markdown Explore the dataset The first column is the class label (1 for signal, 0 for background), followed by the 18 features (8 low-level features then 10 high-level features).The first 8 features are kinematic properties measured by the particle detectors in the accelerator. The last 10 features are functions of the first 8 features. These are high-level features derived by physicists to help discriminate between the two classes. ###Code COLUMNS = [ # labels 'class', # low-level features 'lepton_1_pT', 'lepton_1_eta', 'lepton_1_phi', 'lepton_2_pT', 'lepton_2_eta', 'lepton_2_phi', 'missing_energy_magnitude', 'missing_energy_phi', # high-level derived features 'MET_rel', 'axial_MET', 'M_R', 'M_TR_2', 'R', 'MT2', 'S_R', 'M_Delta_R', 'dPhi_r_b', 'cos(theta_r1)' ] ###Output _____no_output_____ ###Markdown The entire dataset consists of 5 million rows. However, for the purpose of this tutorial, let's consider only a fraction of the dataset (100,000 rows) so that less time is spent on the moving the data and more time on understanding the functionality of the api. ###Code susy_iterator = pd.read_csv('SUSY.csv.gz', header=None, names=COLUMNS, chunksize=100000) susy_df = next(susy_iterator) susy_df.head() # Number of datapoints and columns len(susy_df), len(susy_df.columns) # Number of datapoints belonging to each class (0: background noise, 1: signal) len(susy_df[susy_df["class"]==0]), len(susy_df[susy_df["class"]==1]) ###Output _____no_output_____ ###Markdown Split the dataset ###Code train_df, test_df = train_test_split(susy_df, test_size=0.4, shuffle=True) print("Number of training samples: ",len(train_df)) print("Number of testing sample: ",len(test_df)) x_train_df = train_df.drop(["class"], axis=1) y_train_df = train_df["class"] x_test_df = test_df.drop(["class"], axis=1) y_test_df = test_df["class"] # The labels are set as the kafka message keys so as to store data # in multiple-partitions. Thus, enabling efficient data retrieval # using the consumer groups. x_train = list(filter(None, x_train_df.to_csv(index=False).split("\n")[1:])) y_train = list(filter(None, y_train_df.to_csv(index=False).split("\n")[1:])) x_test = list(filter(None, x_test_df.to_csv(index=False).split("\n")[1:])) y_test = list(filter(None, y_test_df.to_csv(index=False).split("\n")[1:])) NUM_COLUMNS = len(x_train_df.columns) len(x_train), len(y_train), len(x_test), len(y_test) ###Output _____no_output_____ ###Markdown Store the train and test data in kafkaStoring the data in kafka simulates an environment for continuous remote data retrieval for training and inference purposes. ###Code def error_callback(exc): raise Exception('Error while sendig data to kafka: {0}'.format(str(exc))) def write_to_kafka(topic_name, items): count=0 producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092']) for message, key in items: producer.send(topic_name, key=key.encode('utf-8'), value=message.encode('utf-8')).add_errback(error_callback) count+=1 producer.flush() print("Wrote {0} messages into topic: {1}".format(count, topic_name)) write_to_kafka("susy-train", zip(x_train, y_train)) write_to_kafka("susy-test", zip(x_test, y_test)) ###Output _____no_output_____ ###Markdown Define the tfio train datasetThe `IODataset` class is utilized for streaming data from kafka into tensorflow. The class inherits from `tf.data.Dataset` and thus has all the useful functionalities of `tf.data.Dataset` out of the box. ###Code def decode_kafka_item(item): message = tf.io.decode_csv(item.message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(item.key) return (message, key) BATCH_SIZE=64 SHUFFLE_BUFFER_SIZE=64 train_ds = tfio.IODataset.from_kafka('susy-train', partition=0, offset=0) train_ds = train_ds.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE) train_ds = train_ds.map(decode_kafka_item) train_ds = train_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Build and train the model ###Code # Set the parameters OPTIMIZER="adam" LOSS=tf.keras.losses.BinaryCrossentropy(from_logits=True) METRICS=['accuracy'] EPOCHS=10 # design/build the model model = tf.keras.Sequential([ tf.keras.layers.Input(shape=(NUM_COLUMNS,)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(1, activation='sigmoid') ]) print(model.summary()) # compile the model model.compile(optimizer=OPTIMIZER, loss=LOSS, metrics=METRICS) # fit the model model.fit(train_ds, epochs=EPOCHS) ###Output _____no_output_____ ###Markdown Note: Please do not confuse the training step with online training. It's an entirely different paradigm which will be covered in a later section.Since only a fraction of the dataset is being utilized, our accuracy is limited to ~78% during the training phase. However, please feel free to store additional data in kafka for a better model performance. Also, since the goal was to just demonstrate the functionality of the tfio kafka datasets, a smaller and less-complicated neural network was used. However, one can increase the complexity of the model, modify the learning strategy, tune hyper-parameters etc for exploration purposes. For a baseline approach, please refer to this [article](https://www.nature.com/articles/ncomms5308Sec11). Infer on the test dataTo infer on the test data by adhering to the 'exactly-once' semantics along with fault-tolerance, the `streaming.KafkaGroupIODataset` can be utilized. Define the tfio test datasetThe `stream_timeout` parameter blocks for the given duration for new data points to be streamed into the topic. This removes the need for creating new datasets if the data is being streamed into the topic in an intermittent fashion. ###Code test_ds = tfio.experimental.streaming.KafkaGroupIODataset( topics=["susy-test"], group_id="testcg", servers="127.0.0.1:9092", stream_timeout=10000, configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) def decode_kafka_test_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) test_ds = test_ds.map(decode_kafka_test_item) test_ds = test_ds.batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Though this class can be used for training purposes, there are caveats which need to be addressed. Once all the messages are read from kafka and the latest offsets are committed using the `streaming.KafkaGroupIODataset`, the consumer doesn't restart reading the messages from the beginning. Thus, while training, it is possible only to train for a single epoch with the data continuously flowing in. This kind of a functionality has limited use cases during the training phase wherein, once a datapoint has been consumed by the model it is no longer required and can be discarded.However, this functionality shines when it comes to robust inference with exactly-once semantics. evaluate the performance on the test data ###Code res = model.evaluate(test_ds) print("test loss, test acc:", res) ###Output _____no_output_____ ###Markdown Since the inference is based on 'exactly-once' semantics, the evaluation on the test set can be run only once. In order to run the inference again on the test data, a new consumer group should be used. Track the offset lag of the `testcg` consumer group ###Code !./kafka_2.13-2.7.0/bin/kafka-consumer-groups.sh --bootstrap-server 127.0.0.1:9092 --describe --group testcg ###Output _____no_output_____ ###Markdown Once the `current-offset` matches the `log-end-offset` for all the partitions, it indicates that the consumer(s) have completed fetching all the messages from the kafka topic. Online learningThe online machine learning paradigm is a bit different from the traditional/conventional way of training machine learning models. In the former case, the model continues to incrementally learn/update it's parameters as soon as the new data points are available and this process is expected to continue indefinitely. This is unlike the latter approaches where the dataset is fixed and the model iterates over it `n` number of times. In online learning, the data once consumed by the model may not be available for training again.By utilizing the `streaming.KafkaBatchIODataset`, it is now possible to train the models in this fashion. Let's continue to use our SUSY dataset for demonstrating this functionality. The tfio training dataset for online learningThe `streaming.KafkaBatchIODataset` is similar to the `streaming.KafkaGroupIODataset` in it's API. Additionally, it is recommended to utilize the `stream_timeout` parameter to configure the duration for which the dataset will block for new messages before timing out. In the instance below, the dataset is configured with a `stream_timeout` of `10000` milliseconds. This implies that, after all the messages from the topic have been consumed, the dataset will wait for an additional 10 seconds before timing out and disconnecting from the kafka cluster. If new messages are streamed into the topic before timing out, the data consumption and model training resumes for those newly consumed data points. To block indefinitely, set it to `-1`. ###Code online_train_ds = tfio.experimental.streaming.KafkaBatchIODataset( topics=["susy-train"], group_id="cgonline", servers="127.0.0.1:9092", stream_timeout=10000, # in milliseconds, to block indefinitely, set it to -1. configuration=[ "session.timeout.ms=7000", "max.poll.interval.ms=8000", "auto.offset.reset=earliest" ], ) ###Output _____no_output_____ ###Markdown Every item that the `online_train_ds` generates is a `tf.data.Dataset` in itself. Thus, all the standard transformations can be applied as usual. ###Code def decode_kafka_online_item(raw_message, raw_key): message = tf.io.decode_csv(raw_message, [[0.0] for i in range(NUM_COLUMNS)]) key = tf.strings.to_number(raw_key) return (message, key) for mini_ds in online_train_ds: mini_ds = mini_ds.shuffle(buffer_size=32) mini_ds = mini_ds.map(decode_kafka_online_item) mini_ds = mini_ds.batch(32) model.fit(mini_ds, epochs=3) ###Output _____no_output_____
HW7-Compressive_Sensing.ipynb
###Markdown Project ###Code student_name = 'Salih Kilicli' ###Output _____no_output_____ ###Markdown Instructions Encoding / DecodingThe first part of this project you will write a set of functions to handle the recovery of sparse vectors of dimension $N$.1. Complete the function `create_observation_matrix` to generate an observation matrix with dimension $m \times N$ containing values drawn from a standard normal distribution scaled by $\sqrt{\frac{\pi}{2m}}$.2. Complete the function `create_observation_vector` to create the observation vector by projecting a sparse input vector to a lower dimension using the observation matrix.3. Run your implementation of the functions above using a sparse random input signal generated by the given function, `create_sparse_signal`. You can use `matplotlib.pyplot` to plot the input sparse signal (see Helper functions below).4. Write the $\ell_1$-minimization problem as a linear programming problem. To find its solution, complete the function `optimize` which uses `scipy.optimize.linprog`, `scipy.optimize.minimize` or cvxpy.5. Run your implementation and use the provided code blocks to output the error and results. Verify that the original input signal has been appropriately recovered. Wavelet Image ProcessingIn this section you will use Wavelets to generate a sparse signal from a grayscal image, and then utilize the encoding/decoding functions you have already completed from the previous section to encode and decode the wavelet coefficients.1. Complete the function `decompose_image` to write the input image as a sum of Haar wavelets (see [`pywt.wavedec2`](https://pywavelets.readthedocs.io/en/latest/ref/2d-dwt-and-idwt.html?highlight=wavedec2d-multilevel-decomposition-using-wavedec2)). The function should return both the coefficient array and slicing data (see [`pywt.coeffs_to_array`](https://pywavelets.readthedocs.io/en/latest/ref/dwt-coefficient-handling.html)).2. Complete the function `reconstruct_image` to reconstruct an image from the Haar coefficients and slicing data (see [`pywt.array_to_coeffs`](https://pywavelets.readthedocs.io/en/latest/ref/dwt-coefficient-handling.htmlsplitting-concatenated-coefficient-array-back-into-its-components) and [`pywt.waverec2`](https://pywavelets.readthedocs.io/en/latest/ref/2d-dwt-and-idwt.htmld-multilevel-reconstruction-using-waverec2)).3. Verify your implementation of `decompose_image` and `reconstruct_image`. In the **Test Code** section load the __shapes2_32.jpg__ image from file (this function is provided), and run the subsequent code blocks to decompose and reconstruct the input image as well as compare the results. 4. Complete the function `create_sparse_wavelet_signal`. This function will return a copy of the input array where the component of `s` largest values are the same and the remaining `N-s` values are set to zero. 5. Run the remainder of the code blocks in **Test Code** and verify that you are able to reconstruct an approximation of the original image using the recovered sparse coefficient vector. Values for `m` and `s` have been chosen for you, but you should play with these values and write additional tests to see their affect on the results. What is your conclusion on the effect of `m` and `s`? Explain why you reach this conclusion. Submitting Your AssignmentYou will submit your completed assignment in two formats:- Jupyter Notebook (.ipynb)- HTML (.html) Jupyter Notebook (.ipynb)You may directly use this notebook to complete your assignment or you may use an external editor/IDE of your choice. However, to submit your code please ensure that your code works in this notebook. HTML (.html)To create an HTML file for your assignment simply select `File > Download as > HTML (.html)` from within the Jupyter Notebook. Both files should be uploaded to [Canvas](https://canvas.tamu.edu). scipy.optimize and cvxpyThis project could be completed with any optimization package, but we recommend that you first try with scipy.optimize, and if you wish additionally with [cvxpy](https://www.cvxpy.org/index.html). We will provide solutions for both scipy.optimize and cvxpy after you submit your project.Also, note that the `scipy.optimize.linprog` supports only `'interior-point'`, `'revised simplex'` and `'simplex'`, while CVX supports many others which may provide better results.If you are using the Anaconda package as was suggested at the beginning of the course you will already have scipy.optimize. However, you may not have cvxpy. The cvxpy package provides a much more understandable and easier means of implementing and performing various optimizations. If you wish to try this check out the [cvxpy installation instructions](https://www.cvxpy.org/install/) for your system. **Note**: Your system may have multiple installations of python, anaconda, and/or pip. Do yourself a favor and verify all paths to your installation and to the conda, pip or other tools you are using to install external packages. If you use the wrong one the package will not be available in your working environment. Helper FunctionsThe following block contains several plotting functions along with a function to create a random sparse signal, a function to output the status of optimize, and a function to load images using PIL. ###Code import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') import math import numpy as np import seaborn as sns from scipy.optimize import linprog, minimize from PIL import Image import cvxpy as cp import pywt import warnings warnings.filterwarnings('ignore') def plot_sparse_vectors(vec_a, vec_b, **kwargs): """ Plots the passed arrays in one or three separate subplots. If 'full' is specifed as True then the following three subplots will be generated: - The topmost subplot contains both arrays; vec_a will be drawn first twice as thick as vec_b. The title will be set if 'title' is specified. - The bottom left subplot contains only the vec_a, and will be given a tilte is 'title_a' is specified. - The bottom right subplot contains only the vec_b, and will be given a tilte is 'title_b' is specified. If 'full' is not specified or is False, then a single subplot will generated as follows: - The plot contains both arrays; vec_a will be drawn first twice as thick as vec_b. The title will be set if 'title' is specified. """ use_full_layout = 'full' in kwargs and kwargs['full'] if use_full_layout: fig = plt.figure(figsize=(20, 8)) gs = fig.add_gridspec(2, 2) else: fig = plt.figure(figsize=(20, 4)) gs = fig.add_gridspec(1, 1) ax = fig.add_subplot(gs[0,:]) if 'title' in kwargs: ax.set_title(kwargs['title'], fontsize=10) plt.plot(vec_a, 'g', linewidth=4) plt.plot(vec_b, 'r', linewidth=2) if use_full_layout: ax = fig.add_subplot(gs[1,0]) if 'title_a' in kwargs: ax.set_title(kwargs['title_a'], fontsize=10) plt.plot(vec_a, 'g', linewidth=2) ax = fig.add_subplot(gs[1,1]) if 'title_b' in kwargs: ax.set_title(kwargs['title_b'], fontsize=10) plt.plot(vec_b, 'r', linewidth=2) plt.show() def plot_image_comparison(img_left, img_right, title_left, title_right): """ Plots img_left and img_right as subplots on the same row. The title_left and title_right are supplied to img_left and img_right, respectively. """ fig = plt.figure(figsize=(10, 4)) ax = fig.add_subplot(1, 2, 1) ax.imshow(img_left, cmap=plt.cm.gray) ax.set_title(title_left, fontsize=16) ax.set_xticks([]) ax.set_yticks([]) ax = fig.add_subplot(1, 2, 2) ax.imshow(img_right, cmap=plt.cm.gray) ax.set_title(title_right, fontsize=16) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() plt.show() def create_sparse_signal(N, s): """ Returns a length N array containing s random values drawn from a standard normal distribution. The remaining N-s values are set to zero. """ # Create a mask with `s` randomly selected elements set to True mask = np.full(N, False) mask[:s] = True np.random.shuffle(mask) # Define an s-sparse vector using random values x = np.zeros(N) x[mask] = np.random.randn(s) return x def output_linprog_status(res): """ Outputs the state of the optimization at the return of scipy.optimize.linprog or scipy.optimize.minimize. """ print('Message:', res.message) print('Success:', res.success) print('Objective Value:', res.fun) print('Number of Iterations:', res.nit) print('Exit Status:') if res.status == 0: print(' Optimization proceeding nominally.') elif res.status == 1: print(' Iteration limit reached.') elif res.status == 2: print(' Problem appears to be infeasible.') elif res.status == 3: print(' Problem appears to be unbounded.') elif res.status == 4: print(' Numerical difficulties encountered.') else: print('Unknown.') # Alias for linprog status output - minimize and linprog return the same structure output_minimize_status = output_linprog_status def output_cvxpy_status(problem): # Output optimation final status print('Objective Value:', problem.value) print('Number of Iterations:', problem.solver_stats.num_iters) print('Exit Status:', problem.status) def output_opt_status(opt_res): if type(opt_res) is cp.problems.problem.Problem: output_cvxpy_status(opt_res) else: output_linprog_status(opt_res) # minimize uses the same function def load_image(filename): """ Loads an image, specified by filename, and returns a 2D array whose values are in the range [0,1]. """ # load the image img = Image.open(filename).convert('L') # convert image data to numpy array with values in [0,1] img_arr = np.divide(np.asarray(img), 255.0) return img_arr ###Output _____no_output_____ ###Markdown Your Solution: Encoding / DecodingComplete the `create_observation_matrix()` and `create_observation_vector()` functions below, and test them using the **Test Code** below. ###Code def create_observation_matrix(m, N): """ This function returns an mxN array of random values from a standard normal distribution scaled by sqrt( pi / 2m ). """ return np.sqrt(np.pi/(2*m)) * np.random.standard_normal(size=(m, N)) def create_observation_vector(A, x): """ This function uses the observation matrix A (mxN) to project the sparse vector x (Nx1) to a lower dimensional space. The reduced vector (mx1) is returned. """ return np.dot(A, x) ###Output _____no_output_____ ###Markdown Complete the `optimize()` function below using `scipy.optimize.linprog`, `scipy.optimize.minimize` or cvxpy. **Hint**: If using linprog, when using the interior point method, consider setting `'sparse':True`, `'cholesky':False`, and `'sym_pos':False` in the `options` dictionary (see [scipy.optimize.linprog](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.htmlscipy-optimize-linprog) and [options for interior-point](https://docs.scipy.org/doc/scipy/reference/optimize.linprog-interior-point.htmllinprog-method-interior-point)). Problem statementThe $\ell_1$-norm linear programming problem for finding the sparse solution $x$ is:$$\text{minimize:} \quad \|z\|_{\ell^1}$$$$ \text{subject to:} \ Az = y $$where $z \in \mathcal{R}^n$, or simply: $$ x = argmin_{z \in \mathcal{R}^n} \|z\|_{\ell^1} \quad \text{subject to} \quad Az = y.$$__Note:__ The $\ell_1$-minimization problem above is __not__ a __linear program__ since the objective function $\|z\|_1=\sum_{i=1}^N|z_i|$ is __not linear__. However, we can transform it to a linear problem with a simple trick. Notice, the problem above is equivalent to the following linear program:$$ \text{minimize:} \quad \sum_{i=1}^N x_i$$$$\text{subject to:} \ Az=y \\ \quad x_i\ge z_i \qquad \text{for all } i=1,\dots, N$$ $$\quad x_i\ge -z_i \qquad \text{for all } i=1,\dots, N.$$. ###Code def optimize(A, y): """ Uses the observation matrix and observation vector to produce the objective function, equality constraints, inequality constraints, and bounds to be passed to linprog, minimize or cvxpy. minimize ||z||_1 = sum(np.abs(z)) subject to A @ z = y for z in R^n or equivalently minimize sum(x) subject to A @ z = y, -z_i <= x_i <= z_i for every i This function then performs the optimization and returns the structure returned by linprog or minimize (or problem & minimal value from cvxpy). """ # create the variable to be minimized x = cp.Variable(shape = A.shape[1]) z = cp.Variable(shape = A.shape[1]) # create the constraint Az = y constraints = [A @ z == y, x >= z, x >= -z] # create the objective var to minimize objective = cp.Minimize(cp.sum(x)) # set up the problem prob = cp.Problem(objective, constraints) # solve the problem prob.solve(solver = 'ECOS') # ECOS, OSQP, SCS -> no need to install # Number of nonzero elements (above a threshold 1e-8) in the solution print(f'Feasible ({prob.status}) solution in R^{z.shape[0]} has {sum(np.abs(z.value)>=1e-8)} nonzeros.') # return the minimized objective value return prob, z.value ###Output _____no_output_____ ###Markdown Test CodeAfter completing the above functions run the following code blocks to view your results. SetupThe following code block uses your implementation to generate a sparse input vector of length N, as well as creates the observation matrix, A, and the observation vector, y. ###Code # Original signal dimension (N=500 default) N = 500 # Reduced dimension (m=150 default) m = 150 # Sparsity - number of non-zeros in signal (s=20 default) s = 20 # Define an s-sparse vector using random values x = create_sparse_signal(N, s) # Define the observation matrix, R^{m x N} A = create_observation_matrix(m, N) # Define the observation vector, R^m y = create_observation_vector(A, x) prob, z = optimize(A, y) nonzeros_z = z[np.abs(z) >= 1e-8] print(f'\nnonzeros_z.shape = {nonzeros_z.shape}') print(f'\nnonzeros_z = \n\n{nonzeros_z}') ###Output Feasible (optimal) solution in R^500 has 20 nonzeros. nonzeros_z.shape = (20,) nonzeros_z = [ 0.03815071 0.73893797 -1.73143026 0.95339646 0.91925605 -0.43211342 0.7911034 0.73075551 -0.13404511 0.56158518 -1.1332936 -0.01450314 0.04174507 -0.54135962 1.17035387 0.36356738 -0.09519428 0.9292345 -1.20620132 0.32404099] ###Markdown The following code block plots the original sparse signal. ###Code fig = plt.figure(figsize=(20, 5)) plt.plot(x, 'b', linewidth=2, alpha=0.75) plt.title('The original sparse signal') plt.show() ###Output _____no_output_____ ###Markdown Perform OptimizationThe following code block runs your optimiation, outputs the status, reovery error and number of non-zeros in the result and thresholded result. ###Code opt_res, x_star = optimize(A, y) # Output optimation final status output_opt_status(opt_res) # Output the L2 recovery error, norm(x-xstar) print('L\u00B2-recovery error:', np.linalg.norm(x - x_star)) # Output the number of non-zeros print('Result vector has', np.count_nonzero(x_star), 'non-zeros out of', N) # Threshold near-zero values and count 'non-zeros' z = x_star.copy() z[np.abs(z) < 1e-8] = 0 # set 'small' values to zero print('Thresholded result vector has', np.count_nonzero(z), 'non-zeros out of', N) # plot the input and recovered vectors plot_sparse_vectors(x, z, full=True, title='Combined', title_a='Original', title_b='Recovered') ###Output Feasible (optimal) solution in R^500 has 20 nonzeros. Objective Value: 12.850267839412183 Number of Iterations: 12 Exit Status: optimal L²-recovery error: 1.680103561242266e-10 Result vector has 500 non-zeros out of 500 Thresholded result vector has 20 non-zeros out of 500 ###Markdown Your Solution: Wavelets ###Code def decompose_image(img_arr, wavelet='haar'): """ This function takes a 2D array of image coefficients in the range [0,1] and uses pywt.wavedec2 to decompose those coefficients into wavelet coefficients. It also uses pywt.coeffs_to_array to reorder those coefficients and create our coefficient array and slicing data. The coefficients and slicing data are both returned by this function. Visit: https://pywavelets.readthedocs.io/en/latest/ref/wavelets.html#wavelet-families """ # decompose the wavelet into its coefficients coeffs = pywt.wavedec2(img_arr, wavelet) # reorder the coefficients to a single array in (coeff_arr, coeff_slices) format array = pywt.coeffs_to_array(coeffs, padding=0) return array def reconstruct_image(coeffs_arr, coeffs_slices, wavelet='haar'): """ This function takes wavelet coefficients and slicing data (as produced by pywt.coeffs_to_array) and uses pywt.array_to_coeffs and pywt.waverec2 to reconstruct an image (a 2D array). The reconstructed image is returned. """ # convert the array into wavelet coefficients coeffs = pywt.array_to_coeffs(coeffs_arr, coeffs_slices, output_format='wavedec2') # use wavelet coefficients to reconstruct the 2D image image = pywt.waverec2(coeffs, wavelet='haar') return image def create_sparse_wavelet_signal(coeffs_arr, s): """ Returns a copy of coeffs_arr where all values are zero except the s largest values, no matter where they appear in the array. """ # create a 1D copy of 2D coeffs_arr array # coeffs_arr.ravel() = coeffs_arr.flatten() = coeffs_arr.reshape(-1) coeffs = coeffs_arr.copy().ravel() # create a 1D array of zeros s_largest = np.zeros(coeffs.shape) # sort the coeffs array (in abs value) and select the indices with largest values # notice argpartition finds smallest values so use -array to find largest ones flat_indices = np.argpartition(-np.absolute(coeffs), s-1)[:s] # assign s largest elements to s_largest, rest 0 s_largest[flat_indices] = coeffs[flat_indices] return s_largest ###Output _____no_output_____ ###Markdown __Example:__ Selecting s-largest value (in abs value) of an array A ###Code S = 5 assert (S < A.size), 's should be smaller than size of A' # create an example 2D array A = np.array([[5, 3, 0], [-2, -4, 1], [3, 2, -6]]) print(f'A =\n\n{A}') flat_A = A.ravel() print(f'\nflattened(A) = {flat_A}') flat_indices = np.argpartition(-np.abs(flat_A), S-1)[:S] print(f'\nIndex of largest {s} elements = {flat_indices}') B = np.zeros(flat_A.shape) B[flat_indices] = flat_A[flat_indices] print(f'\nLargest {S} elements of A = B = \n\n{B}') print(f'\nReshaped(B) =\n\n{B.reshape(A.shape)}') ###Output A = [[ 5 3 0] [-2 -4 1] [ 3 2 -6]] flattened(A) = [ 5 3 0 -2 -4 1 3 2 -6] Index of largest 20 elements = [8 0 4 1 6] Largest 5 elements of A = B = [ 5. 3. 0. 0. -4. 0. 3. 0. -6.] Reshaped(B) = [[ 5. 3. 0.] [ 0. -4. 0.] [ 3. 0. -6.]] ###Markdown Test CodeAfter completing the above functions run the following code blocks to view your results.The following code block uses your implementation to ... Setup: Load the input image ###Code plt.figure(figsize=(10, 4)) img_arr = load_image('shapes2_32.jpg') plt.imshow(img_arr, cmap='gray'); plt.axis('off'); ###Output _____no_output_____ ###Markdown Setup: Wavelet DecompositionDecompose the `img_arr` into wavelet coefficients and some bookkeeping data used by `pywt.wavedec2` and `pywt.waverec2`. ###Code # Transform the 2D image data and get the separated coefficient and slice indexing data coeffs_arr, coeffs_slices = decompose_image(img_arr) ###Output _____no_output_____ ###Markdown Setup: Wavelet Reconstruction - Sanity CheckSanity Check: Reconstruct the image from your decomposition to ensure that it matches the original input. ###Code img_recon = reconstruct_image(coeffs_arr, coeffs_slices) # Compute difference between img_arr and img_recon print('L\u221E error between original and reconstruction:', np.linalg.norm(img_arr - img_recon, np.inf)) # Visually verify the reconstruction output plot_image_comparison(img_arr, img_recon, 'Original', 'Reconstruction') ###Output L∞ error between original and reconstruction: 4.0190073491430667e-14 ###Markdown Setup: Remove 'small' coefficientsThe following block sets our values for `N`, `m` and `s`, and creates a sparse input signal from the input `coeffs_arr`. ###Code # Find the number of coefficients in the signal N = coeffs_arr.shape[0] * coeffs_arr.shape[1] # coeffs_arr.size is the same thing (simpler) # Choose m m = math.floor(.7 * N) # Choose s s = math.floor(.4 * m) # Create our sparse input signal from the wavelet coefficients x = create_sparse_wavelet_signal(coeffs_arr, s) print('Signal Length (N) =', N) print('Reduced Dimension (m) =', m) print('Sparsity (s) =', s) ###Output Signal Length (N) = 1024 Reduced Dimension (m) = 716 Sparsity (s) = 286 ###Markdown Plot the input `coeffs_arr` and the sparse `x` on top of one another. ###Code plot_sparse_vectors(coeffs_arr.reshape(N), x, title='Original vs s-Sparse Vector') ###Output _____no_output_____ ###Markdown Setup: Wavelet Reconstruction (2) - Sanity CheckVerify that the sparse version of the coefficient array can be used to reconstruct the original image as well. ###Code # Reshape the sparse coefficient array to match the original input image sparse_coeffs_arr = x.reshape(coeffs_arr.shape) # reconstruct the image from the sparse coefficient array sparse_img_recon = reconstruct_image(sparse_coeffs_arr, coeffs_slices) # Compute difference between img_arr and sparse_img_recon print('L\u221E error between original and sparse reconstruction:', np.linalg.norm(img_arr - sparse_img_recon, np.inf)) # Visually verify the reconstruction output plot_image_comparison(img_arr, sparse_img_recon, 'Original', 'Sparse Reconstruction') ###Output L∞ error between original and sparse reconstruction: 0.016789215686292436 ###Markdown Setup: Create observation matrix and vectorUse the previous implementation of `create_observation_matrix` and `create_observation_vector` to generate the observation vector from `x`. ###Code # Define the observation matrix, R^{m x N} A = create_observation_matrix(m, N) # Define the observation vector, R^m y = create_observation_vector(A, x) ###Output _____no_output_____ ###Markdown Perform Optimization (this may take some time)The following code blocks runs your optimization, outputs the status, recovery error and number of non-zeros in the result and thresholded result. ###Code opt_res, xstar = optimize(A, y) # Output optimation final status output_opt_status(opt_res) # Output the L2 recovery error, norm(x-xstar) print('L\u00B2-recovery error:', np.linalg.norm(x-xstar)) # Output the number of non-zeros print('Result Vector has', np.count_nonzero(xstar), 'non-zeros out of', N) # Threshold near-zero values and count 'non-zeros' z = xstar.copy() z[np.abs(z) < 1e-8] = 0 print('Result Vector has', np.count_nonzero(z), 'non-zeros out of', N) # plot the input and recovered vectors plot_sparse_vectors(x, z, full=True, title='Combined', title_a='Original', title_b='Recovered') ###Output Feasible (optimal) solution in R^1024 has 286 nonzeros. Objective Value: 115.23676469715092 Number of Iterations: 15 Exit Status: optimal L²-recovery error: 2.1270347955117434e-09 Result Vector has 1024 non-zeros out of 1024 Result Vector has 286 non-zeros out of 1024 ###Markdown Wavelet Reconstruct from L1-minimizationUse the reconstructed values to perform the wavelet reconstruction and compare with the original input. ###Code # Reshape the reconstructed coefficient array to match the original input image coeffs_decode_arr = z.reshape(coeffs_arr.shape[0], coeffs_arr.shape[1]) # reconstruct the image from the reconstructed coefficient array l1_img_recon = reconstruct_image(coeffs_decode_arr, coeffs_slices) # Compute difference between img_arr and img_recon print(f'\nL\u221E between original and reconstruction:, {np.linalg.norm(img_arr - l1_img_recon, np.inf)}\n') # Visually verify the reconstruction output plot_image_comparison(img_arr, l1_img_recon, 'Original', 'Reconstruction') ###Output L∞ between original and reconstruction:, 0.01678921618558593 ###Markdown Your Solution: `m` and `s`What is your conclusion on the effect of `m` and `s`? Explain why you reach this conclusion.As the number of non-sparse ($s$) elements _decreases_ the signal seems to be _smoother_, and in the extreme case where $s=0$ it is just a straigth line. $s$ behaves like the __amplitude__ of the signal, whereas the reduced dimension size $m$ more behaves like the $\mathbf{\dfrac{1}{wavelength}}$ and the signal _streches out_ as $m$ _decreases_. Below, some test examples for various $m$ and $s$ values given. ###Code from IPython.display import Markdown, display N = coeffs_arr.size m = math.floor(.7 * N) s = math.floor(.4 * m) # Different m and s values to test s_test = [(m, 256), (m, 128), (m, 64), (m, 32), (m, 16)] m_test = [(m, s), (600, s), (500, s), (400, s), (300, s)] def plot_differences(m, s, N = coeffs_arr.size): # Create our sparse input signal from the wavelet coefficients x = create_sparse_wavelet_signal(coeffs_arr, s) A = create_observation_matrix(m, N) y = create_observation_vector(A, x) opt_res, xstar = optimize(A, y) # Threshold near-zero values and count 'non-zeros' z = xstar.copy() z[np.abs(z) < 1e-8] = 0 print('Result Vector has', np.count_nonzero(z), 'non-zeros out of', N) # plot the input and recovered vectors plot_sparse_vectors(x, z, full=True, title='Combined', title_a='Original', title_b='Recovered') # Reshape the reconstructed coefficient array to match the original input image coeffs_decode_arr = z.reshape(coeffs_arr.shape) # reconstruct the image from the reconstructed coefficient array l1_img_recon = reconstruct_image(coeffs_decode_arr, coeffs_slices) # Visually verify the reconstruction output plot_image_comparison(img_arr, l1_img_recon, 'Original', 'Reconstruction') # Compute the L2 and Linf recovery error (error between original and reconstructed signals) display(Markdown('---')) print(f'For m = {m}, s = {s}:\n') print('L\u00B2 - recovery error:', np.linalg.norm(x-xstar)) print('L\u221E - recovery error:', np.linalg.norm(img_arr - l1_img_recon, np.inf)) display(Markdown('---')) for (m, s) in m_test: print(f'\nm = {m}, s = {s}\n') plot_differences(m, s) for (m, s) in s_test: print(f'\nm = {m}, s = {s}\n') plot_differences(m, s) ###Output m = 716, s = 256 Feasible (optimal) solution in R^1024 has 256 nonzeros. Result Vector has 256 non-zeros out of 1024
jupyter-notebook/Dump.ipynb
###Markdown Define features ###Code features = [('id', 'NUMERIC'), ('number_of_words', 'NUMERIC'), ('average word length', 'NUMERIC'), ('length of the longest word', 'NUMERIC'), ('whether start with number', ['True', 'False']), ('whether start with who/what/why/where/when/how', ['True', 'False']), ('number_of_character_1_grams', 'NUMERIC'), ('number_of_character_2_grams', 'NUMERIC'), ('number_of_character_3_grams', 'NUMERIC'), ('clindex', 'NUMERIC'), ('formality_measure', 'NUMERIC'), ('is_exclamation_question_mark_present', ['0', '1']), ('lix', 'NUMERIC'), ('number_of_uppercase_words', 'NUMERIC'), ('rix', 'NUMERIC'), ('number_of_word_1_grams', 'NUMERIC'), # ('number_of_contractions','NUMERIC'), ('label', ['0', '1']), ] ###Output _____no_output_____ ###Markdown New features ###Code # https://stackoverflow.com/questions/10677020/real-word-count-in-nltk def number_of_words(text): # TODO # regexptokenizer = RegexpTokenizer(r'\w+') # words = regexptokenizer.tokenize(text) words = word_tokenize(text) return len(words) def number_of_character_1_grams(text): characters = [c for c in text] onegrams = ngrams(characters, 1) return len([gram for gram in onegrams]) def number_of_character_2_grams(text): if len(text) == 0: return [] characters = [c for c in text] twograms = ngrams(characters, 2) return len([gram for gram in twograms]) def number_of_character_3_grams(text): if len(text) <= 1: return 0 characters = [c for c in text] threegrams = ngrams(characters, 3) return len([gram for gram in threegrams]) # https://en.wikipedia.org/wiki/Coleman%E2%80%93Liau_index def clindex(text): text_lower = text.lower() number_of_letters = 0 for character in text_lower: if character in ascii_lowercase: number_of_letters += 1 number_of_sentences = len(sent_tokenize(text)) n_of_words = number_of_words(text) l = 0 s = 0 # TODO should l and s be 0? if n_of_words == 0: pass else: # l = Letters ÷ Words × 100 l = number_of_letters / n_of_words * 100 # s = Sentences ÷ Words × 100 s = number_of_sentences / n_of_words * 100 return 0.0588 * l - 0.296 * s - 15.8 # https://stackoverflow.com/questions/10674832/count-verbs-nouns-and-other-parts-of-speech-with-pythons-nltk def formality_measure(text): tokenized_text = nltk.word_tokenize(text.lower()) t = nltk.Text(tokenized_text) pos_tags = nltk.pos_tag(t) counts = Counter(tag for word,tag in pos_tags) return (counts['NN'] + counts['NNP'] + counts['NNS'] + counts['JJ'] + counts['JJR'] + counts['JJS'] + counts['IN'] + counts['DT'] + counts['PDT'] + counts['WDT'] - counts['PRP'] - counts['PRP$'] - counts['WP'] - counts['WP$'] - counts['VB'] - counts['VBD'] - counts['VBG'] - counts['VBN'] - counts['VBP'] - counts['VBZ'] - counts['RB'] - counts['RBR'] - counts['RBS'] - counts['WRB'] - counts['UH'] + 100) / 2 def is_exclamation_question_mark_present(text): return 0 if '!' not in text and '?' not in text else 1 def lix(text): # TODO should we return 0? if len(sent_tokenize(text)) == 0: return 0 return number_of_words(text) / len(sent_tokenize(text)) def number_of_uppercase_words(text): words = word_tokenize(text) n_of_uppercase_words = 0 for word in words: if word[0] in ascii_uppercase: n_of_uppercase_words += 1 return n_of_uppercase_words def rix(text): lw = 0 words = word_tokenize(text) for word in words: if len(word) >= 7: lw += 1 # TODO should we return 0? if len(sent_tokenize(text)) == 0: return 0 return lw / len(sent_tokenize(text)) def number_of_word_1_grams(text): onegrams = ngrams(word_tokenize(text), 1) return len([gram for gram in onegrams]) # def number_of_contractions(text): # stripped_contractions = ['aint', 'amnt', 'arent', 'cant', 'couldve', 'couldnt', 'couldntve', # 'didnt', 'doesnt', 'dont', 'gonna', 'gotta', 'hadnt', 'hadntve', 'hasnt', # 'havent','hell', 'hes', 'hesnt', 'howd', 'howll', # 'hows', 'id', 'idnt', 'idve', 'ill', 'im', 'ive', 'ivent', 'isnt', # 'itd', 'itll', 'its', 'itsnt', 'mightnt','mightve', 'mustnt', 'mustntve', 'mustve', 'neednt', 'ol', 'oughtnt', # 'shant', 'shed', 'shes', 'shouldve','shouldnt', 'shouldntve', 'somebodydve', 'somebodydntve', 'somebodys', # 'someonell', 'someones','somethingd', 'somethingdnt', 'somethingdntve', 'somethingdve', 'somethingll', # 'somethings', 'thatll', 'thats', 'thatd', 'thered', 'therednt', 'theredntve', # 'theredve', 'therere', 'theres', 'theyd', 'theydnt', 'theydntve', 'theydve', # 'theyll', 'theyontve', 'theyre', 'theyve', 'theyvent', 'wasnt', # 'wed', 'wedve', 'wednt', 'wedntve', 'well', 'wontve', 'were', 'weve', 'werent', # 'whatd', 'whatll', 'whats', 'whatve', 'whens', 'whered', 'wheres', # 'whereve', 'whod', 'whodve', 'wholl', 'whore', 'whos', 'whove', 'whyd', 'whyre', # 'whys', 'wont', 'wontve', 'wouldve', 'wouldnt', 'wouldntve', 'yall', 'yallllve', 'yallre', 'yallllvent', 'yaint', # 'youd', 'youdve', 'youll', 'youre', 'yourent', 'youve', 'youvent'] # words = word_tokenize(text) # num = len([word.replace("'","") for word in words if word in stripped_contractions]) # return(num) def extract_features(tweet_id, text): doc = text.strip().split(' ') f1 = 0 f2 = 0 f3 = 0 f4 = False f5 = False for token in doc: word = token.lower() if f1 == 0: if word[0].isdigit(): f4 = True if word in ['who', 'what', 'why', 'where', 'when', 'how']: f5 = True f1 += 1 length = len(word) f2 += length f3 = max(f3, length) if f1 == 0: return False return (tweet_id, f1, f2 * 1.0 / f1, f3, f4, f5, number_of_character_1_grams(text), number_of_character_2_grams(text), number_of_character_3_grams(text), clindex(text), formality_measure(text), is_exclamation_question_mark_present(text), lix(text), number_of_uppercase_words(text), rix(text), number_of_word_1_grams(text)) # https://github.com/ipython/ipython/issues/10123 directory_path = os.getcwd() dataset_no_figures_path = directory_path + '/../data/dataset_no_figures/' id_features = {} with open(dataset_no_figures_path + 'instances_train.jsonl', 'r') as f: for line in f: dic = json.loads(line) if len(dic['postText'][0]) > 0: feat = extract_features(dic['id'], dic['postText'][0]) if feat: id_features.setdefault(dic['id'], feat) print(len(id_features)) id_labels = {} with open(dataset_no_figures_path + 'truth_train.jsonl', 'r') as f: for line in f: dic = json.loads(line) label = 1 if dic['truthClass'][0] == 'n': label = 0 if dic['id'] in id_features: id_labels.setdefault(dic['id'], label) print(len(id_labels)) data = {} data.setdefault('attributes', features) data.setdefault('description', '') data.setdefault('relation', 'team-one') data.setdefault('data', []) for i in id_labels: tmp = [_ for _ in id_features[i]] tmp.append(str(id_labels[i])) data['data'].append(tmp) with open(dataset_no_figures_path + 'sample_train.arff', 'w') as f: f.write(arff.dumps(data)) ###Output _____no_output_____ ###Markdown Generate test .arff file ###Code id_features = {} id_labels = {} with open(dataset_no_figures_path + 'instances_test.jsonl', 'r') as f: for line in f: dic = json.loads(line) if len(dic['postText'][0]) > 0: feat = extract_features(dic['id'], dic['postText'][0]) if feat: id_features.setdefault(dic['id'], feat) if dic['id'] in id_features: id_labels.setdefault(dic['id'], '?') print(len(id_features)) data = {} data.setdefault('attributes', features) data.setdefault('description', '') data.setdefault('relation', 'team-one') data.setdefault('data', []) for i in id_labels: tmp = [_ for _ in id_features[i]] tmp.append(str(id_labels[i])) data['data'].append(tmp) with open(dataset_no_figures_path + 'sample_test.arff', 'w') as f: f.write(arff.dumps(data)) ###Output _____no_output_____
02_DataAnalysis/labs/BigQuery/lab02_Google_BigQuery_en_Python.ipynb
###Markdown Google BigQuery en Pythonhttps://pypi.org/project/google-cloud-bigquery/ ###Code # instalar bigquery !pip install google-cloud-bigquery # cargamos las librerías from google.cloud import bigquery from google.oauth2 import service_account # Si trabajamos con Token y secret del service account #creds = service_account.Credentials.from_service_account_file('PATH DEL FICHERO JSON en .key') creds = service_account.Credentials.from_service_account_file('/content/thebridgept0521-00ccc9a47591.json') ###Output _____no_output_____ ###Markdown > previamente debemos crear el directorio en nuestro root /home//.key con el comando **mkdir**. ###Code # Alternativa con Google Oauth de Google Colab from google.colab import auth auth.authenticate_user() ###Output _____no_output_____ ###Markdown Jerarquía estructura BigQuery- ProjectID- DatasetID o Dataset- Table ###Code # introducimos el projectID proj_id = 'thebridgept0521' # En caso de trabajar con el token client = bigquery.Client(project=proj_id) # Probamos Gcp-BQ query = ( 'SELECT name ' 'FROM `bigquery-public-data.usa_names.usa_1910_2013` ' 'WHERE state = "TX" ' 'LIMIT 100 ' ) # También podemos estructura la query de esta forma query = """ SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = "TX" LIMIT 100 """ # Ejecutaremos el job de BigQuery query_job = client.query(query) # esta es la llamada a la API # Iterar sobre el propio job para extraer los resultados rows = query_job.result() for row in rows: print(row.name) # Test # Perform a query. QUERY = ( ' SELECT DISTINCT visitId, h.page.pageTitle FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20170801`, ' ' UNNEST(hits) AS h WHERE visitId = 1501570398') query_job = client.query(QUERY) # API request rows = query_job.result() # Waits for query to finish for row in rows: print(row) ###Output _____no_output_____ ###Markdown Google BigQuery en Pythonhttps://pypi.org/project/google-cloud-bigquery/ ###Code # instalar bigquery !pip install google-cloud-bigquery # cargamos las librerías from google.cloud import bigquery from google.oauth2 import service_account # Si trabajamos con Token y secret del service account #creds = service_account.Credentials.from_service_account_file('PATH DEL FICHERO JSON en .key') creds = service_account.Credentials.from_service_account_file('/content/thebridgept0521-00ccc9a47591.json') ###Output _____no_output_____ ###Markdown > previamente debemos crear el directorio en nuestro root /home//.key con el comando **mkdir**. ###Code # Alternativa con Google Oauth de Google Colab from google.colab import auth auth.authenticate_user() ###Output _____no_output_____ ###Markdown Jerarquía estructura BigQuery- ProjectID- DatasetID o Dataset- Table ###Code # introducimos el projectID proj_id = 'thebridgept0521' # En caso de trabajar con el token client = bigquery.Client(project=proj_id) # Probamos Gcp-BQ query = ( 'SELECT name ' 'FROM `bigquery-public-data.usa_names.usa_1910_2013` ' 'WHERE state = "TX" ' 'LIMIT 100 ' ) # También podemos estructura la query de esta forma query = """ SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = "TX" LIMIT 100 """ # Ejecutaremos el job de BigQuery query_job = client.query(query) # esta es la llamada a la API # Iterar sobre el propio job para extraer los resultados rows = query_job.result() for row in rows: print(row.name) # Test # Perform a query. QUERY = ( ' SELECT DISTINCT visitId, h.page.pageTitle FROM `bigquery-public-data.google_analytics_sample.ga_sessions_20170801`, ' ' UNNEST(hits) AS h WHERE visitId = 1501570398') query_job = client.query(QUERY) # API request rows = query_job.result() # Waits for query to finish for row in rows: print(row) query_job = client.query(QUERY) # API request rows = query_job.result() # Waits for query to finish for row in rows: print(type(row[1])) # También podemos transformar en un dataframe directamente sin para por el Iterator df = query_job.to_dataframe() df type(df) ###Output _____no_output_____ ###Markdown > A partir del dataframe podemos realizar EDA, transformaciones, limpieza, agregaciones, visualizaciones, enriquecimiento de nuevos datos, join con otras tablas... etc. etc. etc. *** ###Code # # Realizamos una nueva tarea con otra consulta # QUERY = """ # SELECT name, state, SUM(number) as count # FROM `bigquery-public-data.usa_names.usa_1910_current` # WHERE year BETWEEN 1990 AND 2000 AND # state IN ('TX', 'NY', 'CA', 'FL', 'NM', 'IL') # GROUP BY name, state # ORDER BY count DESC # LIMIT 10 # """ # Realizamos una nueva tarea con otra consulta QUERY = """ SELECT name, SUM(number) as count FROM `bigquery-public-data.usa_names.usa_1910_current` GROUP BY name, state ORDER BY count DESC """ # realizamos el job de BQ query_job = client.query(QUERY) df = client.query(QUERY).to_dataframe() df.head(20) df.sample(100) df.shape ###Output _____no_output_____ ###Markdown > desde este punto como siempre realizamos nuestro EDA ###Code # visualizamos el ejemplo anterior %matplotlib inline df.plot(kind='bar', x='name', y='count') ###Output _____no_output_____ ###Markdown *** ###Code # Test # Perform a query natality sql = """ SELECT source_year AS year, COUNT(is_male) AS birth_count FROM `bigquery-public-data.samples.natality` GROUP BY year ORDER BY year DESC LIMIT 15 """ query_job = client.query(sql) # API request df = client.query(sql).to_dataframe() df df.plot(kind='bar', x='year', y='birth_count'); ###Output _____no_output_____ ###Markdown *** ###Code # Test # Perform a query natality sql = """ SELECT wday, SUM(CASE WHEN is_male THEN 1 ELSE 0 END) AS male_births, SUM(CASE WHEN is_male THEN 0 ELSE 1 END) AS female_births FROM `bigquery-public-data.samples.natality` WHERE wday IS NOT NULL GROUP BY wday ORDER BY wday ASC """ query_job = client.query(sql) # API request df = client.query(sql).to_dataframe() df df.plot(x='wday') ###Output _____no_output_____ ###Markdown **** ###Code # test sql = """ SELECT plurality, COUNT(1) AS count, year FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(plurality) AND plurality > 1 GROUP BY plurality, year ORDER BY count DESC """ df = client.query(sql).to_dataframe() df.head() pivot_table = df.pivot(index='year', columns='plurality', values='count') pivot_table.plot(kind='bar', stacked=True, figsize=(15, 7)); sql = """ SELECT gestation_weeks, COUNT(1) AS count FROM `bigquery-public-data.samples.natality` WHERE NOT IS_NAN(gestation_weeks) AND gestation_weeks <> 99 GROUP BY gestation_weeks ORDER BY gestation_weeks """ df = client.query(sql).to_dataframe() ax = df.plot(kind='bar', x='gestation_weeks', y='count', figsize=(15,7)) ax.set_title('Count of Births by Gestation Weeks') ax.set_xlabel('Gestation Weeks') ax.set_ylabel('Count'); ###Output _____no_output_____
Programming_Language_Translator.ipynb
###Markdown Cloning Facebook Research TransCoder Repository ###Code !git clone https://github.com/facebookresearch/TransCoder.git ###Output Cloning into 'TransCoder'... remote: Enumerating objects: 2194, done. remote: Counting objects: 100% (2194/2194), done. remote: Compressing objects: 100% (1106/1106), done. remote: Total 2194 (delta 1088), reused 2191 (delta 1085), pack-reused 0 Receiving objects: 100% (2194/2194), 4.03 MiB | 15.81 MiB/s, done. Resolving deltas: 100% (1088/1088), done. ###Markdown Installing FastBPE ###Code !git clone https://github.com/glample/fastBPE %cd fastBPE !g++ -std=c++11 -pthread -O3 fastBPE/main.cc -IfastBPE -o fast !python setup.py install %cd .. ###Output Cloning into 'fastBPE'... remote: Enumerating objects: 5, done. remote: Counting objects: 20% (1/5) remote: Counting objects: 40% (2/5) remote: Counting objects: 60% (3/5) remote: Counting objects: 80% (4/5) remote: Counting objects: 100% (5/5) remote: Counting objects: 100% (5/5), done. remote: Compressing objects: 20% (1/5) remote: Compressing objects: 40% (2/5) remote: Compressing objects: 60% (3/5) remote: Compressing objects: 80% (4/5) remote: Compressing objects: 100% (5/5) remote: Compressing objects: 100% (5/5), done. Unpacking objects: 1% (1/59) Unpacking objects: 3% (2/59) Unpacking objects: 5% (3/59) Unpacking objects: 6% (4/59) Unpacking objects: 8% (5/59) Unpacking objects: 10% (6/59) Unpacking objects: 11% (7/59) Unpacking objects: 13% (8/59) Unpacking objects: 15% (9/59) Unpacking objects: 16% (10/59) Unpacking objects: 18% (11/59) Unpacking objects: 20% (12/59) Unpacking objects: 22% (13/59) Unpacking objects: 23% (14/59) Unpacking objects: 25% (15/59) Unpacking objects: 27% (16/59) Unpacking objects: 28% (17/59) Unpacking objects: 30% (18/59) remote: Total 59 (delta 0), reused 2 (delta 0), pack-reused 54 Unpacking objects: 32% (19/59) Unpacking objects: 33% (20/59) Unpacking objects: 35% (21/59) Unpacking objects: 37% (22/59) Unpacking objects: 38% (23/59) Unpacking objects: 40% (24/59) Unpacking objects: 42% (25/59) Unpacking objects: 44% (26/59) Unpacking objects: 45% (27/59) Unpacking objects: 47% (28/59) Unpacking objects: 49% (29/59) Unpacking objects: 50% (30/59) Unpacking objects: 52% (31/59) Unpacking objects: 54% (32/59) Unpacking objects: 55% (33/59) Unpacking objects: 57% (34/59) Unpacking objects: 59% (35/59) Unpacking objects: 61% (36/59) Unpacking objects: 62% (37/59) Unpacking objects: 64% (38/59) Unpacking objects: 66% (39/59) Unpacking objects: 67% (40/59) Unpacking objects: 69% (41/59) Unpacking objects: 71% (42/59) Unpacking objects: 72% (43/59) Unpacking objects: 74% (44/59) Unpacking objects: 76% (45/59) Unpacking objects: 77% (46/59) Unpacking objects: 79% (47/59) Unpacking objects: 81% (48/59) Unpacking objects: 83% (49/59) Unpacking objects: 84% (50/59) Unpacking objects: 86% (51/59) Unpacking objects: 88% (52/59) Unpacking objects: 89% (53/59) Unpacking objects: 91% (54/59) Unpacking objects: 93% (55/59) Unpacking objects: 94% (56/59) Unpacking objects: 96% (57/59) Unpacking objects: 98% (58/59) Unpacking objects: 100% (59/59) Unpacking objects: 100% (59/59), done. /content/fastBPE Compiling fastBPE/fastBPE.pyx because it changed. [1/1] Cythonizing fastBPE/fastBPE.pyx running install running bdist_egg running egg_info creating fastBPE.egg-info writing fastBPE.egg-info/PKG-INFO writing dependency_links to fastBPE.egg-info/dependency_links.txt writing top-level names to fastBPE.egg-info/top_level.txt writing manifest file 'fastBPE.egg-info/SOURCES.txt' package init file 'fastBPE/__init__.py' not found (or not a regular file) reading manifest template 'MANIFEST.in' writing manifest file 'fastBPE.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py running build_ext building 'fastBPE' extension creating build creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/fastBPE x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -IfastBPE -I/usr/include/python3.6m -c fastBPE/fastBPE.cpp -o build/temp.linux-x86_64-3.6/fastBPE/fastBPE.o -std=c++11 -Ofast -pthread creating build/lib.linux-x86_64-3.6 x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/fastBPE/fastBPE.o -o build/lib.linux-x86_64-3.6/fastBPE.cpython-36m-x86_64-linux-gnu.so creating build/bdist.linux-x86_64 creating build/bdist.linux-x86_64/egg copying build/lib.linux-x86_64-3.6/fastBPE.cpython-36m-x86_64-linux-gnu.so -> build/bdist.linux-x86_64/egg creating stub loader for fastBPE.cpython-36m-x86_64-linux-gnu.so byte-compiling build/bdist.linux-x86_64/egg/fastBPE.py to fastBPE.cpython-36.pyc creating build/bdist.linux-x86_64/egg/EGG-INFO copying fastBPE.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO copying fastBPE.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying fastBPE.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying fastBPE.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt zip_safe flag not set; analyzing archive contents... __pycache__.fastBPE.cpython-36: module references __file__ creating dist creating 'dist/fastBPE-0.1.1-py3.6-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing fastBPE-0.1.1-py3.6-linux-x86_64.egg creating /usr/local/lib/python3.6/dist-packages/fastBPE-0.1.1-py3.6-linux-x86_64.egg Extracting fastBPE-0.1.1-py3.6-linux-x86_64.egg to /usr/local/lib/python3.6/dist-packages Adding fastBPE 0.1.1 to easy-install.pth file Installed /usr/local/lib/python3.6/dist-packages/fastBPE-0.1.1-py3.6-linux-x86_64.egg Processing dependencies for fastBPE==0.1.1 Finished processing dependencies for fastBPE==0.1.1 /content ###Markdown Installing PyTorch Checking CUDA version to install the compatible PyTorch version ###Code !nvcc --version ###Output nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2019 NVIDIA Corporation Built on Sun_Jul_28_19:07:16_PDT_2019 Cuda compilation tools, release 10.1, V10.1.243 ###Markdown Install the correct PyTorch version ###Code %pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html ###Output Looking in links: https://download.pytorch.org/whl/torch_stable.html Requirement already satisfied: torch==1.6.0+cu101 in /usr/local/lib/python3.6/dist-packages (1.6.0+cu101) Requirement already satisfied: torchvision==0.7.0+cu101 in /usr/local/lib/python3.6/dist-packages (0.7.0+cu101) Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch==1.6.0+cu101) (0.16.0) Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch==1.6.0+cu101) (1.18.5) Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision==0.7.0+cu101) (7.0.0) ###Markdown Installing SacreBleu ###Code %pip install sacrebleu=="1.2.11" ###Output Collecting sacrebleu==1.2.11 Downloading https://files.pythonhosted.org/packages/0d/fb/ad7d721fbeeba9e2fe459f489f38a792ca1e5f5b61f09e608f22f400ca66/sacrebleu-1.2.11.tar.gz Collecting typing [?25l Downloading https://files.pythonhosted.org/packages/05/d9/6eebe19d46bd05360c9a9aae822e67a80f9242aabbfc58b641b957546607/typing-3.7.4.3.tar.gz (78kB)  |████████████████████████████████| 81kB 5.1MB/s [?25hBuilding wheels for collected packages: sacrebleu, typing Building wheel for sacrebleu (setup.py) ... [?25l[?25hdone Created wheel for sacrebleu: filename=sacrebleu-1.2.11-cp36-none-any.whl size=18641 sha256=fab6129dcfbffa8e1fa169c2c0069cbb2071be3df7bd20dec73775063201924b Stored in directory: /root/.cache/pip/wheels/93/0f/06/e1c5dcbca58e907c17b59be8e1f10ae4e43bb1fb68197a8d7c Building wheel for typing (setup.py) ... [?25l[?25hdone Created wheel for typing: filename=typing-3.7.4.3-cp36-none-any.whl size=26309 sha256=1f753426f146b7959b9a2d1aa6f8d1438c2794ba348d7ad877fff832e46c81d0 Stored in directory: /root/.cache/pip/wheels/2d/04/41/8e1836e79581989c22eebac3f4e70aaac9af07b0908da173be Successfully built sacrebleu typing Installing collected packages: typing, sacrebleu Successfully installed sacrebleu-1.2.11 typing-3.7.4.3 ###Markdown Installing Clang ###Code %pip install clang ###Output Collecting clang Downloading https://files.pythonhosted.org/packages/6d/d7/40cdcb82d072cd1c5e3f7ce249a9dfbd8d7d2194d3f0885b5eaa8f310f2b/clang-6.0.0.2-py2.py3-none-any.whl Installing collected packages: clang Successfully installed clang-6.0.0.2 ###Markdown Update the code to point to the correct llvm path ###Code %cd /usr/lib/llvm-6.0/lib !ln -s libclang.so.1 libclang.so %cd /content !sed -i "s|clang.cindex.Config.set_library_path('/usr/lib/llvm-7/lib/')|clang.cindex.Config.set_library_path('/usr/lib/llvm-6.0/lib/')|g" /content/TransCoder/preprocessing/src/code_tokenizer.py ###Output /usr/lib/llvm-6.0/lib /content ###Markdown Downloading the model checkpoints First checkpoint for C++ -> Java, Java -> C++ and Java -> Python ###Code %mkdir checkpoints %cd checkpoints !wget https://dl.fbaipublicfiles.com/transcoder/model_1.pth ###Output /content/checkpoints --2020-08-09 22:17:45-- https://dl.fbaipublicfiles.com/transcoder/model_1.pth Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 172.67.9.4, 104.22.75.142, 104.22.74.142, ... Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|172.67.9.4|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 622089114 (593M) [application/octet-stream] Saving to: ‘model_1.pth’ model_1.pth 100%[===================>] 593.27M 66.4MB/s in 9.3s 2020-08-09 22:17:55 (63.6 MB/s) - ‘model_1.pth’ saved [622089114/622089114] ###Markdown Second checkpoint for C++ -> Python, Python -> C++ and Python -> Java ###Code !wget https://dl.fbaipublicfiles.com/transcoder/model_2.pth %cd .. ###Output --2020-08-09 22:17:56-- https://dl.fbaipublicfiles.com/transcoder/model_2.pth Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.74.142, 172.67.9.4, 104.22.75.142, ... Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.74.142|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 622089114 (593M) [application/octet-stream] Saving to: ‘model_2.pth’ model_2.pth 100%[===================>] 593.27M 50.6MB/s in 11s 2020-08-09 22:18:07 (55.9 MB/s) - ‘model_2.pth’ saved [622089114/622089114] /content ###Markdown Running the model for translation Update the code to point to the correct BPE codes file path ###Code !sed -i 's|default="data/BPE_with_comments_codes"|default="/content/TransCoder/data/BPE_with_comments_codes"|g' /content/TransCoder/translate.py ###Output _____no_output_____ ###Markdown Finally, we reached the interesting part. Let's translate some code files. First, upload the files you want to translate into another language among (cpp, java and python) ###Code %mkdir -p examples %cd /content/examples from google.colab import files files.upload() %cd /content ###Output /content/examples ###Markdown Second, update the following command to reflect your chosen src lang, tgt lang, the model checkpoint path as mentioned in the previous section and the uploaded input file path. ###Code INPUT_FILE_PATH = '/content/examples/2.cpp' SRC_LANG = 'cpp' TGT_LANG = 'python' MODEL_PATH = '/content/checkpoints/model_1.pth' if (SRC_LANG, TGT_LANG) in [('cpp', 'java'), ('java', 'cpp'), ('java', 'python')] else '/content/checkpoints/model_2.pth' !cat $INPUT_FILE_PATH print('=' * 20) !echo 'Using checkpoint: $MODEL_PATH' !python /content/TransCoder/translate.py --src_lang $SRC_LANG --tgt_lang $TGT_LANG --model_path $MODEL_PATH < $INPUT_FILE_PATH ###Output #include <bits/stdc++.h> using namespace std; int main() { const int MAX_SIZES = 3; map<string,int> size_map = {{"small",0}, {"medium", 1}, {"large", 2}}; int T, C, N; cin >> T; assert(T > 0); while(T--){ cin >> C >> N; assert(C > 0 && N > 0); map<string, vector<long long> > coffee; for(int i = 0; i < C; i++){ string coffee_name; cin >> coffee_name; long long price; for(int j = 0; j < MAX_SIZES; j++){ cin >> price; coffee[coffee_name].push_back(price); } } int delivery_cost = 100/N; for(int i = 0; i < N; i++){ string person_name, coffee_size, coffee_name; cin >> person_name >> coffee_size >> coffee_name; long long total_cost = coffee[coffee_name][size_map[coffee_size]] + delivery_cost; if(total_cost % 5 == 1) total_cost--; else if(total_cost % 5 == 4) total_cost++; cout << person_name << " " << total_cost << "\n"; } } return 0; } ==================== Using checkpoint: /content/checkpoints/model_2.pth Loading codes from /content/TransCoder/data/BPE_with_comments_codes ... Read 50000 codes from the codes file. ==================== def __main ( ) : MAX_SIZES = 3 size_map = { 'small' : 0 , 'medium' : 1 , 'large' : 2 } T , C , N = sys.argv [ 1 : ] assert T > 0 while T : C , N = sys.argv [ 2 : ] assert C > 0 and N > 0 coffee = { } for i in range ( C ) : coffee_name = sys.argv [ 3 ] price = sys.argv [ 4 ] for j in range ( MAX_SIZES ) : price = sys.argv [ 5 ] coffee [ coffee_name ].append ( price ) delivery_cost = 100 / N for i in range ( N ) : person_name , coffee_size , coffee_name = sys.argv [ 3 ] total_cost = coffee [ coffee_name ] [ size_map [ coffee_size ] ] + delivery_cost if total_cost % 5 == 1 : total_cost -= 1 elif total_cost % 5 == 4 : total_cost += 1 print ( person_name , total_cost , end = ' ' )
Home Work (Python).ipynb
###Markdown Домашнее задание по теме "Основы Python" **Задание 1** ###Code len('Насколько проще было бы писать программы, если бы не заказчики')>len('640Кб должно хватить для любых задач. Билл Гейтс (по легенде)') len('Насколько проще было бы писать программы, если бы не заказчики')>len('640Кб должно хватить для любых задач. Билл Гейтс (по легенде)') phrase_1='Насколько проще было бы писать программы, если бы не заказчики' phrase_2='640Кб должно хватить для любых задач. Билл Гейтс (по легенде)' if phrase_1>phrase_2: print('фраза 1 длиннее фразы 2') print('конец программы') phrase_1 = '640Кб должно хватить для любых задач. Билл Гейтс (по легенде)' phrase_2 = 'Насколько проще было бы писать программы, если бы не заказчики' if phrase_2>phrase_1: print('фраза 2 длиннее фразы 1') phrase_1 = 'Насколько проще было бы писать программы, если бы не заказчики' phrase_2 = 'Насколько проще было бы писать программы, если бы не заказчики' if phrase_1==phrase_2: print('фразы равной длины') ###Output фразы равной длины ###Markdown **Задание 2** ###Code x=2020 if x%2==0: print(x,'-високосный год') else: print(x,'-обычный год') x=2019 if x%2==0: print(x,'-високосный год') else: print(x,'-обычный год') ###Output 2019 -обычный год ###Markdown **Задание 3** ###Code day=30 month=9 if day==30 and month==9: print('дева') ###Output дева ###Markdown **Задание 4** ###Code width = 10 length = 205 height = 5 if width<15 and length<15 and height<15: print('Коробка №1') elif width>15 and length>15 and heigh>15: print('Коробка №2') elif width>200 and lehgth>200 and heigh>200: print('Упаковка для лыж') else: print('Стандартная коробка №3') ###Output Стандартная коробка №3 ###Markdown Домашнее задание по теме "Основы Python" **Задание 1** ###Code len('Насколько проще было бы писать программы, если бы не заказчики')>len('640Кб должно хватить для любых задач. Билл Гейтс (по легенде)') len('Насколько проще было бы писать программы, если бы не заказчики')>len('640Кб должно хватить для любых задач. Билл Гейтс (по легенде)') phrase_1 = 'Насколько проще было бы писать программы, если бы не заказчики' phrase_2 = '640Кб должно хватить для любых задач. Билл Гейтс (по легенде)' if phrase_1 > phrase_2: print('фраза 1 длиннее фразы 2') phrase_1 = '640Кб должно хватить для любых задач. Билл Гейтс (по легенде)' phrase_2 = 'Насколько проще было бы писать программы, если бы не заказчики' if phrase_2 > phrase_1: print('фраза 2 длиннее фразы 1') phrase_1 = 'Насколько проще было бы писать программы, если бы не заказчики' phrase_2 = 'Насколько проще было бы писать программы, если бы не заказчики' if phrase_1==phrase_2: print('фразы равной длины') ###Output фразы равной длины ###Markdown **Задание 2** ###Code x=2020 if x%4==0: print(x,'-високосный год') else: print(x,'-обычный год') x=2019 if x%4==0: print(x,'-високосный год') else: print(x,'-обычный год') ###Output 2019 -обычный год ###Markdown **Задание 3** ###Code m = 'август' d = 30 if m == 'март' and d >= 21: print('знак зодиака Овен') elif m == 'март' and d < 21: print('знак зодиака Рыбы') if m == 'апрель' and d >= 21: print('знак зодиака Телец') elif m== 'апрель'and d < 21: print('знак зодиака Овен') if m == 'май' and d >= 22: print('знак зодиака Близнецы') elif m == 'май' and d < 22: print('знак зодиака Телец') if m == 'июнь' and d >= 22: print('знак зодиака Рак') elif m == 'июнь' and d < 22: print('знак зодиака Близнецы') if m == 'июль' and d >= 23: print('знак зодиака Лев') elif m == 'июль' and d < 23: print('знак зодиака Рак') if m == 'август' and d >= 24: print('знак зодиака Дева') elif m == 'август' and d < 24: print('знак зодиака Лев') if m == 'сентябрь' and d >= 24: print('знак зодиака Весы') elif m == 'сентябрь' and d < 24: print('знак зодиака Дева') if m == 'октябрь' and d >= 24: print('знак зодиака Скорпион') elif m == 'октябрь' and d < 24: print('знак зодиака Весы') if m == 'ноябрь' and d >= 23: print('знак зодиака Стрелец') elif m == 'ноябрь' and d < 23: print('знак зодиака Скорпион') if m == 'декабрь' and d >= 22: print('знак зодиака Козерог') elif m == 'декабрь' and d < 22: print('знак зодиака Стрелец') if m == 'январь' and d >= 21: print('знак зодиака Водолей') elif m == 'январь' and d < 21: print('знак зодиака Стрелец') if m == 'февраль' and d >= 19: print('знак зодиака Рыбы') elif m == 'февраль' and d < 19: print('знак зодиака Водолей') m = 'октябрь' d = 26 if m == 'март' and d >= 21: print('знак зодиака Овен') elif m == 'март' and d < 21: print('знак зодиака Рыбы') if m == 'апрель' and d >= 21: print('знак зодиака Телец') elif m== 'апрель'and d < 21: print('знак зодиака Овен') if m == 'май' and d >= 22: print('знак зодиака Близнецы') elif m == 'май' and d < 22: print('знак зодиака Телец') if m == 'июнь' and d >= 22: print('знак зодиака Рак') elif m == 'июнь' and d < 22: print('знак зодиака Близнецы') if m == 'июль' and d >= 23: print('знак зодиака Лев') elif m == 'июль' and d < 23: print('знак зодиака Рак') if m == 'август' and d >= 24: print('знак зодиака Дева') elif m == 'август' and d < 24: print('знак зодиака Лев') if m == 'сентябрь' and d >= 24: print('знак зодиака Весы') elif m == 'сентябрь' and d < 24: print('знак зодиака Дева') if m == 'октябрь' and d >= 24: print('знак зодиака Скорпион') elif m == 'октябрь' and d < 24: print('знак зодиака Весы') if m == 'ноябрь' and d >= 23: print('знак зодиака Стрелец') elif m == 'ноябрь' and d < 23: print('знак зодиака Скорпион') if m == 'декабрь' and d >= 22: print('знак зодиака Козерог') elif m == 'декабрь' and d < 22: print('знак зодиака Стрелец') if m == 'январь' and d >= 21: print('знак зодиака Водолей') elif m == 'январь' and d < 21: print('знак зодиака Стрелец') if m == 'февраль' and d >= 19: print('знак зодиака Рыбы') elif m == 'февраль' and d < 19: print('знак зодиака Водолей') ###Output знак зодиака Скорпион ###Markdown **Задание 4** ###Code width = 10 length = 205 height = 5 if 15 < width < 50 or 15 < length < 50 or 15 < height < 50: print(width,length,height) print('Коробка №2') elif width < 15 and length < 15 and heigh < 15: print('Коробка №1') elif length > 200: print('Упаковка для лыж') else: print('Стандартная коробка №3') print('конец программы') ###Output _____no_output_____
notebooks/losses_evaluation/Dstripes/basic/ellwlb/convolutional/AE/DstripesAE_Convolutional_reconst_1ellwlb_05ssim.ipynb
###Markdown Settings ###Code %env TF_KERAS = 1 import os sep_local = os.path.sep import sys sys.path.append('..'+sep_local+'..') print(sep_local) os.chdir('..'+sep_local+'..'+sep_local+'..'+sep_local+'..'+sep_local+'..') print(os.getcwd()) import tensorflow as tf print(tf.__version__) ###Output _____no_output_____ ###Markdown Dataset loading ###Code dataset_name='Dstripes' import tensorflow as tf train_ds = tf.data.Dataset.from_generator( lambda: training_generator, output_types=tf.float32 , output_shapes=tf.TensorShape((batch_size, ) + image_size) ) test_ds = tf.data.Dataset.from_generator( lambda: testing_generator, output_types=tf.float32 , output_shapes=tf.TensorShape((batch_size, ) + image_size) ) _instance_scale=1.0 for data in train_ds: _instance_scale = float(data[0].numpy().max()) break _instance_scale import numpy as np from collections.abc import Iterable if isinstance(inputs_shape, Iterable): _outputs_shape = np.prod(inputs_shape) _outputs_shape ###Output _____no_output_____ ###Markdown Model's Layers definition ###Code units=20 c=50 enc_lays = [ tf.keras.layers.Conv2D(filters=units, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=units*9, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), # No activation tf.keras.layers.Dense(latents_dim) ] dec_lays = [ tf.keras.layers.Dense(units=c*c*units, activation=tf.nn.relu), tf.keras.layers.Reshape(target_shape=(c , c, units)), tf.keras.layers.Conv2DTranspose(filters=units, kernel_size=3, strides=(2, 2), padding="SAME", activation='relu'), tf.keras.layers.Conv2DTranspose(filters=units*3, kernel_size=3, strides=(2, 2), padding="SAME", activation='relu'), # No activation tf.keras.layers.Conv2DTranspose(filters=3, kernel_size=3, strides=(1, 1), padding="SAME") ] ###Output _____no_output_____ ###Markdown Model definition ###Code model_name = dataset_name+'AE_Convolutional_reconst_1ell_05ssmi' experiments_dir='experiments'+sep_local+model_name from training.autoencoding_basic.autoencoders.autoencoder import autoencoder as AE inputs_shape=image_size variables_params = \ [ { 'name': 'inference', 'inputs_shape':inputs_shape, 'outputs_shape':latents_dim, 'layers': enc_lays } , { 'name': 'generative', 'inputs_shape':latents_dim, 'outputs_shape':inputs_shape, 'layers':dec_lays } ] from utils.data_and_files.file_utils import create_if_not_exist _restore = os.path.join(experiments_dir, 'var_save_dir') create_if_not_exist(_restore) _restore #to restore trained model, set filepath=_restore ae = AE( name=model_name, latents_dim=latents_dim, batch_size=batch_size, variables_params=variables_params, filepath=None ) from evaluation.quantitive_metrics.structural_similarity import prepare_ssim_multiscale from statistical.losses_utilities import similarity_to_distance from statistical.ae_losses import expected_loglikelihood_with_lower_bound as ellwlb ae.compile(loss={'x_logits': lambda x_true, x_logits: ellwlb(x_true, x_logits)+ 0.5*similarity_to_distance(prepare_ssim_multiscale([ae.batch_size]+ae.get_inputs_shape()))(x_true, x_logits)}) ###Output _____no_output_____ ###Markdown Callbacks ###Code from training.callbacks.sample_generation import SampleGeneration from training.callbacks.save_model import ModelSaver es = tf.keras.callbacks.EarlyStopping( monitor='loss', min_delta=1e-12, patience=12, verbose=1, restore_best_weights=False ) ms = ModelSaver(filepath=_restore) csv_dir = os.path.join(experiments_dir, 'csv_dir') create_if_not_exist(csv_dir) csv_dir = os.path.join(csv_dir, ae.name+'.csv') csv_log = tf.keras.callbacks.CSVLogger(csv_dir, append=True) csv_dir image_gen_dir = os.path.join(experiments_dir, 'image_gen_dir') create_if_not_exist(image_gen_dir) sg = SampleGeneration(latents_shape=latents_dim, filepath=image_gen_dir, gen_freq=5, save_img=True, gray_plot=False) ###Output _____no_output_____ ###Markdown Model Training ###Code from training.callbacks.disentangle_supervied import DisentanglementSuperviedMetrics from training.callbacks.disentangle_unsupervied import DisentanglementUnsuperviedMetrics gts_mertics = DisentanglementSuperviedMetrics( ground_truth_data=eval_dataset, representation_fn=lambda x: ae.encode(x), random_state=np.random.RandomState(0), file_Name=gts_csv, num_train=10000, num_test=100, batch_size=batch_size, continuous_factors=False, gt_freq=10 ) gtu_mertics = DisentanglementUnsuperviedMetrics( ground_truth_data=eval_dataset, representation_fn=lambda x: ae.encode(x), random_state=np.random.RandomState(0), file_Name=gtu_csv, num_train=20000, num_test=500, batch_size=batch_size, gt_freq=10 ) ae.fit( x=train_ds, input_kw=None, steps_per_epoch=int(1e4), epochs=int(1e6), verbose=2, callbacks=[ es, ms, csv_log, sg, gts_mertics, gtu_mertics], workers=-1, use_multiprocessing=True, validation_data=test_ds, validation_steps=int(1e4) ) ###Output _____no_output_____ ###Markdown Model Evaluation inception_score ###Code from evaluation.generativity_metrics.inception_metrics import inception_score is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200) print(f'inception_score mean: {is_mean}, sigma: {is_sigma}') ###Output _____no_output_____ ###Markdown Frechet_inception_distance ###Code from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32) print(f'frechet inception distance: {fis_score}') ###Output _____no_output_____ ###Markdown perceptual_path_length_score ###Code from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32) print(f'perceptual path length score: {ppl_mean_score}') ###Output _____no_output_____ ###Markdown precision score ###Code from evaluation.generativity_metrics.precision_recall import precision_score _precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200) print(f'precision score: {_precision_score}') ###Output _____no_output_____ ###Markdown recall score ###Code from evaluation.generativity_metrics.precision_recall import recall_score _recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200) print(f'recall score: {_recall_score}') ###Output _____no_output_____ ###Markdown Image Generation image reconstruction Training dataset ###Code %load_ext autoreload %autoreload 2 from training.generators.image_generation_testing import reconstruct_from_a_batch from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir') create_if_not_exist(save_dir) reconstruct_from_a_batch(ae, training_generator, save_dir) from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'reconstruct_testing_images_like_a_batch_dir') create_if_not_exist(save_dir) reconstruct_from_a_batch(ae, testing_generator, save_dir) ###Output _____no_output_____ ###Markdown with Randomness ###Code from training.generators.image_generation_testing import generate_images_like_a_batch from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir') create_if_not_exist(save_dir) generate_images_like_a_batch(ae, training_generator, save_dir) from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'generate_testing_images_like_a_batch_dir') create_if_not_exist(save_dir) generate_images_like_a_batch(ae, testing_generator, save_dir) ###Output _____no_output_____ ###Markdown Complete Randomness ###Code from training.generators.image_generation_testing import generate_images_randomly from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'random_synthetic_dir') create_if_not_exist(save_dir) generate_images_randomly(ae, save_dir) from training.generators.image_generation_testing import interpolate_a_batch from utils.data_and_files.file_utils import create_if_not_exist save_dir = os.path.join(experiments_dir, 'interpolate_dir') create_if_not_exist(save_dir) interpolate_a_batch(ae, testing_generator, save_dir) ###Output 100%|██████████| 15/15 [00:00<00:00, 19.90it/s]
Example 5.3.3.ipynb
###Markdown 5.3.3 Beta distribution and Jacobi Chaos$$ f(k;\alpha,\beta) = \frac{(1-k)^{\alpha} (1+k)^{\beta}}{2^{\alpha+\beta+1} B(\alpha+1,\beta+1)} = Beta (k, \beta+1, \alpha+1, loc =-1, scale =2)$$When $\alpha=\beta=0$, $k\sim U(-1,1)$;When $\alpha =1, \beta =3$, $$ f(k; 1, 3) = \frac{(1-k)(1+k)^3}{32 B(2,4)} = \frac{5(1-k)(1+k)^3}{8}$$[Wiki - Beta Distribution](https://en.wikipedia.org/wiki/Beta_distribution)$$ \zeta \sim Beta (k, \beta+1, \alpha+1, loc =-1, scale =2)$$[Beta in Python](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html)When $\alpha = \beta =0$, Jacobi Chaos is [Legendre-chaos](https://en.wikipedia.org/wiki/Legendre_polynomials)**Legendre Polynomial: ($\alpha = \beta = 0$)**$$\begin{align*}P_0 &= 1\\P_1 &= x\\P_2 &= \frac{1}{2}(3x^2 - 1)\\P_3 &= \frac{1}{2}(5x^3 - 3x)\\P_4 &= \frac{1}{8}(35x^4 - 30x^2 + 3)\\\cdots\end{align*}$$Corresponding Hypergeometric orthogonal polynomial$$ P_n^{(\alpha,\beta)}(x) = \frac{(\alpha+1)_n}{n!}\ _2F_1(-n,n+\alpha+\beta+1;\alpha+1;\frac{1-x}{2})$$No package for Jacobi chaos in Python ###Code k=0.1 print(beta.pdf(k,4,2,loc=-1,scale=2)) print(5*(1-k)*(1+k)**3/8) import numpy as np import numpy.polynomial.legendre as Le #$\zeta \sim U(-1,1)$, when $\alpha=\beta=0$, Jacobi=Legendre from math import factorial from scipy.stats import beta from scipy.special import gamma #gamma function from matplotlib import pyplot as plt from scipy.integrate import odeint %matplotlib notebook def Jacobi(params): ''' The first 4 (degree from 0 to 4) Meixner polynomial Follow definition on P642 ''' n = params[0] #degree a = params[1] #parameter alpha value b = params[2] #parameter beta value if n==0: return lambda u: 1 elif n==1: return lambda u: (a+1) - (a+b+2)*(1-u)/2 elif n==2: return lambda u: (a+1)*(a+2)/2 - (a+2)*(a+b+3)*(1-u)/2 + (a+b+3)*(a+b+4)*(1-u)**2/8 elif n==3: return lambda u: (a+1)*(a+2)*(a+3)/6 - (a+2)*(a+3)*(a+b+4)*(1-u)/4 + (a+3)*(a+b+4)*(a+b+5)*(1-u)**2/8 - (a+b+4)*(a+b+5)*(a+b+6)*(1-u)**3/48 else: #this actually means n=4 return lambda u: (a+1)*(a+2)*(a+3)*(a+4)/24 - (a+2)*(a+3)*(a+4)*(a+b+5)*(1-u)/12 + (a+3)*(a+4)*(a+b+5)*(a+b+6)*(1-u)**2/16 - (a+4)*(a+b+5)*(a+b+6)*(a+b+7)*(1-u)**3/48 + (a+b+5)*(a+b+6)*(a+b+7)*(a+b+8)*(1-u)**4/384 def f(params): c = params[0] a = params[1] b = params[2] if a==1 and b==1: return lambda x: x*(a+b+1) else: return lambda x: x*c def Phi(n): #define H_n coeffs = [0]*(n+1) coeffs[n] = 1 return coeffs def inner2_le(params): n = params[0] a = params[1] #store the value of alpha from beta distr b = params[2] #store the value of beta from beta distr return gamma(n+a+1)*gamma(n+b+1)/((2*n+a+b+1)*gamma(n+a+b+1)*factorial(n)) def product3_le(i,j,l,params): #compute \Phi_i*\Phi_j*\Phi_l a = params[0] b = params[1] if a==0 and b==0: return lambda x: Le.legval(x, Le.legmul(Le.legmul(Phi(i),Phi(j)),Phi(l))) else: #actually this means a=1, b=3 return lambda x: Jacobi([i]+params)(x)*Jacobi([j]+params)(x)*Jacobi([l]+params)(x) def inner3_le(P,i,j,l,params): #compute <\Phi_i\Phi_j\Phi_l> a = params[0] b = params[1] if a==0 and b==0: #Set up Gauss-Legendre quadrature, weighting function is 1 m=(P+1)**2 x, w=Le.leggauss(m) #x is point, w is the corresponding weight inner=sum([product3_le(i,j,l,params)(x[idx]) * w[idx] for idx in range(m)]) return inner/2 ##because of the weight else: nsample = 1000 rv = beta.rvs(b+1, a+1, loc=-1, scale=2, size=nsample, random_state=None) inner = np.mean(product3_le(i,j,l,params)(rv))*gamma(a+1)*gamma(b+1)/gamma(a+b+2) return inner def ode_system_le(y, t, P, params): #P indicates the highest degree a = params[0] b = params[1] dydt = np.zeros(P+1) for l in range(len(dydt)): dydt[l] = -(sum(sum(inner3_le(P,i,j,l,params)*ki_le[i]*y[j] for j in range(P+1)) for i in range(P+1)))/inner2_le((l,a,b)) return dydt #h = unif_icdf([-1,1]) #index k follows uniform distr P = 4 params = [0, 0] ki_le = [0,1]+[0]*(P-1) sol_le = odeint(ode_system_le, [1.0]+[0.0]*P, np.linspace(0,1,101), args=(P, params)) plt.figure() plt.ylim([-1.2,1.2]) plt.xlim([0,1]) x= np.linspace(0,1,101) for i in range(P+1): plt.plot(x,sol_le[:,i],label=i) plt.axhline(y=1.0, color='r', linestyle='-.',label='Deterministic') plt.legend(prop={'size': 8}) ###Output _____no_output_____ ###Markdown Error plot when $\alpha=\beta=0$$$\bar{y}_{exact}(t) = \frac{\hat{y_0}}{2t}(e^{t} - e^{-t}) \ \ \ \ \ \ \ \ \bar{y}(t) = y_0$$So $$\epsilon_{mean}(t) = \left| \frac{\bar{y}(t) - \bar{y}_{exact}(t)}{\bar{y}_{exact}(t)}\right|$$$$\sigma_{exact}(t) = \frac{1-e^{-2}}{2} \ \ \ \ \ \ \ \ \sigma(t) = a_1y_1^2 +a_2y_2^2+a_3y_3^2+a_4y_4^2$$The coefficients $(a_1, a_2, a_3, a_4)$ in $\sigma(t)$ can be obtained by code below.So$$\epsilon_{variance}(t) = \left| \frac{\sigma(t) - \sigma_{exact}(t)}{\sigma_{exact}(t)} \right|= \ldots$$ This is $\alpha=\beta=0$$\downarrow$ ###Code allcoeff_533_0 = np.zeros((5,4)) #store ki value/ column 0 stores ki when P=1; column 1 stores ki when P=2 allcoeff_533_0[1,:]=np.ones(4) y_533_0 = np.zeros((5,4)) #row 0 stores y0 for each P from 1-4; row 1 stores y1 for P from 1-4;... params = [0, 0] for i in range(4): P=i+1 ki_le = allcoeff_533_0[:,i] y_mid=odeint(ode_system_le, [1.0]+[0.0]*P, np.linspace(0,1,2), args=(P, params))[1,:] y_533_0[:,i] = y_mid.tolist()+[0]*(4-P) for i in range(9): #to compute $\bar{y}(t)$ print(beta.expect(Jacobi((i,0,0)), args=(1,1), loc=-1, scale=2, lb=None, ub=None, conditional=False)) def g(params): n = params return lambda u: (Jacobi((n,0,0))(u))**2 for i in range(1,5): print(beta.expect(g(i), args=(1, 1), loc=-1, scale=2, lb=None, ub=None, conditional=False)) ############# alpha = beta = 0 ################ mean_533_0 = y_533_0[0,:] mean_exact_533_0 = 1/2*(np.e - np.e**(-1)) error_mean_533_0 = np.abs((mean_533_0 - mean_exact_533_0)/mean_exact_533_0) sigma2_533_0=np.zeros(4) for i in range(4): sigma2_533_0[i]=1/3*y_533_0[1,i]**2+1/5*y_533_0[2,i]**2+1/7*y_533_0[3,i]**2+1/9*y_533_0[4,i]**2 sigma2_exact_533_0 = 1/2-1/2*np.e**(-2) error_var_533_0 = np.abs((sigma2_533_0-sigma2_exact_533_0)/sigma2_exact_533_0) ###Output _____no_output_____ ###Markdown Error plot when $\alpha=1,\beta=3$$$\bar{y}_{exact}(t) = \frac{5\hat{y_0}}{8}(-12e + 612 e^{-1}) \ \ \ \ \ \ \ \ \bar{y}(t) = y_0$$So $$\epsilon_{mean}(t) = \left| \frac{\bar{y}(t) - \bar{y}_{exact}(t)}{\bar{y}_{exact}(t)}\right|$$$$\sigma_{exact}(t) = 5\hat{y_0}^2e^{-2} - \frac{25}{64}\hat{y_0}^2(-12e+612e^{-1})^2 \ \ \ \ \ \ \ \ \sigma(t) = a_1y_1^2 +a_2y_2^2+a_3y_3^2+a_4y_4^2$$The coefficients $(a_1, a_2, a_3, a_4)$ in $\sigma(t)$ can be obtained by code below.So$$\epsilon_{variance}(t) = \left| \frac{\sigma(t) - \sigma_{exact}(t)}{\sigma_{exact}(t)} \right|= \ldots$$ This is $\alpha=1,\beta=3$$\downarrow$ ###Code allcoeff_533_1 = np.zeros((5,4)) #store ki value/ column 0 stores ki when P=1; column 1 stores ki when P=2 allcoeff_533_1[0,:]=1/3*np.ones(4) allcoeff_533_1[1,:]=1/3*np.ones(4) y_533_1 = np.zeros((5,4)) #row 0 stores y0 for each P from 1-4; row 1 stores y1 for P from 1-4;... params = [1, 3] for i in range(4): P=i+1 ki_le = allcoeff_533_1[:,i] y_mid=odeint(ode_system_le, [1.0]+[0.0]*P, np.linspace(0,1,2), args=(P, params))[1,:] y_533_1[:,i] = y_mid.tolist()+[0]*(4-P) y_533_1 ###Output _____no_output_____ ###Markdown `beta.expect(func, args=(a, b), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)` ###Code for i in range(9): #to compute $\bar{y}(t)$ print(beta.expect(Jacobi((i,1,3)), args=(4,2), loc=-1, scale=2, lb=None, ub=None, conditional=False)) def g(params): n = params return lambda u: (Jacobi((n,1,3))(u))**2 for i in range(1,5): print(beta.expect(g(i), args=(4, 2), loc=-1, scale=2, lb=None, ub=None, conditional=False)) ############# alpha = 1, beta = 3 ################ mean_533_1 = y_533_1[0,:] mean_exact_533_1 = 5/8*(-12*np.e +612*np.e**(-1)) error_mean_533_1 = np.abs((mean_533_1 - mean_exact_533_1)/mean_exact_533_1) sigma2_533_1=np.zeros(4) for i in range(4): sigma2_533_1[i]=8/7*y_533_1[1,i]**2+10/9*y_533_1[2,i]**2+1.0389610389610364*y_533_1[3,i]**2+0.9615384615384587*y_533_1[4,i]**2 sigma2_exact_533_1 = 5*np.e**(-2) -25/64*(-12*np.e +612*np.e**(-1))**2 error_var_533_1 = np.abs((sigma2_533_1-sigma2_exact_533_1)/sigma2_exact_533_1) print(mean_533_1) print(mean_exact_533_1) print(error_mean_533_1) print(error_var_533_1) ###Output [0.90656886 0.9902277 0.99044444 0.98238702] 120.32677253463385 [0.99246578 0.99177051 0.99176871 0.99183567] [1.0000008 1.00000001 1.00000001 1.00000002] ###Markdown The error of mean plots when $\alpha=\beta=0$ is a little different since it is close to machine epsilon??, I am using lengendre package in python since $\alpha=\beta=0$. But when $\alpha=1, \beta=3$, the error plots are so strange, I am using the lengendre functions I defined by myself ###Code plt.figure() plt.xlim([0,5]) plt.semilogy([1,2,3,4],error_mean_533_0,'-bs',label='mean,alpha=0,beta=0') plt.semilogy([1,2,3,4],error_var_533_0,'-rs',label='variance, alpha=0,beta=0') plt.semilogy([1,2,3,4],error_mean_533_1,'-.b^',label='mean, alpha=1,beta=3') plt.semilogy([1,2,3,4],error_var_533_1,'-.r^',label='variance, alpha=1,beta=3') plt.legend() ###Output _____no_output_____
notebooks/xnn_notebook_simulated_data.ipynb
###Markdown Train an XNN model This notebook shows how to implement using Keras (with TensorFlow backend) an Explainable Neural Network as described in [Explainable Neural Networks based on Additive Index Models](https://arxiv.org/pdf/1806.01933.pdf).The architecture of the network is as follows:![XNN Architecture](xnn_arch.png)[Explainable Neural Networks based on Additive Index Models](https://arxiv.org/pdf/1806.01933.pdf)And consists of three layers:(i) The projection layer (first hidden layer) using linear activation function(ii) Subnetworks, which learn a potentially nonlinear transformation of the input(iii) Combination layer calculates a weighted sum the output of the ridge functions Import packages ###Code import numpy as np import pandas as pd import shap import subprocess import sys import pydot import keras from keras import backend from keras.layers import Activation, Add, Dense, Dropout, Input, Lambda, Concatenate from keras.models import Model from keras.utils import plot_model import plotly.plotly as py import chart_studio.plotly as py import plotly.tools as tls import matplotlib.pyplot as plt from timeit import default_timer as timer import tensorflow as tf from keras import backend as K seed = 12345 np.random.seed(seed) my_init = keras.initializers.RandomUniform(seed=seed) output_label = "sim_final" out_dir = "output_sim4/" output_to_files = False def projection_initializer(shape, dtype=None): inps = shape[0] subs = shape[1] if subs > pow(inps, 2) - 1: raise ValueError("Currently we support only up to 2^features - 1 number of subnetworks.") weights = [] for i in range(subs): w = [0] * inps w[i] = 1 weights.append(w) return weights def alpha_beta(alpha, beta, X , R): """ Calculate the layerwise backpropagation function """ positive_values = [item for item in X if item > 0] negative_values = [item for item in X if item < 0] ans = np.array([0.0]*len(X)) if len(positive_values) > 0: ans += alpha*np.array([item / float(sum(positive_values)) if item > 0 else 0 for item in X]) if len(negative_values) > 0: ans += -beta * np.array([item / float(sum(negative_values)) if item < 0 else 0 for item in X]) return ans*R def deep_lift(X_bar, X , R): """ Deep lift backpropagation function""" ans = np.array(X) - np.array(X_bar) ans = ans / (sum(X) - sum(X_bar)) return ans*R ###Output _____no_output_____ ###Markdown XNN Class ###Code class XNN: # define base model def __init__(self, features, ridge_functions=3, arch=[20,12], bg_samples=100, seed=None, is_categorical=False): self.seed = seed self.bg_samples = bg_samples self.is_categorical = is_categorical # # Prepare model architecture # # Input to the network, our observation containing all the features input = Input(shape=(features,), name='main_input') # Input to ridge function number i is the dot product of our original input vector times coefficients ridge_input = Dense(ridge_functions, name="projection_layer", activation='linear')(input) self.ridge_networks = [] # Each subnetwork uses only 1 neuron from the projection layer as input so we need to split it ridge_inputs = Lambda( lambda x: tf.split(x, ridge_functions, 1), name='lambda_1' )(ridge_input) for i, ridge_input in enumerate(ridge_inputs): # Generate subnetwork i mlp = self._mlp(ridge_input, i, arch) self.ridge_networks.append(mlp) added = Concatenate(name='concatenate_1')(self.ridge_networks) # Add the correct output layer for the problem if self.is_categorical: out = Dense(1, activation='sigmoid', input_shape= (ridge_functions, ), name='main_output')(added) else: out = Dense(1, activation='linear', input_shape= (ridge_functions, ), name='main_output')(added) self.model = Model(inputs=input, outputs=out) optimizer = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, decay=0.0, amsgrad=True) # Use the correct loss for the problem if self.is_categorical: self.model.compile(loss={'main_output': 'binary_crossentropy'}, optimizer=optimizer) else: self.model.compile(loss={'main_output': 'mean_squared_error'}, optimizer=optimizer) self.explainer = None def _mlp(self, input, idx, arch=[20,12], activation='relu'): if len(arch) < 1: return #raise exception # Hidden layers mlp = Dense(arch[0], activation=activation, name='mlp_{}_dense_0'.format(idx), kernel_initializer=my_init)(input) for i, layer in enumerate(arch[1:]): mlp = Dense(layer, activation=activation, name='mlp_{}_dense_{}'.format(idx, i+1), kernel_initializer=my_init)(mlp) # Output of the MLP mlp = Dense(1, activation='linear', name='mlp_{}_dense_last'.format(idx), kernel_regularizer=keras.regularizers.l1(1e-3), kernel_initializer=my_init)(mlp) return mlp def print_architecture(self): self.model.summary() def fit(self, X, y, epochs=5, batch_size=128, validation_set=0.0, verbose=0): inputs = {'main_input': X} if validation_set == 0: self.model.fit(inputs, y, epochs=epochs, batch_size=batch_size, validation_split=validation_set, verbose=verbose) else: self.model.fit(inputs, y, epochs=epochs, batch_size=batch_size, validation_data=validation_set, verbose=verbose) # # Prepare the explainer # np.random.seed(self.seed) if isinstance(X, pd.DataFrame): background = X.iloc[np.random.choice(X.shape[0], self.bg_samples, replace=False)] else: background = X[np.random.choice(X.shape[0], self.bg_samples, replace=False)] # Explain predictions of the model on the subset self.explainer = shap.DeepExplainer(self.model, background) def predict(self, X, pred_contribs=False): pred_start = timer() preds = self.model.predict(X) pred_end = timer() print("Predictions took {}".format(pred_end - pred_start)) if pred_contribs: explainer_start = timer() self.shap_values = self.explainer.shap_values(X) explainer_end = timer() print("Explainer took {}".format(explainer_end - explainer_start)) concat_start = timer() preds = np.concatenate((preds, self.shap_values[0], preds), axis=1) preds[:,-1] = self.explainer.expected_value concat_end = timer() print("Concat took {}".format(concat_end - concat_start)) return preds def plot_shap(self, X): shap.summary_plot(self.shap_values, X) def save(self, filename): self.model.save(filename) ###Output _____no_output_____ ###Markdown Load dataset ###Code # Load the dataset xnn_data_dir = '~/article-information-2019/data/xnn_output/' #xnn_data_dir = '' DATA=pd.read_csv(xnn_data_dir + 'train_simulated_transformed.csv') print(list(DATA.columns)) TEST=pd.read_csv(xnn_data_dir + 'test_simulated_transformed.csv') print(list(TEST.columns)) selected_vars = ['binary1', 'binary2', 'cat1_0', 'cat1_1', 'cat1_2', 'cat1_3', 'cat1_4', 'fried1_std', 'fried2_std', 'fried3_std', 'fried4_std', 'fried5_std'] target_var = 'outcome' X=DATA[selected_vars].values Y=DATA[target_var].values TEST_X = TEST[selected_vars].values TEST_Y = TEST[target_var].values features = X.shape[1] DATA.columns ###Output _____no_output_____ ###Markdown Fit XNN ###Code # Initialize the XNN is_cat = True xnn = XNN(features=features, ridge_functions=features, arch=[8, 6], is_categorical= is_cat) # plot_model(xnn.model, to_file='model_regression.png') xnn.print_architecture() cv_test_preds = {} cv_train_preds = {} epoch = [] fold_list = list(set(DATA['cv_fold'])) epochs_max = 20000 # Make predictions on the CV folds for cv_fold in fold_list: TRAIN = DATA[DATA['cv_fold'] != cv_fold] VALID = DATA[DATA['cv_fold'] == cv_fold] X = TRAIN[selected_vars].values Y = TRAIN[target_var].values X_VALID = VALID[selected_vars].values Y_VALID = VALID[target_var].values xnn.fit(X, Y, epochs=epochs_max, batch_size=1024, validation_set=(X_VALID, Y_VALID), verbose=1) if output_to_files: xnn.save(out_dir + 'cv_' + str(cv_fold) + '_hmda_model.h5') # CV predictions cv_test_preds[cv_fold] = xnn.predict(TEST_X, pred_contribs=True) cv_train_preds[cv_fold] = xnn.predict(X_VALID, pred_contribs=True) if output_to_files: pd.DataFrame(pd.concat([TEST, pd.DataFrame(cv_test_preds[cv_fold])], axis=1)).to_csv(out_dir + "test_output_" + str(cv_fold) + "_" + str(epochs_max) + "_" + output_label +".csv" , index=False) pd.DataFrame(pd.concat([VALID, pd.DataFrame(cv_train_preds[cv_fold])], axis=1)).to_csv(out_dir + "valid_output_" + str(cv_fold) + "_" + str(epochs_max) + "_" + output_label + ".csv" , index=False) # Run the model on the full training set and make predictions on the test set X=DATA[selected_vars].values Y=DATA[target_var].values xnn.fit(X, Y, epochs=epochs_max, batch_size=1024, validation_set=0, verbose=1) test_preds = xnn.predict(TEST_X, pred_contribs=True) if output_to_files: pd.DataFrame(pd.concat([TEST, pd.DataFrame(test_preds)], axis=1)).to_csv(out_dir + "main_" + str(epochs_max) + "_" + output_label + ".csv" , index=False) xnn.save(out_dir + 'final_sim_model.h5') ###Output _____no_output_____ ###Markdown Record layer information Plot projection layer ###Code # Record the inputs, outputs, weights, and biases import scipy as sp int_output = {} int_output2 = {} int_weights = {} int_bias = {} int_input = {} original_activations = {} x_labels = list(map(lambda x: 'x' + str(x+1), range(features))) intermediate_output = [] # Record and plot the projection weights # weight_list = [] for layer in xnn.model.layers: layer_name = layer.get_config()['name'] if layer_name != "main_input": print(layer_name) weights = layer.get_weights() # Record the biases try: bias = layer.get_weights()[1] int_bias[layer_name] = bias except: print("No Bias") # Record outputs for the test set intermediate_layer_model = Model(inputs=xnn.model.input, outputs=xnn.model.get_layer(layer_name).output) if (is_cat) and (layer_name == 'main_output'): int_output[layer_name] = sp.special.logit(intermediate_layer_model.predict(TEST_X)) int_output[layer_name + "_p"] = intermediate_layer_model.predict(TEST_X) else: int_output[layer_name] = intermediate_layer_model.predict(TEST_X) # Record the outputs from the training set if is_cat and (layer_name == 'main_output'): original_activations[layer_name] = sp.special.logit(intermediate_layer_model.predict(X)) original_activations[layer_name + "_p"] = intermediate_layer_model.predict(X) else: original_activations[layer_name] = intermediate_layer_model.predict(X) # Record other weights, inputs, and outputs int_weights[layer_name] = weights int_input[layer_name] = layer.input int_output2[layer_name] = layer.output # Plot the projection layers if "projection_layer" in layer.get_config()['name']: print(layer.get_config()['name']) # Record the weights for each projection layer weights = [np.transpose(layer.get_weights()[0])] weight_list2=[] for i, weight in enumerate(weights[0]): weight_list.append(weight) weight_list2.append(list(np.reshape(weight, (1,features))[0])) # Plot weights plt.bar(x_labels, abs(np.reshape(weight, (1,features))[0]), 1, color="blue") plt.xlabel("Subnetowork {} coefficient".format(i)) plt.ylabel("Weight value") plt.show() if "main_output" in layer.get_config()['name']: weights_main = layer.get_weights() print(weights_main) if output_to_files: pd.DataFrame(weight_list2).to_csv("wp_" + output_label + ".csv", index=False) ###Output _____no_output_____ ###Markdown Calculate the feature importances ###Code # Calculate ridge and input function local feature importances item = 0 feature_output = [] feature_output2 = [] feature_output3 = [] # Find the average outputs S_bar = sum(original_activations["main_output"])/len(original_activations["main_output"]) # original_activations[layer_name] output_weights = np.array([int_weights["main_output"][0][ii][0] for ii in range(features)]) output_Z_bar = sum(original_activations["concatenate_1"]*output_weights)/len(original_activations["concatenate_1"]) # For each ridge function calculate the average input activation input_Z_bar = {} for ridge_num in range(features): input_weights = np.array([int_weights["projection_layer"][0][ii][ridge_num] for ii in range(features)]) input_Z_bar[ridge_num] = sum(X*input_weights)/len(X) # For each test instance, calculate the feature importance scores for test_num in range(len(TEST_X)): # Calculate the output activations activation_list=[int_weights["main_output"][0][ii][0]*int_output["concatenate_1"][test_num][ii] for ii in range(features)] # Calculate layerwise backpropagaiton to the ridge functions # For classification, change this to the inverse sigmoid of the output features_ab = alpha_beta(2, 1, activation_list , int_output["main_output"][test_num][0]) features_ab2 = alpha_beta(2, 1, activation_list , int_output["main_output"][test_num][0]-S_bar) # Calculate deep lift backpropagation to the ridge functions features_dl = deep_lift(output_Z_bar, activation_list , int_output["main_output"][test_num][0]-S_bar) # Calculate the deep lift and layerwise information scores for the input layer input_scores = [] input_scores_dl = [] input_scores2 = [] input_scores_dl2 = [] for ridge_num in range(features): weights = int_weights["projection_layer"][0][ridge_num] output = TEST_X[test_num,:] # [int_weights["projection_layer"][0][ii][0] for ii in range(features)] # Calculate the activations from the projection layer act = TEST_X[test_num,:]*np.array([int_weights["projection_layer"][0][ii][ridge_num] for ii in range(features)]) # Input relevance scores for a single ridge function input_scores += list(alpha_beta(2,1, act, features_ab[ridge_num])) input_scores_dl += list(deep_lift(input_Z_bar[ridge_num], act, features_dl[ridge_num])) input_scores2 += list(alpha_beta(2,1, act, features_ab2[ridge_num])) # print(sum(TEST_X[0,:]*np.array([int_weights["projection_layer"][0][ii][0] for ii in range(features)]))+int_bias["projection_layer"][0]) # Sum the contribution of the variable importance from each of the projections input_sum = [sum(input_scores[ii+features*jj] for jj in range(features)) for ii in range(features)] input_sum2 = [sum(input_scores2[ii+features*jj] for jj in range(features)) for ii in range(features)] input_sum_dl = [sum(input_scores_dl[ii+features*jj] for jj in range(features)) for ii in range(features)] input_abs_sum = [sum(abs(input_scores[ii+features*jj]) for jj in range(features)) for ii in range(features)] # Recored the feature importance information for this instance feature_output.append(input_sum+input_abs_sum+[int_output["main_output"][test_num][0]]+list(features_ab)+input_scores) feature_output2.append(input_sum+list(features_ab)+input_sum_dl + list(features_dl)) feature_output3.append(input_sum2+list(features_ab2)+input_sum_dl + list(features_dl)) ###Output _____no_output_____ ###Markdown Find and plot the ridge functions ###Code intermediate_output = [] for feature_num in range(features): intermediate_layer_model = Model(inputs=xnn.model.input, outputs=xnn.model.get_layer('mlp_'+str(feature_num)+'_dense_last').output) intermediate_output.append(intermediate_layer_model.predict(X)) # Record and plot the ridge functions ridge_x = [] ridge_y = [] for weight_number in range(len(weight_list)): ridge_x.append(list(sum(X[:, ii]*weight_list[weight_number][ii] for ii in range(features)))) ridge_y.append(list(intermediate_output[weight_number])) plt.plot(sum(X[:, ii]*weight_list[weight_number][ii] for ii in range(features)), intermediate_output[weight_number], 'o') plt.xlabel("x") plt.ylabel("Subnetwork " + str(weight_number)) plt.legend(loc='lower right') plt.show() if output_to_files: pd.DataFrame(ridge_x).to_csv("ridge_x_"+ output_label +".csv", index=False) pd.DataFrame(ridge_y).to_csv("ridge_y_" + output_label + ".csv", index=False) pd.DataFrame(feature_output2).to_csv("feature_output2_" + output_label + ".csv", index=False) pd.DataFrame(feature_output3).to_csv("feature_output3_" + output_label + ".csv", index=False) # Make predictions on the test set preds = xnn.predict(TEST_X, pred_contribs=True) if output_to_files: pd.DataFrame(preds).to_csv("preds_" + output_label + ".csv", index=False) pd.DataFrame(TEST).to_csv("TEST_" + output_label + ".csv", index=False) # Calculate the Shapley values. shap.initjs() shap.summary_plot(xnn.shap_values, X) y=xnn.shap_values ind=1 # Calculate the average absolute feature importance across the dataset layerwise_average_input=np.array([0.0]*features) layerwise_average_input2=np.array([0.0]*features) layerwise_average_ridge=np.array([0.0]*features) layerwise_average_ridge2=np.array([0.0]*features) layerwise_average_shap=np.array([0.0]*features) lift_average_input=np.array([0.0]*features) lift_average_ridge=np.array([0.0]*features) for ii in range(len(feature_output2)): layerwise_average_input += np.abs(np.array(feature_output2[ii][0:features]))) layerwise_average_ridge += np.abs(np.array(feature_output2[ii][features:(2*features)])) layerwise_average_input2 += np.abs(np.array(feature_output3[ii][0:features])) layerwise_average_ridge2 += np.abs(np.array(feature_output3[ii][features:(2*features)])) lift_average_input += np.abs(np.array(feature_output2[ii][(2*features):(3*features)])) lift_average_ridge += np.abs(np.array(feature_output2[ii][(3*features):(4*features)])) layerwise_average_shap += np.abs(np.array(y[0][ii])) layerwise_average_input = layerwise_average_input/len(feature_output2) layerwise_average_ridge = layerwise_average_ridge/len(feature_output2) layerwise_average_input2 = layerwise_average_input2/len(feature_output2) layerwise_average_ridge2 = layerwise_average_ridge2/len(feature_output2) layerwise_average_shap = layerwise_average_shap/len(feature_output2) lift_average_input = lift_average_input/len(feature_output2) lift_average_ridge = lift_average_ridge/len(feature_output2) SCORES = [list(layerwise_average_input), list(layerwise_average_ridge), list(layerwise_average_input2), list(layerwise_average_ridge2), list(layerwise_average_shap), list(lift_average_input), list(lift_average_ridge)] if output_to_files: pd.DataFrame(SCORES).to_csv("scores_" + output_label + ".csv", index=False) ###Output _____no_output_____ ###Markdown Plot feature importance scores ###Code plt.bar(x, abs(np.reshape(y[0][ind], (1,features))[0]), 1, color="blue") plt.xlabel("Shap Score Example " + str(ind)) plt.ylabel("") plt.show() plt.bar(x, abs(np.reshape(feature_output2[ind][0:features], (1,features))[0]), 1, color="blue") plt.xlabel("Input Layerwise Propagation Score Example " + str(ind)) plt.ylabel("") plt.show() plt.bar(x, abs(np.reshape(feature_output2[ind][features:(2*features)], (1,features))[0]), 1, color="blue") plt.xlabel("Ridge Layerwise Propagation Score Example " + str(ind)) plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(feature_output2[ind][2*features:(3*features)], (1,features))[0]), 1, color="blue") plt.xlabel("Deep Lift Input Score Example " + str(ind)) plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(feature_output2[ind][3*features:(4*features)], (1,features))[0]), 1, color="blue") plt.xlabel("Deep Lift Ridge Score Example " + str(ind)) plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(layerwise_average_input, (1,features))[0]), 1, color="blue") plt.xlabel("Input Layerwise Propagation Score Average") plt.ylabel("") plt.show() plt.bar(x, abs(np.reshape(layerwise_average_ridge, (1,features))[0]), 1, color="blue") plt.xlabel("Ridge Layerwise Propagation Score Average") plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(layerwise_average_input2, (1,features))[0]), 1, color="blue") plt.xlabel("Input Layerwise Propagation Score Average 2") plt.ylabel("") plt.show() plt.bar(x, abs(np.reshape(layerwise_average_ridge2, (1,features))[0]), 1, color="blue") plt.xlabel("Ridge Layerwise Propagation Score Average 2") plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(lift_average_input, (1,features))[0]), 1, color="blue") plt.xlabel("Input Lift Score Average") plt.ylabel("") plt.show() plt.bar(x, abs(np.reshape(lift_average_ridge, (1,features))[0]), 1, color="blue") plt.xlabel("Ridge Lift Score Average") plt.ylabel("Weight value") plt.show() plt.bar(x, abs(np.reshape(layerwise_average_shap, (1,features))[0]), 1, color="blue") plt.xlabel("Shapley Score Average") plt.ylabel("Weight value") plt.show() ###Output _____no_output_____
Runge-kutta-mv .ipynb
###Markdown Create a notebook to perform Runge-Kutta integration for multiple coupled variables ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Define our coupled derivatives to integrate ###Code def dydx(x,y): #set the derivatives #our equation is d^2y/dx^2 = y #so we can wirte #dy/dx= z #dz/dx = -y #we will set y = y[0] #we will set z = y[1] #declare an array y_derivs = np.zeros(2) y_derivs[0] = y[1] y_derive[1] = -1*y[0] return y_derivs ###Output _____no_output_____ ###Markdown Define the 4th order Rk method ###Code def rk4_mv_core(dydx,xi,yi,h): #declare k arrays k1 = np.zeros(nv) k2 = np.zeros(nv) k3 = np.zeros(nv) k4 = np.zeros(nv) #define xat 1/2 step x_ipoh = xi + 0.5*h #define x at 1 step x_ipo = xi+h #declare a temp y array y_temp = np.zeros(nv) #get k1 values y_derivs = dxdy(xi,yi) k1 = h*yderivs[:] #get k2 values y_temp[:] = yi[:]+0.5*k1[:] y_derivs = dydx(x_ipoh, y_temp) k2[:] = h*y_derives[:] #get k3 values y_temp[:] = yi[:]+0.5*k2[:] y_derivs = dydx(x_ipoh, y_temp) k3[:] = h*y_derives[:] #get k4 values y_temp[:] = yi[:]+0.5*k3[:] y_derivs = dydx(x_ipoh, y_temp) k4[:] = h*y_derives[:] #advance y by a step h yipo = yi + (k1+2*k2 + 2*k3 + k4)/6 return yipo def rk4_mv_ad(dydx,x_i,y_i,nv,h,tol): #define safety scale SAFETY = 0.9 H_NEW_FAC = 2.0 #set a maximum number of iteration imax = 10000 #set an iteration variable i = 0 #create an error Delta = np.full(nv,2*tol) #remember the step h_step = h #adjust step while(Delta.max()/tol > 1.0): #estimate our error by taking one step of size h #vs two steps of size h/2 y_2 = rk4_mv_core(dydx,x_i, y_i,nv,h_step) y_1 = rk4_mv_core(dydx,x_i,y_i, nv,0.5*h_step) y_11 = rk4_mv_core(dydx,x_i+0.5*h_step,y_1,nv,0.5*h_step) #compute an error Delta = np.fabs(y_2-y_11) #if the error is too large, take a smaller step if(Delta.max()/tol>1.0): #our error is too large, decrease the step h_step *= SAFETY * (Delta.max()/tol)**(-0.25) #check iteration if(i>imax): print('too many iterations in rk4_mv_ad()') raise StopIteration('ending after i = ',i) #iterate i += 1 #next time, try to take a bigger step h_new = np.fmin(h_step * (delta.max()/tol)**(-0.9), h_step*H_NEW_FAC) #return the answer, a new step, and the stp we actually took return y_2, h_new, h_step ###Output _____no_output_____ ###Markdown Define a wrapper for RK4 ###Code def rk4_mv(dfdx,a,b,y_a,tol): #dfdx is the derivative wrt x #a is the lower bound #b is the upper bound #y_a are the boundary conditions #tol is the tolerance for integrating y #define our starting step xi = a yi = y_a.copy() #an initial step size == make very small h = 1.0e-4 * (b-a) #set a maximum number of iterations imax = 10000 #set a iteration variable i = 0 #set the number of coupled odes to the #size of y_a nv = len(y_a) #set the initial conditions x = np.full(1,a) y = np.ful((1,nv),y_a) #set a flag flag = 1 #loop unitl we reach the right side while(flag): #calculate y_i+1 yi_new, h_new, h_step = rk4_mv_ad(dydx,xi,yi,nv,h,tol) #update the step h = h_new #prevent an overshoot if(xi+h_step>b): #take a smaller step h = b-xi #recalculate y_i+1 yi_new, h_new, h_step = rk4_mv_ad(dydx,xi, yi,nv,h,tol) #break flag = 0 ###Output _____no_output_____
docs/session_4/02_calculate_ndvi_part_1.ipynb
###Markdown Calculating NDVI: Part 1This exercise follows on from the previous section. In the [final exercise of the previous session](../session_3/03_geomedian_exercise.ipynb), you constructed a notebook to create geomedian composite.In this section, we will create a new notebook based on the notebook from the previous section. Most of the code will remain unchanged, but we will change the area of interest and time extent. We will also add steps to resample the new dataset and create a geomedian. In the next section, we will calculate and plot NDVI. ###Code .. note:: We will be using the notebook we created in the previous section, `Create a geomedian composite <../session_3/03_geomedian_exercise.ipynb>`_. If you have not already set up a copy of the notebook called ``Geomedian_composite.ipynb`` with the required packages and functions, follow the instructions in previous section. Ensure you have completed all the steps, including loading the Sentinel-2 dataset. ###Output _____no_output_____ ###Markdown Set up notebook Create a copy of the notebookBefore you continue with the next step,1. Log in to the Sandbox and open the **Training** folder.2. Make a copy of the `Geomedian_composite.ipynb` notebook.3. Rename the notebook to `Calculate_ndvi.ipynb`.See [create a copy of a notebook and rename it](https://training.digitalearthafrica.org/en/latest/session_1/04_running_a_notebook.htmlCreate-a-copy-of-the-notebook) for more details. Clearing the notebookWe will need to remove any output from previous runs of the notebook.1. Select **Kernel -> Restart Kernel and Clear All Outputs…**.2. When prompted, select **Restart**. Running the notebookThis notebook is still set up to run the Session 3 exercise, so you will need to follow the instructions below to modify it. Work cell by cell and pay attention to what needs to be changed. Set-up1. Run the first cell, which contains the packages and functions for the analysis. No need to change anything here.2. For the `dc = datacube.Datacube` command, change the app name to `"Calculate_ndvi"`. It should look like: ``` dc = datacube.Datacube(app="Calculate_ndvi") ``` Load the data1. Change the x and y values to those shown below and run the cell. ``` x=(-6.1495, -6.1380) y=(13.9182, 13.9111) ```2. Change the time in the `load_ard` function to `("2019-01", "2019-12")`.3. Remove the option `min_gooddata=0.7`. If you completed steps 2, 3 and 4, your load cell should look like ``` sentinel_2_ds = load_ard( dc=dc, products=["s2_l2a"], x=x, y=y, time=("2019-01", "2019-12"), output_crs="EPSG:6933", measurements=['red', 'green', 'blue'], resolution=(-10, 10), group_by='solar_day') ``` 4. Run the cell. The load should return 71 time steps. Plot timestepsThe fifth cell of the notebook contains an `rgb` command to plot the loaded data. To match our example below, modify this cell so that it matches the code below:```timesteps = [1, 6, 8]rgb(sentinel_2_ds, bands=['red', 'green', 'blue'], index=timesteps)```This will plot images for the 1st, 6th and 8th timestep of the loaded data (remember that Python starts counting at 0). Your image should match the one below. ###Code .. note:: You may also like to run this cell a few times, experimenting with different values for the ``timesteps`` parameter. The load command should have returned 71 time steps, meaning the values in your ``timesteps`` list can be anywhere from ``0`` to ``70``. ###Output _____no_output_____ ###Markdown Resampling the datasetResampling is used to create a new set of times at regular intervals. Using the resample method, the data can be arranged in days, months, quarterly (three months) or yearly. Below gives examples of how the data are grouped. * `'nD'` - number of days (e.g. `'7D'` for seven days) * `'nM'` - number of months (e.g. `'6M'` for six months) * `'nY'` - number of years (e.g. `'2Y'` for two years) Follow the steps below to resample the dataset time steps to quarterly.1. Delete the code for plotting all RGB images: ``` rgb(sentinel_2_ds, bands=['red', 'green', 'blue'], col='time', size=4) ``` 2. In the cleared cell, write the following code to resample the data and store it in the `resample_sentinel_2_ds` variable: ``` resample_sentinel_2_ds = sentinel_2_ds.resample(time='3MS') ``` `resample_sentinel_2_ds` describes how to group the data into quarterly segments. We can now use this to calculate the geomedian for each quarterly segment. ###Code .. note:: ``S`` at the end of ``'3MS'`` is to group the data by start of the month. ###Output _____no_output_____
labs/.ipynb_checkpoints/lab1-checkpoint.ipynb
###Markdown Lab 1When reporting probabilities in a scientific context, the standard is to convert this probabilty into a sigma value, which represents the probabilty of the data To convert sigma values back to a probabilty, some convoluted integration is required. Luckily, python has these capabilites built in. The *erfc* function is one of several scipy functions which returns a probabilty given an input sigma value. ###Code for x in range(1, 6): print(sp.special.erfc(x)) ###Output 0.15729920705028516 0.004677734981047266 2.2090496998585445e-05 1.541725790028002e-08 1.5374597944280347e-12 ###Markdown Here we can see that *erfc* values roughly match up with the negative 1, 2, 3, and 4 sigma values on a z table (or the positive values subtracted from 1), giving us the probabilty that our target event happened outside of our measured sigma value. As previously mentioned, the accepted standard is to convert this probabilty into a sigma value, but a probabilty can also be converted back into a sigma, as is shown below. ###Code sp.stats.norm.ppf(3e-7) ###Output _____no_output_____ ###Markdown Here we see the sigma value reported as a negative number. This is probably due to the fact that the built in function uses the left side of the normal distribution to find the associated sigma value as this would come up first when searching from negative to positive. Rayleigh Distribution A Rayliegh distribution is distinct in that it is not identical on each side of its peak. Applications of Rayleigh distributions are most common in places where long-lived or large events are less common than those of shorter length. Examples are wave height or product lifespan. Let's create a sample set of data with built-in Python functions. ###Code #def prob_graph(loc, scale, xleft, xright, size) d = sp.stats.rayleigh.rvs(loc = 2.0, scale = 1, size = 100000) xleft = 1.95 xright = 7 fig, ax = plt.subplots(1, 1) ax.hist(d,50, density=True) plt.tick_params(labelsize = 20) plt.xlim(xleft, xright) x = np.linspace(xleft,xright,1000) ax.plot(x, sp.stats.rayleigh.pdf(x,loc = 2, scale = 1),linewidth = 7,alpha = 0.6) plt.show() ###Output _____no_output_____ ###Markdown Looks pretty good! The 100,000 sample size seems to have created a pretty accurate distrobution. However, towards the top end (~X = 6), we can't really tell what is going on. The height of the distribution is controlled by the 'scale' factor in the pdf, with a higher scale representing a wider and shorter distribution. Plotting our data on a semilog graph reveals some interesting secrets. ###Code #def prob_graph(loc, scale, xleft, xright, size) d = sp.stats.rayleigh.rvs(loc = 2.0, scale = 1, size = 100000) xleft = 1.95 xright = 7 fig, ax = plt.subplots(1, 1) ax.set_yscale('log') ax.hist(d,50, density=True) plt.tick_params(labelsize = 20) plt.xlim([xleft, xright]) x = np.linspace(xleft,xright,1000) ax.plot(x,sp.stats.rayleigh.pdf(x,loc = 2, scale = 1),linewidth = 7,alpha = 0.6) plt.show() ###Output _____no_output_____ ###Markdown Even with the large sample size, there is a suprisingly large amount of innacuracy towards the tail of the distribution. The theoretical data above could represent the lifetime of a company's product in years. If a similar, slightly redesigned product has a lifespan of 4.5 years, what is the chance that this is not an improvement over our original product? ###Code sp.stats.rayleigh.cdf(4.5) sp.stats.norm.ppf(0.999959934702607) ###Output _____no_output_____ ###Markdown This comes out to be a sigma value of 3.94, which while very significant, would not be accepted by the scientific community in a physics-related context. Binomial Distribution ###Code fig, ax = plt.subplots(1,1) n, p = 100, .45 m, v, s, k = sp.stats.binom.stats(n, p, moments="mvsk") x = np.arange(sp.stats.binom.ppf(0.01, n, p), sp.stats.binom.ppf(0.99, n, p)) plt.xlim(30, 60) ax.plot(x, sp.stats.binom.pmf(x, n, p), 'o') ax.vlines(x, 0, sp.stats.binom.pmf(x, n, p)) fig, ax = plt.subplots(1,1) n, p = 100, .45 m, v, s, k = sp.stats.binom.stats(n, p, moments="mvsk") x = np.arange(sp.stats.binom.ppf(0.01, n, p), sp.stats.binom.ppf(0.99, n, p)) plt.xlim(30, 60) ax.plot(x, sp.stats.binom.pmf(x, n, p), 'o') ax.set_yscale('log') ax.vlines(x, 0, sp.stats.binom.pmf(x, n, p)) ###Output _____no_output_____ ###Markdown In a semilog plot, the distribution takes on the shape of a slightly skewed parabola, looking very similar to, but slightly different from a Gaussian curve. Using the distrubition above, let's assume we flip a coin that is slightly biased to one side. We'd assume most outcomes would land around 45 on one side to 55 on the other, which is reflected in the graph. One difference in comparison to our previous question, which dealt with a continuous probabilty, is that our probabilty only takes on integer values, which makes the binomial distribution good for counting events if we know the general probability that it should happen. Unlike individual data points, statistics about the binomial distribution don't have to necessarily be an integer value. If the average family has 1.9 kids, that clearly does not mean that any familiy has that exact value. So what happens if we get 60 heads on a second coin with unknown properties? Could it be the same type of coin? ###Code sp.stats.binom.cdf(60, n, p) sp.stats.norm.ppf(0.9990617681011207) ###Output _____no_output_____
notebooks/employee-attrition.ipynb
###Markdown Data Science pipeline in action to solve employee attrition problem This code pattern is a high level overview of what to expect in a data science pipeline and tools that can be used along the way. It starts from framing business question to deploying the model. The pipeline is demonstrated through the employee attrition problem. Employees are the backbone of the organization. Organization's performance is heavily based on the quality of the employees. Challenges that an organization has to face due employee attrition are:1. Expensive in terms of both money and time to train new employees.2. Loss of experienced employees3. Impact in productivity4. Impact profitBefore getting our hands dirty with the data, first step is to frame the business question. Having clarity on below questions is very crucial because the solution that is being developed will make sense only if we have well stated problem.“Good data science is more about the questions you pose of the data rather than data munging and analysis” — Riley Newman Business questions to brainstorm:1. What factors are contributing more to employee attrition?2. What type of measures should the company take in order to retain their employees?3. What business value does the model bring?4. Will the model save lots of money?5. Which business unit faces the attrition problem? Data Science Process Pipeline Above image explains the steps involved in solving a data science problem. It starts from data extraction to result interpretation. Once the model produces acceptable performance, it can be deployed in real-time. Let's solve employee attrition problem... ###Code !pip install pygal !pip install cufflinks !pip install aif360 #import all required libraries #Data Analysis import pandas as pd import numpy as np import json #Visulaization libraries from bokeh.plotting import figure, show, output_file from bokeh.io import output_notebook from bokeh.models import ColumnDataSource, LabelSet from bokeh.palettes import Viridis5 import seaborn as sns import matplotlib.pyplot as plt import pygal import cufflinks as cf from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot #model developemnt libraries from sklearn import preprocessing from sklearn.ensemble import AdaBoostClassifier from sklearn import metrics from sklearn.pipeline import Pipeline from sklearn.feature_selection import mutual_info_classif from sklearn.feature_selection import chi2 from sklearn.cross_validation import train_test_split from sklearn.metrics import classification_report #Bias Mitigation libraries from aif360.metrics import BinaryLabelDatasetMetric from aif360.datasets import BinaryLabelDataset from IPython.display import Markdown, display from aif360.algorithms.preprocessing.reweighing import Reweighing # from IPython.display import SVG, display import warnings warnings.filterwarnings("ignore") #deployment library from watson_machine_learning_client import WatsonMachineLearningAPIClient ###Output _____no_output_____ ###Markdown 1. Data Collection - Source: Kaggle- Data: IBM HR Analytics dataset (synthetically generated) https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset/home- License: * Database: https://opendatacommons.org/licenses/odbl/1.0/ * Contents: https://opendatacommons.org/licenses/dbcl/1.0/ Rule of thumb* Know all the available dataset for the problem (database/ internet/ third party etc) . Dataset must be reliable and authentic.* Extract data in a format that can be used* Required Skills for data extraction in general(mostly used and not specific to the pattern): - Distributed Storage: Hadoop, Apache Spark. - Database Management: MySQL, PostgresSQL, MongoDB. - Know to querying Relational Databases and retrieve unstructured Data like text, videos, audio files, documents. Download dataset ###Code !wget https://github.com/IBM/employee-attrition-aif360/raw/master/data/emp_attrition.csv --output-document=emp_attrition.csv #Reading csv file in pandas dataframe format. df_data = pd.read_csv('emp_attrition.csv') df_data.head() #Get list of columns in the dataset df_data.columns #Dropping columns (intution) columns = ['DailyRate', 'EducationField', 'EmployeeCount', 'EmployeeNumber', 'HourlyRate', 'MonthlyRate', 'Over18', 'RelationshipSatisfaction', 'StandardHours'] df_data.drop(columns, inplace=True, axis=1) ###Output _____no_output_____ ###Markdown 1.1 Get description of data Generates descriptive statistics that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.Reference link: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html ###Code #This will give description only for numeric fields df_data.describe() #To get description of all columns df_data.describe(include = 'all') ###Output _____no_output_____ ###Markdown 2. Data Cleaning This phase is the most time consuming yet the most importat one. Here, we filter and extract only the information that is needed for problem solving. Quality of the model is highly dependant on the quality of the data that is given as an input. * Understand meaning of every feature and identify errors.* Look for any missing values and find a way to fill the missing values.* Remove duplicate or corrupted records.* Scaling and normalization of data.* Character encoding (string to numerical representation).* Handle inconsistent entry.* Use tools like pandas(python), dplyr(R), numpy. 2.1 Handling missing values ###Code #Find number of missing values in every feature df_data.isnull().sum() ###Output _____no_output_____ ###Markdown Looks like the best dataset!!! No null values :-) But what if we have null values ???? Let's see what we can do in that case.* Find why that data is missing. Human error or missed during extraction* Drop missing values. * Some ways for filling missing values: - Zero - Mean ( works with normal distribution ) - Random values from same distribution ( works well with equal distribution ) - Value after missing value (make sense if data set has some logical order) 2.2 Encode categorical features(in string) as most of the tools works with numbers ###Code #Columns with string values categorical_column = ['Attrition', 'BusinessTravel', 'Department', 'Gender', 'JobRole', 'MaritalStatus', 'OverTime'] #Deep copy the original data data_encoded = df_data.copy(deep=True) #Use Scikit-learn label encoding to encode character data lab_enc = preprocessing.LabelEncoder() for col in categorical_column: data_encoded[col] = lab_enc.fit_transform(df_data[col]) le_name_mapping = dict(zip(lab_enc.classes_, lab_enc.transform(lab_enc.classes_))) print('Feature', col) print('mapping', le_name_mapping) data_encoded.head() ###Output _____no_output_____ ###Markdown 3. Data Exploration * Find patterns in data through data visualization. Reveal hidden secrets of the data through graphs, analysis and charts. - Univariate analysis * Continous variables : Histograms, boxplots. This gives us understanding about the central tendency and spread * Categorical variable : Bar chart showing frequency in each category - Bivariate analysis * Continous & Continous : Scatter plots to know how continous variables interact with each other * Categorical & categorical : Stacked column chart to show how the frequencies are spread between two categorical variables * Categorical & Continous : Boxplots, Swamplots or even bar charts* Detect outliers* Feature engineering 3.1 Get data distribution between output classes ###Code data_encoded['Attrition'].value_counts() ###Output _____no_output_____ ###Markdown From the above result, we can find that about 82% of people stick to the company while rest of them quit :-(**** Data is unbalanced **** 3.2 Finding correlation between variables ###Code data_correlation = data_encoded.corr() plt.rcParams["figure.figsize"] = [15,10] sns.heatmap(data_correlation,xticklabels=data_correlation.columns,yticklabels=data_correlation.columns) ###Output _____no_output_____ ###Markdown Analysis of correlation results (sample analysis)- Monthly income is highly correlated with Job level.- Job level is highly correlated with total working hours.- Monthly income is highly correlated with total working hours.- Age is also positively correlated with the Total working hours.- Marital status and stock option level are negatively correlated ###Code #Viewing the analysis obtained above data_corr_filtered = df_data[['MonthlyIncome', 'TotalWorkingYears', 'Age', 'MaritalStatus', 'StockOptionLevel', 'JobLevel']] correlation = data_corr_filtered.corr() plt.rcParams["figure.figsize"] = [20,10] sns.heatmap(correlation,xticklabels=data_corr_filtered.columns,yticklabels=data_corr_filtered.columns) ###Output _____no_output_____ ###Markdown 3.3 Understanding relationship between features and finding patterns in data through visualizationPopular data visualization libraries in python are: 1. Matplotlib 2. Seaborn 3. ggplot 4. Bokeh 5. pygal 6. Plotly 7. geoplotlib 8. Gleam 9. missingno 10. Leather 3.3.1 Age AnalysisFinding relationship between age and attrition. ###Code #Plot to see distribution of age overall plt.rcParams["figure.figsize"] = [7,7] plt.hist(data_encoded['Age'], bins=np.arange(0,80,10), alpha=0.8, rwidth=0.9, color='blue') ###Output _____no_output_____ ###Markdown Finding based on above plotThis plot tells that there are more employees in the range of 30 to 40. Approximately 45% of employees fall in this range. ###Code #We are going to bin age (multiples of 10) to see which age group are likely to leave the company. #Before that, let us take only employee who are likely to quit. positive_attrition_df = data_encoded.loc[data_encoded['Attrition'] == 1] negative_attrition_df = data_encoded.loc[data_encoded['Attrition'] == 0] plt.hist(positive_attrition_df['Age'], bins=np.arange(0,80,10), alpha=0.8, rwidth=0.9, color='red') ###Output _____no_output_____ ###Markdown Findings based on above plot- Employees whose age is in the range of 30 - 40 are more likely to quit.- Employees in the range of 20 to 30 are also equally imposing the threat to employers. 3.3.2 Business Travel vs AttritionThere are 3 categories in this: 1. No travel (0). 2. Travel Frequently (1). 3. Travel Rarely (2).Attrition: No = 0 and Yes = 1 ###Code ax = sns.countplot(x="BusinessTravel", hue="Attrition", data=data_encoded) for p in ax.patches: ax.annotate('{}'.format(p.get_height()), (p.get_x(), p.get_height()+1)) ###Output _____no_output_____ ###Markdown FindingsFrom the above plot it can be inferred that travel can not be a compelling factor for attrition. Employee who travel rarely are likely to quit more 3.3.3 Department Vs AttritionThere are three categories in department: 1. Human Resources: 0 2. Research & Development: 1 3. Sales: 2Attrition: No = 0 and Yes = 1 ###Code ax = sns.countplot(x="Department", hue="Attrition", data=data_encoded) for p in ax.patches: ax.annotate('{}'.format(p.get_height()), (p.get_x(), p.get_height()+1)) ###Output _____no_output_____ ###Markdown Inference: 1. 56% of employess from research and development department are likely to quit. 2. 38% of employees from sales department are likely to quit. 3.3.4 Distance from home Vs Employee Attrition ###Code plt.hist(negative_attrition_df['DistanceFromHome'], bins=np.arange(0,80,10), alpha=0.8, rwidth=0.9, color='red') plt.hist(positive_attrition_df['DistanceFromHome'], bins=np.arange(0,80,10), alpha=0.8, rwidth=0.9, color='red') ###Output _____no_output_____ ###Markdown FindingsPeople who live closeby (0-10 miles) are likely to quit more based on the data 3.3.5 Education vs AttritionThere are five categories: 1. Below College - 1 2. College - 2 3. Bachelor - 3 4. Master - 4 5. Doctor - 5 ###Code ax = sns.countplot(x="Education", hue="Attrition", data=data_encoded) for p in ax.patches: ax.annotate('{}'.format(p.get_height()), (p.get_x(), p.get_height()+1)) ###Output _____no_output_____ ###Markdown Inference: 1. 41% of employees having bachelor's degree are likely to quit. 2. 24% of employees having master's are the next in line 3.3.6 Gender vs Attrition ###Code df_age = data_encoded.copy(deep=True) df_age.loc[df_age['Age'] <= 20, 'Age'] = 0 df_age.loc[(df_age['Age'] > 20) & (df_age['Age'] <= 30), 'Age'] = 1 df_age.loc[(df_age['Age'] > 30) & (df_age['Age'] <= 40), 'Age'] = 2 df_age.loc[(df_age['Age'] > 40) & (df_age['Age'] <= 50), 'Age'] = 3 df_age.loc[(df_age['Age'] > 50), 'Age'] = 4 df_age = pd.DataFrame({'count': df_age.groupby(["Gender", "Attrition"]).size()}).reset_index() df_age['Gender-attrition'] = df_age['Gender'].astype(str) + "-" + df_age['Attrition'].astype(str).map(str) df_age ###Output _____no_output_____ ###Markdown Here,* Gender - 0 and Attrition - 0 ===> Female employees who will stay* Gender - 0 and Attrition - 1 ===> Female employees who will leave* Gender - 1 and Attrition - 0 ===> Male employees who will stay* Gender - 1 and Attrition - 1 ===> Male employees who will leave ###Code output_notebook() # x and y axes Gender_Attrition = df_age['Gender-attrition'].tolist() count = df_age['count'].tolist() print(count) # Bokeh's mapping of column names and data lists source = ColumnDataSource(data=dict(Gender_Attrition=Gender_Attrition, count=count, color=Viridis5)) plot_bar = figure(x_range=Gender_Attrition, plot_height=350, title="Counts") # Render and show the vbar plot plot_bar.vbar(x='Gender_Attrition', top='count', width=0.9, color='color', source=source) show(plot_bar) ###Output _____no_output_____ ###Markdown FindingsFrom the above plot, we can infer that male employees are likely to leave organization as they amount to 63% compared to female who have 36 % attrition rate. 3.3.7 Job Role Vs Attrition Categories in job role:* Healthcare Representative : 0 * Human Resources : 1* Laboratory Technician : 2* Manager : 3 * Manufacturing Director : 4* Research Director : 5* Research Scientist : 6* Sales Executive : 7 * Sales Representative : 8 ###Code df_jrole = pd.DataFrame({'count': data_encoded.groupby(["JobRole", "Attrition"]).size()}).reset_index() #Considering attrition case df_jrole_1 = df_jrole.loc[df_jrole['Attrition'] == 1] import pygal chart = pygal.Bar(print_values=True) chart.x_labels = map(str, range(0,9)) chart.add('Count', df_jrole_1['count']) #chart.render() display(SVG(chart.render(disable_xml_declaration=True))) ###Output _____no_output_____ ###Markdown Findings:Top three roles facing attrition- 26% of employees who are likely to quit belong to Laboratory Technician group- 24% of employees belong to Sales Executive group- 19% of employees belong to Research Scientist group 3.3.8 Marital Status vs Attrition Categories: 1. 'Divorced': 0 2. 'Married' : 1 3. 'Single' : 2 ###Code #analyzing employees who has positive attrition init_notebook_mode(connected=True) cf.go_offline() positive_attrition_df['MaritalStatus'].value_counts().iplot(kind='bar') ###Output _____no_output_____ ###Markdown Inference:Nearly 50 % of the employees who are single are likely to quit 3.3.9 Monthly Income vs Attrition ###Code sns.distplot(negative_attrition_df['MonthlyIncome'], label='Negative attrition') sns.distplot(positive_attrition_df['MonthlyIncome'], label='positive attrition') plt.legend() ###Output _____no_output_____ ###Markdown Inference: Looks like people who are less likely to leave the company are the ones who are less paid. 4. Model Development 4.1 Extracting label from input data ###Code input_data = data_encoded.drop(['Attrition'], axis=1) input_data.head() target_data = data_encoded[['Attrition']] target_data.head() len(input_data.columns) ###Output _____no_output_____ ###Markdown 4.2 Feature Selection It is the process of choosing the best features that can be used in the predictive modeling. 1. Fight against the curse of dimensionality.2. Reduce the overall training time.3. Defense against overfitting.4. Increase model generalizability.Some of the feature selection methods are,1. Filter methods - F Test - Mutual information - Variance threshold - Chi Square - Correlation coefficient - ANNOVA - LDA2. Wrapper methods - Forward search - Backward selection - Recursive feature elimination3. Embedded methods - LASSO Linear Regression ###Code input_data.columns col_values = list(input_data.columns.values) ###Output _____no_output_____ ###Markdown Mutual InformationIt measures the dependence of one variable to another. If,* Mutual information is 0, then variable X carries no information about the variable Y. X and Y are independent.* Mutual information is 1, then variable X can be determined from variable Y. X and Y are dependent.Features can be selected based on their mutual information value. ###Code #gives top 10 features having maximum mutual information value feature_scores = mutual_info_classif(input_data, target_data) for score, fname in sorted(zip(feature_scores, col_values), reverse=True)[:10]: print(fname, score) ###Output _____no_output_____ ###Markdown chi-squarechi-square test is applied to test the independence of two events. This method is used to evaluate the likelihood of correlation or association between features using their frequency distribution. This works best with categorial features. ###Code #gives top 10 features having maximum chi-square value feature_scores = chi2(input_data, target_data)[0] for score, fname in sorted(zip(feature_scores, col_values), reverse=True)[:10]: print(fname, score) df_data.shape #column selection based on feature selection data_selected = df_data[['MonthlyIncome', 'TotalWorkingYears', 'YearsAtCompany', 'YearsInCurrentRole', 'YearsWithCurrManager', 'Age', 'OverTime', 'DistanceFromHome', 'StockOptionLevel', 'JobLevel', 'JobRole', 'WorkLifeBalance', 'Gender', 'Attrition']] data_selected.head() len(data_selected.columns) data_selected.shape #encoding labels data_selected.loc[data_selected.Attrition == 'No', 'Attrition'] = 0 data_selected.loc[data_selected.Attrition == 'Yes', 'Attrition'] = 1 data_selected.head() input_data = data_selected.drop(['Attrition'], axis=1) target_data = data_selected[['Attrition']] data_selected.shape ###Output _____no_output_____ ###Markdown Get Train, Validation and test data ###Code input_data = data_selected[0:1269] print('Shape of the input data is ', input_data.shape) input_data['Attrition'].value_counts() validation_data = data_selected[1269:1469] print('Shape of the validation data is ', validation_data.shape) validation_input_data = validation_data.drop(['Attrition'], axis=1) print('Shape of the validation input data is ', validation_input_data.shape) validation_target_data = validation_data[['Attrition']] print('Shape of the validation target data is ', validation_target_data.shape) #Using 1 sample as test data to check deployment test_data = data_selected[1469:] print(test_data) print('Shape of the test data is ', test_data.shape) test_input_data = test_data.drop(['Attrition'], axis=1) print('Shape of the test input data is ', test_input_data.shape) test_target_data = test_data[['Attrition']] print('Shape of the test target data is ', test_target_data.shape) !wget https://github.com/IBM/employee-attrition-aif360/raw/master/data/Pipeline_LabelEncoder-0.1.zip --output-document=Pipeline_LabelEncoder-0.1.zip !ls !pip install Pipeline_LabelEncoder-0.1.zip #encoding training and validation data. #custom label encoder library from Pipeline_LabelEncoder.sklearn_label_encoder import PipelineLabelEncoder preprocessed_data = PipelineLabelEncoder(columns = ['OverTime', 'JobRole', 'Gender']).fit_transform(input_data) print('-------------------------') print('validation data encoding') validation_enc_data = PipelineLabelEncoder(columns = ['OverTime', 'JobRole', 'Gender']).transform(validation_input_data) ###Output _____no_output_____ ###Markdown 4.3 Bias Mitigation The AI Fairness 360 toolkit is an open-source library to help detect and remove bias in machine learning models. The AI Fairness 360 Python package includes a comprehensive set of metrics for datasets and models to test for biases, explanations for these metrics, and algorithms to mitigate bias in datasets and models.- Github: https://github.com/IBM/AIF360- Interative experience: http://aif360.mybluemix.net/ Convert dataset into a format that can be used by bias mitigation algorithmsWe suspect that there is a bias present in the gender attribute. Intution: Female employees are given favourable outcome (no attrition) compared to male employees. Identify the following in the dataset:1. Favorable label2. Unfavorable label3. Privileged group4. Unprivileged group ###Code # Gender is the protected attribute. #label 0: Employee will stay #label 1: Employee will leave # Gender 0: Female and Gender 1: Male privileged_groups = [{'Gender': 0}] unprivileged_groups = [{'Gender': 1}] favorable_label = 0 unfavorable_label = 1 #Create binary label dataset that can be used by bias mitigation algorithms BM_dataset = BinaryLabelDataset(favorable_label=favorable_label, unfavorable_label=unfavorable_label, df=preprocessed_data, label_names=['Attrition'], protected_attribute_names=['Gender'], unprivileged_protected_attributes=unprivileged_groups) display(Markdown("#### Training Data Details")) print("shape of the training dataset", BM_dataset.features.shape) print("Training data favorable label", BM_dataset.favorable_label) print("Training data unfavorable label", BM_dataset.unfavorable_label) print("Training data protected attribute", BM_dataset.protected_attribute_names) print("Training data privileged protected attribute (1:Male and 0:Female)", BM_dataset.privileged_protected_attributes) print("Training data unprivileged protected attribute (1:Male and 0:Female)", BM_dataset.unprivileged_protected_attributes) metric_orig_train = BinaryLabelDatasetMetric(BM_dataset, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.mean_difference()) ###Output _____no_output_____ ###Markdown Negative difference indicate the presence of bias. Refer above link to know more about the working of the algorithm. ###Code RW = Reweighing(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) RW.fit(BM_dataset) train_tf_dataset = RW.transform(BM_dataset) train_tf_dataset.labels metric_orig_train = BinaryLabelDatasetMetric(train_tf_dataset, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.mean_difference()) ###Output _____no_output_____ ###Markdown 4.4 Algorithm This is a highly unbalanced data. Class 0 covers 83.88% of the data whereas class 1 covers 16.12% of the data. Following are the few ways to handle unbalance data.1. Data Level Approach - Random under-sampling - Cluster based over sampling - Synthetic Minority Over-sampling Technique - Modified Synthetic Minority Over-sampling Technique2. Algorithm Ensemble - Bagging - Boosting - Adaptive Boosting (Ada-boost) - Gradient Tree Boosting - XGBoost In our model, Ada-boost ensemble technique is used. Adaboost Short DescriptionMany weak and inaccurate classifiers are combined to produce a highly accurate prediction. The classifer is serially trained. Samples that are misclassified in previous round are given more focus. Initially weight is equal for all the samples. Weight of misclassified instances are increased each time and weight of correctly classified instances are decreased, this will let more misclassfied sampled to be selected for the next round. After each classifier is trained, the weight is assigned to the classifier as well based on accuracy. More accurate classifier is assigned higher weight so that it will have more impact in final outcome. ###Code #n_estimators is the maximum number of estimators at which the boosting is terminated. Default is 50 and this can be tuned as well. cls = AdaBoostClassifier(n_estimators=100) ###Output _____no_output_____ ###Markdown Classification model can be evaluated using different metrics. Some of the important metrics are: 1. Confusion matrix 2. Accuracy 3. Precision 4. Recall 5. Specificity 6. F1-Score ###Code #finding best estimator #tune other parameters for better accuracy estimator = [100, 150, 200, 250, 300, 400, 500, 700, 1000] for i in estimator: cls = AdaBoostClassifier(n_estimators=i) cls.fit(train_tf_dataset.features, train_tf_dataset.labels,sample_weight=train_tf_dataset.instance_weights) print('--------------------------------------------------------------------------------------------') print('------ Training Results for {} estimators ---------'.format(i)) predicted_output = cls.predict(train_tf_dataset.features) accuracy = metrics.accuracy_score(train_tf_dataset.labels, predicted_output) print('Accuracy for {} estimators is {}'.format(i, accuracy)) print(classification_report(train_tf_dataset.labels, predicted_output)) print('------ Test Results for {} estimators ---------'.format(i)) predicted_output = cls.predict(validation_enc_data) accuracy = metrics.accuracy_score(validation_target_data, predicted_output) print('Accuracy for {} estimators is {}'.format(i, accuracy)) print(classification_report(validation_target_data, predicted_output)) print('--------------------------------------------------------------------------------------------') #Choose the best estimator value from above and replace the 'num_of_estimators' with the value. num_of_estimators = 100 cls = AdaBoostClassifier(n_estimators=num_of_estimators) cls.fit(train_tf_dataset.features, train_tf_dataset.labels,sample_weight=train_tf_dataset.instance_weights) #Creating model pipeline test_pp = PipelineLabelEncoder(columns = ['OverTime', 'JobRole', 'Gender']) model_pipeline = Pipeline(steps=[('preprocessor', test_pp), ('classifier', cls)]) ###Output _____no_output_____ ###Markdown For better accuracy,1. Tune hyper-parameters.2. Try above mentioned methods for handling unbalanced data. ###Code model_pipeline.predict(test_input_data) ###Output _____no_output_____ ###Markdown 5. Inference 1. Factors contributing more to the employee attrition are MonthlyIncome, TotalWorkingYears, YearsAtCompany, YearsInCurrentRole, YearsWithCurrManager, Age, OverTime, DistanceFromHome, StockOptionLevel, JobLevel, JobRole, WorkLifeBalance, Gender.2. Top three roles facing attrition - 26% of employees who are likely to quit belong to Laboratory Technician group. - 24% of employees belong to Sales Executive group. - 19% of employees belong to Research Scientist group. (other inferences are mentioned below each graph)3. The model developed will be able to predict whether an employee will stay or not. This will help company to know the status of an employee in advance and take necessary actions to prevent loss that will incur. 6. Deployment Authenticate to the Watson Machine Learning service. Enter the credentials needed. Credentials can be retrieved from the 'Service Credentials' tab of the service instance instance Replace the information in the following cell with your Watson Machine Learning (WML) credentials.You can find these credentials in your WML instance dashboard under the Service credentials tab.```wml_credentials = { "username": "------------", "password": "------------", "instance_id": "------------", "url": "------------"}``` ###Code # @hidden_cell wml_credentials = { } #Create WML API Client client = WatsonMachineLearningAPIClient(wml_credentials) #Create metadata that can be used for creating and saving the custom library. Here, it is for pipeline label encoder. #Give the path of the custom package (zip). library_metadata = { client.runtimes.LibraryMetaNames.NAME: "PipelineLabelEncoder-Custom", client.runtimes.LibraryMetaNames.DESCRIPTION: "label_encoder_sklearn", client.runtimes.LibraryMetaNames.FILEPATH: "Pipeline_LabelEncoder-0.1.zip", client.runtimes.LibraryMetaNames.VERSION: "1.0", client.runtimes.LibraryMetaNames.PLATFORM: {"name": "python", "versions": ["3.5"]} } #Store library custom_library_details = client.runtimes.store_library(library_metadata) #Retrieve library uid from the details custom_library_uid = client.runtimes.get_library_uid(custom_library_details) print("Custom Library UID is: " + custom_library_uid) #Define metadata required for creating runtime resource. Yse custom library uid obtained from above step to bind the custom library. #Runtime resource that is being defined here will be used for configuring online deployment runtime environment runtimes_meta = { client.runtimes.ConfigurationMetaNames.NAME: "Employee_Attrition", client.runtimes.ConfigurationMetaNames.DESCRIPTION: "Data Science Life Cycle explained through employee attrition problem", client.runtimes.ConfigurationMetaNames.PLATFORM: { "name": "python", "version": "3.5" }, client.runtimes.ConfigurationMetaNames.LIBRARIES_UIDS: [custom_library_uid] } #create runtime resource runtime_resource_details = client.runtimes.store(runtimes_meta) runtime_resource_details #From the runtime resource retrieve url and uid runtime_url = client.runtimes.get_url(runtime_resource_details) print("Runtimes resource URL: " + runtime_url) runtime_uid = client.runtimes.get_uid(runtime_resource_details) print("Runtimes resource UID: " + runtime_uid) #client.repository is used for storing and managing the model, definitions, runtime requirements details in WML repository #This metadata associates model with runtime resources model_property = {client.repository.ModelMetaNames.NAME: "Employee attrition Model", client.repository.ModelMetaNames.RUNTIME_UID: runtime_uid } published_model = client.repository.store_model(model=model_pipeline, meta_props=model_property) #get uid for the stored model published_model_uid = client.repository.get_model_uid(published_model) model_details = client.repository.get_details(published_model_uid) #create deployment created_deployment = client.deployments.create(published_model_uid, name="Emp_attrition_model") #get scoring end point scoring_endpoint = client.deployments.get_scoring_url(created_deployment) print(scoring_endpoint) #Testing deployment scoring_payload = {'fields': ['MonthlyIncome', 'TotalWorkingYears', 'YearsAtCompany', 'YearsInCurrentRole', 'YearsWithCurrManager', 'Age', 'OverTime', 'DistanceFromHome', 'StockOptionLevel', 'JobLevel', 'JobRole', 'WorkLifeBalance', 'Gender'], 'values': [[4404, 6, 4, 3, 2, 34, 'No', '8', 0, 2, 'Laboratory Technician', 4, 'Male']]} predictions = client.deployments.score(scoring_endpoint, scoring_payload) print('prediction',json.dumps(predictions, indent=2)) ###Output _____no_output_____
caps_mnist_pruned&quantized.ipynb
###Markdown Original implementation at:https://github.com/ageron/handson-ml/blob/master/extra_capsnets.ipynbGeron's model doesn't use the keras functional API. In the keras functional API, you don't need to give the batchsize. When you print the model, you get this:```Layer (type) Output Shape Param _________________________________________________________________input (InputLayer) [(None, 28, 28, 1)] 0 _________________________________________________________________conv_layer_1 (Conv2D) (None, 20, 20, 256) 20992 _________________________________________________________________conv_layer_2 (Conv2D) (None, 6, 6, 256) 5308672 _________________________________________________________________reshape_layer_1 (Reshape) (None, 1, 1152, 8) 0 _________________________________________________________________caps1_output_layer (SquashLa (None, 1, 1152, 8) 0 _________________________________________________________________Total params: 5,329,664Trainable params: 5,329,664Non-trainable params: 0```Notice that the Input-layer has shape (None, 28, 28, 1), but we only specified (28, 28, 1). It added None implicitly and that takes care of the batch.So for anywhere Geron uses the batch size explicitly, you don't need to do anything and tensorflow will take care of.Also note that tensorflow 1 APIs are still provided with the compat layer. I used the reduce_sum from TF1 in the squash layer, that allowed me to use Geron's code.Documentation on how to migrate from TF1 to TF2 can be found here:https://www.tensorflow.org/guide/migrate ###Code from google.colab import drive drive.mount('/content/drive') import numpy as np import tensorflow as tf import pandas as pd import tensorflow.keras as K #import tensorflow_model_optimization as tfmot pip install -q tensorflow-model-optimization import tensorflow_model_optimization as tfmot caps1_n_maps = 32 caps1_n_caps = caps1_n_maps * 6 * 6 # 1152 primary capsules caps1_n_dims = 8 caps2_n_caps = 10 caps2_n_dims = 16 tf.random.set_seed(500000) #class SquashLayer(K.layers.Layer, tfmot.sparsity.keras.PrunableLayer): class SquashLayer(K.layers.Layer): def __init__(self, axis=-1, **kwargs): super(SquashLayer, self).__init__(**kwargs) self.axis = axis def build(self, input_shapes): pass """ def get_prunable_weights(self): return [] """ def call(self, inputs): EPSILON = 1.0e-9 squared_norm = tf.compat.v1.reduce_sum(tf.square(inputs),\ axis=self.axis,\ keepdims=True) safe_norm = tf.sqrt(squared_norm + EPSILON) squash_factor = squared_norm / (1. + squared_norm) unit_vector = inputs / safe_norm return squash_factor * unit_vector def get_config(self): config = super(SquashLayer, self).get_config() config.update({"axis": self.axis}) return config #class SafeNorm(K.layers.Layer, tfmot.sparsity.keras.PrunableLayer): class SafeNorm(K.layers.Layer): def __init__(self, axis=-1, keep_dims = False, **kwargs): super(SafeNorm, self).__init__(**kwargs) self.axis = axis self.keep_dims = keep_dims def build(self, input_shapes): pass """ def get_prunable_weights(self): return [] """ def call(self, input): EPSILON = 1.0e-9 squared_norm = tf.compat.v1.reduce_sum(tf.square(inputs),\ axis=self.axis,\ keepdims= self.keep_dims) safe_norm = tf.sqrt(squared_norm + EPSILON) return safe_norm def get_config(self): config = super(SafeNorm, self).get_config() config.update({"axis": self.axis, "keep_dims": self.keep_dims}) return config # This should be the part where the digit layer, and where we tile things # This is incomplete, and work in progress # TODO: Complete this class MyDigitCapsLayer(K.layers.Layer, tfmot.sparsity.keras.PrunableLayer): def __init__(self, **kwargs): super(MyDigitCapsLayer, self).__init__(**kwargs) def get_config(self): config = super(MyDigitCapsLayer, self).get_config() return config def build(self, input_shapes): init_sigma = 0.1 # TODO: use self.kernel = self.add_weight(\ "kernel",\ (caps1_n_caps, caps2_n_caps, caps2_n_dims, caps1_n_dims),\ initializer="random_normal",\ dtype=tf.float32) # To debug this function, I used prints to print the shape # expand_dims just adds an exis, so if you say expand_dims(inshape=(5, 3), -1), # you get the output shape (5, 3, 1), it just adds an axis at the end # Then tile just multiplies one of the dimensions (that is it stacks along that direction N times) # so tile(inshape=(5, 3, 1), [1, 1, 1000]) will yield a shape (5, 3, 1000) # # Notice I didn't tile in build, but in call, Most probaly this is the right thing to do # but we'll only figure out when we actually train def get_prunable_weights(self): return [self.kernel] def call(self, inputs): # Add a dimension at the end exp1 = tf.expand_dims(inputs, -1, name="caps1_output_expanded") # add a dimension along 3rd axis exp1 = tf.expand_dims(exp1, 2, name="caps2_output_espanced") # tile along 3rd axis tile = tf.tile(exp1, [1, 1, caps2_n_caps, 1, 1], name="caps1_output_tiled") caps2_predicted = tf.matmul(self.kernel, tile, name="caps2_predicted") return caps2_predicted # https://www.tensorflow.org/api_docs/python/tf/keras/losses/Loss class MarginLoss(K.losses.Loss): def __init__(self, **kwargs): super(MarginLoss, self).__init__(**kwargs) def get_config(self): config = super(MarginLoss, self).get_config() return config def safe_norm(self, input, axis=-2, epsilon=1e-5, keep_dims=False, name=None): squared_norm = tf.reduce_sum(tf.square(input), axis=axis, keepdims=keep_dims) return tf.sqrt(squared_norm + epsilon) """ def get_prunable_weights(self): return [] """ def call(self,y_true, input): # print(f"y_true.shape = {y_true.shape}, y_pred.shape = {y_pred.shape}") # return K.losses.MeanSquaredError()(y_true, y_pred) #y_true = K.Input(shape=[], dtype=tf.int64, name="y") m_plus = 0.9 m_minus = 0.1 lambda_ = 0.5 #y_true one hot encode y_train T = tf.one_hot(y_true, depth=caps2_n_caps, name="T") caps2_output_norm = self.safe_norm(input, keep_dims = True) present_error_raw = tf.square(\ tf.maximum(0., m_plus - caps2_output_norm), name="present_error_raw") present_error = tf.reshape(\ present_error_raw, shape=(-1, 10), name="present_error") absent_error_raw = tf.square(\ tf.maximum(0., caps2_output_norm - m_minus), name="absent_error_raw") absent_error = tf.reshape(\ absent_error_raw, shape=(-1, 10), name="absent_error") L = tf.add(\ T * present_error,\ lambda_ * (1.0 - T) * absent_error, name="L") marginLoss = tf.reduce_mean(\ tf.reduce_sum(L, axis=1),\ name="margin_loss") return marginLoss #class RoutingByAgreement(K.layers.Layer, tfmot.sparsity.keras.PrunableLayer): class RoutingByAgreement(K.layers.Layer): def __init__(self, round_number=-1, **kwargs): super(RoutingByAgreement, self).__init__(**kwargs) self.round_number = round_number def get_config(self): config = super(RoutingByAgreement, self).get_config() config.update({"round_number": self.round_number}) return config def build(self, input_shapes): self.raw_weights_1 = self.add_weight("raw_weights", \ (caps1_n_caps, caps2_n_caps, 1, 1), \ initializer = "zeros", \ dtype=tf.float32,) #print("Routing layer: self.raw_weights = ", self.raw_weights.shape, "input_shape = ", input_shapes) """ def get_prunable_weights(self): return [self.raw_weights_1] """ @staticmethod def squash(inputs): EPSILON = 1.0e-5 squared_norm = tf.compat.v1.reduce_sum(tf.square(inputs),\ keepdims=True) safe_norm = tf.sqrt(squared_norm + EPSILON) squash_factor = squared_norm / (1. + squared_norm) unit_vector = inputs / safe_norm return squash_factor * unit_vector def single_round_routing(self, inputs, raw_weights, agreement): raw_weights = tf.add(raw_weights, agreement) routing_wt = tf.nn.softmax(raw_weights, axis=2) wt_predictions = tf.multiply(routing_wt, inputs) wt_sum = tf.reduce_sum(wt_predictions, axis=1, keepdims=True) return wt_sum def call(self, inputs): agreement = tf.zeros(shape=self.raw_weights_1.shape) sqsh_wt_sum = None x = inputs for i in range(2): wt_sum = self.single_round_routing(inputs, self.raw_weights_1, agreement) sqsh_wt_sum = RoutingByAgreement.squash(wt_sum) sqsh_wt_sum_tiled = tf.tile(\ sqsh_wt_sum ,\ [1, caps1_n_caps, 1, 1, 1],\ name="caps2_output_round_1_tiled") agreement = tf.matmul(\ x, \ sqsh_wt_sum_tiled,\ transpose_a=True,\ name="agreement") return sqsh_wt_sum (x_train, y_train,), (x_test, y_test) = K.datasets.mnist.load_data() print(x_train.shape, x_test.shape) x_train = x_train/255.0 x_test = x_test/255.0 #print(x_train[500]) class Model: @staticmethod def build(inshape=(28, 28, 1)): inp = K.Input(shape=inshape, dtype=tf.float32, name='input') # Primary capsules # For each digit in the batch # 32 maps, each 6x6 grid of 8 dimensional vectors # First Conv layer conv1_params = \ { "filters": 256, "kernel_size": 9, "strides": 1, "padding": "valid", "activation": tf.nn.relu, } x = K.layers.Conv2D(**conv1_params, name="conv_layer_1")(inp) # Second conv layer conv2_params = \ { "filters": caps1_n_maps * caps1_n_dims, # 256 convolutional filters "kernel_size": 9, "strides": 2, "padding": "valid", "activation": tf.nn.relu } x = K.layers.Conv2D(**conv2_params, name="conv_layer_2")(x) # Reshape x = K.layers.Reshape(\ (caps1_n_caps, caps1_n_dims),\ name="reshape_layer_1")(x) x = SquashLayer(name="caps1_output_layer")(x) x = MyDigitCapsLayer(name = "caps2_predicted")(x) caps2_predicted = x # Save this value for later #routing by agreement (2 rounds) x = RoutingByAgreement(name="routing1", round_number=2)(x) return K.Model(inputs=inp, outputs=x, name='my') m = Model.build() print(m.summary()) # y_train_train = tf.one_hot(y_train, depth=caps2_n_caps, name="T") # print(y_train_train.shape) # #print(y_train) class MyAccuracy(K.metrics.Metric): def __init__(self, **kwargs): super(MyAccuracy, self).__init__(**kwargs) self.acc_obj = K.metrics.Accuracy() self.state = 0 def get_config(self): config = super(MyAccuracy, self).get_config() config.update({"acc_obj": None, "state": self.state}) return config def safe_norm(self, input, axis=-2, epsilon=1e-5, keep_dims=True, name=None): squared_norm = tf.reduce_sum(tf.square(input), axis=axis, keepdims=keep_dims) return tf.sqrt(squared_norm + epsilon) def update_state(self, y_true, input, sample_weight=None): if self.acc_obj is None: self.acc_obj = K.metrics.Accuracy() y_proba = self.safe_norm(input, axis=-2) y_proba_argmax = tf.argmax(y_proba, axis=2) y_pred = tf.squeeze(y_proba_argmax, axis=[1,2], name="y_pred") #y_true = tf.reshape(y_true, (y_true.shape[0], )) y_true = tf.cast(y_true, dtype=tf.int64) self.acc_obj.update_state(y_true, y_pred, sample_weight) def reset_state(self): self.acc_obj.reset_state() def result(self): return self.acc_obj.result() class MyReshapeLayer(K.layers.Layer): def __init__(self, axis=-1, keep_dims = False, **kwargs): super(MyReshapeLayer, self).__init__(**kwargs) def build(self, input_shapes): pass def safe_norm(self, input, axis=-2, epsilon=1e-5, keep_dims=True, name=None): squared_norm = tf.reduce_sum(tf.square(input), axis=axis, keepdims=keep_dims) return tf.sqrt(squared_norm + epsilon) def call(self, input): print('printing shapes ------------------- ') EPSILON = 1.0e-9 print(input) y_proba = self.safe_norm(input, axis=-2) print(y_proba) y_proba_argmax = tf.argmax(y_proba, axis=2) print(y_proba_argmax) y_pred = tf.squeeze(y_proba_argmax, axis=[1,2], name="y_pred") print(y_pred) return tf.cast(y_pred, tf.int64) def get_config(self): config = super(MyReshapeLayer, self).get_config() return config from keras.callbacks import ModelCheckpoint, CSVLogger comparison_metric = MyAccuracy() #checkpoint_filepath = "/content/drive/MyDrive/Weights/weights-improvement-{epoch:02d}-{val_my_accuracy:.2f}.hdf5" model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filepath = "/content/drive/MyDrive/MnistResults/best_weights1.hdf5", save_weights_only=True, monitor=f"val_{comparison_metric.name}", mode='max', save_best_only=True) model_checkpoint_callback2 = tf.keras.callbacks.ModelCheckpoint( filepath = "/content/drive/MyDrive/MnistResults/latest_weights1.hdf5", save_weights_only=True, monitor=f"val_{comparison_metric.name}", mode='max', save_best_only=False) log_csv = CSVLogger("/content/drive/MyDrive/MnistResults/mylogs1.csv", separator = ",", append = False) callback_list = [model_checkpoint_callback, model_checkpoint_callback2, log_csv] comparison_metric.name m.compile(optimizer='adam', loss=MarginLoss(), metrics=[MyAccuracy()]) history = m.fit(x_train, y_train, batch_size=32, epochs=5, verbose= 1, validation_split=0.2, callbacks = callback_list) # print(f'Best Validation Accuracy = {np.max(history.history["val_my_accuracy"])}') # print(f'Best Training Accuracy = {np.max(history.history["my_accuracy"])}') #m.save("/content/drive/MyDrive/WeightsMnist/save.tf", save_format='tf') # #!rm -f "/content/drive/MyDrive/WeightsMnist/save3.tf" basemodel_file = m.save("/content/drive/MyDrive/MnistResults/save_basemodel.tf", save_format='tf') #Extra layer for evaluate class DimensionCorrection(K.layers.Layer): def __init__(self, **kwargs): super(DimensionCorrection, self).__init__(**kwargs) def safe_norm(self, input, axis=-2, epsilon=1e-7, keep_dims=False, name=None): squared_norm = tf.reduce_sum(tf.square(input), axis=axis, keepdims=keep_dims) return tf.sqrt(squared_norm + epsilon) def call(self,y_pred): y_proba = self.safe_norm(y_pred, axis=-2) y_proba_argmax = tf.argmax(y_proba, axis=2) y_pred = tf.squeeze(y_proba_argmax, axis=[1,2], name="y_pred") return y_pred y_test = tf.cast(y_test, dtype= tf.int64) print(y_test.shape) m = Model.build() m.load_weights('/content/drive/MyDrive/MnistResults/latest_weights1.hdf5') m.compile(optimizer='Adam', loss=MarginLoss) newmodel = K.models.Sequential(\ [\ m,\ DimensionCorrection(),\ ]\ ) newmodel.summary() m.trainable = False newmodel.compile(optimizer='adam') y_pred = newmodel.predict(x_test) import sklearn from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score print(confusion_matrix(y_test, y_pred)) print(f"accuracy = {accuracy_score(y_test, y_pred)}") # mm = K.models.load_model('/content/drive/MyDrive/WeightsMnist/save2.tf',\ # custom_objects=\ # {\ # "SquashLayer": SquashLayer,\ # "SafeNorm": SafeNorm,\ # "MyDigitCapsLayer": MyDigitCapsLayer,\ # "RoutingByAgreement": RoutingByAgreement,\ # "MyAccuracy": MyAccuracy,\ # "MarginLoss": MarginLoss,\ # }) # y_pred_eval = DimensionCorrection() # m2 = Model.build() # m2.load_weights('/content/drive/MyDrive/WeightsMnist/latest_weights1.hdf5') # m3 = K.models.Sequential() # m3.add(m2) # m3.add(y_pred_eval) # m3.build() # m3.compile(optimizer='adam', loss=MarginLoss(), metrics=[MyAccuracy()]) # m3.evaluate(x_test, y_test, batch_size= 32, verbose= 1) # #m3.evaluate(x_test, y_test, batch_size= 32, verbose= 1) #converter = tf.lite.TFLiteConverter.from_keras_model(m) ###Output _____no_output_____ ###Markdown ###Code # converter.optimizations = [tf.lite.Optimize.DEFAULT] # converter.target_spec.supported_types = [tf.float16] # quantize_model = converter.convert() # mm = K.models.load_model('/content/drive/MyDrive/WeightsMnist/save2.tf',\ # custom_objects=\ # {\ # "SquashLayer": SquashLayer,\ # "SafeNorm": SafeNorm,\ # "MyDigitCapsLayer": MyDigitCapsLayer,\ # "RoutingByAgreement": RoutingByAgreement,\ # "MyAccuracy": MyAccuracy,\ # "MarginLoss": MarginLoss,\ # }) # print(type(mm), mm.summary()) # print(mm.weights[0][0][0][0][0:5]) # e = mm.load_weights('/content/drive/MyDrive/WeightsMnist/latest_weights1.hdf5') # print(mm.weights[0][0][0][0][0:5]) # Create the .tflite file # tflite_model_file = "/content/drive/MyDrive/WeightsMnist/compressed.tflite" # converter = tf.lite.TFLiteConverter.from_keras_model(mm) # converter.optimizations = [tf.lite.Optimize.DEFAULT] # converter.target_spec.supported_ops = [ # tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops. # tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops. # ] # tflite_model = converter.convert() # with open(tflite_model_file, "wb") as f: # f.write(tflite_model) ###Output _____no_output_____ ###Markdown ###Code !du -sh /content/drive/MyDrive/MnistResults/* ###Output 27M /content/drive/MyDrive/MnistResults/latest_weights1.hdf5 512 /content/drive/MyDrive/MnistResults/mylogs1.csv 79M /content/drive/MyDrive/MnistResults/save_basemodel.tf ###Markdown Use this tutorial for pruningquantization has already been done earlierhttps://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras PRUNING ###Code # pip install -q tensorflow-model-optimization import tensorflow_model_optimization as tfmot import tempfile prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude # TODO: Remove this line mm = m print("ORIGINAL MODEL") print(mm.summary()) print('-' * 80) # Compute end step to finish pruning after 2 epochs. batch_size = 128 epochs = 2 validation_split = 0.1 # 10% of training set will be used for validation set. num_images = x_train.shape[0] * (1 - validation_split) end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs # Define model for pruning. pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50, final_sparsity=0.80, begin_step=0, end_step=end_step) } """ model_for_pruning = prune_low_magnitude(mm, **pruning_params) # `prune_low_magnitude` requires a recompile. model_for_pruning.compile(optimizer='adam', loss=MarginLoss(), metrics=[MyAccuracy()]) model_for_pruning.summary() """ ###################################################################### logdir = tempfile.mkdtemp() callbacks = [ tfmot.sparsity.keras.UpdatePruningStep(), tfmot.sparsity.keras.PruningSummaries(log_dir=logdir), ] # Helper function uses `prune_low_magnitude` to make only the # Dense layers train with pruning. def apply_pruning_to_layers(layer): #print("called") if isinstance(layer, MyDigitCapsLayer): print(f"Layer {layer} {layer.name} slated for pruning") return tfmot.sparsity.keras.prune_low_magnitude(layer, **pruning_params) elif layer.name == "conv_layer_2": print(f"Layer {layer} {layer.name} slated for pruning") return tfmot.sparsity.keras.prune_low_magnitude(layer, **pruning_params) print(f"Layer {layer} {layer.name} unchanged") return layer # Use `tf.keras.models.clone_model` to apply `apply_pruning_to_layers` # to the layers of the model. model_for_pruning = tf.keras.models.clone_model( mm, clone_function=apply_pruning_to_layers, ) print(model_for_pruning.summary()) """ model_for_pruning = K.models.Sequential(\ [\ model_for_pruning,\ MyReshapeLayer(),\ ]\ ) """ model_for_pruning.compile(optimizer='adam', loss=MarginLoss(), metrics=[MyAccuracy()]) #model_for_pruning.compile(optimizer='adam', loss=MarginLoss()) model_for_pruning.fit(x_train, y_train, batch_size=32, epochs=2, validation_split=validation_split, callbacks=callbacks) _, model_for_pruning_accuracy = model_for_pruning.evaluate( x_test, y_test, verbose=1) model_for_export = tfmot.sparsity.keras.strip_pruning(model_for_pruning) pruned_keras_file = "/content/drive/MyDrive/MnistResults/pruned_file1.h5" tf.keras.models.save_model(model_for_export, pruned_keras_file, include_optimizer=False) print('Saved pruned Keras model to:', pruned_keras_file) #converter = tf.lite.TFLiteConverter.from_keras_model(model_for_export) tflite_model_file = "/content/drive/MyDrive/MnistResults/compressed1.tflite" converter = tf.lite.TFLiteConverter.from_keras_model(model_for_export) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops. tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops. ] tflite_model = converter.convert() with open(tflite_model_file, "wb") as f: f.write(tflite_model) def get_gzipped_model_size(file): # Returns size of gzipped model, in bytes. import os import zipfile _, zipped_file = tempfile.mkstemp('.zip') with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f: f.write(file) return os.path.getsize(zipped_file) #print("Size of gzipped baseline Keras model: %.2f bytes" % (get_gzipped_model_size(basemodel_file))) print("Size of gzipped pruned Keras model: %.2f bytes" % (get_gzipped_model_size(pruned_keras_file))) print("Size of gzipped pruned TFlite model: %.2f bytes" % (get_gzipped_model_size(tflite_model_file))) !du -sh /content/drive/MyDrive/MnistResults/* ###Output 11M /content/drive/MyDrive/MnistResults/compressed1.tflite 27M /content/drive/MyDrive/MnistResults/latest_weights1.hdf5 512 /content/drive/MyDrive/MnistResults/mylogs1.csv 27M /content/drive/MyDrive/MnistResults/pruned_file1.h5 79M /content/drive/MyDrive/MnistResults/save_basemodel.tf
Curious Algorithm.ipynb
###Markdown A Curious AlgorithmDuring a lecture in a summer calculus class, I took to drawing random geometric patterns around the edges of my notes. As I was toying with different shapes and ideas for simple space filling curves, I came across an algorithm that happened to result in consistent patterns when drawn within triangles. Consider this simple algorithm below: 1. Given any triangle, $P$, pick a point anywhere along one of $P$'s edges and call it `current_point`. 2. From `current_point`, draw to the *farthest* edge of $P$, such that the line drawn is perpindicular to the chosen edge.3. Set `current_point` equal to the end of this drawn perpindicular line, and repeat this recursive process for some number of steps.Following this "right angle algorithm" in detail on paper, I noticed a couple curious properties. The most prominent property I noticed was that given any "initial triangle" and any starting point, the algorithm would quickly converge to some repeating shape, which I will call the "ultimate shape". Interested in finding the exact properties of this ultimate shape and putting my drawing skills to the test, I went home and wrote a program to generate a triangle and implement this right angle algorithm on it, graphing the result. This write up is a description of what I found when testing this algorithm, highlighting its more interesting features.If you would like to see the code I wrote for this, visit the GitHub repository linked [here](https://github.com/samgrassi01/A-Curious-Algorithm). Putting the Algorithm to the TestThe algorithm starts drawing from some point along the edge of the initial triangle, and draws a line to the farthest perpinducular edge, repeating the process from its new location in a recursive manner. When the algorithm is faced with two equal distances, it randomely picks one of the two edges to draw to. With this basic understanding of the algorithms' internals, we are equipt to begin the exploration into why it produces the ultimate shapes it does. Picking an equilateral triangle to begin, I started the algorithm at one of its vertices and let it run for 100 steps, resulting in the graph shown below. **NOTE:** The function `return_points` takes two angles and the right point of the triangle to build, returning the necessary points to make the triangle with the passed exact angles and right end point. The function `drawTriangle` takes `(number_of_iterations, starting_point, outer_triangle_points, steps_to_show)` where `number_of_iterations` is the number of steps the algorithm will execute, `starting_point` is where the algorithm will being drawing, `outer_triangle_points` is the set of three points generated by `return_points` to define the outer triangle, and finally `steps_to_show` is the index-range of steps to graph. ###Code eq_triangle = return_points(60, 60, [4, 0]) visited_points = drawTriangle(100, [4, 0], eq_triangle, [0, 100]) ###Output _____no_output_____ ###Markdown As you can see, after just a few steps the algorithm converged to a different triangle within the outer one. It can be seen that the ultimate triangle has each edge perpindicular to one of the outer triangle's edges, with all three of its vertices touching the outer triangle's edges. One way I like to think of the outer triangle is an initial condition to this algorithm that will "mold" the lines into their "natural resting points" over time. You can see the result of this above. It seems that with every new step, the outer triangle is forcing the algorithm into its final repeating shape. To eak some more information out of this pattern, I wrote a function, `give_info` to return the inner angles of this ultimate triangle. Below those inner angles are printed along with the last steps the algorithm took for more clarity. ###Code visited_points = drawTriangle(100, [4, 0], eq_triangle, [90, 100]) give_info(visited_points, eq_triangle) ###Output Outer Triangle Information: Inner angles: [60, 60, 60] Inner Triangle Information: Inner angles: [60, 60, 60] ###Markdown Right off the bat, we notice that not only does this algorithm converge to triangle, but this ultimate triangle is *similar* to the outer one, as all the interior angles are the same! This is a rather interesting result. As this initial equilateral outer triangles is scaled up and down, the convergence of the algorithm is not affected, however notice what happens when we change the starting point of the algorithm from $(4, 0)$ to $(3,0)$ and $(1, 0)$, where the final steps the algorithm took for each situation are graphed below. ###Code visited_points = drawTriangle(100, [3, 0], eq_triangle, [90, 100]) visited_points = drawTriangle(100, [1, 0], eq_triangle, [90, 100]) ###Output _____no_output_____ ###Markdown As the starting point of the algorithm shifted, the ultimate triangle flipped around the axis defined by $x=2$. Infact, when the starting point is to the left or right of $2$, the ultimate triangle will always be pointing in one direction or the other; unless the algorithm starts at the edge points of $(0,0)$ and $(4,0)$, where the ultimate triangles orientation will be determined randomely. When the starting point is at 2, the algorithm picks a random side to follow due to the symmetry of the triangle, and the ultimate triangle will be oriented to either the left or right. Curiousely enough, regardless of where the algorithm starts drawing from, the inner ultimate triangle is always the same size and has the same interior angles.What if we applied this algorithm to an isosceles triangle? Take the example shown below, with the interior angles of both the ultimate inner triangle and initial triangle printed with the resulting graph. ###Code iso1 = return_points(50, 65, [4, 0]) visited_points = drawTriangle(100, [3.6, 0], iso1, [0, 100]) give_info(visited_points, iso1) ###Output Outer Triangle Information: Inner angles: [65, 65, 50] Inner Triangle Information: Inner angles: [50, 65, 65] ###Markdown As you can see, the same thing happened for this particular isosceles triangle; the ultimate triangle the algorithm converged to is similar to the outer triangle!At this point, you are likely thinking that the ultimate shape may not always be a triangle, depending on the properties of the initial (outer) triangle! I will get to that, but first I am going to show that this property of convergence to similar triangles also holds for scalene triangles. ###Code scalene1 = return_points(60, 70, [4, 0]) visited_points = drawTriangle(100, [3.6, 0], scalene1, [0, 100]) give_info(visited_points, scalene1) ###Output Outer Triangle Information: Inner angles: [50, 70, 60] Inner Triangle Information: Inner angles: [50, 60, 70] ###Markdown Once again, we can see the inner ultimate triangle is similar to the outer triangle. One natural question may be, "If the computational resources are not available to find this ultimate triangle, how else might it be found exactly"? The answer would be that this exact inner triangle could be found with relative ease using geometry. Take a look at the *general* diagram below for one of these cases.We know $a, b, c$, and $A, B, C$. It is also known that each of the edges of the inner triangle will be perpindicular with its corresponding edge on the outer triangle, and that the inner ultimate triangle will be similar to the outer one (same interior angles). With this information, all the inner angles can be found, giving enough information to solve for $x, y$, and $z$ shown in the diagram above. After finding these values, the points of the inner ultimate triangle can be found. One interesting formula that can be used to *approximate* the side lengths of the inner ultimate triangle is given by$$a' \approx \frac{sin(\gamma) \cdot a}{\varphi}$$where $\gamma$ is the peak angle of the initial triangle, $a'$ is the inner side length to be approximated, $a$ is the corresponding outer side length, and $\varphi=1.61803 \cdots$, the Golden Ratio. The resulting error of the approximations when using this formula is highly dependent on the triangle being analyzed. In the example triangles I worked on, I saw side length approximations errors of the ultimate inner triangle between $0.1\%$ and $7\%$.The side length to be solved for, $a'$, can be found exactly with$$a' = \frac{sin(\gamma) \cdot a}{c}$$where $c \approx \varphi$. I have a hunch $c$ is given by a function of the peak angle $\gamma$, however I have yet to find this function exactly, assuming it exists. Other Ultimate ShapesAs alluded to earlier, when the angles of the outer triangle are adjusted, the algorithm can generate other interesting repeating shapes. One of the simpler repeating shapes is given below from an isosceles triangle. As a quick note, for most of the examples below I chose not to show the first steps the algorithm took as seeing them is usually not especially informative and they clutter the graph. ###Code iso2 = return_points(30, 75, [4, 0]) visited_points = drawTriangle(100, [3.6, 0], iso2, [90, 100]) ###Output _____no_output_____ ###Markdown This is the first repeating ultimate shape we have seen that produces something other than a triangle. The above ultimate shape is nothing to get too excited about however, so lets start by slightly increasing and decreasing the interior angles of the isosceles triangle to see what else the algorithm comes up with. ###Code iso3 = return_points(40, 70, [4, 0]) visited_points = drawTriangle(100, [1, 0], iso3, [90, 100]) iso4 = return_points(20, 80, [4, 0]) visited_points = drawTriangle(100, [3, 0], iso4, [80, 100]) ###Output _____no_output_____ ###Markdown Those patterns are much more interesting! Recall that the algorithm will always draw the longest possible line it can while still obeying the right angle rule, as we can see the result of this taking form in the previous two examples. For this specific isosceles triangle, we can see that as the top angle decreases, the number of "zig-zags" formed within the ultimate shape increases, as the angles are much steeper. As shown below, scalene triangles succumb to a similar phenomena as well, producing different repeating shapes. ###Code scalene2 = return_points(40, 80, [4, 0]) visited_points = drawTriangle(110, [3, 0], scalene2, [90, 110]) scalene3 = return_points(20, 86, [4, 0]) visited_points = drawTriangle(110, [2, 0], scalene3, [80, 110]) ###Output _____no_output_____ ###Markdown Lets take a look at what happens when we move the top angle in the other direction, starting with a $45-90-45$ triangle. In this case, it is interesting seeing all the steps the algorithm takes, so I plot them all below. The starting point is $(3.7, 0)$. ###Code iso6 = return_points(90, 45, [4, 0]) visited_points = drawTriangle(130, [3.7, 0], iso6, [0, 130]) ###Output _____no_output_____ ###Markdown The final ultimate shape and its properties are shown below. ###Code visited_points = drawTriangle(110, [3, 0], iso6, [100, 110]) give_info(visited_points, iso6) ###Output Outer Triangle Information: Inner angles: [45, 45, 90] Inner angles of each triangle are: [45, 90, 45] ###Markdown When the algorithm was implemented on the above right triangle, it produced some interesting results. The most immidiately noticeable of which being that the hourglass like ultimate shape, is built out of two $45-90-45$ triangles!In the current implementation of the algorithm I have prevented it from drawing along edges or meeting the triangles vertices, to force it into developing the hourglass ultimate shape seen above. It is for this reason that on what looks to be the fourth step above (shown on the first graph of the triangle), the algorithm chose to draw down instead of up to the top vertice of the triangle. If the algorithm had been allowed to do so, the resulting inner shape would have been the two ultimate triangles flipped around the y-axis and scaled up, as pictured below by a previous implementation of the algorithm.The algorithm is applied to a few more obtuse triangles to demonstrate this property of the algorithm converging to an "hour-glass" ultimate shape, composed to two similar triangles. ###Code iso7 = return_points(100, 40, [4, 0]) visited_points = drawTriangle(150, [3.4, 0], iso7, [100, 150]) give_info(visited_points, iso7) scalene4 = return_points(110, 30, [4, 0]) visited_points = drawTriangle(150, [1, 0], scalene4, [100, 150]) iso8 = return_points(140, 20, [4, 0]) visited_points = drawTriangle(150, [2.2, 0], iso8, [100, 150]) ###Output _____no_output_____ ###Markdown While this property is true for all obtuse triangles, note what happens as $\gamma$, the peak angle, approaches 180 degrees. As $\gamma \rightarrow 180$, the range of starting points from which the algorithm will converge to this ultimate hour-glass shape decreases, approaching the center of the triangle. Notice what happens if the algorithm starts outside of this "critical range". ###Code iso9 = return_points(140, 20, [4, 0]) visited_points = drawTriangle(100, [2.3, 0], iso9, [0, 100]) ###Output _____no_output_____ ###Markdown The algorithm gets "stuck" in a corner and approaches the left/right endpoints as the number of steps approaches infinity! Finding the Ultimate TriangleWe have noticed that the ultimate shape may or may not be a triangle in different initial triangles. An important question is "can we define a set of angles for each type of triangle, where the algorithm will always converge to an ultimate triangle?".Lets begin with finding rules for when an isosceles triangle will or will not result in an ultimate triangle. Consider the two initial isosceles triangles below. Notice the minute difference in their interior angles, and the large difference in the ultimate shapes. ###Code iso2 = return_points(43.2, 68.4, [4, 0]) visited_points = drawTriangle(100, [3.6, 0], iso2, [90, 100]) iso2 = return_points(43.3, 68.35, [4, 0]) visited_points = drawTriangle(100, [4, 0], iso2, [90, 100]) iso2 = return_points(43.3, 68.35, [4, 0]) visited_points = drawTriangle(100, [4, 0], iso2, [0, 10]) ###Output _____no_output_____
Oops.ipynb
###Markdown create a class for dictonary parsing 1 . write a functoin to give all the keys2 .write a function to give all the values 3 . write a function to throw an exception in case of input is not dictonary4. write a function to take user input and then parse a key and value out of dictonary 5. write a function to insert new key value pair into dictonary ###Code class dict_parsing: def __init__(self,a): self.a = a def getkeys(self): if self.notdict(): return list(self.a.keys()) def getvalues(self): if self.notdict(): return list(self.a.values()) def notdict(self): if type(self.a) != dict: raise Exception(self.a,'Not a dictionary') return 1 def userinput(self): self.a = eval(input()) print(self.a,type(self.a)) print(self.getkeys()) print(self.getvalues()) def insertion(self,k,v): self.a[k] = v d = {"name":"faiz","mobile_number":9873300865,"email_id":"[email protected]"} dict_class = dict_parsing(d) dict_class.getkeys() dict_class.getvalues() dict_class.insertion(15,"bokhari") list1 = [1,2,3,4,5,6] dic = dict_parsing(list1) dic.notdict() dict_class.userinput() ###Output {"name":"faiz","mobile_number":9873300865,"email_id":"[email protected]"} {'name': 'faiz', 'mobile_number': 9873300865, 'email_id': '[email protected]'} <class 'dict'> ['name', 'mobile_number', 'email_id'] ['faiz', 9873300865, '[email protected]'] ###Markdown q1 . Create your own package for all the list function q2 .create your onw package for all the tuple functionq3 . create your own package for all dictonary functionq4 . create your own package for all the set functionrestriction : always use exception handling never usr print statement always use logging while writing a code and log every activity performed by code in respective logging file ###Code class xyz: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def test(self): print("this is my 1 test method of class xyz") def test1(self): print("this is my 2 test method of class xyz") def test2(self): print("this is my 3 test method of class xyz") def test3(self): print("this is my 3 test method of class xyz") p = xyz(1,2,3) p.test1() class xyz1(xyz): pass q = xyz1(3,4,5) q.test1() class xyz1(xyz): def test1(self): print("this is a test method avialable in xyz1") g = xyz1(4,5,6) g.test1() class xyz: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def test(self): print("this is a meth of xyz class ") class xyz1: def __init__(self,p,q,v): self.p = p self.v = v self.q = q def test1(self): print("this is a meth from class xyz1") class child(xyz1,xyz): def __init__(self,*args,**kwargs): xyz.__init__(self,*args) xyz1.__init__(self,**kwargs) n = child(4,5,6,p=3,q=4,v=5) n.p n.v class xyz: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def test(self): print("this is a meth of xyz class ") class xyz1(xyz): def test1(self): print("this is a meth from class xyz1") class xyz2(xyz1): def test2(self): print("this is a meth from class xyz2") class xyz3(xyz2): def test3(self): print("this is a meth from class xyz3") v = xyz2(1,2,3) m = xyz3(4,9,10) class readFile: def __init__(self,fileObj, lines): self.file = fileObj self.lines = lines def readFile(self): file2=open(self.file,'r') line=file2.readline() while(line!=""): print(line) line=file2.readline() def writeFile(self): content_write = open(self.file,'w') content_write.writelines(lines) content_write.close() class readFile1(readFile): def readFile1(self): print("inheritance of readFile class") file1 = r'test1.txt' lines = 'Inserted Lines .......' read_write = readFile1(file1,lines) read_write.writeFile() read_write.readFile() class test: def __init__(self,a,b,c): self.a = a self.b = b self.c = c class test1(test): pass u = test(4,5,6) u.a v = test1(1,2,3) v.a class test: def __init__(self): self._a = 4 #protected variable self.__b = 10 #private variable class test1(test): def __init__(self): self._a = 7 self.__b = 12 u = test() u._a u.__b v = test1() v._a v.__b class test: def __init__(self,a,b,c): self._a = a self.__b = b self.c = c class test1(test): pass v = test(4,5,6) v._a v._test__b v.c u = test1(7,8,9) u.c u._a u._test1__b u._test__b class bonousclaculator: def __init__(self, empid , emprating) : self.empid = empid self.emprating = emprating self._empmail = "[email protected]" self.__bonusforratingA = "70%" self.__bonusforraringB = "60%" self.__bonusforratinC = "40%" def bonuscalculator(self) : if self.emprating == "A": bonus = self.__bonusforratingA return bonus elif self.emprating == "B" : bonus = self.__bonusforraringB return bonus else : bonus = self.__bonusforratinC return bonus emp1 = bonousclaculator(101 , "A") emp2 = bonousclaculator(102 , "B") emp3 = bonousclaculator(103, "C") emp1.bonuscalculator() emp2.bonuscalculator() emp3.bonuscalculator() emp1.empid = 104 emp1.empid emp1.emprating = "B" emp1.bonuscalculator() emp1.__bonusforraringB = "90%" emp1.bonuscalculator() emp2.emprating emp2.bonuscalculator() emp2.__bonusforraringB = "100%" emp2.bonuscalculator() emp2.empid = 3548784 emp2.empid emp2.__bonusforraringB = "fsdfsfagsf" emp2._bonousclaculator__bonusforraringB emp2._bonousclaculator__bonusforraringB = "435456" emp2._bonousclaculator__bonusforraringB emp1._empmail emp1._empmail = "[email protected]" emp1._empmail #kevy project def test(a,b): return a+b test(3,4) test("fazlullah"," bokhari") class insta: def share_stories(self): print("this will share my insta story ") class facebook: def share_stories(self): print("this will shared my facebook story ") def shared_story(app): app.share_stories() i = insta() f = facebook() shared_story(i) shared_story(f) class social_media: def share_stories(self): print("share a story") def upload_pictures(self): print("this will help you tp uopload picture on social media") class insta(social_media): def share_stories(self): print("this will share my insta story ") class facebook(social_media): def share_stories(self): print("this will shared my facebook story ") i = insta() f = facebook() f.share_stories() i.share_stories() class test(Exception): def __init__(self,msg): self.msg = msg try: raise(test("this is my own exceptiom class ")) except test as t: print(t) """q1 create your own class for to achive multiple , multilevel inheritance q2 create your own class to represenet ploymorprism q3 create your own class for custome exception q4 create your own class to achive encaptulation q5 create your own class to achive method overloading and overriding . """ # q1 create your own class for to achive multiple , multilevel inheritance class Faiz: def __init__(self,name,mob,YT_link): self.name = name self.mob = mob self.yt_link = YT_link def printFaizDetails(self): print("Name", self.name) print("Mobile number: ",self.mob) print("YouTube Link: ",self.yt_link) class Employee(Faiz): def getYouTubeLink(self): return self.yt_link class GetEmployeeDetails(Employee): def prinDetails(self): return self.getYouTubeLink() g = GetEmployeeDetails('Fazlullah Bokhar',9873300865, 'https://www.youtube.com/channel/UCGKe5Z0tCXeRmrTXRTJg4fA') g.printFaizDetails() g.getYouTubeLink() #Multiple inheritance # Parent class1 class Batch_number: batchnumber = "" def __init__(self,a,b,c): self.a = a self.b= b self.c = c def batch(self): print(self.batchnumber) # Parent class2 class course_name: cname = "" def course(self): print(self.cname) # Child class class Student(Batch_number, course_name): def deets(self): print("Batch :", self.batchnumber) print("course :", self.cname) # Child class code s1 = Student(4,5,6) s1.batchnumber = "2" s1.cname = "FSDS" s1.deets() bn = Batch_number(4,5,6) bn1 = Batch_number(1,2,3) bn1.batchnumber bn1.batchnumber = "sudh" bn1.batchnumber bn.batchnumber Batch_number.batchnumber = "faiz" bn.batchnumber bn1.batchnumber class Batch_number: batchnumber = "FSDS" def __init__(self,a,b,c): self.a = a self.b= b self.c = c @staticmethod def batch(): print("this is statics method batch") def batch1(self): print("this is statics method batch one") bn = Batch_number(1,2,3) bn.batch() Batch_number.batchnumber Batch_number.a bn.a Batch_number.batch1() bn.batch1() # 2 create your own class to represenet ploymorprism class PersonDetails: def __init__(self,name,p_id,add): self.name = name self.id = p_id self.add = add class Teacher(PersonDetails): def printDetails(self): name = "Mr." + self.name t_id = self.id address = self.add details = [name,t_id,address] return details class Student(PersonDetails): def printDetails(self): name = self.name t_id = self.id address = self.add details = [name,t_id,address] return details s = Student("Faiz",9873,"Delhi") s.printDetails() t = Teacher("Fazlullah Bokhari",12345,"Banglore") t.printDetails() # 3 create your own class for custome exception class CustomeException(Exception): def __init__(self,msg): self.msg = msg try: a = int(input("enter first number: ")) b = int(input("enter second number: ")) result = a/b if b == 5: raise(CustomeException("This is custome exception class")) except CustomeException as c: print(c) except ValueError as msg: print(msg) except ZeroDivisionError as msg: print(msg) else: try: result = a/b print("result:" ,result) except Exception as e: print(e) # 4 create your own class to achive encaptulation # 5 create your own class to achive method overloading and overriding class abc : pass from abc import abstractmethod class data_project : @abstractmethod def read_file(self) : pass def validate_file_name(slef) : pass def validate_datatype(self) : pass def validate_db_connn(self) : pass def create_connn(self) : pass def insert_data(self) : pass def delete_data(self): pass def update_data(self) : pass def perform_stats(self) : pass def perform_eda(self) : pass class test: def fun(self): print("this is my sample ") def __str__(self): return str("this is function called at the time of print") t = test() print(t) t # Overloading class test: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def __str__(self): return "overloaded complete" t = test(4,5,6) print(t) def xyz(*args): return args xyz(1,2,5,48,7,8) xyz("overloading ","example") #Overriding class test: def __init__(self,a,b,c): self.a = a self.b = b self.c = c def __str__(self): return "overriding" def class_fun(self): print("this is a print from class_fun") class test1(test): def class_fun(self): print("overriding") test1_obj = test1(8,9,10) test_obj = test(10,20,30) test1_obj.class_fun() test_obj.class_fun() #4:31 ###Output _____no_output_____ ###Markdown Class, object and Inheritance Class : Is a user defined blueprint from which objects are created.Classes are created by keyword class. Members : Are nothing but variables and functions defined within a class. Note : Function defined as a member of a class is generally called as method. Attributes : Are nothing but the members of the class. Object : Is an instance of a class from which class attributes can be accessed. Note : Self parameter should be passed as a default parameter to the function within the class. ###Code #Example to perform arithmatic operations using class. class cal: def fn(self, a, b): print('Addition', a+b) print('subtraction', a-b) print('multiplication', a*b) print('division', a/b) print('floor_division', a//b) print('modulus', a%b) print('power', a**b) ob = cal() #object ob.fn(5, 3) ###Output Addition 8 subtraction 2 multiplication 15 division 1.6666666666666667 floor_division 1 modulus 2 power 125 ###Markdown Inheritance : Is nothing but using the attributes and methods of one class in another. Sub class: Is a class which inherits all the attributes and methods of another class. Base class : Is a class from which all the attributes and methods are inherited. ###Code #example for inheritance. class family: grand_parent_1 = 'a' grand_parent_2 = 'b' parent_1 = 'c' parent_2 = 'd' class parent(family): parent_1_ch_1 = 'e' parent_1_ch_2 = 'f' parent_1_ch_1_c_1 = 'g' parent_1_ch_1_c_2 = 'h' p = parent() print('My grandparent_1 name is {} and my grandparent_2 name is {} they have two childs one of them is {} and the other one is {} then again parent_1 has two childs one of them is {} and the other one is {} and again the child of parent_1 has two childs one of them is {} and the other one is {}'.format(p.grand_parent_1, p.grand_parent_2, p.parent_1, p.parent_2, p.parent_1_ch_1, p.parent_1_ch_2, p.parent_1_ch_1_c_1, p.parent_1_ch_1_c_2)) class a: number = 0 name = 'noname' #these are the attributes which are just like variables in python. def fn(): b = a() #this is an object created for class 'a' b.number = 18 b.name = 'virat' print(b.name + " " + str(b.number)) if __name__=='__main__': fn() ###Output virat 18 ###Markdown Note: While defining a function inside a class a paremeter called self is always passed. ###Code class a: def b(self, x, y): self.x = x self.y = y #these are the class methods def main(): c = a() c.b(5, 6) print(c.x+c.y) if __name__=='__main__': main() ###Output 11 ###Markdown Inheritance: Inheritance is defined as a way in which a particular class inherits features from its base class.Base class is also knows as ‘Superclass’ and the class which inherits from the Superclass is knows as ‘Subclass’ ###Code class pet: def __init__(self, name, age): #this is the constructor in python self.name = name self.age = age class dog(pet): def __init__(self, gender): self.gender = gender d = dog('toomy') d.name = 'tommy' d.age = 7 d.gender = 'female' print(d.name, d.age, d.gender) ###Output tommy 7 female ###Markdown Iterators: Iterators are objects that can be iterated upon.Python uses the __iter__() method to return an iterator object of the class.The iterator object then uses the __next__() method to get the next item.for loops stops when StopIteration Exception is raised. ###Code class reverse: def __init__(self, data): #is run when an object is created self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if(self.index == 0): raise StopIteration self.index -= 1 return self.data[self.index] def main(): rev = reverse('dog') for char in rev: print(char, end = '') if __name__=='__main__': main() class a: def fn(self): print('Hello') b = a() b.fn() class a: def __init__(self, name): self.name = name def fn(self): print('Hello Im', self.name) b = a('Virat') b.fn() class csstudent: stream = 'EEE' def __init__(self, roll): self.roll = roll a = csstudent(101) b = csstudent(102) print(a.roll) print(b.roll) print(csstudent.stream) class eestudent: stream = 'EEE' def __init__(self, roll): self.roll = roll def setAddress(self, address): self.address = address def getAddress(self): return self.address a = eestudent(101) a.setAddress('Bangalore') print(a.getAddress()) ###Output Bangalore ###Markdown Note: Empty class in python can be created using pass statement. ###Code class a: pass class A: __a = 0 #hidden variable inside a class def inc(self, b): self.__a += b print(self.__a) x = A() x.inc(2) print(x.__a) ###Output 2 ###Markdown Note: In the above program, we tried to access hidden variable outside the class using object and it threw an exception. ###Code #Accessing the value of hidden variable using tricky syntax. class A: __a = 10 x = A() print(x._A__a) ###Output 10 ###Markdown Note: We can access the value of hidden attribute by a tricky syntax as shown in the above example. Printing Objects: Printing objects gives us information about objects we are working with. ###Code class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return 'Test a:%s b%s'%(self.a, self.b) def __str__(self): return "From str method of Test: a is %s, b is %s"%(self.a, self.b) t = Test(1234, 5678) print(t) #this calls __str__ print([t]) #this calls __repr__ #example for inheritence class person: def __init__(self, name): self.name = name def getName(self): return self.name def isEmp(self): return False class Employee(person): def isEmp(self): return True emp = person('AB') print(emp.getName(), emp.isEmp()) emp = Employee('Virat') print(emp.getName(), emp.isEmp()) ###Output AB False Virat True ###Markdown Note: Issubclass() is a function that directly tells us if a class is subclass of another class. ###Code #example demonstrating above example class base(object): pass class derived(base): pass print(issubclass(derived, base)) print(issubclass(base, derived)) d = derived() b = base() print(isinstance(d, base)) print(isinstance(b, derived)) #example demonstarting the multiple inheritance class Base1(object): def __init__(self): self.str1 = 'Virat' print('Base1') class Base2(object): def __init__(self): self.str2 = 'AB' print('Base2') class Derived(Base1, Base2): def __init__(self): Base1.__init__(self) Base2.__init__(self) print('Derived') def dis(self): print(self.str1, self.str2) d = Derived() d.dis() ###Output Base1 Base2 Derived Virat AB ###Markdown Polymorphism in Python Polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being used for different types. ###Code #example for inbuilt polymorphic functions. print(len('Cricket')) print(len([1, 2, 3])) #note: here len is used to find the length of both string as well as list. #example for user-defined polymorphism. def add(x, y, z = 0): return x+y+z print(add(2, 3)) print(add(2, 3, 4)) #polymorphism with class methods. class ind(): def cap(self): print('Delhi is the capital of India') def lan(self): print('Hindi is the official language') def type(self): print('India is a developing country') class usa(): def cap(self): print('Washington D.C. is the capital of India') def lan(self): print('English is the primary language') def type(self): print('usa is a developed country') in_ob = ind() us_ob = usa() for i in (in_ob, us_ob): i.cap() i.lan() i.type() ###Output Delhi is the capital of India Hindi is the official language India is a developing country Washington D.C. is the capital of India English is the primary language usa is a developed country ###Markdown Note: In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class. This is particularly useful in cases where the method inherited from the parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the child class. This process of re-implementing a method in the child class is known as Method Overriding. ###Code #example polymorphism with inheritance. class bird(): def intro(self): print('There are many type of birds') def flight(self): print('Many birds can fly') class sparrow(bird): def flight(self): print('Sparrow can fly') class ostrich(bird): def flight(self): print('Ostrich can not fly') ob_bi = bird() ob_sp = sparrow() ob_os = ostrich() ob_bi.intro() ob_bi.flight() ob_sp.intro() ob_sp.flight() ob_os.intro() ob_os.flight() # example implementing polymorphism with function. class ind(): def cap(self): print('Delhi is the capital of India') def lan(self): print('Hindi is the official language') def type(self): print('India is a developing country') class usa(): def cap(self): print('Washington D.C. is the capital of India') def lan(self): print('English is the primary language') def type(self): print('usa is a developed country') def fn(obj): obj.cap() obj.lan() obj.type() ob_in = ind() ob_us = usa() fn(ob_in) fn(ob_us) from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def frombirthyear(cls, name, year): return cls(name, date.today().year-year) @staticmethod def isAdult(age): return age>18 person1 = Person('Virat', 30) person2 = Person.frombirthyear('Virat', 1990) print(person1.age) print(person2.age) print(Person.isAdult(30)) #example for changing the class member in python. class CSSstudent: stream = 'cse' def __init__(self, name, roll): self.name = name self.roll = roll a = CSSstudent('virat', 31) b = CSSstudent('AB', 34) print('Initially') print(a.stream) print(b.stream) a.stream = 'ece' #you can not change class variable using object. print('After changing') print(a.stream) print(b.stream) ###Output Initially cse cse After changing ece cse ###Markdown Note: We can only change class variables using class name. ###Code #example demonstrating above note. class CSSstudent: stream = 'cse' def __init__(self, name, roll): self.name = name self.roll = roll a = CSSstudent('virat', 31) print(a.stream) CSSstudent.stream = 'ece' b = CSSstudent('AB', 34) print(b.stream) ###Output cse ece ###Markdown Constructors in python Constructors are generally used for instantiating an object.The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.In Python the __init__() method is called the constructor and is always called when an object is created. There are two types of constructors in python.1. __Default__ Constructor.2. __Parameterized__ Constructor. The default constructor is simple constructor which doesn’t accept any arguments.It’s definition has only one argument which is a reference to the instance being constructed.Constructor with parameters is known as parameterized constructor.The parameterized constructor take its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer. ###Code class A: name = "" def __init__(self): #default constructor self.name = "AB" def print_name(self): print(self.name) obj = A() obj.print_name() class Subtraction: first = 0 second = 0 answer = 0 def __init__(self, f, s): #parameterized constructor self.first = f self.second = s def display(self): print('First = '+ str(self.first)) print('Second = '+ str(self.second)) print('Answer ='+str(self.answer)) def calculate(self): self.answer = self.first - self.second ob = Subtraction(2000, 1000) ob.calculate() ob.display() ###Output First = 2000 Second = 1000 Answer =1000 ###Markdown Destructors in python Destrucors are called when an object gets destroyed. In Python, destructors are not needed as much needed in C++ because Python has a garbage collector that handles memory management automatically.The _____del_____() method is known as destructor in python. It is called when all references to the object have been deleted i.e when an object is garbage collected. ###Code #example demonstrating usage of destructor in python. class A: def __init__(self): print('Created') def __del__(self): print('Destructor is called') a = A() del a ###Output Created Destructor is called ###Markdown Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope. ###Code class A: def __init__(self): print('Created') def __del__(self): print('Destructor called') def make_ob(): print('Making object...') ob = A() print('func end....') return ob print('calling make_ob func...') ob = make_ob() print('Program end') ###Output calling make_ob func... Making object... Created func end.... Program end ###Markdown str() v/s repr() in python str() and repr() are both used to string represention of an object. ###Code #example of str() a = 'Hello World' print(str(a)) print(str(230/13)) #example of repr() b = 'Hello World' print(repr(b)) print(repr(230/13)) import datetime a = datetime.datetime.now() print(str(a)) print(repr(a)) class complex: def __init__(self, real, imag): self.real = real self.imag = imag def __repr__(self): return 'Rational(%s, %s)'%(self.real, self.imag) def __str__(self): return '%s + i%s'%(self.real, self.imag) t = complex(10, 20) print(str(t)) print(repr(t)) #examples using type function. a = 3 print(type(a)) l = [1, 2, 3] print(type(l)) b = 'hello' print(type(b)) ###Output <class 'int'> <class 'list'> <class 'str'> ###Markdown Note: Every type in Python is defined by Class. So in above example, unlike C or Java where int, char, float are primary data types, in Python they are object of int class or str class. So we can make a new type by creating a class of that type. For example we can create a new type Student by creating Student class. ###Code #example. class student: pass st_ob = student() print(type(st_ob)) ###Output <class '__main__.student'> ###Markdown Class and Instance Attribute in Python. Class Attributes belongs to class instance, they will be shared by all the instances. Such attributes are defined in the class body. ###Code class sampleclass: count = 0 def increase(self): sampleclass.count += 1 s1 = sampleclass() s1.increase() print(s1.count) s2 = sampleclass() s2.increase() print(s2.count) print(sampleclass.count) ###Output 1 2 2 ###Markdown Instance Attributes: Unlike class attributes instance attributes are not shared by all the objects. Every object has it's own copy of instance attribute.To list the attributes of an object we have two functions:1.vars() : This function displays the object attributes in dictionary format.2.dir() : Whereas this function displays more attributes than vars function. This displays class attributes as well. ###Code class emp: def __init__(self, name, age): self.name = name self.age = age def show(self): print(self.name) print(self.age) e1 = emp('XYZ', 20) print(vars(e1)) print(dir(e1)) ###Output {'name': 'XYZ', 'age': 20} ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'show'] ###Markdown Reflection in Python. Reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to a function. For example, if we write type(obj) then Python will return an object which represents the type of obj.Using reflection, we can write one recursive reverse function that will work for strings, lists, and any other sequence that supports slicing and concatenation. If an obj is a reference to a string, then Python will return the str type object. Further, if we write str() we get a string which is the empty string. In other words, writing str() is the same thing as writing “”. Likewise, writing list() is the same thing as writing []. ###Code def reverse(seq): SeqType = type(seq) emptySeq = SeqType() if seq == emptySeq: return emptySeq restrev = reverse(seq[1:]) first = seq[0:1] result = restrev + first return result print(reverse([1, 2, 3, 4])) print(reverse("HELLO")) ###Output [4, 3, 2, 1] OLLEH ###Markdown Reflection-enabling functions: Include type(), isinstance(), getattr(), dir() and callable().Callable(): Any function that can be called. For an object, determines whether the object can be called. A class can be made callable by defining __class__() method. This method return True if the object appears to be callable, else it returns False. ###Code #example for callable(). x = 5 def fn(): print('callable') y = fn if(callable(x)): print('True') else: print('False') if(callable(y)): print('True') else: print('False') #example for callable when used in OOPS. class a: def __call__(self): print('Something') print(callable(a)) ###Output True ###Markdown Dir: This method try's to return the valid attributes of an object.If the object has __dir__() method, the method will be called and must return the list of attributes. If the object doesn’t have __dir()__ method, this method tries to find information from the __dict__ attribute (if defined), and from type object. In this case, the list returned from dir() may not be complete. ###Code #example. a = [1, 2, 3, 4] print(dir(a)) b = ['a', 'b'] print(dir(a)) ###Output ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ###Markdown Getattr(): Will return the value of named attribute of an object. If not found, it returns the default value provided to the function. The getattr method takes three parameters object, name and default(optional). ###Code #example. class employee: salary = 25000 company = 'XYZ' e = employee() print(getattr(e, 'salary')) print(e.salary) ###Output 25000 25000 ###Markdown Barrier Objects in Python. Some common function calls related to threading.Barrier class are:barrier.broken: Returns True if the barrier is in broken state.barrier.parties: Number of threads required to pass a barrier.barrier.abort(): Put the barrier into broken state. This causes any future calls to wait() to fail with the BrokenBarrierError.Abort function calls on barrier are often required to skip the conditions of deadlocking during program execution.barrier.reset(): Return the barrier to default, empty state.barrier.wait(): Pass the barrier. When all the threads party to the barrier have called this function, they are all released simultaneously. If a timeout is provided, it is used in preference to any that was supplied to the class constructor.The return value is an integer in the range 0 to parties – 1, different for each thread. If the call times out, the barrier is put into the broken state. This method may raise a BrokenBarrierError exception if the barrier is broken or reset while a thread is waiting.barrier.n_wait: The number of threads currently waiting in the barrier. ###Code import threading barrier = threading.Barrier(3) class thread(threading.Thread): def __init__(self, thread_ID): threading.Thread.__init__(self) self.thread_ID = thread_ID def run(self): print(str(self.thread_ID) + '\n') barrier.wait() t1 = thread(100) t2 = thread(101) t1.start() t2.start() barrier.wait() print('Exit\n') ###Output 100 101 Exit ###Markdown Timer Objects in python. Timer objects are used to represent actions that needs to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action was actually performed by the interpreter because it is the responsibility of the thread scheduler to actually schedule the thread corresponding to the timer object.Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly. ###Code #example for creating a timer object. import threading def fn(): print('Hello there') timer = threading.Timer(10.0, fn) timer.start() print('Exit') ###Output Exit Hello there ###Markdown cancelling a timer: Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage. ###Code import threading def fn(): print('Hello There') timer = threading.Timer(1.0, fn) timer.start() print('Cancelling Timer') timer.cancel() print('Exit') ###Output Cancelling Timer Exit ###Markdown Garbage Collection in python. Python's memory allocation and deallocation is automatic. Python uses two stratergies to allocate and deallocate the memory.1.Reference counting.2.Garbage Collection. Prior to Python version 2.0, the Python interpreter only used reference counting for memory management. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated. ###Code #example for reference counting. b = 9 #here 9 is an object and 'b' is reference to an object. b = 4 #reference count of object 'b' becomes zero as the value of object changes. ###Output _____no_output_____ ###Markdown A reference cycle is created when there is no way that the refence count of the object can reach.Note: A reference cycle is created when there is no way the reference count of the object can reach. Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are common. The easiest way to create a reference cycle is to create an object which refers to itself. ###Code #example demonstarting above note. def fn(): x = [] x.append(x) fn() #Ways to make an object eligible for garbage collection #1. x = [] x.append(1) x.append(2) del x ###Output _____no_output_____ ###Markdown 2.Automatic Garbage Collection of Cycles: Because reference cycles take computational work to discover, garbage collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations is greater than the threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects in Python known as generation 0 objects) by importing the gc module and asking for garbage collection thresholds. ###Code import gc print(gc.get_threshold()) ###Output (700, 10, 10) ###Markdown Here, the default threshold on the above system is 700. This means when the number of allocations vs. the number of deallocations is greater than 700 the automatic garbage collector will run. Thus any portion of your code which frees up large blocks of memory is a good candidate for running manual garbage collection. 3.Manual Garbage Collection: Invoking the garbage collector manually during the execution of a program can be a good idea on how to handle memory being consumed by reference cycles. ###Code import gc collected = gc.collect() print(collected) ###Output 204 ###Markdown Inheritance ###Code class Animal: def __init__(self): print("Animal Got Created") def whoami(self): print('i am an animal') def eat(self): print('eating') class Dog(Animal): def __init__(self): Animal.__init__(self) print("nik got created") def whoami(self): print('i am nik -mr.street') def talk(self): print('our nik says bhoww bhoww') nik = Dog() nik.eat() nik.whoami() ###Output i am nik -mr.street
doc/ipython-notebooks/multiclass/Tree/TreeEnsemble.ipynb
###Markdown Ensemble of Decision Trees *By Parijat Mazumdar (GitHub ID: [mazumdarparijat](https://github.com/mazumdarparijat))* This notebook illustrates the use of [Random Forests](http://en.wikipedia.org/wiki/Random_forest) in Shogun for classification and regression. We will understand the functioning of Random Forests, discuss about the importance of its various parameters and appreciate the usefulness of this learning method. What is Random Forest? Random Forest is an ensemble learning method in which a collection of decision trees are grown during training and the combination of the outputs of all the individual trees are considered during testing or application. The strategy for combination can be varied but generally, in case of classification, the mode of the output classes is used and, in case of regression, the mean of the outputs is used. The randomness in the method, as the method's name suggests, is infused mainly by the random subspace sampling done while training individual trees. While choosing the best split during tree growing, only a small randomly chosen subset of all the features is considered. The subset size is a user-controlled parameter and is usually the square root of the total number of available features. The purpose of the random subset sampling method is to decorrelate the individual trees in the forest, thus making the overall model more generic; i.e. decrease the variance without increasing the bias (see [bias-variance trade-off](http://en.wikipedia.org/wiki/Bias%E2%80%93variance_dilemma)). The purpose of Random Forest, in summary, is to reduce the generalization error of the model as much as possible. Random Forest vs Decision Tree In this section, we will appreciate the importance of training a Random Forest over a single decision tree. In the process, we will also learn how to use Shogun's [Random Forest class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CRandomForest.html). For this purpose, we will use the [letter recognition dataset](https://archive.ics.uci.edu/ml/datasets/Letter+Recognition). This dataset contains pixel information (16 features) of 20000 samples of the English alphabet. This is a 26-class classification problem where the task is to predict the alphabet given the 16 pixel features. We start by loading the training dataset. ###Code import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline def load_file(feat_file,label_file): feats=sg.create_features(sg.CSVFile(feat_file)) labels=sg.create_labels(sg.CSVFile(label_file)) return (feats, labels) trainfeat_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_fm_letter.dat') trainlab_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_label_letter.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next, we decide the parameters of our Random Forest. ###Code def setup_random_forest(num_trees,rand_subset_size,combination_rule,feature_types): rf=sg.create_machine("RandomForest", num_bags=num_trees, combination_rule=combination_rule) rf.get("machine").put("m_randsubset_size", rand_subset_size) rf.get("machine").put("nominal", feature_types) return rf comb_rule=sg.create_combination_rule("MajorityVote") feat_types=np.array([False]*16) rand_forest=setup_random_forest(10,4,comb_rule,feat_types) ###Output _____no_output_____ ###Markdown In the above code snippet, we decided to create a forest using 10 trees in which each split in individual trees will be using a randomly chosen subset of 4 features. Note that 4 here is the square root of the total available features (16) and is hence the usually chosen value as mentioned in the introductory paragraph. The strategy for combination chosen is [Majority Vote](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1MajorityVote.html) which, as the name suggests, chooses the mode of all the individual tree outputs. The given features are all continuous in nature and hence feature types are all set false (i.e. not nominal). Next, we train our Random Forest and use it to classify letters in our test dataset. ###Code # train forest rand_forest.put('labels', train_labels) rand_forest.train(train_feats) # load test dataset testfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_fm_letter.dat') testlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_label_letter.dat') test_feats,test_labels=load_file(testfeat_file,testlab_file) # apply forest output_rand_forest_train=rand_forest.apply_multiclass(train_feats) output_rand_forest_test=rand_forest.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown We have with us the labels predicted by our Random Forest model. Let us also get the predictions made by a single tree. For this purpose, we train a [CART-flavoured decision tree](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CARTree.html). ###Code def train_cart(train_feats,train_labels,feature_types,problem_type): c=sg.create_machine("CARTree", nominal=feature_types, mode=problem_type, folds=2, apply_cv_pruning=False, labels=train_labels) c.train(train_feats) return c # train CART cart=train_cart(train_feats,train_labels,feat_types,"PT_MULTICLASS") # apply CART model output_cart_train=cart.apply_multiclass(train_feats) output_cart_test=cart.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown With both results at our disposal, let us find out which one is better. ###Code accuracy=sg.create_evaluation("MulticlassAccuracy") rf_train_accuracy=accuracy.evaluate(output_rand_forest_train,train_labels)*100 rf_test_accuracy=accuracy.evaluate(output_rand_forest_test,test_labels)*100 cart_train_accuracy=accuracy.evaluate(output_cart_train,train_labels)*100 cart_test_accuracy=accuracy.evaluate(output_cart_test,test_labels)*100 print('Random Forest training accuracy : '+str(round(rf_train_accuracy,3))+'%') print('CART training accuracy : '+str(round(cart_train_accuracy,3))+'%') print print('Random Forest test accuracy : '+str(round(rf_test_accuracy,3))+'%') print('CART test accuracy : '+str(round(cart_test_accuracy,3))+'%') ###Output _____no_output_____ ###Markdown As it is clear from the results above, we see a significant improvement in the predictions. The reason for the improvement is clear when one looks at the training accuracy. The single decision tree was over-fitting on the training dataset and hence was not generic. Random Forest on the other hand appropriately trades off training accuracy for the sake of generalization of the model. Impressed already? Let us now see what happens if we increase the number of trees in our forest. Random Forest parameters : Number of trees and random subset size In the last section, we trained a forest of 10 trees. What happens if we make our forest with 20 trees? Let us try to answer this question in a generic way. ###Code def get_rf_accuracy(num_trees,rand_subset_size): rf=setup_random_forest(num_trees,rand_subset_size,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) out_test=rf.apply_multiclass(test_feats) acc=sg.create_evaluation("MulticlassAccuracy") return acc.evaluate(out_test,test_labels) ###Output _____no_output_____ ###Markdown The method above takes the number of trees and subset size as inputs and returns the evaluated accuracy as output. Let us use this method to get the accuracy for different number of trees keeping the subset size constant at 4. ###Code num_trees4=[5,10,20,50,100] rf_accuracy_4=[round(get_rf_accuracy(i,4)*100,3) for i in num_trees4] print('Random Forest accuracies (as %) :' + str(rf_accuracy_4)) # plot results x4=[1] y4=[86.48] # accuracy for single tree-CART x4.extend(num_trees4) y4.extend(rf_accuracy_4) plt.plot(x4,y4,'--bo') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %)') plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown NOTE : The above code snippet takes about a minute to execute. Please wait patiently. We see from the above plot that the accuracy of the model keeps on increasing as we increase the number of trees on our Random Forest and eventually satarates at some value. Extrapolating the above plot qualitatively, the saturation value will be somewhere around 96.5%. The jump of accuracy from 86.48% for a single tree to 96.5% for a Random Forest with about 100 trees definitely highlights the importance of the Random Forest algorithm.The inevitable question at this point is whether it is possible to achieve higher accuracy saturation by working with lesser (or greater) random feature subset size. Let us figure this out by repeating the above procedure for random subset size as 2 and 8. ###Code # subset size 2 num_trees2=[10,20,50,100] rf_accuracy_2=[round(get_rf_accuracy(i,2)*100,3) for i in num_trees2] print('Random Forest accuracies (as %) :' + str(rf_accuracy_2)) # subset size 8 num_trees8=[5,10,50,100] rf_accuracy_8=[round(get_rf_accuracy(i,8)*100,3) for i in num_trees8] print('Random Forest accuracies (as %) :' + str(rf_accuracy_8)) ###Output _____no_output_____ ###Markdown NOTE : The above code snippets take about a minute each to execute. Please wait patiently. Let us plot all the results together and then comprehend the results. ###Code x2=[1] y2=[86.48] x2.extend(num_trees2) y2.extend(rf_accuracy_2) x8=[1] y8=[86.48] x8.extend(num_trees8) y8.extend(rf_accuracy_8) plt.plot(x2,y2,'--bo',label='Subset Size = 2') plt.plot(x4,y4,'--r^',label='Subset Size = 4') plt.plot(x8,y8,'--gs',label='Subset Size = 8') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %) ') plt.legend(bbox_to_anchor=(0.92,0.4)) plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown As we can see from the above plot, the subset size does not have a major impact on the saturated accuracy obtained in this particular dataset. While this is true in many datasets, this is not a generic observation. In some datasets, the random feature sample size does have a measurable impact on the test accuracy. A simple strategy to find the optimal subset size is to use cross-validation. But with Random Forest model, there is actually no need to perform cross-validation. Let us see how in the next section. Out-of-bag error The individual trees in a Random Forest are trained over data vectors randomly chosen with replacement. As a result, some of the data vectors are left out of training by each of the individual trees. These vectors form the out-of-bag (OOB) vectors of the corresponding trees. A data vector can be part of OOB classes of multiple trees. While calculating OOB error, a data vector is applied to only those trees of which it is a part of OOB class and the results are combined. This combined result averaged over similar estimate for all other vectors gives the OOB error. The OOB error is an estimate of the generalization bound of the Random Forest model. Let us see how to compute this OOB estimate in Shogun. ###Code rf=setup_random_forest(100,2,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) # set evaluation strategy rf.put("oob_evaluation_metric", sg.create_evaluation("MulticlassAccuracy")) oobe=rf.get("oob_error") print('OOB accuracy : '+str(round(oobe*100,3))+'%') ###Output _____no_output_____ ###Markdown The above OOB accuracy calculated is found to be slighly less than the test error evaluated in the previous section (see plot for num_trees=100 and rand_subset_size=2). This is because of the fact that the OOB estimate depicts the expected error for any generalized set of data vectors. It is only natural that for some set of vectors, the actual accuracy is slightly greater than the OOB estimate while in some cases the accuracy observed in a bit lower.Let us now apply the Random Forest model to the [wine dataset](https://archive.ics.uci.edu/ml/datasets/Wine). This dataset is different from the previous one in the sense that this dataset is small and has no separate test dataset. Hence OOB (or equivalently cross-validation) is the only viable strategy available here. Let us read the dataset first. ###Code trainfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat') trainlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next let us find out the appropriate feature subset size. For this we will make use of OOB error. ###Code def get_oob_errors_wine(num_trees,rand_subset_size): feat_types=np.array([False]*13) rf=setup_random_forest(num_trees,rand_subset_size,sg.create_combination_rule("MajorityVote"),feat_types) rf.put('labels', train_labels) rf.train(train_feats) rf.put("oob_evaluation_metric", sg.create_evaluation("MulticlassAccuracy")) return rf.get("oob_error") size=[1,2,4,6,8,10,13] oobe=[round(get_oob_errors_wine(400,i)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([0,14]) plt.xlabel('Random subset size') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown From the above plot it is clear that subset size of 2 or 3 produces maximum accuracy for wine classification. At this value of subset size, the expected classification accuracy is of the model is 98.87%. Finally, as a sanity check, let us plot the accuracy vs number of trees curve to ensure that 400 is indeed a sufficient value ie. the oob error saturates before 400. ###Code size=[50,100,200,400,600] oobe=[round(get_oob_errors_wine(i,2)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([40,650]) plt.ylim([90,100]) plt.xlabel('Number of trees') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown Ensemble of Decision Trees *By Parijat Mazumdar (GitHub ID: [mazumdarparijat](https://github.com/mazumdarparijat))* This notebook illustrates the use of [Random Forests](http://en.wikipedia.org/wiki/Random_forest) in Shogun for classification and regression. We will understand the functioning of Random Forests, discuss about the importance of its various parameters and appreciate the usefulness of this learning method. What is Random Forest? Random Forest is an ensemble learning method in which a collection of decision trees are grown during training and the combination of the outputs of all the individual trees are considered during testing or application. The strategy for combination can be varied but generally, in case of classification, the mode of the output classes is used and, in case of regression, the mean of the outputs is used. The randomness in the method, as the method's name suggests, is infused mainly by the random subspace sampling done while training individual trees. While choosing the best split during tree growing, only a small randomly chosen subset of all the features is considered. The subset size is a user-controlled parameter and is usually the square root of the total number of available features. The purpose of the random subset sampling method is to decorrelate the individual trees in the forest, thus making the overall model more generic; i.e. decrease the variance without increasing the bias (see [bias-variance trade-off](http://en.wikipedia.org/wiki/Bias%E2%80%93variance_dilemma)). The purpose of Random Forest, in summary, is to reduce the generalization error of the model as much as possible. Random Forest vs Decision Tree In this section, we will appreciate the importance of training a Random Forest over a single decision tree. In the process, we will also learn how to use Shogun's [Random Forest class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CRandomForest.html). For this purpose, we will use the [letter recognition dataset](https://archive.ics.uci.edu/ml/datasets/Letter+Recognition). This dataset contains pixel information (16 features) of 20000 samples of the English alphabet. This is a 26-class classification problem where the task is to predict the alphabet given the 16 pixel features. We start by loading the training dataset. ###Code import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') from shogun import CSVFile,features,MulticlassLabels def load_file(feat_file,label_file): feats=features(CSVFile(feat_file)) labels=MulticlassLabels(CSVFile(label_file)) return (feats, labels) trainfeat_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_fm_letter.dat') trainlab_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_label_letter.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next, we decide the parameters of our Random Forest. ###Code from shogun import RandomForest, MajorityVote from numpy import array def setup_random_forest(num_trees,rand_subset_size,combination_rule,feature_types): rf=RandomForest(rand_subset_size,num_trees) rf.put('combination_rule', combination_rule) rf.set_feature_types(feature_types) return rf comb_rule=MajorityVote() feat_types=array([False]*16) rand_forest=setup_random_forest(10,4,comb_rule,feat_types) ###Output _____no_output_____ ###Markdown In the above code snippet, we decided to create a forest using 10 trees in which each split in individual trees will be using a randomly chosen subset of 4 features. Note that 4 here is the square root of the total available features (16) and is hence the usually chosen value as mentioned in the introductory paragraph. The strategy for combination chosen is [Majority Vote](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CMajorityVote.html) which, as the name suggests, chooses the mode of all the individual tree outputs. The given features are all continuous in nature and hence feature types are all set false (i.e. not nominal). Next, we train our Random Forest and use it to classify letters in our test dataset. ###Code # train forest rand_forest.put('labels', train_labels) rand_forest.train(train_feats) # load test dataset testfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_fm_letter.dat') testlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_label_letter.dat') test_feats,test_labels=load_file(testfeat_file,testlab_file) # apply forest output_rand_forest_train=rand_forest.apply_multiclass(train_feats) output_rand_forest_test=rand_forest.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown We have with us the labels predicted by our Random Forest model. Let us also get the predictions made by a single tree. For this purpose, we train a [CART-flavoured decision tree](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CCARTree.html). ###Code from shogun import CARTree, PT_MULTICLASS def train_cart(train_feats,train_labels,feature_types,problem_type): c=CARTree(feature_types,problem_type,2,False) c.put('labels', train_labels) c.train(train_feats) return c # train CART cart=train_cart(train_feats,train_labels,feat_types,PT_MULTICLASS) # apply CART model output_cart_train=cart.apply_multiclass(train_feats) output_cart_test=cart.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown With both results at our disposal, let us find out which one is better. ###Code from shogun import MulticlassAccuracy accuracy=MulticlassAccuracy() rf_train_accuracy=accuracy.evaluate(output_rand_forest_train,train_labels)*100 rf_test_accuracy=accuracy.evaluate(output_rand_forest_test,test_labels)*100 cart_train_accuracy=accuracy.evaluate(output_cart_train,train_labels)*100 cart_test_accuracy=accuracy.evaluate(output_cart_test,test_labels)*100 print('Random Forest training accuracy : '+str(round(rf_train_accuracy,3))+'%') print('CART training accuracy : '+str(round(cart_train_accuracy,3))+'%') print print('Random Forest test accuracy : '+str(round(rf_test_accuracy,3))+'%') print('CART test accuracy : '+str(round(cart_test_accuracy,3))+'%') ###Output _____no_output_____ ###Markdown As it is clear from the results above, we see a significant improvement in the predictions. The reason for the improvement is clear when one looks at the training accuracy. The single decision tree was over-fitting on the training dataset and hence was not generic. Random Forest on the other hand appropriately trades off training accuracy for the sake of generalization of the model. Impressed already? Let us now see what happens if we increase the number of trees in our forest. Random Forest parameters : Number of trees and random subset size In the last section, we trained a forest of 10 trees. What happens if we make our forest with 20 trees? Let us try to answer this question in a generic way. ###Code def get_rf_accuracy(num_trees,rand_subset_size): rf=setup_random_forest(num_trees,rand_subset_size,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) out_test=rf.apply_multiclass(test_feats) acc=MulticlassAccuracy() return acc.evaluate(out_test,test_labels) ###Output _____no_output_____ ###Markdown The method above takes the number of trees and subset size as inputs and returns the evaluated accuracy as output. Let us use this method to get the accuracy for different number of trees keeping the subset size constant at 4. ###Code import matplotlib.pyplot as plt % matplotlib inline num_trees4=[5,10,20,50,100] rf_accuracy_4=[round(get_rf_accuracy(i,4)*100,3) for i in num_trees4] print('Random Forest accuracies (as %) :' + str(rf_accuracy_4)) # plot results x4=[1] y4=[86.48] # accuracy for single tree-CART x4.extend(num_trees4) y4.extend(rf_accuracy_4) plt.plot(x4,y4,'--bo') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %)') plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown NOTE : The above code snippet takes about a minute to execute. Please wait patiently. We see from the above plot that the accuracy of the model keeps on increasing as we increase the number of trees on our Random Forest and eventually satarates at some value. Extrapolating the above plot qualitatively, the saturation value will be somewhere around 96.5%. The jump of accuracy from 86.48% for a single tree to 96.5% for a Random Forest with about 100 trees definitely highlights the importance of the Random Forest algorithm.The inevitable question at this point is whether it is possible to achieve higher accuracy saturation by working with lesser (or greater) random feature subset size. Let us figure this out by repeating the above procedure for random subset size as 2 and 8. ###Code # subset size 2 num_trees2=[10,20,50,100] rf_accuracy_2=[round(get_rf_accuracy(i,2)*100,3) for i in num_trees2] print('Random Forest accuracies (as %) :' + str(rf_accuracy_2)) # subset size 8 num_trees8=[5,10,50,100] rf_accuracy_8=[round(get_rf_accuracy(i,8)*100,3) for i in num_trees8] print('Random Forest accuracies (as %) :' + str(rf_accuracy_8)) ###Output _____no_output_____ ###Markdown NOTE : The above code snippets take about a minute each to execute. Please wait patiently. Let us plot all the results together and then comprehend the results. ###Code x2=[1] y2=[86.48] x2.extend(num_trees2) y2.extend(rf_accuracy_2) x8=[1] y8=[86.48] x8.extend(num_trees8) y8.extend(rf_accuracy_8) plt.plot(x2,y2,'--bo',label='Subset Size = 2') plt.plot(x4,y4,'--r^',label='Subset Size = 4') plt.plot(x8,y8,'--gs',label='Subset Size = 8') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %) ') plt.legend(bbox_to_anchor=(0.92,0.4)) plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown As we can see from the above plot, the subset size does not have a major impact on the saturated accuracy obtained in this particular dataset. While this is true in many datasets, this is not a generic observation. In some datasets, the random feature sample size does have a measurable impact on the test accuracy. A simple strategy to find the optimal subset size is to use cross-validation. But with Random Forest model, there is actually no need to perform cross-validation. Let us see how in the next section. Out-of-bag error The individual trees in a Random Forest are trained over data vectors randomly chosen with replacement. As a result, some of the data vectors are left out of training by each of the individual trees. These vectors form the out-of-bag (OOB) vectors of the corresponding trees. A data vector can be part of OOB classes of multiple trees. While calculating OOB error, a data vector is applied to only those trees of which it is a part of OOB class and the results are combined. This combined result averaged over similar estimate for all other vectors gives the OOB error. The OOB error is an estimate of the generalization bound of the Random Forest model. Let us see how to compute this OOB estimate in Shogun. ###Code rf=setup_random_forest(100,2,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) # set evaluation strategy eval=MulticlassAccuracy() oobe=rf.get_oob_error(eval) print('OOB accuracy : '+str(round(oobe*100,3))+'%') ###Output _____no_output_____ ###Markdown The above OOB accuracy calculated is found to be slighly less than the test error evaluated in the previous section (see plot for num_trees=100 and rand_subset_size=2). This is because of the fact that the OOB estimate depicts the expected error for any generalized set of data vectors. It is only natural that for some set of vectors, the actual accuracy is slightly greater than the OOB estimate while in some cases the accuracy observed in a bit lower.Let us now apply the Random Forest model to the [wine dataset](https://archive.ics.uci.edu/ml/datasets/Wine). This dataset is different from the previous one in the sense that this dataset is small and has no separate test dataset. Hence OOB (or equivalently cross-validation) is the only viable strategy available here. Let us read the dataset first. ###Code trainfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat') trainlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next let us find out the appropriate feature subset size. For this we will make use of OOB error. ###Code import matplotlib.pyplot as plt def get_oob_errors_wine(num_trees,rand_subset_size): feat_types=array([False]*13) rf=setup_random_forest(num_trees,rand_subset_size,MajorityVote(),feat_types) rf.put('labels', train_labels) rf.train(train_feats) eval=MulticlassAccuracy() return rf.get_oob_error(eval) size=[1,2,4,6,8,10,13] oobe=[round(get_oob_errors_wine(400,i)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([0,14]) plt.xlabel('Random subset size') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown From the above plot it is clear that subset size of 2 or 3 produces maximum accuracy for wine classification. At this value of subset size, the expected classification accuracy is of the model is 98.87%. Finally, as a sanity check, let us plot the accuracy vs number of trees curve to ensure that 400 is indeed a sufficient value ie. the oob error saturates before 400. ###Code size=[50,100,200,400,600] oobe=[round(get_oob_errors_wine(i,2)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([40,650]) plt.ylim([95,100]) plt.xlabel('Number of trees') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown Ensemble of Decision Trees *By Parijat Mazumdar (GitHub ID: [mazumdarparijat](https://github.com/mazumdarparijat))* This notebook illustrates the use of [Random Forests](http://en.wikipedia.org/wiki/Random_forest) in Shogun for classification and regression. We will understand the functioning of Random Forests, discuss about the importance of its various parameters and appreciate the usefulness of this learning method. What is Random Forest? Random Forest is an ensemble learning method in which a collection of decision trees are grown during training and the combination of the outputs of all the individual trees are considered during testing or application. The strategy for combination can be varied but generally, in case of classification, the mode of the output classes is used and, in case of regression, the mean of the outputs is used. The randomness in the method, as the method's name suggests, is infused mainly by the random subspace sampling done while training individual trees. While choosing the best split during tree growing, only a small randomly chosen subset of all the features is considered. The subset size is a user-controlled parameter and is usually the square root of the total number of available features. The purpose of the random subset sampling method is to decorrelate the individual trees in the forest, thus making the overall model more generic; i.e. decrease the variance without increasing the bias (see [bias-variance trade-off](http://en.wikipedia.org/wiki/Bias%E2%80%93variance_dilemma)). The purpose of Random Forest, in summary, is to reduce the generalization error of the model as much as possible. Random Forest vs Decision Tree In this section, we will appreciate the importance of training a Random Forest over a single decision tree. In the process, we will also learn how to use Shogun's [Random Forest class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CRandomForest.html). For this purpose, we will use the [letter recognition dataset](https://archive.ics.uci.edu/ml/datasets/Letter+Recognition). This dataset contains pixel information (16 features) of 20000 samples of the English alphabet. This is a 26-class classification problem where the task is to predict the alphabet given the 16 pixel features. We start by loading the training dataset. ###Code import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline def load_file(feat_file,label_file): feats=sg.features(sg.CSVFile(feat_file)) labels=sg.labels(sg.CSVFile(label_file)) return (feats, labels) trainfeat_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_fm_letter.dat') trainlab_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_label_letter.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next, we decide the parameters of our Random Forest. ###Code def setup_random_forest(num_trees,rand_subset_size,combination_rule,feature_types): rf=sg.machine("RandomForest", num_bags=num_trees, combination_rule=combination_rule) rf.get("machine").put("m_randsubset_size", rand_subset_size) rf.get("machine").put("nominal", feature_types) return rf comb_rule=sg.combination_rule("MajorityVote") feat_types=np.array([False]*16) rand_forest=setup_random_forest(10,4,comb_rule,feat_types) ###Output _____no_output_____ ###Markdown In the above code snippet, we decided to create a forest using 10 trees in which each split in individual trees will be using a randomly chosen subset of 4 features. Note that 4 here is the square root of the total available features (16) and is hence the usually chosen value as mentioned in the introductory paragraph. The strategy for combination chosen is [Majority Vote](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1MajorityVote.html) which, as the name suggests, chooses the mode of all the individual tree outputs. The given features are all continuous in nature and hence feature types are all set false (i.e. not nominal). Next, we train our Random Forest and use it to classify letters in our test dataset. ###Code # train forest rand_forest.put('labels', train_labels) rand_forest.train(train_feats) # load test dataset testfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_fm_letter.dat') testlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_label_letter.dat') test_feats,test_labels=load_file(testfeat_file,testlab_file) # apply forest output_rand_forest_train=rand_forest.apply_multiclass(train_feats) output_rand_forest_test=rand_forest.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown We have with us the labels predicted by our Random Forest model. Let us also get the predictions made by a single tree. For this purpose, we train a [CART-flavoured decision tree](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CARTree.html). ###Code def train_cart(train_feats,train_labels,feature_types,problem_type): c=sg.machine("CARTree", nominal=feature_types, mode=problem_type, folds=2, apply_cv_pruning=False, labels=train_labels) c.train(train_feats) return c # train CART cart=train_cart(train_feats,train_labels,feat_types,"PT_MULTICLASS") # apply CART model output_cart_train=cart.apply_multiclass(train_feats) output_cart_test=cart.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown With both results at our disposal, let us find out which one is better. ###Code accuracy=sg.evaluation("MulticlassAccuracy") rf_train_accuracy=accuracy.evaluate(output_rand_forest_train,train_labels)*100 rf_test_accuracy=accuracy.evaluate(output_rand_forest_test,test_labels)*100 cart_train_accuracy=accuracy.evaluate(output_cart_train,train_labels)*100 cart_test_accuracy=accuracy.evaluate(output_cart_test,test_labels)*100 print('Random Forest training accuracy : '+str(round(rf_train_accuracy,3))+'%') print('CART training accuracy : '+str(round(cart_train_accuracy,3))+'%') print print('Random Forest test accuracy : '+str(round(rf_test_accuracy,3))+'%') print('CART test accuracy : '+str(round(cart_test_accuracy,3))+'%') ###Output _____no_output_____ ###Markdown As it is clear from the results above, we see a significant improvement in the predictions. The reason for the improvement is clear when one looks at the training accuracy. The single decision tree was over-fitting on the training dataset and hence was not generic. Random Forest on the other hand appropriately trades off training accuracy for the sake of generalization of the model. Impressed already? Let us now see what happens if we increase the number of trees in our forest. Random Forest parameters : Number of trees and random subset size In the last section, we trained a forest of 10 trees. What happens if we make our forest with 20 trees? Let us try to answer this question in a generic way. ###Code def get_rf_accuracy(num_trees,rand_subset_size): rf=setup_random_forest(num_trees,rand_subset_size,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) out_test=rf.apply_multiclass(test_feats) acc=sg.evaluation("MulticlassAccuracy") return acc.evaluate(out_test,test_labels) ###Output _____no_output_____ ###Markdown The method above takes the number of trees and subset size as inputs and returns the evaluated accuracy as output. Let us use this method to get the accuracy for different number of trees keeping the subset size constant at 4. ###Code num_trees4=[5,10,20,50,100] rf_accuracy_4=[round(get_rf_accuracy(i,4)*100,3) for i in num_trees4] print('Random Forest accuracies (as %) :' + str(rf_accuracy_4)) # plot results x4=[1] y4=[86.48] # accuracy for single tree-CART x4.extend(num_trees4) y4.extend(rf_accuracy_4) plt.plot(x4,y4,'--bo') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %)') plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown NOTE : The above code snippet takes about a minute to execute. Please wait patiently. We see from the above plot that the accuracy of the model keeps on increasing as we increase the number of trees on our Random Forest and eventually satarates at some value. Extrapolating the above plot qualitatively, the saturation value will be somewhere around 96.5%. The jump of accuracy from 86.48% for a single tree to 96.5% for a Random Forest with about 100 trees definitely highlights the importance of the Random Forest algorithm.The inevitable question at this point is whether it is possible to achieve higher accuracy saturation by working with lesser (or greater) random feature subset size. Let us figure this out by repeating the above procedure for random subset size as 2 and 8. ###Code # subset size 2 num_trees2=[10,20,50,100] rf_accuracy_2=[round(get_rf_accuracy(i,2)*100,3) for i in num_trees2] print('Random Forest accuracies (as %) :' + str(rf_accuracy_2)) # subset size 8 num_trees8=[5,10,50,100] rf_accuracy_8=[round(get_rf_accuracy(i,8)*100,3) for i in num_trees8] print('Random Forest accuracies (as %) :' + str(rf_accuracy_8)) ###Output _____no_output_____ ###Markdown NOTE : The above code snippets take about a minute each to execute. Please wait patiently. Let us plot all the results together and then comprehend the results. ###Code x2=[1] y2=[86.48] x2.extend(num_trees2) y2.extend(rf_accuracy_2) x8=[1] y8=[86.48] x8.extend(num_trees8) y8.extend(rf_accuracy_8) plt.plot(x2,y2,'--bo',label='Subset Size = 2') plt.plot(x4,y4,'--r^',label='Subset Size = 4') plt.plot(x8,y8,'--gs',label='Subset Size = 8') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %) ') plt.legend(bbox_to_anchor=(0.92,0.4)) plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown As we can see from the above plot, the subset size does not have a major impact on the saturated accuracy obtained in this particular dataset. While this is true in many datasets, this is not a generic observation. In some datasets, the random feature sample size does have a measurable impact on the test accuracy. A simple strategy to find the optimal subset size is to use cross-validation. But with Random Forest model, there is actually no need to perform cross-validation. Let us see how in the next section. Out-of-bag error The individual trees in a Random Forest are trained over data vectors randomly chosen with replacement. As a result, some of the data vectors are left out of training by each of the individual trees. These vectors form the out-of-bag (OOB) vectors of the corresponding trees. A data vector can be part of OOB classes of multiple trees. While calculating OOB error, a data vector is applied to only those trees of which it is a part of OOB class and the results are combined. This combined result averaged over similar estimate for all other vectors gives the OOB error. The OOB error is an estimate of the generalization bound of the Random Forest model. Let us see how to compute this OOB estimate in Shogun. ###Code rf=setup_random_forest(100,2,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) # set evaluation strategy rf.put("oob_evaluation_metric", sg.evaluation("MulticlassAccuracy")) oobe=rf.get("oob_error") print('OOB accuracy : '+str(round(oobe*100,3))+'%') ###Output _____no_output_____ ###Markdown The above OOB accuracy calculated is found to be slighly less than the test error evaluated in the previous section (see plot for num_trees=100 and rand_subset_size=2). This is because of the fact that the OOB estimate depicts the expected error for any generalized set of data vectors. It is only natural that for some set of vectors, the actual accuracy is slightly greater than the OOB estimate while in some cases the accuracy observed in a bit lower.Let us now apply the Random Forest model to the [wine dataset](https://archive.ics.uci.edu/ml/datasets/Wine). This dataset is different from the previous one in the sense that this dataset is small and has no separate test dataset. Hence OOB (or equivalently cross-validation) is the only viable strategy available here. Let us read the dataset first. ###Code trainfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat') trainlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next let us find out the appropriate feature subset size. For this we will make use of OOB error. ###Code def get_oob_errors_wine(num_trees,rand_subset_size): feat_types=np.array([False]*13) rf=setup_random_forest(num_trees,rand_subset_size,sg.combination_rule("MajorityVote"),feat_types) rf.put('labels', train_labels) rf.train(train_feats) rf.put("oob_evaluation_metric", sg.evaluation("MulticlassAccuracy")) return rf.get("oob_error") size=[1,2,4,6,8,10,13] oobe=[round(get_oob_errors_wine(400,i)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([0,14]) plt.xlabel('Random subset size') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown From the above plot it is clear that subset size of 2 or 3 produces maximum accuracy for wine classification. At this value of subset size, the expected classification accuracy is of the model is 98.87%. Finally, as a sanity check, let us plot the accuracy vs number of trees curve to ensure that 400 is indeed a sufficient value ie. the oob error saturates before 400. ###Code size=[50,100,200,400,600] oobe=[round(get_oob_errors_wine(i,2)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([40,650]) plt.ylim([90,100]) plt.xlabel('Number of trees') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown Ensemble of Decision Trees *By Parijat Mazumdar (GitHub ID: [mazumdarparijat](https://github.com/mazumdarparijat))* This notebook illustrates the use of [Random Forests](http://en.wikipedia.org/wiki/Random_forest) in Shogun for classification and regression. We will understand the functioning of Random Forests, discuss about the importance of its various parameters and appreciate the usefulness of this learning method. What is Random Forest? Random Forest is an ensemble learning method in which a collection of decision trees are grown during training and the combination of the outputs of all the individual trees are considered during testing or application. The strategy for combination can be varied but generally, in case of classification, the mode of the output classes is used and, in case of regression, the mean of the outputs is used. The randomness in the method, as the method's name suggests, is infused mainly by the random subspace sampling done while training individual trees. While choosing the best split during tree growing, only a small randomly chosen subset of all the features is considered. The subset size is a user-controlled parameter and is usually the square root of the total number of available features. The purpose of the random subset sampling method is to decorrelate the individual trees in the forest, thus making the overall model more generic; i.e. decrease the variance without increasing the bias (see [bias-variance trade-off](http://en.wikipedia.org/wiki/Bias%E2%80%93variance_dilemma)). The purpose of Random Forest, in summary, is to reduce the generalization error of the model as much as possible. Random Forest vs Decision Tree In this section, we will appreciate the importance of training a Random Forest over a single decision tree. In the process, we will also learn how to use Shogun's [Random Forest class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CRandomForest.html). For this purpose, we will use the [letter recognition dataset](https://archive.ics.uci.edu/ml/datasets/Letter+Recognition). This dataset contains pixel information (16 features) of 20000 samples of the English alphabet. This is a 26-class classification problem where the task is to predict the alphabet given the 16 pixel features. We start by loading the training dataset. ###Code import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline def load_file(feat_file,label_file): feats=sg.create_features(sg.read_csv(feat_file)) labels=sg.create_labels(sg.read_csv(label_file)) return (feats, labels) trainfeat_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_fm_letter.dat') trainlab_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_label_letter.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next, we decide the parameters of our Random Forest. ###Code def setup_random_forest(num_trees,rand_subset_size,combination_rule,feature_types): rf=sg.create_machine("RandomForest", num_bags=num_trees, combination_rule=combination_rule) rf.get("machine").put("m_randsubset_size", rand_subset_size) rf.get("machine").put("nominal", feature_types) return rf comb_rule=sg.create_combination_rule("MajorityVote") feat_types=np.array([False]*16) rand_forest=setup_random_forest(10,4,comb_rule,feat_types) ###Output _____no_output_____ ###Markdown In the above code snippet, we decided to create a forest using 10 trees in which each split in individual trees will be using a randomly chosen subset of 4 features. Note that 4 here is the square root of the total available features (16) and is hence the usually chosen value as mentioned in the introductory paragraph. The strategy for combination chosen is [Majority Vote](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1MajorityVote.html) which, as the name suggests, chooses the mode of all the individual tree outputs. The given features are all continuous in nature and hence feature types are all set false (i.e. not nominal). Next, we train our Random Forest and use it to classify letters in our test dataset. ###Code # train forest rand_forest.put('labels', train_labels) rand_forest.train(train_feats) # load test dataset testfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_fm_letter.dat') testlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_label_letter.dat') test_feats,test_labels=load_file(testfeat_file,testlab_file) # apply forest output_rand_forest_train=rand_forest.apply_multiclass(train_feats) output_rand_forest_test=rand_forest.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown We have with us the labels predicted by our Random Forest model. Let us also get the predictions made by a single tree. For this purpose, we train a [CART-flavoured decision tree](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CARTree.html). ###Code def train_cart(train_feats,train_labels,feature_types,problem_type): c=sg.create_machine("CARTree", nominal=feature_types, mode=problem_type, folds=2, apply_cv_pruning=False, labels=train_labels) c.train(train_feats) return c # train CART cart=train_cart(train_feats,train_labels,feat_types,"PT_MULTICLASS") # apply CART model output_cart_train=cart.apply_multiclass(train_feats) output_cart_test=cart.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown With both results at our disposal, let us find out which one is better. ###Code accuracy=sg.create_evaluation("MulticlassAccuracy") rf_train_accuracy=accuracy.evaluate(output_rand_forest_train,train_labels)*100 rf_test_accuracy=accuracy.evaluate(output_rand_forest_test,test_labels)*100 cart_train_accuracy=accuracy.evaluate(output_cart_train,train_labels)*100 cart_test_accuracy=accuracy.evaluate(output_cart_test,test_labels)*100 print('Random Forest training accuracy : '+str(round(rf_train_accuracy,3))+'%') print('CART training accuracy : '+str(round(cart_train_accuracy,3))+'%') print print('Random Forest test accuracy : '+str(round(rf_test_accuracy,3))+'%') print('CART test accuracy : '+str(round(cart_test_accuracy,3))+'%') ###Output _____no_output_____ ###Markdown As it is clear from the results above, we see a significant improvement in the predictions. The reason for the improvement is clear when one looks at the training accuracy. The single decision tree was over-fitting on the training dataset and hence was not generic. Random Forest on the other hand appropriately trades off training accuracy for the sake of generalization of the model. Impressed already? Let us now see what happens if we increase the number of trees in our forest. Random Forest parameters : Number of trees and random subset size In the last section, we trained a forest of 10 trees. What happens if we make our forest with 20 trees? Let us try to answer this question in a generic way. ###Code def get_rf_accuracy(num_trees,rand_subset_size): rf=setup_random_forest(num_trees,rand_subset_size,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) out_test=rf.apply_multiclass(test_feats) acc=sg.create_evaluation("MulticlassAccuracy") return acc.evaluate(out_test,test_labels) ###Output _____no_output_____ ###Markdown The method above takes the number of trees and subset size as inputs and returns the evaluated accuracy as output. Let us use this method to get the accuracy for different number of trees keeping the subset size constant at 4. ###Code num_trees4=[5,10,20,50,100] rf_accuracy_4=[round(get_rf_accuracy(i,4)*100,3) for i in num_trees4] print('Random Forest accuracies (as %) :' + str(rf_accuracy_4)) # plot results x4=[1] y4=[86.48] # accuracy for single tree-CART x4.extend(num_trees4) y4.extend(rf_accuracy_4) plt.plot(x4,y4,'--bo') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %)') plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown NOTE : The above code snippet takes about a minute to execute. Please wait patiently. We see from the above plot that the accuracy of the model keeps on increasing as we increase the number of trees on our Random Forest and eventually satarates at some value. Extrapolating the above plot qualitatively, the saturation value will be somewhere around 96.5%. The jump of accuracy from 86.48% for a single tree to 96.5% for a Random Forest with about 100 trees definitely highlights the importance of the Random Forest algorithm.The inevitable question at this point is whether it is possible to achieve higher accuracy saturation by working with lesser (or greater) random feature subset size. Let us figure this out by repeating the above procedure for random subset size as 2 and 8. ###Code # subset size 2 num_trees2=[10,20,50,100] rf_accuracy_2=[round(get_rf_accuracy(i,2)*100,3) for i in num_trees2] print('Random Forest accuracies (as %) :' + str(rf_accuracy_2)) # subset size 8 num_trees8=[5,10,50,100] rf_accuracy_8=[round(get_rf_accuracy(i,8)*100,3) for i in num_trees8] print('Random Forest accuracies (as %) :' + str(rf_accuracy_8)) ###Output _____no_output_____ ###Markdown NOTE : The above code snippets take about a minute each to execute. Please wait patiently. Let us plot all the results together and then comprehend the results. ###Code x2=[1] y2=[86.48] x2.extend(num_trees2) y2.extend(rf_accuracy_2) x8=[1] y8=[86.48] x8.extend(num_trees8) y8.extend(rf_accuracy_8) plt.plot(x2,y2,'--bo',label='Subset Size = 2') plt.plot(x4,y4,'--r^',label='Subset Size = 4') plt.plot(x8,y8,'--gs',label='Subset Size = 8') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %) ') plt.legend(bbox_to_anchor=(0.92,0.4)) plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown As we can see from the above plot, the subset size does not have a major impact on the saturated accuracy obtained in this particular dataset. While this is true in many datasets, this is not a generic observation. In some datasets, the random feature sample size does have a measurable impact on the test accuracy. A simple strategy to find the optimal subset size is to use cross-validation. But with Random Forest model, there is actually no need to perform cross-validation. Let us see how in the next section. Out-of-bag error The individual trees in a Random Forest are trained over data vectors randomly chosen with replacement. As a result, some of the data vectors are left out of training by each of the individual trees. These vectors form the out-of-bag (OOB) vectors of the corresponding trees. A data vector can be part of OOB classes of multiple trees. While calculating OOB error, a data vector is applied to only those trees of which it is a part of OOB class and the results are combined. This combined result averaged over similar estimate for all other vectors gives the OOB error. The OOB error is an estimate of the generalization bound of the Random Forest model. Let us see how to compute this OOB estimate in Shogun. ###Code rf=setup_random_forest(100,2,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) # set evaluation strategy rf.put("oob_evaluation_metric", sg.create_evaluation("MulticlassAccuracy")) oobe=rf.get("oob_error") print('OOB accuracy : '+str(round(oobe*100,3))+'%') ###Output _____no_output_____ ###Markdown The above OOB accuracy calculated is found to be slighly less than the test error evaluated in the previous section (see plot for num_trees=100 and rand_subset_size=2). This is because of the fact that the OOB estimate depicts the expected error for any generalized set of data vectors. It is only natural that for some set of vectors, the actual accuracy is slightly greater than the OOB estimate while in some cases the accuracy observed in a bit lower.Let us now apply the Random Forest model to the [wine dataset](https://archive.ics.uci.edu/ml/datasets/Wine). This dataset is different from the previous one in the sense that this dataset is small and has no separate test dataset. Hence OOB (or equivalently cross-validation) is the only viable strategy available here. Let us read the dataset first. ###Code trainfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat') trainlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next let us find out the appropriate feature subset size. For this we will make use of OOB error. ###Code def get_oob_errors_wine(num_trees,rand_subset_size): feat_types=np.array([False]*13) rf=setup_random_forest(num_trees,rand_subset_size,sg.create_combination_rule("MajorityVote"),feat_types) rf.put('labels', train_labels) rf.train(train_feats) rf.put("oob_evaluation_metric", sg.create_evaluation("MulticlassAccuracy")) return rf.get("oob_error") size=[1,2,4,6,8,10,13] oobe=[round(get_oob_errors_wine(400,i)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([0,14]) plt.xlabel('Random subset size') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown From the above plot it is clear that subset size of 2 or 3 produces maximum accuracy for wine classification. At this value of subset size, the expected classification accuracy is of the model is 98.87%. Finally, as a sanity check, let us plot the accuracy vs number of trees curve to ensure that 400 is indeed a sufficient value ie. the oob error saturates before 400. ###Code size=[50,100,200,400,600] oobe=[round(get_oob_errors_wine(i,2)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([40,650]) plt.ylim([90,100]) plt.xlabel('Number of trees') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown Ensemble of Decision Trees *By Parijat Mazumdar (GitHub ID: [mazumdarparijat](https://github.com/mazumdarparijat))* This notebook illustrates the use of [Random Forests](http://en.wikipedia.org/wiki/Random_forest) in Shogun for classification and regression. We will understand the functioning of Random Forests, discuss about the importance of its various parameters and appreciate the usefulness of this learning method. What is Random Forest? Random Forest is an ensemble learning method in which a collection of decision trees are grown during training and the combination of the outputs of all the individual trees are considered during testing or application. The strategy for combination can be varied but generally, in case of classification, the mode of the output classes is used and, in case of regression, the mean of the outputs is used. The randomness in the method, as the method's name suggests, is infused mainly by the random subspace sampling done while training individual trees. While choosing the best split during tree growing, only a small randomly chosen subset of all the features is considered. The subset size is a user-controlled parameter and is usually the square root of the total number of available features. The purpose of the random subset sampling method is to decorrelate the individual trees in the forest, thus making the overall model more generic; i.e. decrease the variance without increasing the bias (see [bias-variance trade-off](http://en.wikipedia.org/wiki/Bias%E2%80%93variance_dilemma)). The purpose of Random Forest, in summary, is to reduce the generalization error of the model as much as possible. Random Forest vs Decision Tree In this section, we will appreciate the importance of training a Random Forest over a single decision tree. In the process, we will also learn how to use Shogun's [Random Forest class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CRandomForest.html). For this purpose, we will use the [letter recognition dataset](https://archive.ics.uci.edu/ml/datasets/Letter+Recognition). This dataset contains pixel information (16 features) of 20000 samples of the English alphabet. This is a 26-class classification problem where the task is to predict the alphabet given the 16 pixel features. We start by loading the training dataset. ###Code import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') from shogun import CSVFile,features,MulticlassLabels def load_file(feat_file,label_file): feats=features(CSVFile(feat_file)) labels=MulticlassLabels(CSVFile(label_file)) return (feats, labels) trainfeat_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_fm_letter.dat') trainlab_file=os.path.join(SHOGUN_DATA_DIR, 'uci/letter/train_label_letter.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next, we decide the parameters of our Random Forest. ###Code from shogun import RandomForest, MajorityVote from numpy import array def setup_random_forest(num_trees,rand_subset_size,combination_rule,feature_types): rf=RandomForest(rand_subset_size,num_trees) rf.put('combination_rule', combination_rule) rf.set_feature_types(feature_types) return rf comb_rule=MajorityVote() feat_types=array([False]*16) rand_forest=setup_random_forest(10,4,comb_rule,feat_types) ###Output _____no_output_____ ###Markdown In the above code snippet, we decided to create a forest using 10 trees in which each split in individual trees will be using a randomly chosen subset of 4 features. Note that 4 here is the square root of the total available features (16) and is hence the usually chosen value as mentioned in the introductory paragraph. The strategy for combination chosen is [Majority Vote](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1MajorityVote.html) which, as the name suggests, chooses the mode of all the individual tree outputs. The given features are all continuous in nature and hence feature types are all set false (i.e. not nominal). Next, we train our Random Forest and use it to classify letters in our test dataset. ###Code # train forest rand_forest.put('labels', train_labels) rand_forest.train(train_feats) # load test dataset testfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_fm_letter.dat') testlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/letter/test_label_letter.dat') test_feats,test_labels=load_file(testfeat_file,testlab_file) # apply forest output_rand_forest_train=rand_forest.apply_multiclass(train_feats) output_rand_forest_test=rand_forest.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown We have with us the labels predicted by our Random Forest model. Let us also get the predictions made by a single tree. For this purpose, we train a [CART-flavoured decision tree](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CARTree.html). ###Code from shogun import CARTree, PT_MULTICLASS def train_cart(train_feats,train_labels,feature_types,problem_type): c=CARTree(feature_types,problem_type,2,False) c.put('labels', train_labels) c.train(train_feats) return c # train CART cart=train_cart(train_feats,train_labels,feat_types,PT_MULTICLASS) # apply CART model output_cart_train=cart.apply_multiclass(train_feats) output_cart_test=cart.apply_multiclass(test_feats) ###Output _____no_output_____ ###Markdown With both results at our disposal, let us find out which one is better. ###Code from shogun import MulticlassAccuracy accuracy=MulticlassAccuracy() rf_train_accuracy=accuracy.evaluate(output_rand_forest_train,train_labels)*100 rf_test_accuracy=accuracy.evaluate(output_rand_forest_test,test_labels)*100 cart_train_accuracy=accuracy.evaluate(output_cart_train,train_labels)*100 cart_test_accuracy=accuracy.evaluate(output_cart_test,test_labels)*100 print('Random Forest training accuracy : '+str(round(rf_train_accuracy,3))+'%') print('CART training accuracy : '+str(round(cart_train_accuracy,3))+'%') print print('Random Forest test accuracy : '+str(round(rf_test_accuracy,3))+'%') print('CART test accuracy : '+str(round(cart_test_accuracy,3))+'%') ###Output _____no_output_____ ###Markdown As it is clear from the results above, we see a significant improvement in the predictions. The reason for the improvement is clear when one looks at the training accuracy. The single decision tree was over-fitting on the training dataset and hence was not generic. Random Forest on the other hand appropriately trades off training accuracy for the sake of generalization of the model. Impressed already? Let us now see what happens if we increase the number of trees in our forest. Random Forest parameters : Number of trees and random subset size In the last section, we trained a forest of 10 trees. What happens if we make our forest with 20 trees? Let us try to answer this question in a generic way. ###Code def get_rf_accuracy(num_trees,rand_subset_size): rf=setup_random_forest(num_trees,rand_subset_size,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) out_test=rf.apply_multiclass(test_feats) acc=MulticlassAccuracy() return acc.evaluate(out_test,test_labels) ###Output _____no_output_____ ###Markdown The method above takes the number of trees and subset size as inputs and returns the evaluated accuracy as output. Let us use this method to get the accuracy for different number of trees keeping the subset size constant at 4. ###Code import matplotlib.pyplot as plt % matplotlib inline num_trees4=[5,10,20,50,100] rf_accuracy_4=[round(get_rf_accuracy(i,4)*100,3) for i in num_trees4] print('Random Forest accuracies (as %) :' + str(rf_accuracy_4)) # plot results x4=[1] y4=[86.48] # accuracy for single tree-CART x4.extend(num_trees4) y4.extend(rf_accuracy_4) plt.plot(x4,y4,'--bo') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %)') plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown NOTE : The above code snippet takes about a minute to execute. Please wait patiently. We see from the above plot that the accuracy of the model keeps on increasing as we increase the number of trees on our Random Forest and eventually satarates at some value. Extrapolating the above plot qualitatively, the saturation value will be somewhere around 96.5%. The jump of accuracy from 86.48% for a single tree to 96.5% for a Random Forest with about 100 trees definitely highlights the importance of the Random Forest algorithm.The inevitable question at this point is whether it is possible to achieve higher accuracy saturation by working with lesser (or greater) random feature subset size. Let us figure this out by repeating the above procedure for random subset size as 2 and 8. ###Code # subset size 2 num_trees2=[10,20,50,100] rf_accuracy_2=[round(get_rf_accuracy(i,2)*100,3) for i in num_trees2] print('Random Forest accuracies (as %) :' + str(rf_accuracy_2)) # subset size 8 num_trees8=[5,10,50,100] rf_accuracy_8=[round(get_rf_accuracy(i,8)*100,3) for i in num_trees8] print('Random Forest accuracies (as %) :' + str(rf_accuracy_8)) ###Output _____no_output_____ ###Markdown NOTE : The above code snippets take about a minute each to execute. Please wait patiently. Let us plot all the results together and then comprehend the results. ###Code x2=[1] y2=[86.48] x2.extend(num_trees2) y2.extend(rf_accuracy_2) x8=[1] y8=[86.48] x8.extend(num_trees8) y8.extend(rf_accuracy_8) plt.plot(x2,y2,'--bo',label='Subset Size = 2') plt.plot(x4,y4,'--r^',label='Subset Size = 4') plt.plot(x8,y8,'--gs',label='Subset Size = 8') plt.xlabel('Number of trees') plt.ylabel('Multiclass Accuracy (as %) ') plt.legend(bbox_to_anchor=(0.92,0.4)) plt.xlim([0,110]) plt.ylim([85,100]) plt.show() ###Output _____no_output_____ ###Markdown As we can see from the above plot, the subset size does not have a major impact on the saturated accuracy obtained in this particular dataset. While this is true in many datasets, this is not a generic observation. In some datasets, the random feature sample size does have a measurable impact on the test accuracy. A simple strategy to find the optimal subset size is to use cross-validation. But with Random Forest model, there is actually no need to perform cross-validation. Let us see how in the next section. Out-of-bag error The individual trees in a Random Forest are trained over data vectors randomly chosen with replacement. As a result, some of the data vectors are left out of training by each of the individual trees. These vectors form the out-of-bag (OOB) vectors of the corresponding trees. A data vector can be part of OOB classes of multiple trees. While calculating OOB error, a data vector is applied to only those trees of which it is a part of OOB class and the results are combined. This combined result averaged over similar estimate for all other vectors gives the OOB error. The OOB error is an estimate of the generalization bound of the Random Forest model. Let us see how to compute this OOB estimate in Shogun. ###Code rf=setup_random_forest(100,2,comb_rule,feat_types) rf.put('labels', train_labels) rf.train(train_feats) # set evaluation strategy eval=MulticlassAccuracy() oobe=rf.get_oob_error(eval) print('OOB accuracy : '+str(round(oobe*100,3))+'%') ###Output _____no_output_____ ###Markdown The above OOB accuracy calculated is found to be slighly less than the test error evaluated in the previous section (see plot for num_trees=100 and rand_subset_size=2). This is because of the fact that the OOB estimate depicts the expected error for any generalized set of data vectors. It is only natural that for some set of vectors, the actual accuracy is slightly greater than the OOB estimate while in some cases the accuracy observed in a bit lower.Let us now apply the Random Forest model to the [wine dataset](https://archive.ics.uci.edu/ml/datasets/Wine). This dataset is different from the previous one in the sense that this dataset is small and has no separate test dataset. Hence OOB (or equivalently cross-validation) is the only viable strategy available here. Let us read the dataset first. ###Code trainfeat_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat') trainlab_file= os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat') train_feats,train_labels=load_file(trainfeat_file,trainlab_file) ###Output _____no_output_____ ###Markdown Next let us find out the appropriate feature subset size. For this we will make use of OOB error. ###Code import matplotlib.pyplot as plt def get_oob_errors_wine(num_trees,rand_subset_size): feat_types=array([False]*13) rf=setup_random_forest(num_trees,rand_subset_size,MajorityVote(),feat_types) rf.put('labels', train_labels) rf.train(train_feats) eval=MulticlassAccuracy() return rf.get_oob_error(eval) size=[1,2,4,6,8,10,13] oobe=[round(get_oob_errors_wine(400,i)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([0,14]) plt.xlabel('Random subset size') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____ ###Markdown From the above plot it is clear that subset size of 2 or 3 produces maximum accuracy for wine classification. At this value of subset size, the expected classification accuracy is of the model is 98.87%. Finally, as a sanity check, let us plot the accuracy vs number of trees curve to ensure that 400 is indeed a sufficient value ie. the oob error saturates before 400. ###Code size=[50,100,200,400,600] oobe=[round(get_oob_errors_wine(i,2)*100,3) for i in size] print('Out-of-box Accuracies (as %) : '+str(oobe)) plt.plot(size,oobe,'--bo') plt.xlim([40,650]) plt.ylim([95,100]) plt.xlabel('Number of trees') plt.ylabel('Multiclass accuracy') plt.show() ###Output _____no_output_____
docs/_build/html/user_guide/notebooks/data_gfs.ipynb
###Markdown **Brian Blaylock** *July 20, 2021* GFS DataThe product names are not as simple as the HRRR dataset, but we can still get GFS data. ###Code from herbie.archive import Herbie from toolbox.cartopy_tools import common_features, pc from paint.standard2 import cm_tmp import matplotlib.pyplot as plt import cartopy.crs as ccrs H = Herbie('2021-07-11', model='gfs', product='pgrb2.0p25') H.SOURCES x = H.xarray('^TMP:2 m above') ax = common_features(crs=x.herbie.crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ax = common_features(crs=ccrs.Geostationary(central_longitude=-100), figsize=[10,10]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, shrink=.8, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ###Output _____no_output_____ ###Markdown Can also use metpy to parse GFS grid_mappingThis works because Herbie attempts to parse the grid_mapping from the cfgrib GRIB info. ###Code crs = x.metpy.parse_cf().metpy_crs.item().to_cartopy() ax = common_features(crs=crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ax = common_features(crs=ccrs.Robinson(), figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ###Output _____no_output_____ ###Markdown Get data from the GFS wave output ###Code H = Herbie('2021-07-11', model='gfs_wave') H.read_idx() x = H.xarray('SWELL:1 in sequence', remove_grib=False) x.swell.plot() x.herbie.crs x ###Output _____no_output_____ ###Markdown **Brian Blaylock** *July 20, 2021* GFS DataThe product names are not as simple as the HRRR dataset, but we can still get GFS data. ###Code from herbie.archive import Herbie from toolbox.cartopy_tools import common_features, pc from paint.standard2 import cm_tmp import matplotlib.pyplot as plt import cartopy.crs as ccrs H = Herbie('2021-07-11', model='gfs', product='pgrb2.0p25') H.SOURCES x = H.xarray('^TMP:2 m above') ax = common_features(crs=x.herbie.crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ax = common_features(crs=ccrs.Geostationary(central_longitude=-100), figsize=[10,10]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, shrink=.8, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ###Output _____no_output_____ ###Markdown Can also use metpy to parse GFS grid_mappingThis works because Herbie attempts to parse the grid_mapping from the cfgrib GRIB info. ###Code crs = x.metpy.parse_cf().metpy_crs.item().to_cartopy() ax = common_features(crs=crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ax = common_features(crs=ccrs.Robinson(), figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ###Output _____no_output_____ ###Markdown Get data from the GFS wave output ###Code H = Herbie('2021-07-11', model='gfs_wave') H.read_idx() x = H.xarray('SWELL:1 in sequence', remove_grib=False) x.swell.plot() x.herbie.crs x ###Output _____no_output_____ ###Markdown **Brian Blaylock** *July 20, 2021* GFS DataThe product names are not as simple as the HRRR dataset, but we can still get GFS data. ###Code from herbie.archive import Herbie from toolbox.cartopy_tools import common_features, pc from paint.standard2 import cm_tmp import matplotlib.pyplot as plt import cartopy.crs as ccrs H = Herbie('2021-07-11', model='gfs', product='pgrb2.0p25') H.SOURCES x = H.xarray('^TMP:2 m above') ax = common_features(crs=x.herbie.crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ax = common_features(crs=ccrs.Geostationary(central_longitude=-100), figsize=[10,10]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, shrink=.8, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ###Output _____no_output_____ ###Markdown Can also use metpy to parse GFS grid_mappingThis works because Herbie attempts to parse the grid_mapping from the cfgrib GRIB info. ###Code crs = x.metpy.parse_cf().metpy_crs.item().to_cartopy() ax = common_features(crs=crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ax = common_features(crs=ccrs.Robinson(), figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ###Output _____no_output_____ ###Markdown Get data from the GFS wave output ###Code H = Herbie('2021-07-11', model='gfs_wave') H.read_idx() x = H.xarray('SWELL:1 in sequence', remove_grib=False) x.swell.plot() x.herbie.crs x ###Output _____no_output_____ ###Markdown **Brian Blaylock** *July 20, 2021* GFS DataThe product names are not as simple as the HRRR dataset, but we can still get GFS data. ###Code from herbie.archive import Herbie from toolbox.cartopy_tools import common_features, pc from paint.standard2 import cm_tmp import matplotlib.pyplot as plt import cartopy.crs as ccrs H = Herbie('2021-07-11', model='gfs', product='pgrb2.0p25') H.SOURCES x = H.xarray('^TMP:2 m above') ax = common_features(crs=x.herbie.crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ax = common_features(crs=ccrs.Geostationary(central_longitude=-100), figsize=[10,10]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) plt.colorbar(p, ax=ax, orientation='horizontal', pad=.05, shrink=.8, **cm_tmp(units='K').cbar_kwargs) ax.set_title(x.t2m.GRIB_name, loc='right') ax.set_title(f"{x.model.upper()}: {H.product_description}", loc='left') ###Output _____no_output_____ ###Markdown Can also use metpy to parse GFS grid_mappingThis works because Herbie attempts to parse the grid_mapping from the cfgrib GRIB info. ###Code crs = x.metpy.parse_cf().metpy_crs.item().to_cartopy() ax = common_features(crs=crs, figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ax = common_features(crs=ccrs.Robinson(), figsize=[8,8]).ax p = ax.pcolormesh(x.longitude, x.latitude, x.t2m, transform=pc, **cm_tmp(units='K').cmap_kwargs) ###Output _____no_output_____ ###Markdown Get data from the GFS wave output ###Code H = Herbie('2021-07-11', model='gfs_wave') H.read_idx() x = H.xarray('SWELL:1 in sequence', remove_grib=False) x.swell.plot() x.herbie.crs x ###Output _____no_output_____
bronze/B07_Probabilistic_Bit.ipynb
###Markdown Prepared by Abuzer Yakaryilmaz Özlem Salehi | July 01, 2019 (updated) This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcommand{\braket}[2]{\langle 1|2\rangle} $$ \newcommand{\dot}[2]{ 1 \cdot 2} $$ \newcommand{\biginner}[2]{\left\langle 1,2\right\rangle} $$ \newcommand{\mymatrix}[2]{\left( \begin{array}{1} 2\end{array} \right)} $$ \newcommand{\myvector}[1]{\mymatrix{c}{1}} $$ \newcommand{\myrvector}[1]{\mymatrix{r}{1}} $$ \newcommand{\mypar}[1]{\left( 1 \right)} $$ \newcommand{\mybigpar}[1]{ \Big( 1 \Big)} $$ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $$ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $$ \newcommand{\onehalf}{\frac{1}{2}} $$ \newcommand{\donehalf}{\dfrac{1}{2}} $$ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $$ \newcommand{\vzero}{\myvector{1\\0}} $$ \newcommand{\vone}{\myvector{0\\1}} $$ \newcommand{\vhadamardzero}{\myvector{ \sqrttwo \\ \sqrttwo } } $$ \newcommand{\vhadamardone}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $$ \newcommand{\myarray}[2]{ \begin{array}{1}2\end{array}} $$ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0} } $$ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1} } $$ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $$ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $$ \newcommand{\norm}[1]{ \left\lVert 1 \right\rVert } $ One Probabilistic Bit A probabilistic bit is a bit that is equal to 0 with probability $Pr(0)$ and equal to 1 with probability$Pr(1)$, for some probabilities $Pr(0), Pr(1) \geq 0$ such that $Pr(0) + Pr(1) = 1$ A coin is a probabilistic bit. After flipping a coin, we can get a Head by probability $Pr(Head)$ or a Tail by probability $Pr(Tail)$. We can represent these two cases by a single bit: 0 represents Head 1 represents Tail Vector Representation Suppose that Asja flips a coin secretly.Because we do not see the result, our information about the outcome will be probabilistic:Since we have two different outcomes Head (0) and Tail (1), then, we can use a column vector of size 2 to hold the probabilities of getting Head and getting Tail. Hence, our knowledge about the outcome is $\myvector{Pr(Head) \\ Pr(Tail)}$.The first entry shows the probability of getting Head, and the second entry shows the probability of getting Tail. If the coin is fair,$\rightarrow$ The result is Head with probability $0.5$ and the result is Tail with probability $0.5$.If the coin has a bias $ \dfrac{Pr(Head)}{Pr(Tail)} = \dfrac{3}{1}$, then our information about the outcome is as follows:$\rightarrow$ The result is Head with probability $ 0.75 $ and the result is Tail with probability $ 0.25 $. For the fair coin, our information after the coin-flip is $ \myvector{0.5 \\ 0.5} $. For the biased coin, it is $ \myvector{0.75 \\ 0.25} $. $ \myvector{0.5 \\ 0.5} $ and $ \myvector{0.75 \\ 0.25} $ are two examples of 2-dimensional (column) vectors. Task 1 Suppose that Balvis secretly flips a coin having bias $ \dfrac{Pr(Head)}{Pr(Tail)} = \dfrac{1}{4}$.Represent your information about the outcome as a column vector.solution:$ \myvector{0.2 \\ 0.8} $ Task 2 Suppose that Fyodor secretly rolls a loaded (tricky) dice with the bias $$ Pr(1):Pr(2):Pr(3):Pr(4):Pr(5):Pr(6) = 7:5:4:2:6:1 . $$Represent your information about the result as a column vector. Remark that the size of your column should be 6.You may use python for your calculations. ###Code divisions=[7,5,4,2,6,1] total=0 for i in range(6): total+=divisions[i] print("Total is:", total) onedivision=1/total print("Probability of one portion is:",onedivision) for i in range(6): print("the probability of rolling",i+1,"is",(onedivision*divisions[i])) ###Output Total is: 25 Probability of one portion is: 0.04 the probability of rolling 1 is 0.28 the probability of rolling 2 is 0.2 the probability of rolling 3 is 0.16 the probability of rolling 4 is 0.08 the probability of rolling 5 is 0.24 the probability of rolling 6 is 0.04
nbs/63_seg_dataset_isri_unlv.ipynb
###Markdown ISRI UNLV> [image] -> [segmentation maps]download dataset from https://code.google.com/archive/p/isri-ocr-evaluation-tools/ dir structure: `./data/isri_unlv/ | bus.2B | 0/ | ...2B.tif | ...2B.txt | ...2B.uzn ... | 1/ ... ...` ###Code #export from ocr.core import save_dict, read_dict, plot from fastai import * from fastai.vision import * import pandas as pd import numpy as np import cv2 from tqdm.notebook import tqdm from pathlib import PosixPath #export cat2id = { 'Background': 0, 'Attent_line': 1, 'Other_Text': 2, 'cc': 3, 'Company_Sig': 4, 'Subject': 5, 'Enclosure': 6, 'Sign/Type': 7, 'Inside_Addr': 8, 'Dateline': 9, 'Footnote': 10, 'Closing': 10, 'Salutat': 11, 'Signer': 12, 'Letterhead': 13, 'Table': 14, 'Caption': 15, 'Header/Footer': 16, 'Text': 17 } class isri_unlv_config: MAIN_DIR = PosixPath('../data/isri_unlv/') SEG_DIR = PosixPath('../data/seg/labels/') IMG_DIR = PosixPath('../data/seg/images/') cat2id = cat2id im = cv2.imread(str(isri_unlv_config.MAIN_DIR/'bus.2B'/'0'/'8500_001.2B.tif')) plot(im) l,t,w,h,cat = [177, 381, 400, 64, 'Dateline'] plot(im[t:t+h , l:l+w]) cat_freq = { 'Attent_line': 8, 'Other_Text': 28, 'cc': 31, 'Company_Sig': 32, 'Subject': 51, 'Enclosure': 116, 'Sign/Type': 259, 'Inside_Addr': 361, 'Dateline': 514, 'Footnote': 615, 'Closing': 634, 'Salutat': 654, 'Signer': 761, 'Letterhead': 1365, 'Table': 1668, 'Caption': 3453, 'Header/Footer': 6723, 'Text': 24762 } cats = ['Background', 'Attent_line', 'Other_Text', 'cc', 'Company_Sig', 'Subject', 'Enclosure', 'Sign/Type', 'Inside_Addr', 'Dateline', 'Footnote', 'Closing', 'Salutat', 'Signer', 'Letterhead', 'Table', 'Caption', 'Header/Footer', 'Text'] cat2id = {c:i for i,c in enumerate(cats)} read = lambda fp: open(fp).read() read_lines = lambda fp: open(fp).readlines() cat_freq = defaultdict(lambda: 0) doc2paths = defaultdict(lambda: {'img': None, 'txt': None, 'uzn': None}) for fp in isri_unlv_config.MAIN_DIR.iterdir(): if str(fp)[-1] == 'B' or str(fp)[-1] == 'A': document_category = str(fp).split('/')[-1] for subfp in fp.iterdir(): if os.path.isdir(subfp): page_id = str(subfp).split('/')[-1] for i,fpath in enumerate(subfp.iterdir()): doc_name = str(fpath).split('/')[-1][:-4] fn = 'isri_unlv_{}_{}'.format(document_category, page_id, i) if str(fpath)[-4:] == '.tif': doc2paths[doc_name]['img'] = fpath if str(fpath)[-4:] == '.txt': doc2paths[doc_name]['txt'] = fpath if str(fpath)[-4:] == '.uzn': doc2paths[doc_name]['uzn'] = fpath doc2paths = dict(doc2paths) del doc2paths['total'] for name in doc2paths.keys(): x = doc2paths[name] if x['uzn'] is None or x['img'] is None or x['txt'] is None: raise Exception('wtf', name) def preprocess_category(cstr): # category string -> id int return cat2id[cstr] if cstr in cat2id else cat2id['Background'] read = lambda fp: open(fp).read() read_lines = lambda fp: open(fp).readlines() cat_freq = defaultdict(lambda: 0) for i, name in enumerate(progress_bar(doc2paths.keys())): fn = 'isri_unlv_{}'.format(i) uzn_path = doc2paths[name]['uzn'] img_path = doc2paths[name]['img'] txt_path = doc2paths[name]['txt'] # img im = cv2.imread(str(img_path)) cv2.imwrite(str(isri_unlv_config.IMG_DIR/(fn+'.png')), im) # seg seg = np.zeros(im.shape[:2] + (1,), dtype=int) + cat2id['Background'] for line in read_lines(uzn_path): try: l,t,w,h,cat = [w for w in line.split(' ') if w != ''] except: continue # there are some ` ` (double space) lines cat = cat[:-1] cat_freq[cat] += 1 cat_id = preprocess_category(cat) l,t,w,h = map(int, [l,t,w,h]) seg[ t:t+h , l:l+w ] = cat_id seg = ImageSegment(tensor(seg).permute(2,0,1)) seg.save(str(isri_unlv_config.SEG_DIR/(fn+'.png'))) # txt # ... cat_freq = dict(sorted(cat_freq.items(), key=lambda k:k[1])) cat_freq ###Output _____no_output_____