text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` %matplotlib inline import numpy as np import pandas as pd from scipy import stats as ss from sklearn import metrics from datetime import datetime import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['figure.figsize'] = (30.0, 15.0) !pip install sklearn !pip install bayesian-optimization !pip install scikit-optimize !pip install shap from sklearn.model_selection import train_test_split import xgboost as xgb from xgboost.sklearn import XGBClassifier from bayes_opt import BayesianOptimization from skopt import BayesSearchCV from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier import shap df_raw = pd.read_csv("data/train.csv") df_raw.head() def get_day(x): return x.date() def DaysBeforeCat(days): if days == 0: return '0 days' elif days in range(1,3): return '1-2 days' elif days in range(3,8): return '3-7 days' elif days in range(8, 32): return '8-31 days' else: return '> 31 days' def getting_ready(df): df['pat_id'].astype('int64') #df.set_index('ReminderId', inplace = True) # Creating new variables #df['NoShow'] = (df['No-show'] == 'Yes')*1 df['noshow'] = (df['response'] == 0)*1 df['prev_app'] = df.sort_values(by = ['pat_id','apt_date']).groupby(['pat_id']).cumcount() df['prev_noshow'] = (df[df['prev_app'] > 0].sort_values(['pat_id', 'apt_date']).groupby(['pat_id'])['noshow'].cumsum() / df[df['prev_app'] > 0]['prev_app']) # TODO: compute prev_app, prev_noshow for fam_id as well df['prev_fam_app'] = df.sort_values(by = ['family_id','apt_date']).groupby(['family_id']).cumcount() df['prev_fam_noshow'] = (df[df['prev_app'] > 0].sort_values(['family_id', 'apt_date']).groupby(['family_id'])['noshow'].cumsum() / df[df['prev_app'] > 0]['prev_app']) df['apt_date'] = pd.to_datetime(df['apt_date']) df['apt_date_isweekday'] = df.apply(lambda x: x['apt_date'].isoweekday(), axis = 1) #df['HasHandicap'] = (df['Handcap'] > 0)*1 #df['PreviousDisease'] = df.apply(lambda x: ((x.Hipertension == 1 )| x.Diabetes == 1 | x.Alcoholism == 1)*1, axis = 1) df['remind_date'] = pd.to_datetime(df['sent_time']) df['remind_date_isweekday'] = df.apply(lambda x: x['remind_date'].isoweekday(), axis = 1) df['remind_apt_gap'] = ((df['apt_date'].apply(get_day) - df['remind_date'].apply(get_day)).astype('timedelta64[D]')).astype(int) df['remind_notsent'] = (df['net_hour'] == -99999)*1 df2 = df[(df['age'] >= 0)] return df2 df = getting_ready(df_raw) df = df.assign(apt_onmonday = (df['apt_date_isweekday'] == 1)*1, apt_ontuesday = (df['apt_date_isweekday'] == 2)*1, apt_onwednesday = (df['apt_date_isweekday'] == 3)*1, apt_onthursday = (df['apt_date_isweekday'] == 4)*1, apt_onfriday = (df['apt_date_isweekday'] == 5)*1, apt_onsaturday = (df['apt_date_isweekday'] == 6)*1, apt_onsunday = (df['apt_date_isweekday'] == 7)*1) df = df.assign(remind_onmonday = (df['remind_date_isweekday'] == 1)*1, remind_ontuesday = (df['remind_date_isweekday'] == 2)*1, remind_onwednesday = (df['remind_date_isweekday'] == 3)*1, remind_onthursday = (df['remind_date_isweekday'] == 4)*1, remind_onfriday = (df['remind_date_isweekday'] == 5)*1, remind_onsaturday = (df['remind_date_isweekday'] == 6)*1, remind_onsunday = (df['remind_date_isweekday'] == 7)*1) df = df.assign(isfemale = (df['gender'] == 'F')*1) df.columns features = ['apt_onmonday', 'apt_ontuesday', 'apt_onwednesday', 'apt_onthursday', 'apt_onfriday', 'apt_onsaturday', 'apt_onsunday', 'remind_onmonday', 'remind_ontuesday', 'remind_onwednesday', 'remind_onthursday', 'remind_onfriday', 'remind_onsaturday', 'remind_onsunday', 'net_hour', 'remind_notsent', 'fam', 'isfemale', 'age', 'dist', 'prev_app', 'prev_noshow', 'prev_fam_app', 'prev_fam_noshow' ] label = 'response' ``` ``` df['apt_date2'] = df.apply(lambda x: x.apt_date.strftime("%x"), axis = 1) scheduled_days = df.groupby(['apt_date2'])[['apt_date']].count() scheduled_days.head() scheduled_days.columns = ['i', 'index', 'date', 'count'] scheduled_days['date'] = pd.to_datetime(scheduled_days['date']) print('first scheduled: ' + str(scheduled_days.date.min())) print('most recent scheduled: ' + str(scheduled_days.date.max())) sns.scatterplot(x = 'date', y = 'count', data = scheduled_days) plt.title('Number of Appointments per Scheduled Day') plt.xlabel('Scheduled Day') plt.xlim('2017-03', '2021-12') plt.gcf().set_size_inches(10, 6) plt.show() herp = df.apt_type[1:100000].value_counts()[1:40] #print(herp.count) #plt.xticks(rotation='vertical') #plt.bar(herp.index,herp) plt.pie(herp,labels=herp.index) plt.show() print('Total appointments: ' + format(df.shape[0], ",d")) print('Distinct patients: ' + format(df.pat_id.unique().shape[0], ",d")) print('Patients with more than one appointment: ' + format((df['pat_id'].value_counts() > 1).sum(), ",d")) df.age.describe() sns.set() def cat_var(df3, var): print(df3.groupby([var])['response'].mean()) ns_rate = [df3.groupby([var])['response'].mean()[i] for i in df3[var].unique()] s_rate = [1-df3.groupby([var])['response'].mean()[i] for i in df3[var].unique()] barWidth = 5 plt.bar(df3[var].unique(), ns_rate, color='lightcoral', edgecolor='white', width=barWidth, label = 'response') plt.bar(df3[var].unique(), s_rate, bottom=ns_rate, color='mediumseagreen', edgecolor='white', width=barWidth, label = 'Show') plt.axhline(y=df3['response'].mean(), color='black', linewidth= 0.8, linestyle='--', label = 'Overall mean') plt.xticks(df3[var].unique()) plt.xlabel(var) plt.legend(loc='upper left', bbox_to_anchor=(1,1), ncol=1) plt.title('response Rate by '+ var, fontsize=15) plt.gcf().set_size_inches(6, 6) plt.show() counts = np.array(df3.groupby([var])['response'].sum()) nobs = np.array(df3.groupby([var])['response'].count()) table = df3.groupby(['response', var]).size().unstack(var) pvalue = ss.chi2_contingency(table.fillna(0))[1] print('Means test p-value: {:1.3f}'.format(pvalue)) if pvalue < 0.05: print('Reject null hypothesis: no-show rate is different for at least one group') else: print('Cannot reject no-show rates are same for all groups') df_net = df[(df['net_hour'] < -1) & (df['net_hour'] > -100)] cat_var(df_net,'age') print('Correlation with No-Show: %.3f' % ss.pointbiserialr(df['response'], df['net_hour'])[0]) df[df.response == 1].count ```
github_jupyter
## Google Sentence Piece를 이용해서 Vocab 파일을 만드는 과정 Google SentencePeice와 한국어 위키를 이용해서 Vocab을 만드는 과정에 대한 설명 입니다. [Colab](https://colab.research.google.com/)에서 실행 했습니다. #### 0. Pip Install 필요한 패키지를 pip를 이용해서 설치합니다. ``` !pip install sentencepiece ``` #### 1. Google Drive Mount Colab에서는 컴퓨터에 자원에 접근이 불가능 하므로 Google Drive에 파일을 올려 놓은 후 Google Drive를 mount 에서 로컬 디스크처럼 사용 합니다. 1. 아래 블럭을 실행하면 나타나는 링크를 클릭하세요. 2. Google 계정을 선택 하시고 허용을 누르면 나타나는 코드를 복사하여 아래 박스에 입력한 후 Enter 키를 입력하면 됩니다. 학습관련 [데이터 및 결과 파일](https://drive.google.com/open?id=15XGr-L-W6DSoR5TbniPMJASPsA0IDTiN)을 참고 하세요. ``` from google.colab import drive drive.mount('/content/drive') # data를 저장할 폴더 입니다. 환경에 맞게 수정 하세요. data_dir = "/content/drive/My Drive/Data/transformer-evolution" ``` #### 2. Imports ``` import os import gzip import pandas as pd import sentencepiece as spm import shutil ``` #### 3. 폴더의 목록을 확인 Google Drive mount가 잘 되었는지 확인하기 위해 data_dir 목록을 확인 합니다. ``` for f in os.listdir(data_dir): print(f) ``` #### 4. CSV 파일을 TEXT 형태로 변환 Google SentencePiece에서 사용할 수 있도록 CSV를 TEXT형태로 변환 합니다. ``` in_file = f"{data_dir}/kowiki.csv.gz" out_file = f"{data_dir}/kowiki.txt" SEPARATOR = u"\u241D" if not os.path.isfile(out_file): df = pd.read_csv(in_file, sep=SEPARATOR, engine="python", compression='gzip') with open(out_file, "w") as f: for index, row in df.iterrows(): f.write(row["text"]) # title 과 text를 중복 되므로 text만 저장 함 f.write("\n\n\n\n") # 구분자 shutil.copy(out_file, "kowiki.txt") ``` #### 5. Vocab 생성 Google SentencePiece를 이용해서 vocab 만드는 방법 입니다. vocab을 만드는데 많은 시간이 소요 됩니다. 잠시 여유를 갖고 기다려 주세요. ``` corpus = "kowiki.txt" prefix = "kowiki" vocab_size = 8000 spm.SentencePieceTrainer.train( f"--input={corpus} --model_prefix={prefix} --vocab_size={vocab_size + 7}" + " --model_type=bpe" + " --max_sentence_length=999999" + # 문장 최대 길이 " --pad_id=0 --pad_piece=[PAD]" + # pad (0) " --unk_id=1 --unk_piece=[UNK]" + # unknown (1) " --bos_id=2 --bos_piece=[BOS]" + # begin of sequence (2) " --eos_id=3 --eos_piece=[EOS]" + # end of sequence (3) " --user_defined_symbols=[SEP],[CLS],[MASK]") # 기타 추가 토큰 for f in os.listdir("."): print(f) shutil.copy("kowiki.model", f"{data_dir}/kowiki.model") shutil.copy("kowiki.vocab", f"{data_dir}/kowiki.vocab") ``` #### 6. Vocab 테스트 생성된 vocab을 간단하게 테스트 해 봅니다. ``` vocab_file = f"{data_dir}/kowiki.model" vocab = spm.SentencePieceProcessor() vocab.load(vocab_file) lines = [ "겨울이 되어서 날씨가 무척 추워요.", "이번 성탄절은 화이트 크리스마스가 될까요?", "겨울에 감기 조심하시고 행복한 연말 되세요." ] for line in lines: pieces = vocab.encode_as_pieces(line) ids = vocab.encode_as_ids(line) print(line) print(pieces) print(ids) print() ```
github_jupyter
``` import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle from threshold_functions import abs_sobel_thresh from threshold_functions import mag_thresh from threshold_functions import dir_threshold from threshold_functions import hls_select from threshold_functions import hsv_select from threshold_functions import binarize_image # Read in an image image = mpimg.imread('test_images/straight_lines1.jpg') img_size = (image.shape[1], image.shape[0]) ksize = 9; test, test1 = binarize_image(image, verbose='False') ''' # Run the function gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh=(20, 150)) grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh=(80, 255)) gradxy = abs_sobel_thresh(image, orient='xy', sobel_kernel=ksize, thresh=(1, 50)) # Run the function mag_binary = mag_thresh(image, sobel_kernel=9, mag_thresh=(30, 100)) # Run the function dir_binary = dir_threshold(image, sobel_kernel=15, thresh=(0.7, 1.3)) # Run the function hls_s_binary = hls_select(image, thresh=(150, 255), channel='S') # Run the function hls_h_binary = hls_select(image, thresh=(50, 200), channel='H') # Run the function hsv_v_binary = hsv_select(image, thresh=([0, 70, 70], [50, 255, 255]), channel='all', verbose='True') combined = np.zeros_like(dir_binary) #combined[((gradx == 1) & (grady == 0)) | ((mag_binary == 1) | (dir_binary == 1)) | (hls_s_binary == 1)] = 1 #combined[((gradx == 1) & (grady == 0)) | (hls_s_binary == 1) | (hsv_v_binary == 1) & (hls_h_binary == 0)] = 1 combined[((gradx == 1) & (grady == 0)) | (hsv_v_binary == 1)] = 1 color_binary = np.dstack(( np.zeros_like(gradx), gradx, grady)) * 255 # Plot the result f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 9)) f.tight_layout() ax1.imshow(image) ax1.set_title('Original Image', fontsize=50) ax2.imshow(color_binary) ax2.set_title('Stacks.', fontsize=50) ax3.imshow(combined, cmap='gray') ax3.set_title('Thresholded Grad. Combined.', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) plt.figure() plt.imshow(gradxy, cmap='gray') plt.figure() plt.imshow(grady, cmap='gray') plt.figure() plt.imshow(hsv_v_binary, cmap='gray') plt.figure() plt.imshow(hls_s_binary, cmap='gray') plt.figure() plt.imshow(hls_h_binary, cmap='gray') ''' import cv2 from warp import warper h, w = test1.shape[:2] src = np.float32([[w, h-10], # br [0, h-10], # bl [546, 460], # tl [732, 460]]) # tr dst = np.float32([[w, h], # br [0, h], # bl [0, 0], # tl [w, 0]]) # tr M = cv2.getPerspectiveTransform(src, dst) warped = cv2.warpPerspective(test1, M, img_size, flags=cv2.INTER_NEAREST) # keep same size as input image plt.figure() plt.imshow(warped, cmap='gray') import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle import array from os.path import join, basename from threshold_functions import abs_sobel_thresh from threshold_functions import mag_thresh from threshold_functions import dir_threshold from threshold_functions import hls_select from threshold_functions import hsv_select # Read in an image image = warped img_size = (image.shape[1], image.shape[0]) ksize = 5; # Run the function gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh=(20, 150)) grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh=(80, 255)) gradxy = abs_sobel_thresh(image, orient='xy', sobel_kernel=ksize, thresh=(20, 150)) # Run the function mag_binary = mag_thresh(image, sobel_kernel=9, mag_thresh=(30, 100)) # Run the function dir_binary = dir_threshold(image, sobel_kernel=15, thresh=(0.7, 1.3)) # Run the function hls_s_binary = hls_select(image, thresh=(150, 255), channel='S') # Run the function hls_h_binary = hls_select(image, thresh=(50, 200), channel='H') # Run the function hsv_v_binary = hsv_select(image, thresh=([0, 70, 70], [50, 255, 255]), channel='all', verbose='True') combined = np.zeros_like(dir_binary, dtype=np.uint8) #combined[((gradx == 1) & (grady == 0)) | ((mag_binary == 1) | (dir_binary == 1)) | (hls_s_binary == 1)] = 1 #combined[((gradx == 1) & (grady == 0)) | (hls_s_binary == 1) | (hsv_v_binary == 1) & (hls_h_binary == 0)] = 1 combined[((gradx == 1) & (grady == 0)) | (hsv_v_binary == 1)] = 1 color_binary = np.dstack(( np.zeros_like(gradx), gradx, grady)) * 255 # Plot the result f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 9)) f.tight_layout() ax1.imshow(image) ax1.set_title('Original Image', fontsize=50) ax2.imshow(color_binary) ax2.set_title('Stacks.', fontsize=50) ax3.imshow(combined, cmap='gray') ax3.set_title('Thresholded Grad. Combined.', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) plt.figure() plt.imshow(gradxy) plt.figure() plt.imshow(grady) plt.figure() plt.imshow(hsv_v_binary) plt.figure() plt.imshow(hls_s_binary) plt.figure() plt.imshow(hls_h_binary) plt.figure() fig = plt.imshow(combined, cmap='gray') fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) image_out_dir = 'output_images' out_path = join(image_out_dir, "test1_255.jpg") final = mpimg.imsave(out_path, combined*255) from PIL import Image image_file = Image.open("output_images/test1.jpg") # open colour image image_file = image_file.convert('1') # convert image to black and white image_file.save('test1_BW.jpg') import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt import cv2 # Read in an image #combined = mpimg.imread('output_images/test1_255.jpg') img_size = (warped.shape[1], warped.shape[0]) #combined = cv2.cvtColor(combined,cv2.COLOR_BGR2GRAY) # Load our image binary_warped = warped # Load our image #binary_warped = mpimg.imread('warped-example.jpg') def find_lane_pixels(binary_warped): # Take a histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0) # Create an output image to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0]//2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # HYPERPARAMETERS # Choose the number of sliding windows nwindows = 9 # Set the width of the windows +/- margin margin = 70 # Set minimum number of pixels found to recenter window minpix = 50 # Set height of windows - based on nwindows above and image shape window_height = np.int(binary_warped.shape[0]//nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated later for each window in nwindows leftx_current = leftx_base rightx_current = rightx_base # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window+1)*window_height win_y_high = binary_warped.shape[0] - window*window_height ### TO-DO: Find the four below boundaries of the window ### win_xleft_low = leftx_current - margin # Update this win_xleft_high = leftx_current + margin # Update this win_xright_low = rightx_current - margin # Update this win_xright_high = rightx_current + margin # Update this # Draw the windows on the visualization image out_img = cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),(0,255,0), 2) out_img = cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2) ### TO-DO: Identify the nonzero pixels in x and y within the window ### good_left_inds = ((nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high) & (nonzeroy >= win_y_low) & (nonzeroy < win_y_high)).nonzero()[0] good_right_inds = ((nonzerox >= win_xright_low) & (nonzerox < win_xright_high) & (nonzeroy >= win_y_low) & (nonzeroy < win_y_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) ### TO-DO: If you found > minpix pixels, recenter next window ### ### (`right` or `leftx_current`) on their mean position ### if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices (previously was a list of lists of pixels) try: left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) except ValueError: # Avoids an error if the above is not implemented fully pass # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] return leftx, lefty, rightx, righty, out_img def fit_polynomial(binary_warped): # Find our lane pixels first leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped) # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension ### TO-DO: Fit a second order polynomial to each using `np.polyfit` ### left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) left_fit_meter = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, 2) right_fit_meter = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, 2) # Generate x and y values for plotting ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] ) try: left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] except TypeError: # Avoids an error if `left` and `right_fit` are still none or incorrect print('The function failed to fit a line!') left_fitx = 1*ploty**2 + 1*ploty right_fitx = 1*ploty**2 + 1*ploty ## Visualization ## # Colors in the left and right lane regions out_img[lefty, leftx] = [255, 0, 0] out_img[righty, rightx] = [0, 0, 255] # Plots the left and right polynomials on the lane lines plt.plot(left_fitx, ploty, color='yellow') plt.plot(right_fitx, ploty, color='yellow') return out_img, ploty, left_fitx, right_fitx, left_fit_meter, right_fit_meter #plt.figure() out_img, ploty, left_fit_cr, right_fit_cr, left_fit_cr_m, right_fit_cr_m = fit_polynomial(binary_warped) plt.imshow(out_img) def curve(A, B, y): return ((1+(2*A*y + B)**2)**(3/2))/(abs(2*A)) def measure_curvature_real(): ''' Calculates the curvature of polynomial functions in meters. ''' # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension # Start by generating our fake example data # Make sure to feed in your real data instead in your project! #ploty, left_fit_cr, right_fit_cr = generate_data(ym_per_pix, xm_per_pix) # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image y_eval = 0 ##### TO-DO: Implement the calculation of R_curve (radius of curvature) ##### left_curverad = curve(left_fit_cr_m[0], left_fit_cr_m[1], y_eval*ym_per_pix) ## Implement the calculation of the left line here right_curverad = curve(right_fit_cr_m[0], right_fit_cr_m[1], y_eval*ym_per_pix) ## Implement the calculation of the right line here return left_curverad, right_curverad # Calculate the radius of curvature in meters for both lane lines left_curverad, right_curverad = measure_curvature_real() print(left_curverad, 'm', right_curverad, 'm') # Should see values of 533.75 and 648.16 here, if using # the default `generate_data` function with given seed number ```
github_jupyter
# L1-SVM vs L2-SVM: using the Barrier and SMO algorithms ``` %cd .. import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from collections import Counter import time from sklearn.metrics import confusion_matrix, classification_report from opt.svm import SVC from opt.utils.data_splitter import split4ovr, split4ovo from opt.utils.metrics import measure_performance # Fix random seed np.random.seed(0) ``` ## Dataset ``` # This code block is used for reducing the MNIST dataset # from opt.utils.preprocess import process_raw_data # process_raw_data(input_filepath='data/mnist/', # output_filepath='data/filtered_mnist', # classes2keep=[0,1,6,9], # nTrain=500, # nTest=200) # Load data data = np.load('data/filtered_mnist.npz') x_train = data['a'] y_train = data['b'] x_test = data['c'] y_test = data['d'] print("Number of training samples: ", len(y_train)) print("Distribution of training samples: ", Counter(y_train)) print("Number of test samples: ", len(y_test)) print("Distribution of training samples: ", Counter(y_test)) # Visualise data plt.rcParams.update({'font.size': 16}) fig, (ax1, ax2, ax3, ax4) = plt.subplots(1,4, figsize=(35,35)) imx, imy = (28,28) visual = np.reshape(x_train[2], (imx,imy)) ax1.set_title("Example Data Image, y="+str(int(y_train[2]))) ax1.imshow(visual, vmin=0, vmax=1) visual = np.reshape(x_train[36], (imx,imy)) ax2.set_title("Example Data Image, y="+str(int(y_train[36]))) ax2.imshow(visual, vmin=0, vmax=1) visual = np.reshape(x_train[10], (imx,imy)) ax3.set_title("Example Data Image, y="+str(int(y_train[10]))) ax3.imshow(visual, vmin=0, vmax=1) visual = np.reshape(x_train[8], (imx,imy)) ax4.set_title("Example Data Image, y="+str(int(y_train[8]))) ax4.imshow(visual, vmin=0, vmax=1) # plt.savefig("report/report_pics/data.pdf", format="pdf") # # Visualise data # plt.rcParams.update({'font.size': 16}) # fig, (ax1, ax2, ax3, ax4) = plt.subplots(1,4, figsize=(35,35)) # imx, imy = (28,28) # visual = np.reshape(x_test[10], (imx,imy)) # ax1.set_title("Example Data Image, y="+str(int(y_test[10]))) # ax1.imshow(visual, vmin=0, vmax=1) # visual = np.reshape(x_test[412], (imx,imy)) # ax2.set_title("Example Data Image, y="+str(int(y_test[412]))) # ax2.imshow(visual, vmin=0, vmax=1) # visual = np.reshape(x_test[524], (imx,imy)) # ax3.set_title("Example Data Image, y="+str(int(y_test[524]))) # ax3.imshow(visual, vmin=0, vmax=1) # visual = np.reshape(x_test[636], (imx,imy)) # ax4.set_title("Example Data Image, y="+str(int(y_test[636]))) # ax4.imshow(visual, vmin=0, vmax=1) # # plt.savefig("report/report_pics/bad_data.pdf", format="pdf") ``` ## Barrier method ``` # OVO data x_train_ovo, y_train_ovo = split4ovo(x_train, y_train) # OVR data: y_train_ovr = split4ovr(y_train) # Train OVR: svm.fit(x_train, y_train_ovr) # Initialise L1-SVM L1_barrier_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L1', opt_algo="barrier") # Barrier fit L1_barrier_svm.fit(x_train_ovo, y_train_ovo, t=1, mu=20, tol=1e-6, max_iter=100, tolNewton=1e-12, maxIterNewton=100) # Test L1_barrier_yhat = L1_barrier_svm.predict(x_test) print("Time taken: ", L1_barrier_svm.time_taken) measure_performance(y_test, L1_barrier_yhat, average="macro") # Initialise L2-SVM L2_barrier_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L2', opt_algo="barrier") # Barrier fit L2_barrier_svm.fit(x_train_ovo, y_train_ovo, t=1, mu=20, tol=1e-6, max_iter=100, tolNewton=1e-12, maxIterNewton=100) # Test L2_barrier_yhat = L2_barrier_svm.predict(x_test) print("Time taken: ", L2_barrier_svm.time_taken) measure_performance(y_test, L2_barrier_yhat, average="macro") ``` #### Convergence Plots ``` fig, (ax1, ax2) = plt.subplots(1,2, figsize=(25,10)) plt.rcParams.update({'font.size': 20}) # L1-SVM for ClassVsClass, info in L1_barrier_svm.opt_info.items(): ax1.plot(np.linalg.norm(np.array(info['iterates'])-info['x'], axis=1), label=ClassVsClass) ax1.set_title("L1-SVM \n Barrier method: Iterate Convergence Plot") ax1.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax1.set_xlabel("Iterations $k$") ax1.set_yscale("log") ax1.legend() ax1.grid(which='both', axis='both') # L2-SVM for ClassVsClass, info in L2_barrier_svm.opt_info.items(): ax2.plot(np.linalg.norm(np.array(info['iterates'])-info['x'], axis=1), label=ClassVsClass) ax2.set_title("L2-SVM \n Barrier method: Iterate Convergence Plot") ax2.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax2.set_xlabel("Iterations $k$") ax2.set_yscale("log") ax2.legend() ax2.grid(which='both', axis='both') plt.tight_layout() # plt.savefig("report/report_pics/barrier_iterate_conv.pdf", format="pdf") plt.show() fig, (ax1, ax2) = plt.subplots(1,2, figsize=(25,10)) plt.rcParams.update({'font.size': 20}) # L1-SVM for ClassVsClass, info in L1_barrier_svm.opt_info.items(): ax1.step(np.cumsum(info['newton_iterations']), info['duality_gaps'], label=str(ClassVsClass)+": $\mu=$"+str(info['mu'])) ax1.set_title("L1-SVM \n Progress of Barrier method") ax1.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax1.set_xlabel("Newton Iterations $k$") ax1.set_yscale("log") ax1.legend() ax1.grid(which='both', axis='both') # L2-SVM for ClassVsClass, info in L2_barrier_svm.opt_info.items(): ax2.step(np.cumsum(info['newton_iterations']), info['duality_gaps'], label=str(ClassVsClass)+": $\mu=$"+str(info['mu'])) ax2.set_title("L2-SVM \n Progress of Barrier method") ax2.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax2.set_xlabel("Newton Iterations $k$") ax2.set_yscale("log") ax2.legend() ax2.grid(which='both', axis='both') plt.tight_layout() # plt.savefig("report/report_pics/barrier_duality_gap.pdf", format="pdf") plt.show() ``` #### Confusion matrix ``` L1_barrier_conf_matrix = confusion_matrix(y_test, L1_barrier_yhat, normalize=None) L2_barrier_conf_matrix = confusion_matrix(y_test, L2_barrier_yhat, normalize=None) fig, (ax1, ax2) = plt.subplots(1,2, figsize=(25,10)) plt.rcParams.update({'font.size': 20}) # Plot confusion matrix L1-SVM df_cm = pd.DataFrame(L1_barrier_conf_matrix, index=np.unique(y_test), columns=np.unique(y_test)) sns.heatmap(df_cm, annot=True, fmt='', cmap='Blues', cbar=True, square=True, center=110, linewidths=.1, linecolor='black', ax=ax1) ax1.set_ylim((4,0)) ax1.set_title("L1-SVM \n Barrier method: Confusion Matrix") ax1.set_ylabel('True label') ax1.set_xlabel('Predicted label') # Plot confusion matrix L2-SVM df_cm = pd.DataFrame(L2_barrier_conf_matrix, index=np.unique(y_test), columns=np.unique(y_test)) sns.heatmap(df_cm, annot=True, fmt='', cmap='Blues', cbar=True, square=True, center=110, linewidths=.1, linecolor='black', ax=ax2) ax2.set_ylim((4,0)) ax2.set_title("L2-SVM \n Barrier method: Confusion Matrix") ax2.set_ylabel('True label') ax2.set_xlabel('Predicted label') plt.tight_layout() # plt.savefig("report/report_pics/barrier_confusion_matrix.pdf", format="pdf") plt.show() ``` ## SMO method ``` # Initialise L1-SVM L1_smo_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L1', opt_algo="smo") # SMO fit L1_smo_svm.fit(x_train_ovo, y_train_ovo, tol=1e-3, max_iter=5) # Test L1_smo_yhat = L1_smo_svm.predict(x_test) print("Time taken: ", L1_smo_svm.time_taken) measure_performance(y_test, L1_smo_yhat, average="macro") # Initialise L2-SVM L2_smo_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L2', opt_algo="smo") # SMO fit L2_smo_svm.fit(x_train_ovo, y_train_ovo, tol=1e-3, max_iter=100) # Test L2_smo_yhat = L2_smo_svm.predict(x_test) print("Time taken: ", L2_smo_svm.time_taken) measure_performance(y_test, L2_smo_yhat, average="macro") ``` #### Convergence Plots ``` fig, (ax1, ax2) = plt.subplots(1,2, figsize=(25,10)) plt.rcParams.update({'font.size': 20}) # L1-SVM for ClassVsClass, info in L1_smo_svm.opt_info.items(): ax1.plot(np.linalg.norm(np.array(info['iterates'])-info['x'], axis=1), label=ClassVsClass) ax1.set_title("L1-SVM \n SMO method: Iterate Convergence Plot") ax1.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax1.set_xlabel("Iterations $k$") ax1.set_yscale("log") ax1.legend() ax1.grid(which='both', axis='both') # L2-SVM for ClassVsClass, info in L2_smo_svm.opt_info.items(): ax2.plot(np.linalg.norm(np.array(info['iterates'])-info['x'], axis=1), label=ClassVsClass) ax2.set_title("L2-SVM \n SMO method: Iterate Convergence Plot") ax2.set_ylabel("$|| \mathbf{x}_k-\mathbf{x}^{\star} ||_2$") ax2.set_xlabel("Iterations $k$") ax2.set_yscale("log") ax2.legend() ax2.grid(which='both', axis='both') plt.tight_layout() # plt.savefig("report/report_pics/smo_iterate_conv.pdf", format="pdf") plt.show() ``` #### Confusion matrix ``` L1_smo_conf_matrix = confusion_matrix(y_test, L1_barrier_yhat, normalize=None) L2_smo_conf_matrix = confusion_matrix(y_test, L2_barrier_yhat, normalize=None) fig, (ax1, ax2) = plt.subplots(1,2, figsize=(25,10)) plt.rcParams.update({'font.size': 20}) # Plot confusion matrix L1-SVM df_cm = pd.DataFrame(L1_smo_conf_matrix, index=np.unique(y_test), columns=np.unique(y_test)) sns.heatmap(df_cm, annot=True, fmt='', cmap='Blues', cbar=True, square=True, center=110, linewidths=.1, linecolor='black', ax=ax1) ax1.set_ylim((4,0)) ax1.set_title("L1-SVM \n SMO method: Confusion Matrix") ax1.set_ylabel('True label') ax1.set_xlabel('Predicted label') # Plot confusion matrix L2-SVM df_cm = pd.DataFrame(L2_smo_conf_matrix, index=np.unique(y_test), columns=np.unique(y_test)) sns.heatmap(df_cm, annot=True, fmt='', cmap='Blues', cbar=True, square=True, center=110, linewidths=.1, linecolor='black', ax=ax2) ax2.set_ylim((4,0)) ax2.set_title("L2-SVM \n SMO method: Confusion Matrix") ax2.set_ylabel('True label') ax2.set_xlabel('Predicted label') plt.tight_layout() # plt.savefig("report/report_pics/smo_confusion_matrix.pdf", format="pdf") plt.show() ``` ## CVXOPT method (for comparison) ``` # Initialise L1-SVM L1_cvxopt_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L1', opt_algo="cvxopt") # CVXOPT fit L1_cvxopt_svm.fit(x_train_ovo, y_train_ovo) # Test L1_cvxopt_yhat = L1_cvxopt_svm.predict(x_test) print("Time taken: ", L1_cvxopt_svm.time_taken) measure_performance(y_test, L1_cvxopt_yhat, average="macro") # Initialise L2-SVM L2_cvxopt_svm = SVC(C=1.0, kernel="gauss", param='scale', decision_function_shape="ovo", loss_fn='L2', opt_algo="cvxopt") # CVXOPT fit L2_cvxopt_svm.fit(x_train_ovo, y_train_ovo) # Test L2_cvxopt_yhat = L2_cvxopt_svm.predict(x_test) print("Time taken: ", L2_cvxopt_svm.time_taken) measure_performance(y_test, L2_cvxopt_yhat, average="macro") ``` ## Scikit-Learn SVM (for comparison) ``` # Scikit-learn for L1-SVM from sklearn.svm import SVC as sklearnSVM sklearn_svm = sklearnSVM(C=1.0, kernel='rbf', decision_function_shape='ovo') sklearn_svm.fit(x_train, y_train) sklearn_pred = sklearn_svm.predict(x_test) measure_performance(y_test, sklearn_pred, average="macro") ```
github_jupyter
# Python for Psychologists - Session 2 ## Some more on lists, dictionaries, tuples, errors and modules ### More on lists **Adding elements** Last session we learned how to add an element to a list by using ```python my_list.append(element1) ``` to add a single element or ```python my_list.extend([element1, element2, element3]) ``` to add a whole bunch of elements. We also learned that we can add an entire list as an element to a list. Just to make sure that we got the difference of `append` and `extend` right, try to add the list `[7,8,9]` to the list below by using first the `extend` and then the `append` command. ``` my_list = [1,2,3,4,5,6] ``` By the way, there is also a **shortcut for the extend command**: ```python my_list + [new_element1, new_element2, new_element3] ``` Add [10,11,12] to my_list (without overwriting my_list with the result). **Deleting elements** One thing we have not covered last time is how to **remove** elements from a list, which works as follows: ```python del my_list[1] # this will delete the second element ``` Try to delete the list element [7,8,9] that we have just added via `append`. ``` my_list ``` There are actually more ways of removing an element from a list. Try to figure out what the difference is between - `del my_list[1]` - `my_list.remove(1)` - `my_list.pop(1)` Create a markdown cell below this cell and try to describe for each of the commands in the list above what exactly it does. **Inserting elements** We can also insert an element at a specific index. The syntax is as follows: ```python my_list.insert(position, new_element) # add new_element at position ``` Try to insert the number 99 at the 3rd position of `my_list`. ### Dictionaries We will now get to know another kind of data structure called dictionary. As the name gives away, a dictionary is structured like a dictionary, that is, there is a mapping from one name to some other name (or value). The name under for which we want to know the value it is mapped to is called the *key*. The value is simply called *value.* Dictionaries can be created with the following syntax: ```python my_dict = {"key1": value1, "key2":"value2", "key3":["v", "a", "l", "u", "e", "3"]} ``` Create a dictionary that maps your top 2 cutest animals to the rank you would give them (i.e., 1 or 2). Just in case you don't believe me, below is proof for otters being the cutest animals in the world! ![pandasUrl](https://media.giphy.com/media/9A56kPXH16UqBKmdug/giphy.gif "otters1") ![pandasUrl](https://media.giphy.com/media/VloengiEXvPwY/giphy.gif "otters2") We have learned that lists are an *ordered* collection of things which is important for things like timeseries etc. An important difference between lists and dictionaries is, that dictionary entries cannot be referred to by their position in the dictionary but only directly by their key name. We can get the value that is mapped to a certain key with the following syntax: ```python my_dict["key_name"] ``` Try to fetch the rank of one of the animals in your dictionary. Let us now try to build a sentence that includes one of the animals in the list and its respective rank. **Adding entries** If we wish to add a key-value pair to our dictionary we can do this the same way we tried to fetch a value, however, this time we assign a value to it. The syntax looks like this: ```python my_dict["new_key"] = new_value ``` By the way: the keys of the dictionary entries don't always have to be strings, they can also be numbers or tuples (we will hear about tuples soon). Actually, any object that is *unchangable* will work. Objects that are *changeable*, cannot be keys of dictionary entries (this includes other dictionaries as well). Now try to add a third animal with its rank to your dictionary. Look at the dictionary again afterwards. **Deleting entries** This is, luckily, the same command we already know from the deletion of elements from a list: ```python del my_dict[key_to_be_deleted] ``` Delete the third/newest entry to the dictionary and take a look at the dictionary again. **Size of a dictionary** Also an easy one as this works the same way as for lists: ```python len(my_dict) ``` This will show you the number of key-value pairs. For the two remaining animals in your dictionary create a dictionary for each. The keys in these two new dictionaries should be: - rank (as before the rank in your "cutest animals"-list; integer) - food (something these animals like to eat; string) - size (small, medium or large; string) **Adding several key-value pairs** If we want to add not just one but several entires to a dictionary, we can do that easily with the following syntax: ```python my_dict.update({"new_key1":new_value1, "new_key2":new_value2, "new_key3":new_value3}) ``` Add two more entries to the two dictionaries you have just created: - habitat (where these animals typically live; string) - age (expected age; integer) Take a look at the two dictionaries afterwards. **Creating nested dictionaries** Sometimes we need to save more complex structures of content. For this we could use nested dictionaries. They are easy to create: ```python umbrella_dict = {"subdict1_name":subdict1, "subdict2_name":subdict2} ``` Try to replace your "cute_animals" dictionary by a nested one consisting of the two dictionaries you have just created. Take a look at the resulting dictionary afterwards. Indexing/Referencing in nested dictionaries is as intuitive as it could possibly be: ```python umbrella_dictionary["subdict1_name"]["subdict1_key"] ``` Try to fetch the favourite food of one your two animals. We can also check if a key is among the keys of our dictionary. Use the following syntax to check if some animal is a key in your `cute_animals` dictionary: ```python "key" in my_dict ``` How can we check if a certain *value* is part of the *values* of a dictionary? Try to find out! And remember: google is your friend :) So far we have only looked at the content of our dictionaries by evaluating its name, which led to Python printing the content into the output cell. If we want *work* with the items of a dictionary in form of an object we can use the following syntax: ```python my_dict.items() ``` This will return an object of type `dict_items`. Don't worry if this confuses you right now, it will get clearer throughout the course. Try to get the items of one of the animals inside your cute_animals dictionary. As we can see, inside a dict_items object each key-value pair is represented in parentheses. These parentheses are tuples which we will hear about next. ### Tuples Tuples look a lot like lists, however there is one very important difference: once they are created, they cannot be changed (hence, tuples are *immutable objects*). Tuples are created the same way as lists, only that instead of `[]` we use `()`: ```python my_tuple = (1,2,3, "hallo", (3,4,5)) ``` Tuples can also be indexed like lists using square brackets `[]`. Create a tuple with three elemets and try to change the second element. **Adding elements to a tuple** This works just as with lists: ```python my_tuple = my_tuple + (new_element1, new_element2, new_element3) ``` Add some random numbers to the following one. ``` my_tuple = (1,2,3) ``` In order to add another tuple to an existing tuple use the following syntax: ```python my_tuple = my_tuple + ((element1, element2),) # this is equivalent to: my_tuple = my_tuple + (some_other_tuple,) ``` Add a tuple to my_tuple. Let's see if we can delete an element from a tuple using the `del` command which we are already familiar with. If we want to delete some element from a tuple we will have to overwrite the tuple. Use slicing to delete one element from `my_tuple`. ### Errors ... are a good thing! (well, sometimes...) Usually, they tell you relatively precisely what is going wrong. Python is not a mean machinery that tries to annoy you by throwing errors at random, but it actually gives you a hint which part of your code needs some changes. Let's get to know some errors you might encounter: - **SyntaxError:** Also called "parsing error". This error occurs while Python is trying to decifer your code. Python, like any other language has a certain syntax, which we need to stick to in order for Python to understand your code. Whenever we violate this syntactic structure we get a SyntaxError. - **NameError:** NameErrors occur when we try to access the value of a variable/an object that we haven't even defined yet. It's like talking to your family about some fellow student of yours that they don't know. "Yesterday, I went binge-drinking with Tonya." Of course, their response will be "Who is Tonya?". Well, Python will ask you the same question when referring to an object that you have never introduced. - **IndexError:** We can cause an IndexError when trying to access an element in an subscriptable object (basically objects that are containers which allow for indexing at all) that does not exist. For example, we would cause an IndexError by asking Python to return the value of the 6th element of a list that is only 3 elements long. - **TypeError:** TypeErrors occur whenever we try to do some operation with a data type that just doesn't fit the operation, like trying to do something with two strings that can only be done with two integers or floats. - **KeyError:** These errors usually occur, when we try to access the value of a key, although the key does not exist in the dictionary. - **ZeroDivisionError:** This kind of error is more than intuitive. It is raised simply when we try to divide a number by 0, which is mathematically not defined. Nothing is more fun than causing errors on purpose! Go ahead and try to cause a `NameError`. Now try to cause a... ...`TypeError`! ... `IndexError`! ... `ZeroDivisionError`! ... `KeyError`! Now try to cause a `SyntaxError`! ### Modules A module is a python file (.py) that contains definitions and statements. Inside the folder of this session there is a file called "test_module.py". Open the file with some text editor to see what it contains. In order to use the objects defined in the module script (this may be functions, classes or, as in this case, simple variables), we first have to import them. Execute the cell below. ``` import test_module ``` While it looks as if nothing has happened, the content of the module is now available to us. In order to use it, however, we need to use the following syntax: ```python some_module.some_object # if we want to call a function that is defined inside the module we need parentheses some_module.some_function() ``` Try to access the variable "b" in our test_module. In case of very long module names and if we have to use the module rather frequently, we can also give it a short name. The syntax looks like this: ```python import some_module as mod mod.some_function() ``` Import test_module again, but this time give it a shorter name. Afterwards try to access the variable c. ### Sets Sets are *unordered* and *unindexed* collections of things. Sets also differ from lists in that they cannot contain two identical elements. Sets can be created with the following syntax: ```python my_set = {"element1", element2, 4} ``` Create a set of three random inputs. Now try to create a set with a duplicate value. Take a look at the resulting set afterwards. Try to access the first element of your set. We can also convert lists to sets and vice versa: ```python my_list = [1,2,3,4] my_set = set(my_list) my_list = list(my_set) ``` Take the following list, convert it to a set and back to a list again. **Adding items to a set** We can add single items to a set using the following syntax: ```python my_set.add(new_item) ``` We can also add several items at once: ```python my_set.update({new_item1, new_item2}) ``` Try to add some items to my_set. **Removing items from a set** Removing items from a set works similarly: ```python my_set.remove(item_to_be_removed) ``` Delete one of the items that you have just added.
github_jupyter
``` import pickle import numpy as np import pandas as pd import os import matplotlib.pylab as plt plt.rcParams['font.family'] = 'sans-serif' DATADIR = '../data/' from sklearn.preprocessing import StandardScaler from dispersant_screener.definitions import FEATURES from pypal.models.gpr import predict_coregionalized def load_data(n_samples, label_scaling: bool = False): """Take in Brian's data and spit out some numpy arrays for the PAL""" df_full_factorial_feat = pd.read_csv(os.path.join(DATADIR, 'new_features_full_random.csv'))[FEATURES].values a2 = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['A2_normalized'].values deltaGMax = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['A2_normalized'].values # pylint:disable=unused-variable gibbs = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_deltaG.csv'))['deltaGmin'].values * (-1) gibbs_max = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['deltaGmax'].values force_max = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_fit2.csv'))['F_repel_max'].values # pylint:disable=unused-variable rg = pd.read_csv(os.path.join(DATADIR, 'rg_results.csv'))['Rg'].values y = np.hstack([rg.reshape(-1, 1), gibbs.reshape(-1, 1), gibbs_max.reshape(-1, 1)]) assert len(df_full_factorial_feat) == len(a2) == len(gibbs) == len(y) feat_scaler = StandardScaler() X = feat_scaler.fit_transform(df_full_factorial_feat) if label_scaling: label_scaler = MinMaxScaler() y = label_scaler.fit_transform(y) #greedy_indices = get_maxmin_samples(X, n_samples) return X, y#, greedy_indice X, y = load_data(1) with open('../work/sweeps3/20201021-235927_dispersant_0.01_0.05_0.05_60-models.pkl', 'rb') as fh: models = pickle.load(fh) selected = np.load('../work/sweeps3/20201021-235927_dispersant_0.01_0.05_0.05_60-selected.npy', allow_pickle=True) selected = selected[-1] means0, std0 = predict_coregionalized(models[0], X, 0) means1, std1 = predict_coregionalized(models[0], X, 1) means2, std2 = predict_coregionalized(models[0], X, 2) fig, ax = plt.subplots(1, 3) ax[0].scatter(y[:,0], means0.flatten(), s=1, label='all') ax[1].scatter(y[:,1], means1.flatten(), s=1) ax[2].scatter(y[:,2], means2.flatten(), s=1) ax[0].scatter(y[selected,0], means0.flatten()[selected], s=1, label='sampled') ax[1].scatter(y[selected,1], means1.flatten()[selected], s=1) ax[2].scatter(y[selected,2], means2.flatten()[selected], s=1) ax[0].legend(markerscale=8) ax[0].set_xlabel(r'$R_g$ simulated / $\mathrm{\AA}$') ax[0].set_ylabel(r'$R_g$ predicted / $\mathrm{\AA}$') ax[1].set_xlabel(r'$-\Delta G_\mathrm{ads}$ simulated / $k_\mathrm{B}T$') ax[1].set_ylabel(r'$-\Delta G_\mathrm{ads}$ predicted / $k_\mathrm{B}T$') ax[2].set_xlabel(r'$\Delta G_\mathrm{rep}$ simulated / $k_\mathrm{B}T$') ax[2].set_ylabel(r'$\Delta G_\mathrm{rep}$ predicted / $k_\mathrm{B}T$') for a in ax: a.plot(a.get_xlim(), a.get_ylim(), ls="--", c='k') a.spines['top'].set_color('none') a.spines['right'].set_color('none') a.spines['left'].set_smart_bounds(True) a.spines['bottom'].set_smart_bounds(True) fig.tight_layout() fig.savefig('predictive_performance_models_pal.pdf', bbox_inches='tight') ``` ## Now, make the training data for the GBDTs ``` FEATURES = ['max_[W]', 'max_[Tr]', 'max_[Ta]', 'max_[R]', '[W]', '[Tr]', '[Ta]', '[R]', 'length'] df_full_factorial_feat = pd.read_csv(os.path.join(DATADIR, 'new_features_full_random.csv'))[FEATURES].values a2 = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['A2_normalized'].values deltaGMax = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['A2_normalized'].values # pylint:disable=unused-variable gibbs = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_deltaG.csv'))['deltaGmin'].values * (-1) gibbs_max = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_new.csv'))['deltaGmax'].values force_max = pd.read_csv(os.path.join(DATADIR, 'b1-b21_random_virial_large_fit2.csv'))['F_repel_max'].values # pylint:disable=unused-variable rg = pd.read_csv(os.path.join(DATADIR, 'rg_results.csv'))['Rg'].values y = np.hstack([rg.reshape(-1, 1), gibbs.reshape(-1, 1), gibbs_max.reshape(-1, 1)]) assert len(df_full_factorial_feat) == len(a2) == len(gibbs) == len(y) feat_scaler = StandardScaler() X_new = feat_scaler.fit_transform(df_full_factorial_feat) X_new.shape predictions = np.hstack([ means0.flatten().reshape(-1,1), means1.flatten().reshape(-1,1), means2.flatten().reshape(-1,1) ]) predictions np.save('../work/X_train_GBDT.npy', X_new) np.save('../work/y_train_GBDT.npy', predictions) ```
github_jupyter
# Teil 8 (fortgeführt) - Einleitung für Protokolle ### Kontext Nachdem nun Pläne behandelt wurden, wird es jetzt um ein neues Objekt names Protokoll gehen. Ein Protokoll koordiniert eine Sequenz von Plänen und wendet sie auf entfernten Helfern in einem einzigen Durchgang an. Es ist ein Objekt höchster Ebene und beinhaltet die Logik einer komplexen Berechnung auf mehreren verteilten Helfern. Die wichtigste Eigenschaft eines Protokolls ist die Fähigkeit von Helfern gesendet / gesucht / geholt zu werden und schließlich auf festgelegten Helfern angewendet zu werden. Somit kann ein Nutzer ein Protokoll erstellen und auf einem Helfer in der Cloud bereit stellen. Jeder andere Helfer kann dieses Protokoll dort suchen, herunterladen und bei sich und allen mit ihm verbundenen Helfern anwenden. Im Folgenden können Sie sehen, wie das erreicht wird. Autoren: - Théo Ryffel - Twitter [@theoryffel](https://twitter.com/theoryffel) - GitHub: [@LaRiffle](https://github.com/LaRiffle) Übersetzer: - Jan Moritz Behnken - Github: [@JMBehnken](https://github.com/JMBehnken) ### 1. Erstellen und Anwenden Protokolle werden mit Listen aus `(worker, plan)`-Paaren erstellt. Dabei kann `worker` entweder ein echter Helfer, eine Helfer-Id oder auch ein String eines fiktiven Helfers sein. Der letzte Fall kann verwendet werden, um beim Erstellen zu spezifizieren, dass zwei Pläne beim Anwenden zum selben Helfer gehören (oder auch nicht). `plan` kann entweder einen Plan oder auch einen PointerPlan enthalten. ``` import torch as th import syft as sy hook = sy.TorchHook(th) # IMPORTANT: Local worker should not be a client worker hook.local_worker.is_client_worker = False ``` Es werden drei unterschiedliche Pläne erstellt und in einem Protokoll vereint. Jeder der Pläne erhöht den Zähler jeweils um eins. ``` @sy.func2plan(args_shape=[(1,)]) def inc1(x): return x + 1 @sy.func2plan(args_shape=[(1,)]) def inc2(x): return x + 1 @sy.func2plan(args_shape=[(1,)]) def inc3(x): return x + 1 protocol = sy.Protocol([("worker1", inc1), ("worker2", inc2), ("worker3", inc3)]) ``` Nun muss das Protokoll noch an die Helfer gebunden werden. Dies wird erreicht mit dem Aufrufen von `.deploy(*workers)`. Dafür werden drei Helfer erstellt. ``` bob = sy.VirtualWorker(hook, id="bob") alice = sy.VirtualWorker(hook, id="alice") charlie = sy.VirtualWorker(hook, id="charlie") workers = alice, bob, charlie protocol.deploy(*workers) ``` Wie zu erkennen ist, wurden die Pläne gleich an die richtigen Helfer gesendet: das Protokoll wurde verteilt! Dies geschah in zwei Phasen: - zuerst wurden die Helfer-Strings auf die echten Helfer abgebildet - danach wurden die Pläne ihren jeweiligen Helfern übermittelt ### 2. Starten eines Protokolls Ein Protokoll zu starten, bedeutet alle seine Pläne der Reihe nach abzuarbeiten. Dafür werden die Eingabe-Daten an den Ort des ersten Planes gesendet. Dieser erste Plan wird auf die Daten angewendet und seine Ausgabe-Daten an den zweiten Plan weiter geleitet. Dies setzt sich so fort. Das letzte Ergebnis wird zurückgegeben, sobald alle Pläne abgeschlossen sind. Es enthält Pointer auf den Ort des letzten Planes. ``` x = th.tensor([1.0]) ptr = protocol.run(x) ptr ptr.get() ``` Die Eingabe `1.0` durchlief alle drei Pläne und wurde dort jeweils um eins erhöht. Deshalb entspricht die Ausgabe einer `4.0`! Selbstverständlich können **Protokolle auch mit Pointern** arbeiten. ``` james = sy.VirtualWorker(hook, id="james") protocol.send(james) x = th.tensor([1.0]).send(james) ptr = protocol.run(x) ptr ``` Wie zu erkennen ist, ist das Ergebnis ein Pointer zu `james`. ``` ptr = ptr.get() ptr ptr = ptr.get() ptr ``` ### 3. Suche nach einem Protokoll In einem realen Projekt kann es gewünscht sein ein Protokoll herunterzuladen und automatisiert auf den Daten der eigenen Helfer anzuwenden: Dafür wir ein **nicht verteiltes Protokoll** erstellt und auf einem Helfer bereit gestellt. ``` protocol = sy.Protocol([("worker1", inc1), ("worker2", inc2), ("worker3", inc3)]) protocol.tag('my_protocol') protocol.send(james) me = sy.hook.local_worker # get access to me as a local worker ``` Nun wird eine Suche nach dem Protokoll gestartet. ``` responses = me.request_search(['my_protocol'], location=james) responses ``` Zurückgegeben wurde ein Pointer auf das Protokoll. ``` ptr_protocol = responses[0] ``` Wie gewohnt kann der Pointer genutzt werden um das Objekt zu holen: ``` protocol_back = ptr_protocol.get() protocol_back ``` Von hier wird genau wie in Teil 1. & 2. verfahren. ``` protocol_back.deploy(alice, bob, charlie) x = th.tensor([1.0]) ptr = protocol_back.run(x) ptr.get() ``` Weitere Beispiele mit Protokollen und echten Szenarien sind in Vorbereitung, doch die Möglichkeiten eines solchen Objektes sollten nun schon erkennbar sein! ### PySyft auf GitHub einen Stern geben! Der einfachste Weg, unserer Community zu helfen, besteht darin, die GitHub-Repos mit Sternen auszuzeichnen! Dies hilft, das Bewusstsein für die coolen Tools zu schärfen, die wir bauen. - [Gib PySyft einen Stern](https://github.com/OpenMined/PySyft) ### Nutze unsere Tutorials auf GitHub! Wir haben hilfreiche Tutorials erstellt, um ein Verständnis für Federated und Privacy-Preserving Learning zu entwickeln und zu zeigen wie wir die einzelnen Bausteine weiter entwickeln. - [PySyft Tutorials ansehen](https://github.com/OpenMined/PySyft/tree/master/examples/tutorials) ### Mach mit bei Slack! Der beste Weg, um über die neuesten Entwicklungen auf dem Laufenden zu bleiben, ist, sich unserer Community anzuschließen! Sie können dies tun, indem Sie das Formular unter [http://slack.openmined.org](http://slack.openmined.org) ausfüllen. ### Treten Sie einem Code-Projekt bei! Der beste Weg, um zu unserer Community beizutragen, besteht darin, Entwickler zu werden! Sie können jederzeit zur PySyft GitHub Issues-Seite gehen und nach "Projects" filtern. Dies zeigt Ihnen alle Top-Level-Tickets und gibt einen Überblick darüber, an welchen Projekten Sie teilnehmen können! Wenn Sie nicht an einem Projekt teilnehmen möchten, aber ein wenig programmieren möchten, können Sie auch nach weiteren "einmaligen" Miniprojekten suchen, indem Sie nach GitHub-Problemen suchen, die als "good first issue" gekennzeichnet sind. - [PySyft Projects](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3AProject) - [Good First Issue Tickets](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) ### Spenden Wenn Sie keine Zeit haben, zu unserer Codebase beizutragen, aber dennoch Unterstützung leisten möchten, können Sie auch Unterstützer unseres Open Collective werden. Alle Spenden fließen in unser Webhosting und andere Community-Ausgaben wie Hackathons und Meetups! - [OpenMined's Open Collective Page](https://opencollective.com/openmined)
github_jupyter
# Modules To carry out statistical tests in Python, we will be using an external module called [SciPy](https://www.scipy.org/), and to perform statistical modelling we will use the `ols` function from the external module [statsmodels](https://www.statsmodels.org/stable/index.html). To install these modules, launch the "Comand Prompt" program and run the following commands: `pip install -U statsmodels` `pip install -U scipy` We will alias SciPy as `sp`, import the `ols` function from the `statsmodels.formula.api` module, and import numpy, pandas and plotnine using their usual aliases. ``` import scipy as sp from statsmodels.formula.api import ols import numpy as np import pandas as pd import plotnine as p9 ``` # Data To demonstrate the data analysis functionality of Python, we will use the metabric dataset. Some of the functions we will use do not handle missing data, so we will remove any rows for the dataset where data is missing. As we saw in week 3, we can use the `describe()` method to generate summary statistics for this dataset: ``` metabric = pd.read_csv("../data/metabric_clinical_and_expression_data.csv").dropna() metabric.describe() ``` # Statistical tests ## Tests for normality When we are deciding which statistical test to use in our analysis, we often need to work out whether the data follows a normal distribution or not, as some tests (e.g. t-test) assume that our data are normally distributed. We can test whether a dataset follows a normal distribution by using the Kolmogorov-Smirnov test. For example, the age at diagnosis looks like it could be normally distributed: ``` ( p9.ggplot(metabric, p9.aes("Age_at_diagnosis")) + p9.geom_histogram() ) ``` To run the Kolmogorov-Smirnov test, we use the `kstest()` function from the scipy stats module: ``` sp.stats.kstest(metabric["Age_at_diagnosis"], "norm") ``` The Kolmogorov-Smirnov test has a p value below 0.05, indicating that we can reject the null hypothesis that there is no difference between this distribution and a normal distribution. In other words, the distribution appears non-normal. In SciPy, the results of most tests are returned as an object. When printed directly to screen this is not very pretty and hard to interpret, as we can see above. When running the test, we can assign the results object to a variable, and then access the attributes of the results object to print the results in a clearer format: ``` # run the test and assign the result to a variable age_diagnosis_ks = sp.stats.kstest(metabric["Age_at_diagnosis"], "norm") # print the results by retrieving attributes from the result object print("Age at diagnosis Kolmogorov-Smirnov test:") print("p value = {}".format(age_diagnosis_ks.pvalue)) print("Statsitic = {}".format(age_diagnosis_ks.statistic)) ``` ## Correlation We often want to test whether two continuous variables are related to each other, and we can do this by calculating a correlation. For example, there appears to be a relationship between the expression of the ESR1 gene and the GATA3 gene: ``` ( p9.ggplot(metabric, p9.aes("ESR1", "GATA3")) + p9.geom_point() ) ``` For normally distributed data, we can calculate the Pearson's correlation using the `pearsonr()` function. `pearsonr()` returns the results as a tuple rather than an object, so we need to access the coefficient and p value using indexing: ``` ESR1_GATA3_pearson = sp.stats.pearsonr(metabric["ESR1"], metabric["GATA3"]) print("Pearson correlation between ESR1 & GATA3:") print("coefficient = {}".format(ESR1_GATA3_pearson[0])) print("p value = {}".format(ESR1_GATA3_pearson[1])) ``` For data that is not normally distributed, we can calculate the Spearman rank correlation. For example, a scatter plot of tumour size versus mutation count suggests that these are not normally distributed: ``` ( p9.ggplot(metabric, p9.aes("Tumour_size", "Mutation_count")) + p9.geom_point() ) ``` We can calculate the Spearman rank correlation using the `spearmanr()` function, again accessing the results using indexing: ``` size_mutation_spearman = sp.stats.spearmanr(metabric["Tumour_size"], metabric["Mutation_count"]) print("Spearman rank correlation between tumour size and mutation count:") print("coefficient = {}".format(size_mutation_spearman[0])) print("p value = {}".format(size_mutation_spearman[1])) ``` ## T-test To test whether the mean value of a continuous variable is significantly different between two different groups, we can use the t-test for normally distributed data. For example, age at diagnosis appears to be lower for ER-negative tumours compared with ER-positive tumours: ``` ( p9.ggplot(metabric, p9.aes("ER_status", "Age_at_diagnosis")) + p9.geom_violin() ) ``` We can use the `ttest_ind()` function to carry out the t-test, which confirms that we can reject the null hypothesis that age at diagnosis is not different between ER positive and negative tumours. Note that `ttest_ind()` takes two arguments, which are the values of the two groups. Rather than extracting these values and assigning them to separate variables, we can do the data extraction within the function call: ``` ER_age_t = sp.stats.ttest_ind( # select samples with Negative ER_status and extract the Age_at_diagnosis values metabric[metabric["ER_status"]=="Negative"]["Age_at_diagnosis"], # select samples with Positive ER_status and extract the Age_at_diagnosis values metabric[metabric["ER_status"]=="Positive"]["Age_at_diagnosis"] ) print("t test of age at diagnosis for ER_status Negative vs Positive:") print("t = {}".format(ER_age_t.statistic)) print("p = {}".format(ER_age_t.pvalue)) ``` If we have data that is not normally distributed we may want to use the Mann-Whitney U test, also known as the Wilcoxon rank-sum test, which is the non-parametric equivalent of the t-test. For example, survival time does not follow a normal distribution, but it still appears to be different between ER positive and ER negative tumours: ``` ( p9.ggplot(metabric, p9.aes("ER_status", "Survival_time")) + p9.geom_violin() ) ``` We can use the `mannwhitneyu()` function to run the Mann-Whitney U test, which confirms that we can reject the null hypothesis that age at diagnosis is not different between ER positive and negative tumours. Again, we are subsetting and selecting the data within the function call: ``` ER_survival_MWU = sp.stats.mannwhitneyu( # select samples with Negative ER_status and extract the Age_at_diagnosis values metabric[metabric["ER_status"]=="Negative"]["Age_at_diagnosis"], # select samples with Positive ER_status and extract the Age_at_diagnosis values metabric[metabric["ER_status"]=="Positive"]["Age_at_diagnosis"] ) print("Mann-Whitney U test of survival time for ER_status Negative vs Positive:") print("f = {}".format(ER_survival_MWU.statistic)) print("p = {}".format(ER_age_t.pvalue)) ``` ## ANOVA If we want to test for a difference in the mean value of a continuous variable between >2 groups simultaneously, we can use the analysis of variance (ANOVA). For example, we may want to test for differences between survival times between different cancer types, which appear to be different: ``` ( p9.ggplot(metabric, p9.aes("Cancer_type", "Survival_time")) + p9.geom_boxplot() + p9.theme(axis_text_x = p9.element_text(angle=45, hjust=1)) ) ``` We can use the `f_oneway()` function to run ANOVA, which shows that we cannot reject the null hypothesis that there is no difference in survival time between cancer types: ``` type_survival_anova = sp.stats.f_oneway( # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast"]["Survival_time"], # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast Invasive Ductal Carcinoma"]["Survival_time"], # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast Invasive Lobular Carcinoma"]["Survival_time"] ) print("ANOVA of survival time for different cancer types:") print("f = {}".format(type_survival_anova.statistic)) print("p = {}".format(type_survival_anova.pvalue)) ``` Similar to the t-test, the ANOVA method achieves optimal results when **all** groups are normally distributed. The non-paramteric equivalent of the ANOVA is the Kruskal-Wallis test, and we can call it via the `kruskal` function. It is easy to implement and very similar to how ANOVA is implemented. ``` type_survival_anova = sp.stats.kruskal( # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast"]["Survival_time"], # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast Invasive Ductal Carcinoma"]["Survival_time"], # select samples with Breast cancer and extract the Survival_time values metabric[metabric["Cancer_type"]=="Breast Invasive Lobular Carcinoma"]["Survival_time"] ) print("Kruskal-Wallis test for survival time for different cancer types:") print("f = {}".format(type_survival_anova.statistic)) print("p = {}".format(type_survival_anova.pvalue)) ``` ## Chi-square test If we have two categorical variables of interest, and we want to test whether the status of one variable is linked to the status of the other, we can use the chi-square test. For example, we may want to test whether the ER status of a tumour (Positive or Negative) is linked to the PR status (Positive or Negative). First, we need to format the data into a contingency table, containing counts of positive and negative values for ER and PR: ``` # use the crosstab function to make a contingency table of the total numbers of patients that are ER+ & PR+, ER+ & PR-, ER- & PR+, and ER- & PR- ER_PR_contingency = pd.crosstab(metabric["ER_status"], metabric["PR_status"]) ER_PR_contingency ``` Now, we use the `chi2_contingency()` function to run the chi-square test, and assign the results to a variable. This shows that we can reject the null hypothesis that ER and PR status are independent. The results are returned as a tuple rather than an object, so we retrieve them by using indexing: ``` ER_PR_chi = sp.stats.chi2_contingency(ER_PR_contingency) print("Chi-square test for ER and PR status:") print("Chi-square value = {}".format(ER_PR_chi[0])) print("p value = {}".format(ER_PR_chi[1])) ``` # Data Transformation When working with large datasets, we often have variables with very different ranges and distributions of values. For some analyses, particularly statistical modelling, it is helpful to be able to apply a mathematical transformation to a set of values, which rescales the values and makes their distribution and range more similar to other variables in the dataset. For example, in the Metabric dataset the distribution of tumour sizes is highly left-skewed, as most tumours are small but a few are very large: ``` ( p9.ggplot(metabric, p9.aes("Tumour_size")) + p9.geom_histogram() ) ``` To perform transformations on this data, we can use some functions from numpy: - `sqrt()` = square-root transform - `log2()` = log-transform with base 2 - `log10()` = log-transform with base 10 All of these functions return a pandas series of transformed values. To retain the original (untransformed) data, we can add these transformed values to the metabric dataframe as a new column: ``` metabric["Tumour_size_sqrt"] = np.sqrt(metabric["Tumour_size"]) metabric["Tumour_size_log2"] = np.log2(metabric["Tumour_size"]) metabric["Tumour_size_log10"] = np.log10(metabric["Tumour_size"]) ``` After transformation, the tumour sizes look closer to being normally distributed: ``` # select the variables of interest tumour_size_tranformations = metabric.loc[:,["Patient_ID", "Tumour_size", "Tumour_size_sqrt", "Tumour_size_log2", "Tumour_size_log10"]] # rename the columns for ease of plotting tumour_size_tranformations.columns = ["Patient_ID", "Untransformed", "sqrt", "log2", "log10"] # reformat the untransformed and transformed data into three columns ahead of plotting tumour_size_tranformations = pd.melt(tumour_size_tranformations, id_vars="Patient_ID", var_name="Transformation", value_name="Size") # plot faceted histogram ( p9.ggplot(tumour_size_tranformations, p9.aes("Size")) + p9.facet_wrap("~Transformation", nrow=2, scales="free") + p9.geom_histogram(bins=50) ) ``` # Modelling ## Simple linear regression If we have a continuous variable, and we want to model its relationship with another variable, we can use simple linear regression. In linear regression we call the variable of interest the **response**, and the other variable the **predictor**. The mathematical details of linear regression are beyond the scope of this course, but in the case of simple linear regression it basically amounts to fitting a line through the data that is closest to all of the points. For example, we may want to predict survival time based on tumour size, because survival time appears to differ across the range of tumour sizes: ``` ( p9.ggplot(metabric, p9.aes("Tumour_size", "Survival_time")) + p9.geom_point() ) ``` In Python, we can run simple linear regression using the `ols` function from the `statsmodels` package. There are three steps to completing this analysis: 1. **Instantiate** the model: create an object that holds the model specification and the input dataset. In the model specification, the response is to the left of the tilda `~` and the predictor is to the right 2. **Fit** the model: fit the specified model to the data using the `fit()` function, and assign the results object to a variable 3. **Display** the results: use the `summary()` method of the results object to return a detailed breakdown of the model characteristics ``` # instantiate model simple_model = ols("Survival_time~Tumour_size", data=metabric) # fit the model simple_results = simple_model.fit() # display the results simple_results.summary() ``` The model summary contains a lot of detailed information, but we can create a more concise report of the results by extracting the results of interest e.g. the r2 value, the F-statistic and its p value: ``` print("Simple linear regression: Survival_time~Tumour_size") print("r2 = {}".format(simple_results.rsquared)) print("F-statistic = {}".format(simple_results.fvalue)) print("F-statistic p value= {}".format(simple_results.f_pvalue)) ``` After fitting a linear regression model, we usually want to carry out some basic checks of the model characteristics. This is because linear regression makes some assumptions about the data and our model, and if the data that we have fitted our model to has violated these assumptions, then the predictions from the model may not be reliable. We will not cover these checks in this session as they are beyond the scope of the course, but if you want information on how to do this then please see the [statsmodels documentation](https://www.statsmodels.org/stable/index.html). If we are happy with the checks of model characteristics, we can use the model to predict what the value of our response variable will be, given a certain value for the predictor variable. We do this using the `predict()` method of the results object, which takes the value of the predictor variable as the argument: ``` simple_results.predict({"Tumour_size": 125}) ``` Our model predicts a survival time of 8.6 for a tumour size of 125; however, the low r2 value for this model (r2=0.053) indicates that it fits the data very poorly, so we may not be very confident in this prediction. ## Multivariate linear regression When we are analysing more complex processes, we often need to consider the influence of multiple predictors simultaneously. One way to do this is by using multivariate linear regression, which models the relationship between the response and two or more predictors. For example, we may wish to model the effect on survival time of tumour size, tumour stage, cancer type and ER status. To do this we repeat the simple regression process described above, but specify multiple predictors when instantiating the model. When viewing the results, we extract the `pvalues` attribute of the results object to print the p values associated with each predictor: ``` # instantiate model complex_model = ols("Survival_time~Tumour_size + Tumour_stage + Cancer_type + ER_status", data=metabric) # fit the model complex_results = complex_model.fit() # print the results of interest print("Complex linear regression: Survival_time~Tumour_size + Tumour_stage + Cancer_type + ER_status") print("r2 = {}".format(complex_results.rsquared)) print("F-statistic = {}".format(complex_results.fvalue)) print("F-statistic p value= {}".format(complex_results.f_pvalue)) print("p values for each predictor:") print(complex_results.pvalues) complex_results.summary() ``` Including these extra predictors has almost doubled the r2, but the model fit is still quite poor (r2=0.098). Given the complexity of breast cancer biology and the relative simplicity of our analysis, this isn't a big surprise! # Exercises ## Exercise 1 Is there a significant difference between the tumour size of patients who received chemotherapy versus patients that did not receive chemotherapy? Use either the t-test or Mann-Whitney U test, and provide a visualization to compare tumour size between patients who did or did not receive chemotherapy. When deciding which test to use, remember to check whether the data is normally distributed or not. ## Exercise 2 Is there a correlation between tumour size and survival time? If so, does the correlation become weaker or stronger after tumour size is log10-transformed? Generate a visualization of the relationship between log10-transformed tumour size and survival time. ## Exercise 3 Make a contingency table of the number of patients that did or did not receive chemotherapy and did or did not receive radiotherapy, and use a chi-square test to investigate whether the incidence of these treatments are independent of each other.
github_jupyter
``` from __future__ import print_function from six.moves import range from PIL import Image import sys # dir_path = '~/GANtor-Arts-Center/src/code/main.py' # sys.path.append(dir_path) sys.path.append('../src/code/') import torch.backends.cudnn as cudnn import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import os import time import numpy as np import torchfile from miscc.config import cfg, cfg_from_file from miscc.utils import mkdir_p from miscc.utils import weights_init from miscc.utils import save_img_results, save_model from miscc.utils import KL_loss from miscc.utils import compute_discriminator_loss, compute_generator_loss from tensorboard import summary from tensorboardX import FileWriter import torchvision.utils as vutils device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = torch.device(0) print(torch.cuda.is_available()) from modelv2 import STAGE1_G, STAGE2_G, STAGE2_D # Only classified on genre for GANtor-v2 category = "genre" stage = 2 image_size = 64 if stage == 1 else 256 image_dir = './v2_genre256/'.format(category, image_size) style_1 = '' style_2 = '' genre_1 = "../src/saved_models/v2/s1_genre/netG_epoch_90.pth" genre_2 = "../src/saved_models/v2/s2_genre/netG_epoch_70.pth" config_file = '../cfg/wikiart_s2_v2.yml' cfg_from_file(config_file) Stage1_G = STAGE1_G() stage_1_file = genre_1 if category == "genre" else style_1 stage_2_file = genre_2 if category == "genre" else style_2 if stage == 1: netG = Stage1_G state_dict = torch.load(stage_1_file,map_location=lambda storage, loc: storage) netG.load_state_dict(state_dict) print('Load from: ', stage_1_file) elif stage == 2: netG = STAGE2_G(Stage1_G) state_dict = torch.load(stage_1_file,map_location=lambda storage, loc: storage) netG.STAGE1_G.load_state_dict(state_dict) print('Load from: ', stage_1_file) state_dict = torch.load(stage_2_file, map_location=lambda storage, loc: storage) netG.load_state_dict(state_dict) print('Load from: ', stage_2_file) else: raise Exception ("Stage unspecified!") # netG.eval() if cfg.CUDA: netG.cuda() netG = nn.DataParallel(netG) print(netG) nz = 100 batch_size = 16 embedding_size = 10 num_iters = 10 classes = [1, 4] for i in range(0, num_iters): print ("Iter num %i"%(i)) for class_idx in classes: noise = Variable(torch.FloatTensor(batch_size, nz)) with torch.no_grad(): fixed_noise = \ Variable(torch.FloatTensor(batch_size, nz).normal_(0, 1)) noise, fixed_noise = noise.cuda(), fixed_noise.cuda() noise.data.normal_(0, 1) text_embeddings = torch.zeros((batch_size, embedding_size)).cuda() text_embeddings[:, class_idx] = 1 # inputs = (text_embeddings, noise) with torch.no_grad(): lr_fake, fake = netG(text_embeddings, noise) for im_idx, im in enumerate(fake.data): vutils.save_image( im, '%s%i/%i_%i.png' % (image_dir, class_idx, i, im_idx), normalize=True) ```
github_jupyter
# Doppler timing tests Benchmark tests for various methods in the ``DopplerMap`` class. ``` # Enable progress bars? TQDM = False %matplotlib inline %run notebook_setup.py import starry starry.config.lazy = False starry.config.quiet = True import starry import numpy as np import matplotlib.pyplot as plt import timeit from tqdm.notebook import tqdm as _tqdm tqdm = lambda *args, **kwargs: _tqdm(*args, disable=not TQDM, **kwargs) def get_time(statement="map.flux()", number=100, **kwargs): setup = f"map = starry.DopplerMap(**kwargs); {statement}" t0 = timeit.timeit( statement, setup=setup, number=1, globals={**locals(), **globals()} ) if t0 > 0.1: return t0 else: return ( timeit.timeit( statement, setup=setup, number=number, globals={**locals(), **globals()} ) / number ) ``` ## `DopplerMap.flux()` Benchmarks for different evaluation ``method``s. ### As a function of `ydeg` With `nt = 1`, `nc = 1`, `nw = 200`. ``` methods = ["dotconv", "convdot", "conv", "design"] ydegs = [1, 2, 3, 5, 8, 10, 13, 15] nt = 1 nc = 1 wav = np.linspace(500, 501, 200) time = np.zeros((len(methods), len(ydegs))) for i, method in tqdm(enumerate(methods), total=len(methods)): for j, ydeg in tqdm(enumerate(ydegs), total=len(ydegs), leave=False): time[i, j] = get_time( f"map.flux(method='{method}')", ydeg=ydeg, nt=nt, nc=nc, wav=wav ) plt.figure(figsize=(8, 5)) plt.plot(ydegs, time.T, "o-", label=methods) plt.legend(fontsize=10) plt.yscale("log") plt.xscale("log") plt.xlabel("spherical harmonic degree") plt.ylabel("time [s]"); ``` ### As a function of `nt` With `ydeg = 3`, `nc = 1`, `nw = 200`. ``` methods = ["dotconv", "convdot", "conv", "design"] ydeg = 3 nts = [1, 2, 3, 5, 10, 20] nc = 1 wav = np.linspace(500, 501, 200) time = np.zeros((len(methods), len(nts))) for i, method in tqdm(enumerate(methods), total=len(methods)): for j, nt in tqdm(enumerate(nts), total=len(nts), leave=False): time[i, j] = get_time( f"map.flux(method='{method}')", ydeg=ydeg, nt=nt, nc=nc, wav=wav ) plt.figure(figsize=(8, 5)) plt.plot(nts, time.T, "o-", label=methods) plt.legend(fontsize=10) plt.yscale("log") plt.xscale("log") plt.xlabel("number of epochs") plt.ylabel("time [s]"); ``` ### As a function of `nw` With `ydeg = 3`, `nt = 1`, `nc = 1`. ``` methods = ["dotconv", "convdot", "conv", "design"] ydeg = 3 nt = 1 nc = 1 nws = [100, 200, 300, 400, 500, 800, 1000] wavs = [np.linspace(500, 501, nw) for nw in nws] time = np.zeros((len(methods), len(wavs))) for i, method in tqdm(enumerate(methods), total=len(methods)): for j, wav in tqdm(enumerate(wavs), total=len(wavs), leave=False): time[i, j] = get_time( f"map.flux(method='{method}')", ydeg=ydeg, nt=nt, nc=nc, wav=wav ) plt.figure(figsize=(8, 5)) plt.plot(nws, time.T, "o-", label=methods) plt.legend(fontsize=10) plt.yscale("log") plt.xscale("log") plt.xlabel("number of wavelength bins") plt.ylabel("time [s]"); ```
github_jupyter
``` import re import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline mpl.style.use('seaborn-muted') g = nx.DiGraph() state = 0 g.add_node(state) bool(g.nodes) class Token: def __init__(self, token, ignore_case=True, scrub_re='\.'): self.ignore_case = ignore_case self.scrub_re = scrub_re self.token = token self.token_clean = self._clean(token) def _clean(self, token): if self.ignore_case: token = token.lower() if self.scrub_re: token = re.sub(self.scrub_re, '', token) return token def __call__(self, input_token): return self._clean(input_token) == self.token_clean def __repr__(self): return '%s<%s>' % (self.__class__.__name__, self.token_clean) class GeoFSA(nx.DiGraph): def __init__(self): super().__init__() def _next_state(self): state = max(self.nodes) + 1 if self.nodes else 0 self.add_node(state) return state def add_token(self, accept_fn, parent=None, optional=False): s1 = parent if parent else self._next_state() s2 = self._next_state() self.add_edge(s1, s2, accept_fn=accept_fn) if optional: s3 = self._next_state() self.add_edge(s2, s3) self.add_edge(s1, s3) return s3 return s2 class Matcher: def __init__(self, fsa): self.fsa = fsa self._states = set([0]) self.accepted = [] def step(self, start_state, token, visited=None): if not visited: visited = set() visited.add(start_state) next_states = set() for d_state, attrs in self.fsa[start_state].items(): accept_fn = attrs.get('accept_fn') if accept_fn: if accept_fn(token): next_states.add(d_state) elif d_state not in visited: next_states.update(self.step(d_state, token, visited)) return next_states def __call__(self, token): next_states = set() for state in self._states: next_states.update(self.step(state, token)) if next_states: self._states = next_states self.accepted.append(token) return True return False title_tokens = ['South', 'Lake', 'Tahoe'] states = [['California'], ['CA']] g = GeoFSA() parent = None for token in title_tokens: parent = g.add_token(Token(token), parent=parent) comma = g.add_token(Token(','), parent=parent) for state in states: parent = comma for token in state: parent = g.add_token(Token(token), parent=parent) m = Matcher(g) print(m('South')) print(m('Lake')) print(m('Tahoe')) print(m(',')) # print(m(',')) # print(m(',')) print(m('CA')) m.accepted nx.draw(g) ```
github_jupyter
## Get the Data Either use the provided .csv file or (optionally) get fresh (the freshest?) data from running an SQL query on StackExchange: Follow this link to run the query from [StackExchange](https://data.stackexchange.com/stackoverflow/query/675441/popular-programming-languages-per-over-time-eversql-com) to get your own .csv file <code> select dateadd(month, datediff(month, 0, q.CreationDate), 0) m, TagName, count(*) from PostTags pt join Posts q on q.Id=pt.PostId join Tags t on t.Id=pt.TagId where TagName in ('java','c','c++','python','c#','javascript','assembly','php','perl','ruby','visual basic','swift','r','object-c','scratch','go','swift','delphi') and q.CreationDate < dateadd(month, datediff(month, 0, getdate()), 0) group by dateadd(month, datediff(month, 0, q.CreationDate), 0), TagName order by dateadd(month, datediff(month, 0, q.CreationDate), 0) </code> ## Import Statements ## Data Exploration **Challenge**: Read the .csv file and store it in a Pandas dataframe **Challenge**: Examine the first 5 rows and the last 5 rows of the of the dataframe **Challenge:** Check how many rows and how many columns there are. What are the dimensions of the dataframe? **Challenge**: Count the number of entries in each column of the dataframe **Challenge**: Calculate the total number of post per language. Which Programming language has had the highest total number of posts of all time? Some languages are older (e.g., C) and other languages are newer (e.g., Swift). The dataset starts in September 2008. **Challenge**: How many months of data exist per language? Which language had the fewest months with an entry? ## Data Cleaning Let's fix the date format to make it more readable. We need to use Pandas to change format from a string of "2008-07-01 00:00:00" to a datetime object with the format of "2008-07-01" ## Data Manipulation **Challenge**: What are the dimensions of our new dataframe? How many rows and columns does it have? Print out the column names and print out the first 5 rows of the dataframe. **Challenge**: Count the number of entries per programming language. Why might the number of entries be different? ## Data Visualisaton with with Matplotlib **Challenge**: Use the [matplotlib documentation](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) to plot a single programming language (e.g., java) on a chart. **Challenge**: Show two line (e.g. for Java and Python) on the same chart. # Smoothing out Time Series Data Time series data can be quite noisy, with a lot of up and down spikes. To better see a trend we can plot an average of, say 6 or 12 observations. This is called the rolling mean. We calculate the average in a window of time and move it forward by one overservation. Pandas has two handy methods already built in to work this out: [rolling()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html) and [mean()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.rolling.Rolling.mean.html).
github_jupyter
# Anchor explanations for movie sentiment In this example, we will explain why a certain sentence is classified by a logistic regression as having negative or positive sentiment. The logistic regression is trained on negative and positive movie reviews. ``` import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import spacy from alibi.explainers import AnchorText from alibi.datasets import fetch_movie_sentiment from alibi.utils.download import spacy_model ``` ### Load movie review dataset The `fetch_movie_sentiment` function returns a `Bunch` object containing the features, the targets and the target names for the dataset. ``` movies = fetch_movie_sentiment() movies.keys() data = movies.data labels = movies.target target_names = movies.target_names ``` Define shuffled training, validation and test set ``` train, test, train_labels, test_labels = train_test_split(data, labels, test_size=.2, random_state=42) train, val, train_labels, val_labels = train_test_split(train, train_labels, test_size=.1, random_state=42) train_labels = np.array(train_labels) test_labels = np.array(test_labels) val_labels = np.array(val_labels) ``` ### Apply CountVectorizer to training set ``` vectorizer = CountVectorizer(min_df=1) vectorizer.fit(train) ``` ### Fit model ``` np.random.seed(0) clf = LogisticRegression(solver='liblinear') clf.fit(vectorizer.transform(train), train_labels) ``` ### Define prediction function ``` predict_fn = lambda x: clf.predict(vectorizer.transform(x)) ``` ### Make predictions on train and test sets ``` preds_train = predict_fn(train) preds_val = predict_fn(val) preds_test = predict_fn(test) print('Train accuracy', accuracy_score(train_labels, preds_train)) print('Validation accuracy', accuracy_score(val_labels, preds_val)) print('Test accuracy', accuracy_score(test_labels, preds_test)) ``` ### Load spaCy model English multi-task CNN trained on OntoNotes, with GloVe vectors trained on Common Crawl. Assigns word vectors, context-specific token vectors, POS tags, dependency parse and named entities. ``` model = 'en_core_web_md' spacy_model(model=model) nlp = spacy.load(model) ``` ### Initialize anchor text explainer ``` explainer = AnchorText(nlp, predict_fn) ``` ### Explain a prediction ``` class_names = movies.target_names text = data[4] print(text) ``` Prediction: ``` pred = class_names[predict_fn([text])[0]] alternative = class_names[1 - predict_fn([text])[0]] print('Prediction: %s' % pred) ``` Explanation: ``` np.random.seed(0) explanation = explainer.explain(text, threshold=0.95, use_unk=True) ``` use_unk=True means we will perturb examples by replacing words with UNKs. Let us now take a look at the anchor. The word 'exercise' basically guarantees a negative prediction. ``` print('Anchor: %s' % (' AND '.join(explanation.anchor))) print('Precision: %.2f' % explanation.precision) print('\nExamples where anchor applies and model predicts %s:' % pred) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_true']])) print('\nExamples where anchor applies and model predicts %s:' % alternative) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_false']])) ``` ### Changing the perturbation distribution Let's try this with another perturbation distribution, namely one that replaces words by similar words instead of UNKs. Explanation: ``` np.random.seed(0) explanation = explainer.explain(text, threshold=0.95, use_unk=False, sample_proba=0.5) ``` The anchor now shows that we need more to guarantee the negative prediction: ``` print('Anchor: %s' % (' AND '.join(explanation.anchor))) print('Precision: %.2f' % explanation.precision) print('\nExamples where anchor applies and model predicts %s:' % pred) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_true']])) print('\nExamples where anchor applies and model predicts %s:' % alternative) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_false']])) ``` We can make the token perturbation distribution sample words that are more similar to the ground truth word via the `top_n` argument. Smaller values (default=100) should result in sentences that are more coherent and thus more in the distribution of natural language which could influence the returned anchor. By setting the `use_probability_proba` to True, the sampling distribution for perturbed tokens is proportional to the similarity score between the possible perturbations and the original word. We can also put more weight on similar words via the `temperature` argument. Lower values of `temperature` increase the sampling weight of more similar words. The following example will perturb tokens in the original sentence with probability equal to `sample_proba`. The sampling distribution for the perturbed tokens is proportional to the similarity score between the ground truth word and each of the `top_n` words. ``` np.random.seed(0) explanation = explainer.explain(text, threshold=0.95, use_similarity_proba=True, sample_proba=0.5, use_unk=False, top_n=20, temperature=.2) print('Anchor: %s' % (' AND '.join(explanation.anchor))) print('Precision: %.2f' % explanation.precision) print('\nExamples where anchor applies and model predicts %s:' % pred) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_true']])) print('\nExamples where anchor applies and model predicts %s:' % alternative) print('\n'.join([x for x in explanation.raw['examples'][-1]['covered_false']])) ```
github_jupyter
# Tutorial with 1d advection equation Jiawei Zhuang 7/24/2019 (updated 02/13/2020) ``` !pip install git+https://github.com/JiaweiZhuang/data-driven-pdes@fix-beam %tensorflow_version 1.x import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf tf.enable_eager_execution() %matplotlib inline import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.size'] = 14 from google.colab import files # colab-specific utilities; comment out when running locally tf.enable_eager_execution() tf.__version__, tf.keras.__version__ import xarray from datadrivenpdes.core import grids from datadrivenpdes.core import integrate from datadrivenpdes.core import models from datadrivenpdes.core import tensor_ops from datadrivenpdes.advection import equations as advection_equations from datadrivenpdes.pipelines import model_utils ``` # Define simulation grids ``` # we mostly run simulation on coarse grid # the fine grid is only for obtaining training data and generate the reference "truth" grid_length = 32 fine_grid_resolution = 256 coarse_grid_resolution = 32 assert fine_grid_resolution % coarse_grid_resolution == 0 # 1d domain, so only 1 point along y dimension fine_grid = grids.Grid( size_x=fine_grid_resolution, size_y=1, step=grid_length/fine_grid_resolution ) coarse_grid = grids.Grid( size_x=coarse_grid_resolution, size_y=1, step=grid_length/coarse_grid_resolution ) x_fine, _ = fine_grid.get_mesh() x_coarse, _ = coarse_grid.get_mesh() x_fine.shape, x_coarse.shape ``` # Generate initial condition ``` def make_square(x, height=1.0, center=0.25, width=0.1): """ Args: x: Numpy array. Shape should be (nx, 1) or (nx,) height: float, peak concentration center: float, relative center position in 0~1 width: float, relative width in 0~0.5 Returns: Numpy array, same shape as `x` """ nx = x.shape[0] c = np.zeros_like(x) c[int((center-width)*nx):int((center+width)*nx)] = height return c fig, axes = plt.subplots(1, 2, figsize=[8, 3]) axes[0].plot(x_fine, make_square(x_fine), marker='.') axes[1].plot(x_coarse, make_square(x_coarse), marker='.') for ax in axes: ax.set_ylim(-0.1, 1.1) def make_multi_square(x, height_list, width_list): c_list = [] for height in height_list: for width in width_list: c_temp = make_square(x, height=height, width=width) c_list.append(c_temp) return np.array(c_list) height_list = np.arange(0.1, 1.1, 0.1) width_list = np.arange(1/16, 1/4, 1/16) # width is chosen so that coarse-graining of square wave is symmetric c_init = make_multi_square( x_coarse, height_list = height_list, width_list = width_list ) c_init.shape # (sample, x, y) fig, axes = plt.subplots(1, 5, figsize=[16, 3]) for i, ax in enumerate(axes): ax.plot(x_coarse, c_init[4*i+2, :, 0], marker='.') ax.set_ylim(-0.1, 1.1) ``` # Wrap with velocity fields ``` # for simplicity, use uniform constant velocity field for all samples initial_state = { 'concentration': c_init.astype(np.float32), # tensorflow code expects float32 'x_velocity': np.ones(c_init.shape, np.float32) * 1.0, 'y_velocity': np.zeros(c_init.shape, np.float32) } for k, v in initial_state.items(): print(k, v.shape) # (sample, x, y) ``` # Run baseline advection solver ``` # first-order finite difference model, very diffusive model_1st = models.FiniteDifferenceModel( advection_equations.UpwindAdvection(cfl_safety_factor=0.5), coarse_grid ) # second-order scheme with monotonic flux limiter model_2nd = models.FiniteDifferenceModel( advection_equations.VanLeerAdvection(cfl_safety_factor=0.5), coarse_grid ) time_steps = np.arange(0, 256+1) %time integrated_1st = integrate.integrate_steps(model_1st, initial_state, time_steps) %time integrated_2nd = integrate.integrate_steps(model_2nd, initial_state, time_steps) for k, v in integrated_1st.items(): print(k, v.shape) # (time, sample, x, y) def wrap_as_xarray(integrated): dr = xarray.DataArray( integrated['concentration'].numpy().squeeze(), dims = ('time', 'sample', 'x'), coords = {'time': time_steps, 'x': x_coarse.squeeze()} ) return dr dr_1st = wrap_as_xarray(integrated_1st) dr_1st.isel(time=[0, 10, 128], sample=[4, 10, 16]).plot(col='sample', hue='time') dr_2nd = wrap_as_xarray(integrated_2nd) dr_2nd.isel(time=[0, 10, 128], sample=[4, 10, 16]).plot(col='sample', hue='time') ``` # Run untrained neural net model ``` model_nn = models.PseudoLinearModel( advection_equations.FiniteVolumeAdvection(0.5), coarse_grid, num_time_steps=4, # multi-step loss function stencil_size=3, kernel_size=(3, 1), num_layers=4, filters=32, constrained_accuracy_order=1, learned_keys = {'concentration_edge_x', 'concentration_edge_y'}, # finite volume view, use edge concentration activation='relu', ) model_nn.learned_keys, model_nn.fixed_keys tf.random.set_random_seed(0) %time integrated_untrained = integrate.integrate_steps(model_nn, initial_state, time_steps) (wrap_as_xarray(integrated_untrained) .isel(time=[0, 2, 10], sample=[4, 10, 16]) .plot(col='sample', hue='time', ylim=[-0.2, 0.5]) ) # untrained model is diverging! # weights are initialized at the first model call len(model_nn.get_weights()) model_nn.get_weights()[0].shape # first convolutional filter, (x, y, input_channel, filter_channel) model_nn.get_weights()[2].shape # second convolutional filter, (x, y, filter_channel, filter_channel) ``` # Generate training data from high-resolution baseline simulations ``` # This data-generation code is a bit involved, mostly because we use multi-step loss function. # To produce large training data in parallel, refer to the create_training_data.py script in source code. def reference_solution(initial_state_fine, fine_grid, coarse_grid, coarse_time_steps=256): # use high-order traditional scheme as reference model equation = advection_equations.VanLeerAdvection(cfl_safety_factor=0.5) key_defs = equation.key_definitions # reference model runs at high resolution model = models.FiniteDifferenceModel(equation, fine_grid) # need 8x more time steps for 8x higher resolution to satisfy CFL coarse_ratio = fine_grid.size_x // coarse_grid.size_x steps = np.arange(0, coarse_time_steps*coarse_ratio+1, coarse_ratio) # solve advection at high resolution integrated_fine = integrate.integrate_steps(model, initial_state_fine, steps) # regrid to coarse resolution integrated_coarse = tensor_ops.regrid( integrated_fine, key_defs, fine_grid, coarse_grid) return integrated_coarse def make_train_data(integrated_coarse, coarse_time_steps=256, example_time_steps=4): # we need to re-format data so that single-step input maps to multi-step output # remove the last several time steps, as training input train_input = {k: v[:-example_time_steps] for k, v in integrated_coarse.items()} # merge time and sample dimension as required by model n_time, n_sample, n_x, n_y = train_input['concentration'].shape for k in train_input: train_input[k] = tf.reshape(train_input[k], [n_sample * n_time, n_x, n_y]) print('\n train_input shape:') for k, v in train_input.items(): print(k, v.shape) # (merged_sample, x, y) # pick the shifted time series, as training output output_list = [] for shift in range(1, example_time_steps+1): # output time series, starting from each single time step output_slice = integrated_coarse['concentration'][shift:coarse_time_steps - example_time_steps + shift + 1] # merge time and sample dimension as required by training n_time, n_sample, n_x, n_y = output_slice.shape output_slice = tf.reshape(output_slice, [n_sample * n_time, n_x, n_y]) output_list.append(output_slice) train_output = tf.stack(output_list, axis=1) # concat along shift_time dimension, after sample dimension print('\n train_output shape:', train_output.shape) # (merged_sample, shift_time, x, y) # sanity check on shapes assert train_output.shape[0] == train_input['concentration'].shape[0] # merged_sample assert train_output.shape[2] == train_input['concentration'].shape[1] # x assert train_output.shape[3] == train_input['concentration'].shape[2] # y assert train_output.shape[1] == example_time_steps return train_input, train_output # need to re-evaluate initial condition on high-resolution grid c_init_fine = make_multi_square( x_fine, height_list = height_list, width_list = width_list ) initial_state_fine = { 'concentration': c_init_fine.astype(np.float32), # tensorflow code expects float32 'x_velocity': np.ones(c_init_fine.shape, np.float32) * 1.0, 'y_velocity': np.zeros(c_init_fine.shape, np.float32) } %time integrated_ref = reference_solution(initial_state_fine, fine_grid, coarse_grid) train_input, train_output = make_train_data(integrated_ref) [v.shape for v in initial_state_fine.values()] # make sure that single-step input corresponds to multi-step (advected) output i_sample = 48 # any number between 0 and train_output.shape[0] plt.plot(train_input['concentration'][i_sample].numpy(), label='init') for shift in range(train_output.shape[1])[:3]: plt.plot(train_output[i_sample, shift].numpy(), label=f'shift={shift+1}') plt.title(f'no. {i_sample} sample') plt.legend() ``` # Train neural net model Can skip to the next section "load existing weights" if weights have been saved before. ``` %%time # same as training standard Keras model model_nn.compile( optimizer='adam', loss='mae' ) tf.random.set_random_seed(42) np.random.seed(42) history = model_nn.fit( train_input, train_output, epochs=120, batch_size=32, verbose=1, shuffle=True ) df_history = pd.DataFrame(history.history) df_history.plot(marker='.') df_history['loss'][3:].plot(marker='.') # might not converged yet ``` ## Save trained model ``` model_utils.save_weights(model_nn, 'weights_1d_120epochs.h5') # files.download('weights_1d_120epochs.h5') ``` # Or directly load trained model Need to manually upload weights as Colab local file ``` model_utils.load_weights(model_nn, 'weights_1d_120epochs.h5') ``` # Integrate trained model ``` %time integrated_nn = integrate.integrate_steps(model_nn, initial_state, time_steps) dr_nn = wrap_as_xarray(integrated_nn) dr_nn.sizes dr_nn.isel(time=[0, 10, 128], sample=[4, 10, 16]).plot(col='sample', hue='time') # much better than traditional finite difference scheme ``` ## Evaluate accuracy on training set Here just test on training data. Next section makes new test data. ``` dr_ref = wrap_as_xarray(integrated_ref) # reference "truth" dr_all_train = xarray.concat([dr_nn, dr_2nd, dr_1st, dr_ref], dim='model') dr_all_train.coords['model'] = ['nn', '2nd', '1st', 'ref'] (dr_all_train.isel(time=[0, 16, 64, 128, 256], sample=[4, 10, 16]) .plot(hue='model', col='time', row='sample', alpha=0.6, linewidth=2) ) # neural net model (blue line) almost overlaps with reference truth (red line); so lines are hard to see clearly ( (dr_all_train.sel(model=['nn', '1st', '2nd']) - dr_all_train.sel(model='ref')) .pipe(abs).mean(dim=['x', 'sample']) # mean absolute error .isel(time=slice(0, 129, 2)) # the original error series oscillates between odd & even steps, because CFL=0.5 .plot(hue='model') ) plt.title('Error on training set') plt.grid() ``` # Prediction on new test data ``` np.random.seed(41) height_list_test = np.random.uniform(0.1, 0.9, size=10) # width_list_test = np.random.uniform(1/16, 1/4, size=3) # doesn't make sense to randomly sample widths of square waves, as a square has to align with grid c_init_test = make_multi_square( x_coarse, height_list = height_list_test, width_list = width_list # just use width in training set ) c_init_test.shape # (sample, x, y) height_list_test # , width_list_test plt.plot(x_coarse, c_init_test[5]) initial_state_test = { 'concentration': c_init_test.astype(np.float32), # tensorflow code expects float32 'x_velocity': np.ones(c_init_test.shape, np.float32) * 1.0, 'y_velocity': np.zeros(c_init_test.shape, np.float32) } for k, v in initial_state_test.items(): print(k, v.shape) %time dr_nn_test = wrap_as_xarray(integrate.integrate_steps(model_nn, initial_state_test, time_steps)) %time dr_1st_test = wrap_as_xarray(integrate.integrate_steps(model_1st, initial_state_test, time_steps)) %time dr_2nd_test = wrap_as_xarray(integrate.integrate_steps(model_2nd, initial_state_test, time_steps)) dr_sol_test = xarray.concat([dr_nn_test, dr_2nd_test, dr_1st_test], dim='model') dr_sol_test.coords['model'] = ['Neural net', 'Baseline', 'First order'] (dr_sol_test.isel(time=[0, 16, 64, 128, 256], sample=[4, 10, 16]) .plot(hue='model', col='time', row='sample', alpha=0.6, linewidth=2) ) plt.ylim(0, 1) (dr_sol_test.isel(time=[0, 16, 64, 256], sample=16).rename({'time': 'Time step'}) .plot(hue='model', col='Time step', alpha=0.6, col_wrap=2, linewidth=2, figsize=[6, 4.5], ylim=[None, 0.8]) ) plt.suptitle('Advection under 1-D constant velocity', y=1.05) plt.savefig('1d-test-sample.png', dpi=288, bbox_inches='tight') # files.download('1d-test-sample.png') ``` ### Reference solution for test set ``` # need to re-evaluate initial condition on high-resolution grid c_init_fine_test = make_multi_square( x_fine, height_list = height_list_test, width_list = width_list ) initial_state_fine_test = { 'concentration': c_init_fine_test.astype(np.float32), # tensorflow code expects float32 'x_velocity': np.ones(c_init_fine_test.shape, np.float32) * 1.0, 'y_velocity': np.zeros(c_init_fine_test.shape, np.float32) } %time integrated_ref_test = reference_solution(initial_state_fine_test, fine_grid, coarse_grid) dr_ref_test = wrap_as_xarray(integrated_ref_test) # reference "truth" dr_all_test = xarray.concat([dr_nn_test, dr_2nd_test, dr_1st_test, dr_ref_test], dim='model') dr_all_test.coords['model'] = ['Neural net', 'Baseline', 'First order', 'Reference'] (dr_all_test.isel(time=[0, 16, 64, 128, 256], sample=[4, 10, 16]) .plot(hue='model', col='time', row='sample', alpha=0.6, linewidth=2) ) plt.ylim(0, 1) (dr_all_test.isel(time=[0, 16, 64, 256], sample=16).rename({'time': 'Time step'}) .plot(hue='model', col='Time step', alpha=0.6, col_wrap=2, linewidth=2, figsize=[6, 4.5], ylim=[None, 0.8]) ) plt.suptitle('Advection under 1-D constant velocity', y=1.05) # plt.savefig('1d-test-sample.png', dpi=288, bbox_inches='tight') ``` ## Plot test accuracy ``` ( (dr_all_test.sel(model=['Neural net', 'Baseline', 'First order']) - dr_all_test.sel(model='Reference')) .pipe(abs).mean(dim=['x', 'sample']) # mean absolute error .isel(time=slice(0, 257, 2)) # the original error series oscillates between odd & even steps, because CFL=0.5 .plot(hue='model', figsize=[4.5, 3.5], linewidth=2.0) ) plt.title('Error for 1-D advection') plt.xlabel('Time step') plt.ylabel('Mean Absolute Error (MAE)') plt.grid() plt.xticks(range(0, 257, 50)) plt.savefig('1d-test-mae.png', dpi=288, bbox_inches='tight') # files.download('1d-test-mae.png') ``` # Out-of-sample prediction ``` def make_gaussian(x, height=1.0, center=0.25, width=0.1): """ Args: x: Numpy array. Shape should be (nx, 1) or (nx,) height: float, peak concentration center: float, relative center position in 0~1 width: float, relative width in 0~0.5 Returns: Numpy array, same shape as `x` """ nx = x.shape[0] x_max = x.max() center *= x_max width *= x_max c = height * np.exp(-(x-center)**2 / width**2) return c def make_multi_gaussian(x, height_list, width_list): c_list = [] for height in height_list: for width in width_list: c_temp = make_gaussian(x, height=height, width=width) c_list.append(c_temp) return np.array(c_list) np.random.seed(41) height_list_guass = np.random.uniform(0.1, 0.5, size=10) width_list_guass = np.random.uniform(1/16, 1/4, size=3) c_init_guass = make_multi_gaussian( x_coarse, height_list = height_list_guass, width_list = width_list_guass ) c_init_guass.shape # (sample, x, y) height_list_guass, width_list_guass plt.plot(x_coarse, make_gaussian(x_coarse, height=0.5)) initial_state_gauss = { 'concentration': c_init_guass.astype(np.float32), # tensorflow code expects float32 'x_velocity': np.ones(c_init_guass.shape, np.float32) * 1.0, 'y_velocity': np.zeros(c_init_guass.shape, np.float32) } for k, v in initial_state_gauss.items(): print(k, v.shape) %time dr_nn_gauss = wrap_as_xarray(integrate.integrate_steps(model_nn, initial_state_gauss, time_steps)) (dr_nn_gauss.isel(time=[0, 16, 64, 128, 256], sample=[4, 10, 16]) .plot(hue='time', col='sample', alpha=0.6, linewidth=2) ) (dr_nn_gauss.isel(time=[0, 4, 16, 64], sample=[0, 4, 16]) .plot(col='time', hue='sample', col_wrap=4, alpha=0.6, linewidth=2) ) plt.suptitle('Out-of-sample prediction', y=1.05) (dr_nn_gauss.isel(time=[0, 16, 64, 256], sample=[0, 4, 29]).rename({'time': 'Time step'}) .plot(col='Time step', hue='sample', alpha=0.6, linewidth=2, col_wrap=2, figsize=[6, 4.5]) ) plt.suptitle('Neural net out-of-sample prediction', y=1.05) plt.savefig('out-of-sample.png', dpi=288, bbox_inches='tight') # files.download('out-of-sample.png') ```
github_jupyter
## Homework 3: model free learning ## Part I: On-policy learning and SARSA (3 points) _This notebook builds upon `day10` practice(`qlearning_practice.ipynb`), or to be exact, generating qlearning.py._ The policy we're gonna use is epsilon-greedy policy, where agent takes optimal action with probability $(1-\epsilon)$, otherwise samples action at random. Note that agent __can__ occasionally sample optimal action during random sampling by pure chance. ``` # In google collab, uncomment this: # !wget https://bit.ly/2FMJP5K -q -O setup.py # !bash setup.py 2>&1 1>stdout.log | tee stderr.log # !pip install pyglet==1.4.9 # This code creates a virtual display to draw game images on. # If you are running locally, just ignore it import os if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['DISPLAY'] = ':1' import numpy as np import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 ``` Now you can use code, generated from seminar `seminar_qlearning.ipynb`. Or just copy&paste it. ``` %%writefile qlearning.py from collections import defaultdict import random import math import numpy as np class QLearningAgent: def __init__(self, alpha, epsilon, discount, get_legal_actions): """ Q-Learning Agent based on https://inst.eecs.berkeley.edu/~cs188/sp19/projects.html Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate aka gamma) Functions you should use - self.get_legal_actions(state) {state, hashable -> list of actions, each is hashable} which returns legal actions for a state - self.get_qvalue(state,action) which returns Q(state,action) - self.set_qvalue(state,action,value) which sets Q(state,action) := value !!!Important!!! Note: please avoid using self._qValues directly. There's a special self.get_qvalue/set_qvalue for that. """ self.get_legal_actions = get_legal_actions self._qvalues = defaultdict(lambda: defaultdict(lambda: 0)) self.alpha = alpha self.epsilon = epsilon self.discount = discount def get_qvalue(self, state, action): """ Returns Q(state,action) """ return self._qvalues[state][action] def set_qvalue(self, state, action, value): """ Sets the Qvalue for [state,action] to the given value """ self._qvalues[state][action] = value #---------------------START OF YOUR CODE---------------------# def get_value(self, state): """ Compute your agent's estimate of V(s) using current q-values V(s) = max_over_action Q(state,action) over possible actions. Note: please take into account that q-values can be negative. """ possible_actions = self.get_legal_actions(state) # If there are no legal actions, return 0.0 if len(possible_actions) == 0: return 0.0 <YOUR CODE HERE > return value def update(self, state, action, reward, next_state): """ You should do your Q-Value update here: Q(s,a) := (1 - alpha) * Q(s,a) + alpha * (r + gamma * V(s')) """ # agent parameters gamma = self.discount learning_rate = self.alpha <YOUR CODE HERE > self.set_qvalue(state, action, < YOUR_QVALUE > ) def get_best_action(self, state): """ Compute the best action to take in a state (using current q-values). """ possible_actions = self.get_legal_actions(state) # If there are no legal actions, return None if len(possible_actions) == 0: return None <YOUR CODE HERE > return best_action def get_action(self, state): """ Compute the action to take in the current state, including exploration. With probability self.epsilon, we should take a random action. otherwise - the best policy action (self.getPolicy). Note: To pick randomly from a list, use random.choice(list). To pick True or False with a given probablity, generate uniform number in [0, 1] and compare it with your probability """ # Pick Action possible_actions = self.get_legal_actions(state) action = None # If there are no legal actions, return None if len(possible_actions) == 0: return None # agent parameters: epsilon = self.epsilon <YOUR CODE HERE > return chosen_action from qlearning import QLearningAgent class EVSarsaAgent(QLearningAgent): """ An agent that changes some of q-learning functions to implement Expected Value SARSA. Note: this demo assumes that your implementation of QLearningAgent.update uses get_value(next_state). If it doesn't, please add def update(self, state, action, reward, next_state): and implement it for Expected Value SARSA's V(s') """ def get_value(self, state): """ Returns Vpi for current state under epsilon-greedy policy: V_{pi}(s) = sum _{over a_i} {pi(a_i | s) * Q(s, a_i)} Hint: all other methods from QLearningAgent are still accessible. """ epsilon = self.epsilon possible_actions = self.get_legal_actions(state) # If there are no legal actions, return 0.0 if len(possible_actions) == 0: return 0.0 <YOUR CODE HERE: SEE DOCSTRING > return state_value ``` ### Cliff World Let's now see how our algorithm compares against q-learning in case where we force agent to explore all the time. ![](https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/cliffworld.png "image by cs188") ``` import gym import gym.envs.toy_text env = gym.envs.toy_text.CliffWalkingEnv() n_actions = env.action_space.n print(env.__doc__) # Our cliffworld has one difference from what's on the image: there is no wall. # Agent can choose to go as close to the cliff as it wishes. x:start, T:exit, C:cliff, o: flat ground env.render() def play_and_train(env, agent, t_max=10**4): """This function should - run a full game, actions given by agent.getAction(s) - train agent using agent.update(...) whenever possible - return total reward""" total_reward = 0.0 s = env.reset() for t in range(t_max): a = agent.get_action(s) next_s, r, done, _ = env.step(a) agent.update(s, a, r, next_s) s = next_s total_reward += r if done: break return total_reward from qlearning import QLearningAgent agent_sarsa = EVSarsaAgent(alpha=0.25, epsilon=0.2, discount=0.99, get_legal_actions=lambda s: range(n_actions)) agent_ql = QLearningAgent(alpha=0.25, epsilon=0.2, discount=0.99, get_legal_actions=lambda s: range(n_actions)) from IPython.display import clear_output from pandas import DataFrame def moving_average(x, span=100): return DataFrame( {'x': np.asarray(x)}).x.ewm(span=span).mean().values rewards_sarsa, rewards_ql = [], [] for i in range(5000): rewards_sarsa.append(play_and_train(env, agent_sarsa)) rewards_ql.append(play_and_train(env, agent_ql)) # Note: agent.epsilon stays constant if i % 100 == 0: clear_output(True) print('EVSARSA mean reward =', np.mean(rewards_sarsa[-100:])) print('QLEARNING mean reward =', np.mean(rewards_ql[-100:])) plt.title("epsilon = %s" % agent_ql.epsilon) plt.plot(moving_average(rewards_sarsa), label='ev_sarsa') plt.plot(moving_average(rewards_ql), label='qlearning') plt.grid() plt.legend() plt.ylim(-500, 0) plt.show() ``` Let's now see what did the algorithms learn by visualizing their actions at every state. ``` def draw_policy(env, agent): """ Prints CliffWalkingEnv policy with arrows. Hard-coded. """ n_rows, n_cols = env._cliff.shape actions = '^>v<' for yi in range(n_rows): for xi in range(n_cols): if env._cliff[yi, xi]: print(" C ", end='') elif (yi * n_cols + xi) == env.start_state_index: print(" X ", end='') elif (yi * n_cols + xi) == n_rows * n_cols - 1: print(" T ", end='') else: print(" %s " % actions[agent.get_best_action(yi * n_cols + xi)], end='') print() print("Q-Learning") draw_policy(env, agent_ql) print("SARSA") draw_policy(env, agent_sarsa) ``` ### More on SARSA Here are some of the things you can do if you feel like it: * Play with epsilon. See learned how policies change if you set epsilon to higher/lower values (e.g. 0.75). * Expected Value SASRSA for softmax policy __(2pts)__: $$ \pi(a_i|s) = softmax({Q(s,a_i) \over \tau}) = {e ^ {Q(s,a_i)/ \tau} \over {\sum_{a_j} e ^{Q(s,a_j) / \tau }}} $$ * Implement N-step algorithms and TD($\lambda$): see [Sutton's book](http://incompleteideas.net/book/bookdraft2018jan1.pdf) chapter 7 and chapter 12. * Use those algorithms to train on CartPole in previous / next assignment for this week. ## Part II: experience replay (4 points) There's a powerful technique that you can use to improve sample efficiency for off-policy algorithms: [spoiler] Experience replay :) The catch is that you can train Q-learning and EV-SARSA on `<s,a,r,s'>` tuples even if they aren't sampled under current agent's policy. So here's what we're gonna do: <img src=https://github.com/yandexdataschool/Practical_RL/raw/master/yet_another_week/_resource/exp_replay.png width=480> #### Training with experience replay 1. Play game, sample `<s,a,r,s'>`. 2. Update q-values based on `<s,a,r,s'>`. 3. Store `<s,a,r,s'>` transition in a buffer. 3. If buffer is full, delete earliest data. 4. Sample K such transitions from that buffer and update q-values based on them. To enable such training, first we must implement a memory structure that would act like such a buffer. ``` %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import clear_output import random class ReplayBuffer(object): def __init__(self, size): """ Create Replay buffer. Parameters ---------- size: int Max number of transitions to store in the buffer. When the buffer overflows the old memories are dropped. Note: for this assignment you can pick any data structure you want. If you want to keep it simple, you can store a list of tuples of (s, a, r, s') in self._storage However you may find out there are faster and/or more memory-efficient ways to do so. """ self._storage = [] self._maxsize = size # OPTIONAL: YOUR CODE def __len__(self): return len(self._storage) def add(self, obs_t, action, reward, obs_tp1, done): ''' Make sure, _storage will not exceed _maxsize. Make sure, FIFO rule is being followed: the oldest examples has to be removed earlier ''' data = (obs_t, action, reward, obs_tp1, done) # add data to storage <YOUR CODE > def sample(self, batch_size): """Sample a batch of experiences. Parameters ---------- batch_size: int How many transitions to sample. Returns ------- obs_batch: np.array batch of observations act_batch: np.array batch of actions executed given obs_batch rew_batch: np.array rewards received as results of executing act_batch next_obs_batch: np.array next set of observations seen after executing act_batch done_mask: np.array done_mask[i] = 1 if executing act_batch[i] resulted in the end of an episode and 0 otherwise. """ idxes = <randomly generate batch_size integers to be used as indexes of samples > # collect <s,a,r,s',done> for each index <YOUR CODE > return np.array( < states > ), np.array( < actions > ), np.array( < rewards > ), np.array( < next_states > ), np.array( < is_done > ) ``` Some tests to make sure your buffer works right ``` def obj2arrays(obj): for x in obj: yield np.array([x]) def obj2sampled(obj): return tuple(obj2arrays(obj)) replay = ReplayBuffer(2) obj1 = (0, 1, 2, 3, True) obj2 = (4, 5, 6, 7, False) replay.add(*obj1) assert replay.sample( 1) == obj2sampled(obj1), "If there's just one object in buffer, it must be retrieved by buf.sample(1)" replay.add(*obj2) assert len(replay) == 2, "Please make sure __len__ methods works as intended." replay.add(*obj2) assert len(replay) == 2, "When buffer is at max capacity, replace objects instead of adding new ones." assert tuple(np.unique(a) for a in replay.sample(100)) == obj2sampled(obj2) replay.add(*obj1) assert max(len(np.unique(a)) for a in replay.sample(100)) == 2 replay.add(*obj1) assert tuple(np.unique(a) for a in replay.sample(100)) == obj2sampled(obj1) print("Success!") ``` Now let's use this buffer to improve training: ``` import gym from qlearning import QLearningAgent env = gym.make("Taxi-v3") n_actions = env.action_space.n def play_and_train_with_replay(env, agent, replay=None, t_max=10**4, replay_batch_size=32): """ This function should - run a full game, actions given by agent.getAction(s) - train agent using agent.update(...) whenever possible - return total reward :param replay: ReplayBuffer where agent can store and sample (s,a,r,s',done) tuples. If None, do not use experience replay """ total_reward = 0.0 s = env.reset() for t in range(t_max): # get agent to pick action given state s a = <YOUR CODE > next_s, r, done, _ = env.step(a) # update agent on current transition. Use agent.update <YOUR CODE > if replay is not None: # store current <s,a,r,s'> transition in buffer <YOUR CODE > # sample replay_batch_size random transitions from replay, # then update agent on each of them in a loop s_, a_, r_, next_s_, done_ = replay.sample(replay_batch_size) for i in range(replay_batch_size): <YOUR CODE > s = next_s total_reward += r if done: break return total_reward # Create two agents: first will use experience replay, second will not. agent_baseline = QLearningAgent(alpha=0.5, epsilon=0.25, discount=0.99, get_legal_actions=lambda s: range(n_actions)) agent_replay = QLearningAgent(alpha=0.5, epsilon=0.25, discount=0.99, get_legal_actions=lambda s: range(n_actions)) replay = ReplayBuffer(1000) from IPython.display import clear_output rewards_replay, rewards_baseline = [], [] for i in range(1000): rewards_replay.append( play_and_train_with_replay(env, agent_replay, replay)) rewards_baseline.append(play_and_train_with_replay( env, agent_baseline, replay=None)) agent_replay.epsilon *= 0.99 agent_baseline.epsilon *= 0.99 if i % 100 == 0: clear_output(True) print('Baseline : eps =', agent_replay.epsilon, 'mean reward =', np.mean(rewards_baseline[-10:])) print('ExpReplay: eps =', agent_baseline.epsilon, 'mean reward =', np.mean(rewards_replay[-10:])) plt.plot(moving_average(rewards_replay), label='exp. replay') plt.plot(moving_average(rewards_baseline), label='baseline') plt.grid() plt.legend() plt.show() ``` #### What to expect: Experience replay, if implemented correctly, will improve algorithm's initial convergence a lot, but it shouldn't affect the final performance. ### Outro We will use the code you just wrote extensively in the next week of our course. If you're feeling that you need more examples to understand how experience replay works, try using it for binarized state spaces (CartPole or other __[classic control envs](https://gym.openai.com/envs/#classic_control)__). However, __the code you've written__ for this assignment is already capable of solving many RL problems, and as an added benifit – it is very easy to detach. You can use Q-learning, SARSA and Experience Replay for any RL problems you want to solve – just thow 'em into a file and import the stuff you need.
github_jupyter
``` #default_exp optimization.gradientgrouplasso #export #loosely inspired by the pyglmnet package from einops import rearrange #import autograd.numpy as np import numpy as np class GradientGroupLasso: def __init__(self, dg_M, df_M, reg_l1s, reg_l2, max_iter,learning_rate, tol, beta0_npm= None): n = dg_M.shape[0] d= dg_M.shape[1] m = df_M.shape[2] p = dg_M.shape[2] dummy_beta = np.ones((n,p,m)) self.dg_M = dg_M self.df_M = df_M self.reg_l1s = reg_l1s self.reg_l2 = reg_l2 self.beta0_npm = beta0_npm self.n = n self.p = p self.m = m self.d = d self.dummy_beta = dummy_beta #self.group = np.asarray(group) self.max_iter = max_iter self.learning_rate = learning_rate self.tol = tol self.Tau = None self.alpha = 1. self.lossresults = {} self.dls = {} self.l2loss = {} self.penalty = {} def _prox(self,beta_npm, thresh): """Proximal operator.""" p = self.p result = np.zeros(beta_npm.shape) result = np.asarray(result, dtype = float) for j in range(p): if np.linalg.norm(beta_npm[:,j,:]) > 0.: potentialoutput = beta_npm[:,j,:] - (thresh / np.linalg.norm(beta_npm[:,j,:])) * beta_npm[:,j,:] posind = np.asarray(np.where(beta_npm[:,j,:] > 0.)) negind = np.asarray(np.where(beta_npm[:,j,:] < 0.)) po = beta_npm[:,j,:].copy() po[posind[0],posind[1]] = np.asarray(np.clip(potentialoutput[posind[0],posind[1]],a_min = 0., a_max = 1e15), dtype = float) po[negind[0],negind[1]] = np.asarray(np.clip(potentialoutput[negind[0],negind[1]],a_min = -1e15, a_max = 0.), dtype = float) result[:,j,:] = po return result def _grad_L2loss(self, beta_npm): df_M = self.df_M dg_M = self.dg_M reg_l2 = self.reg_l2 dummy_beta = self.dummy_beta df_M_hat = np.einsum('ndp,npm->ndm',dg_M, beta_npm) error = df_M_hat - df_M grad_beta = np.einsum('ndm,ndp->npm',error,dg_M) #+ reg_l2 * np.ones() #if return grad_beta def _L1penalty(self, beta_npm): p = self.p m = self.m n = self.n beta_mn_p = rearrange(beta_npm, 'n p m -> (m n) p')#np.reshape(beta_mnp, ((m*n,p))) L1penalty = np.linalg.norm(beta_mn_p, axis = 0).sum() return L1penalty def _loss(self,beta_npm, reg_lambda): """Define the objective function for elastic net.""" L = self._logL(beta_npm) P = self._L1penalty(beta_npm) J = -L + reg_lambda * P return J def _logL(self,beta_npm): df_M = self.df_M dg_M = self.dg_M df_M_hat = np.einsum('ndp,npm -> ndm',dg_M, beta_npm) logL = -0.5 * np.linalg.norm((df_M - df_M_hat))**2 return(logL) def _L2loss(self,beta_npm): output = -self._logL(beta_npm) return(output) def fhatlambda(self,learning_rate,beta_npm_new,beta_npm_old): #print('lr',learning_rate) output = self._L2loss(beta_npm_old) + np.einsum('npm,npm', self._grad_L2loss(beta_npm_old),(beta_npm_new-beta_npm_old)) + (1/(2*learning_rate)) * np.linalg.norm(beta_npm_new-beta_npm_old)**2 return(output) def _btalgorithm(self,beta_npm ,learning_rate,b,maxiter_bt,rl): grad_beta = self._grad_L2loss(beta_npm = beta_npm) for i in range(maxiter_bt): beta_npm_postgrad = beta_npm - learning_rate * grad_beta beta_npm_postgrad_postprox = self._prox(beta_npm_postgrad, learning_rate * rl) fz = self._L2loss(beta_npm_postgrad_postprox) #fhatz = self.fhatlambda(lam,beta_npm_postgrad_postprox, beta_npm_postgrad) fhatz = self.fhatlambda(learning_rate,beta_npm_postgrad_postprox, beta_npm) if fz <= fhatz: #print(i) break learning_rate = b*learning_rate return(beta_npm_postgrad_postprox,learning_rate) def fit(self, beta0_npm = None): reg_l1s = self.reg_l1s n = self.n m = self.m p = self.p dg_M = self.dg_M df_M = self.df_M tol = self.tol np.random.RandomState(0) if beta0_npm is None: beta_npm_hat = 1 / (n*m*p) * np.random.normal(0.0, 1.0, [n, p,m]) #1 / (n_features) * np.random.normal(0.0, 1.0, [n_features, n_classes]) else: beta_npm_hat = beta0_npm fit_params = list() for l, rl in enumerate(reg_l1s): fit_params.append({'beta': beta_npm_hat}) if l == 0: fit_params[-1]['beta'] = beta_npm_hat else: fit_params[-1]['beta'] = fit_params[-2]['beta'] alpha = 1. beta_npm_hat = fit_params[-1]['beta'] #g = np.zeros([n_features, n_classes]) L, DL ,L2,PEN = list(), list() , list(), list() learning_rate = self.learning_rate beta_npm_hat_1 = beta_npm_hat.copy() beta_npm_hat_2 = beta_npm_hat.copy() for t in range(0, self.max_iter): #print(t,l,rl) #print(t) L.append(self._loss(beta_npm_hat, rl)) L2.append(self._L2loss(beta_npm_hat)) PEN.append(self._L1penalty(beta_npm_hat)) w = (t / (t+ 3)) beta_npm_hat_momentumguess = beta_npm_hat + w*(beta_npm_hat_1 - beta_npm_hat_2) beta_npm_hat , learning_rate = self._btalgorithm(beta_npm_hat_momentumguess,learning_rate,.5,1000, rl) #print(beta_npm_hat_momentumguess.max(), beta_npm_hat.max(),self._L2loss(beta_npm_hat), learning_rate) beta_npm_hat_2 = beta_npm_hat_1.copy() beta_npm_hat_1 = beta_npm_hat.copy() if t > 1: DL.append(L[-1] - L[-2]) if np.abs(DL[-1] / L[-1]) < tol: print('converged', rl) msg = ('\tConverged. Loss function:' ' {0:.2f}').format(L[-1]) msg = ('\tdL/L: {0:.6f}\n'.format(DL[-1] / L[-1])) break fit_params[-1]['beta'] = beta_npm_hat self.lossresults[rl] = L self.l2loss[rl] = L2 self.penalty[rl] = PEN self.dls[rl] = DL self.fit_ = fit_params #self.ynull_ = np.mean(y) return self def get_sr_lambda_parallel(df_M, dg_M, gl_itermax,reg_l2, max_search, card, tol,learning_rate): print('initializing lambda search') highprobes = np.asarray([]) lowprobes = np.asarray([]) #lambdas_start = np.asarray([0,1]) ul = np.linalg.norm(np.einsum('n d m, n d p -> n p m ', df_M, dg_M),axis=tuple([0, 2])).max() probe_init_low = 0. probe_init_high = ul coeffs = {} combined_norms = {} GGL = GradientGroupLasso(dg_M, df_M, np.asarray([probe_init_low]), reg_l2, gl_itermax,learning_rate, tol, beta0_npm= None) GGL.fit() beta0_npm = GGL.fit_[-1]['beta'] coeffs[probe_init_low] = GGL.fit_[-1]['beta'] combined_norms[probe_init_low] = np.sqrt((np.linalg.norm(coeffs[probe_init_low], axis = 0)**2).sum(axis = 1)) GGL = GradientGroupLasso(dg_M, df_M, np.asarray([probe_init_high]), reg_l2, gl_itermax,learning_rate, tol, beta0_npm= beta0_npm) GGL.fit(beta0_npm = beta0_npm) coeffs[probe_init_high] = GGL.fit_[-1]['beta'] combined_norms[probe_init_high] = np.sqrt((np.linalg.norm(coeffs[probe_init_high], axis = 0)**2).sum(axis = 1)) n_comp = len(np.where(~np.isclose(combined_norms[probe_init_high],0.,1e-12))[0]) lowprobes = np.append(lowprobes, probe_init_low) if n_comp == card: #high_int = probe print('Selected functions',np.where(~np.isclose(combined_norms[probe_init_high],0.,1e-12))[0]) return (probe_init_high, coeffs, combined_norms) if n_comp < card: highprobes = np.append(highprobes, probe_init_high) probe = (lowprobes.max() + highprobes.min()) / 2 if n_comp > card: lowprobes = np.append(lowprobes, probe_init_high) probe = lowprobes.max() * 2 for i in range(max_search): print(i, probe, 'probe') beta0_npm = coeffs[lowprobes.max()] if not np.isin(probe, list(combined_norms.keys())): #print('probe',probe) GGL = GradientGroupLasso(dg_M, df_M, np.asarray([probe]), reg_l2, gl_itermax,learning_rate, tol, beta0_npm = beta0_npm) GGL.fit(beta0_npm = beta0_npm) coeffs[probe] = GGL.fit_[-1]['beta'] combined_norms[probe] = np.sqrt((np.linalg.norm(coeffs[probe], axis = 0)**2).sum(axis = 1)) #np.where(~np.isclose(np.linalg.norm(np.linalg.norm(GGL.fit_[-1]['beta'], axis=2), axis=0) ,0., 1e-16))[0] #n_comp = len(np.where(combined_norms[probe] != 0)[0]) n_comp = len(np.where(~np.isclose(combined_norms[probe],0.,1e-12))[0]) if n_comp == card: #high_int = probe print('Selected functions',np.where(~np.isclose(combined_norms[probe],0.,1e-12))[0]) return(probe, coeffs, combined_norms) else: if n_comp < card: highprobes = np.append(highprobes, probe) if n_comp > card: lowprobes = np.append(lowprobes, probe) if len(highprobes) > 0: probe = (lowprobes.max() + highprobes.min()) / 2 else: probe = lowprobes.max() * 2 if i == max_search - 1: print('Failed to select d functions') return(probe, coeffs, combined_norms) def batch_stream(replicates): reps = np.asarray(list(replicates.keys())) nreps= len(reps) for r in range(nreps): yield(replicates[r]) ```
github_jupyter
``` ############## PLEASE RUN THIS CELL FIRST! ################### # import everything and define a test runner function from importlib import reload from helper import run import ecc, helper # Addition/Subtraction example print((11 + 6) % 19) print((17 - 6) % 19) print((8 + 14) % 19) print((4 - 12) % 19) ``` ### Exercise 1 Solve these equations in \\(F_{31}\\): * \\(2+15=?\\) * \\(17+21=?\\) * \\(29-4=?\\) * \\(15-30=?\\) Remember the % operator does the actual modulo operation. Also remember that `+` and `-` need to be in `()` because in the order of operations `%` comes before `+` and `-`. ``` # Exercise 1 # remember that % is the modulo operator prime = 31 # 2+15=? print((2+15) % prime) # 17+21=? print((17+21) % prime) # 29-4=? print((29-4) % prime) # 15-30=? print((15-30) % prime) ``` ### Exercise 2 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:FieldElementTest:test_add` ``` # Exercise 2 reload(ecc) run(ecc.FieldElementTest('test_add')) ``` ### Exercise 3 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:FieldElementTest:test_sub` ``` # Exercise 3 reload(ecc) run(ecc.FieldElementTest('test_sub')) # Multiplication/Exponentiation Example print(2 * 4 % 19) print(7 * 3 % 19) print(11 ** 3 % 19) print(pow(11, 3, 19)) ``` ### Exercise 4 Solve these equations in \\(F_{31}\\): * \\(24\cdot19=?\\) * \\(17^3=?\\) * \\(5^5\cdot18=?\\) ``` # Exercise 4 # remember that ** is the exponentiation operator prime = 31 # 24*19=? print(24*19 % prime) # 17^3=? print(17**3 % prime) # 5^5*18=? print(5**5*18 % prime) ``` ### Exercise 5 Write a program to calculate \\(0\cdot k, 1\cdot k, 2\cdot k, 3\cdot k, ... 30\cdot k\\) for some \\(k\\) in \\(F_{31}\\). Notice anything about these sets? ``` # Exercise 5 from random import randint prime = 31 k = randint(1,prime) # use range(prime) to iterate over all numbers from 0 to 30 inclusive print(sorted([i*k % prime for i in range(prime)])) ``` ### Exercise 6 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:FieldElementTest:test_mul` ``` # Exercise 6 reload(ecc) run(ecc.FieldElementTest('test_mul')) ``` ### Exercise 7 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:FieldElementTest:test_pow` ``` # Exercise 7 reload(ecc) run(ecc.FieldElementTest('test_pow')) ``` ### Exercise 8 #### BONUS QUESTION, ONLY ATTEMPT IF YOU HAVE TIME Write a program to calculate \\(i^{30}\\) for all i in \\(F_{31}\\). Notice anything? ``` # Exercise 8 # Bonus prime = 31 # use range(1, prime) to iterate over all numbers from 1 to 30 inclusive print([i**30 % prime for i in range(1, prime)]) # Division Example print(2 * 3**17 % 19) print(2 * pow(3, 17, 19) % 19) print(3 * 15**17 % 19) print(3 * pow(15, -1, 19) % 19) ``` ### Exercise 9 Solve these equations in \\(F_{31}\\): * \\(3/24 = ?\\) * \\(17^{-3} = ?\\) * \\(4^{-4}\cdot{11} = ?\\) ``` # Exercise 9 # remember pow(x, p-2, p) is the same as 1/x in F_p prime = 31 # 3/24 = ? print(3*24**(prime-2) % prime) # 17^(-3) = ? print(pow(17, prime-4, prime)) # 4^(-4)*11 = ? print(pow(4, prime-5, prime) * 11 % prime) ``` ### Exercise 10 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:FieldElementTest:test_div` ``` # Exercise 10 reload(ecc) run(ecc.FieldElementTest('test_div')) # Elliptic Curve Example x, y = -1, -1 print(y**2 == x**3 + 5*x + 7) ``` ### Exercise 11 For the curve \\(y^2 = x^3 + 5x + 7\\), which of these points are on the curve? \\((-2,4), (3,7), (18,77)\\) ``` # Exercise 11 # (-2,4), (3,7), (18,77) # equation in python is: y**2 == x**3 + 5*x + 7 points = ((-2,4), (3,7), (18,77)) for x, y in points: # determine whether (x,y) is on the curve if y**2 == x**3 + 5*x + 7: print(f'({x},{y}) is on the curve') else: print(f'({x},{y}) is not on the curve') ``` ### Exercise 12 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:PointTest:test_on_curve` ``` # Exercise 12 reload(ecc) run(ecc.PointTest('test_on_curve')) ``` ### Exercise 13 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:PointTest:test_add0` ``` # Exercise 13 reload(ecc) run(ecc.PointTest('test_add0')) # Point Addition where x1 != x2 Example x1, y1 = (2, 5) x2, y2 = (3, 7) s = (y2-y1)/(x2-x1) x3 = s**2 - x2 - x1 y3 = s*(x1-x3)-y1 print(x3, y3) ``` ### Exercise 14 For the curve \\(y^2 = x^3 + 5x + 7\\), what is \\((2,5) + (-1,-1)\\)? ``` # Exercise 14 x1, y1 = (2,5) x2, y2 = (-1,-1) # formula in python: # s = (y2-y1)/(x2-x1) s = (y2-y1)/(x2-x1) # x3 = s**2 - x2 - x1 x3 = s**2 - x2 - x1 # y3 = s*(x1-x3)-y1 y3 = s*(x1-x3) - y1 # print the coordinates print(x3, y3) ``` ### Exercise 15 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:PointTest:test_add1` ``` # Exercise 15 reload(ecc) run(ecc.PointTest('test_add1')) # Point Addition where x1 = x2 Example a = 5 x1, y1 = (2, 5) s = (3*x1**2+a)/(2*y1) x3 = s**2 - 2*x1 y3 = s*(x1-x3) - y1 print(x3, y3) ``` ### Exercise 16 For the curve \\(y^2 = x^3 + 5x + 7\\), what is \\((-1,1) + (-1,1)\\)? ``` # Exercise 16 a, b = 5, 7 x1, y1 = -1, -1 # formula in python # s = (3*x1**2+a)/(2*y1) s = (3*x1**2+a)/(2*y1) # x3 = s**2 - 2*x1 x3 = s**2 - 2*x1 # y3 = s*(x1-x3) - y1 y3 = s*(x1-x3) - y1 # print the coordinates print(x3, y3) ``` ### Exercise 17 #### Make [this test](/edit/session1/ecc.py) pass: `ecc.py:PointTest:test_add2` ``` # Exercise 17 reload(ecc) run(ecc.PointTest('test_add2')) ```
github_jupyter
# Multiclass logistic regression from scratch If you've made it through our tutorials on linear regression from scratch, then you're past the hardest part. You already know how to load and manipulate data, build computation graphs on the fly, and take derivatives. You also know how to define a loss function, construct a model, and write your own optimizer. Nearly all neural networks that we'll build in the real world consist of these same fundamental parts. The main differences will be the type and scale of the data and the complexity of the models. And every year or two, a new hipster optimizer comes around, but at their core they're all subtle variations of stochastic gradient descent. In [the previous chapter](logistic-regressio-gluon.ipynb), we introduced logistic regression, a classic algorithm for performing binary classification. We implemented a model $$\hat{y} = \sigma( \boldsymbol{x} \boldsymbol{w}^T + b)$$ where $\sigma$ is the sigmoid squashing function. This activation function on the final layer was crucial because it forced our outputs to take values in the range [0,1]. That allowed us to interpret these outputs as probabilties. We then updated our parameters to give the true labels (which take values either 1 or 0) the highest probability. In that tutorial, we looked at predicting whether or not an individual's income exceeded $50k based on features available in 1994 census data. Binary classification is quite useful. We can use it to predict spam vs. not spam or cancer vs not cancer. But not every problem fits the mold of binary classification. Sometimes we encounter a problem where each example could belong to one of $k$ classes. For example, a photograph might depict a cat or a dog or a zebra or ... (you get the point). Given $k$ classes, the most naive way to solve a *multiclass classification* problem is to train $k$ different binary classifiers $f_i(\boldsymbol{x})$. We could then predict that an example $\boldsymbol{x}$ belongs to the class $i$ for which the probability that the label applies is highest: $$\max_i {f_i(\boldsymbol{x})}$$ There's a smarter way to go about this. We could force the output layer to be a discrete probability distribution over the $k$ classes. To be a valid probability distribution, we'll want the output $\hat{y}$ to (i) contain only non-negative values, and (ii) sum to 1. We accomplish this by using the *softmax* function. Given an input vector $z$, softmax does two things. First, it exponentiates (elementwise) $e^{z}$, forcing all values to be strictly positive. Then it normalizes so that all values sum to $1$. Following the softmax operation computes the following $$\text{softmax}(\boldsymbol{z}) = \frac{e^{\boldsymbol{z}} }{\sum_{i=1}^k e^{z_i}}$$ Because now we have $k$ outputs and not $1$ we'll need weights connecting each of our inputs to each of our outputs. Graphically, the network looks something like this: ![](https://github.com/zackchase/mxnet-the-straight-dope/blob/master/img/simple-softmax-net.png?raw=true) We can represent these weights one for each input node, output node pair in a matrix $W$. We generate the linear mapping from inputs to outputs via a matrix-vector product $\boldsymbol{x} W + \boldsymbol{b}$. Note that the bias term is now a vector, with one component for each output node. The whole model, including the activation function can be written: $$\hat{y} = \text{softmax}(\boldsymbol{x} W + \boldsymbol{b})$$ This model is sometimes called *multiclass logistic regression*. Other common names for it include *softmax regression* and *multinomial regression*. For these concepts to sink in, let's actually implement softmax regression, and pick a slightly more interesting dataset this time. We're going to classify images of handwritten digits like these: ![png](https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/example/mnist.png) ## About batch training In the above, we used plain lowercase letters for scalar variables, bolded lowercase letters for **row** vectors, and uppercase letters for matrices. Assume we have $d$ inputs and $k$ outputs. Let's note the shapes of the various variables explicitly as follows: $$\underset{1 \times k}{\boldsymbol z} = \underset{1 \times d}{\boldsymbol{x}}\ \underset{d \times k}{W} + \underset{1 \times k}{\boldsymbol{b}}$$ Often we would one-hot encode the output label, for example $\hat y = 5$ would be $\boldsymbol {\hat y}_{one-hot} = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]$ when one-hot encoded for a 10-class classfication problem. So $\hat{y} = \text{softmax}(\boldsymbol z)$ becomes $$\underset{1 \times k}{\boldsymbol{\hat{y}}_{one-hot}} = \text{softmax}_{one-hot}(\underset{1 \times k}{\boldsymbol z})$$ When we input a batch of $m$ training examples, we would have matrix $\underset{m \times d}{X}$ that is the vertical stacking of individual training examples $\boldsymbol x_i$, due to the choice of using row vectors. $$ X= \begin{bmatrix} \boldsymbol x_1 \\ \boldsymbol x_2 \\ \vdots \\ \boldsymbol x_m \end{bmatrix} = \begin{bmatrix} x_{11} & x_{12} & x_{13} & \dots & x_{1d} \\ x_{21} & x_{22} & x_{23} & \dots & x_{2d} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ x_{m1} & x_{m2} & x_{m3} & \dots & x_{md} \end{bmatrix}$$ Under this batch training situation, ${\boldsymbol{\hat{y}}_{one-hot}} = \text{softmax}({\boldsymbol z})$ turns into $$Y = \text{softmax}(Z) = \text{softmax}(XW + B)$$ where matrix $\underset{m \times k}{B}$ is formed by having $m$ copies of $\boldsymbol b$ as follows $$ B = \begin{bmatrix} \boldsymbol b \\ \boldsymbol b \\ \vdots \\ \boldsymbol b \end{bmatrix} = \begin{bmatrix} b_{1} & b_{2} & b_{3} & \dots & b_{k} \\ b_{1} & b_{2} & b_{3} & \dots & b_{k} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ b_{1} & b_{2} & b_{3} & \dots & b_{k} \end{bmatrix}$$ In actual implementation we can often get away with using $\boldsymbol b$ directly instead of $B$ in the equation for $Z$ above, due to [broadcasting](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html). Each row of matrix $\underset{m \times k}{Z}$ corresponds to one training example. The softmax function operates on each row of matrix $Z$ and returns a matrix $\underset{m \times k}Y$, each row of which corresponds to the one-hot encoded prediction of one training example. ## Imports To start, let's import the usual libraries. ``` from __future__ import print_function import numpy as np import mxnet as mx from mxnet import nd, autograd, gluon mx.random.seed(1) ``` ## Set Context We'll also want to set the compute context where our data will typically live and where we'll be doing our modeling. Feel free to go ahead and change `model_ctx` to `mx.gpu(0)` if you're running on an appropriately endowed machine. ``` data_ctx = mx.cpu() model_ctx = mx.cpu() # model_ctx = mx.gpu() ``` ## The MNIST dataset This time we're going to work with real data, each a 28 by 28 centrally cropped black & white photograph of a handwritten digit. Our task will be come up with a model that can associate each image with the digit (0-9) that it depicts. To start, we'll use MXNet's utility for grabbing a copy of this dataset. The datasets accept a transform callback that can preprocess each item. Here we cast data and label to floats and normalize data to range [0, 1]: ``` def transform(data, label): return data.astype(np.float32)/255, label.astype(np.float32) mnist_train = gluon.data.vision.MNIST(train=True, transform=transform) mnist_test = gluon.data.vision.MNIST(train=False, transform=transform) ``` There are two parts of the dataset for training and testing. Each part has N items and each item is a tuple of an image and a label: ``` image, label = mnist_train[0] print(image.shape, label) ``` Note that each image has been formatted as a 3-tuple (height, width, channel). For color images, the channel would have 3 dimensions (red, green and blue). ## Record the data and label shapes Generally, we don't want our model code to care too much about the exact shape of our input data. This way we could switch in a different dataset without changing the code that follows. Let's define variables to hold the number of inputs and outputs. ``` num_inputs = 784 num_outputs = 10 num_examples = 60000 ``` Machine learning libraries generally expect to find images in (batch, channel, height, width) format. However, most libraries for visualization prefer (height, width, channel). Let's transpose our image into the expected shape. In this case, matplotlib expects either (height, width) or (height, width, channel) with RGB channels, so let's broadcast our single channel to 3. ``` im = mx.nd.tile(image, (1,1,3)) print(im.shape) ``` Now we can visualize our image and make sure that our data and labels line up. ``` import matplotlib.pyplot as plt plt.imshow(im.asnumpy()) plt.show() ``` Ok, that's a beautiful five. ## Load the data iterator Now let's load these images into a data iterator so we don't have to do the heavy lifting. ``` batch_size = 64 train_data = mx.gluon.data.DataLoader(mnist_train, batch_size, shuffle=True) ``` We're also going to want to load up an iterator with *test* data. After we train on the training dataset we're going to want to test our model on the test data. Otherwise, for all we know, our model could be doing something stupid (or treacherous?) like memorizing the training examples and regurgitating the labels on command. ``` test_data = mx.gluon.data.DataLoader(mnist_test, batch_size, shuffle=False) ``` ## Allocate model parameters Now we're going to define our model. For this example, we're going to ignore the multimodal structure of our data and just flatten each image into a single 1D vector with 28x28 = 784 components. Because our task is multiclass classification, we want to assign a probability to each of the classes $P(Y = c \mid X)$ given the input $X$. In order to do this we're going to need one vector of 784 weights for each class, connecting each feature to the corresponding output. Because there are 10 classes, we can collect these weights together in a 784 by 10 matrix. We'll also want to allocate one offset for each of the outputs. We call these offsets the *bias term* and collect them in the 10-dimensional array ``b``. ``` W = nd.random_normal(shape=(num_inputs, num_outputs),ctx=model_ctx) b = nd.random_normal(shape=num_outputs,ctx=model_ctx) params = [W, b] ``` As before, we need to let MXNet know that we'll be expecting gradients corresponding to each of these parameters during training. ``` for param in params: param.attach_grad() ``` ## Multiclass logistic regression In the linear regression tutorial, we performed regression, so we had just one output $\hat{y}$ and tried to push this value as close as possible to the true target $y$. Here, instead of regression, we are performing *classification*, where we want to assign each input $X$ to one of $L$ classes. The basic modeling idea is that we're going to linearly map our input $X$ onto 10 different real valued outputs ``y_linear``. Then, before outputting these values, we'll want to normalize them so that they are non-negative and sum to 1. This normalization allows us to interpret the output $\hat{y}$ as a valid probability distribution. ``` def softmax(y_linear): exp = nd.exp(y_linear-nd.max(y_linear, axis=1).reshape((-1,1))) norms = nd.sum(exp, axis=1).reshape((-1,1)) return exp / norms sample_y_linear = nd.random_normal(shape=(2,10)) sample_yhat = softmax(sample_y_linear) print(sample_yhat) ``` Let's confirm that indeed all of our rows sum to 1. ``` print(nd.sum(sample_yhat, axis=1)) ``` But for small rounding errors, the function works as expected. ## Define the model Now we're ready to define our model ``` def net(X): y_linear = nd.dot(X, W) + b yhat = softmax(y_linear) return yhat ``` ## The cross-entropy loss function Before we can start training, we're going to need to define a loss function that makes sense when our prediction is a probability distribution. The relevant loss function here is called cross-entropy and it may be the most common loss function you'll find in all of deep learning. That's because at the moment, classification problems tend to be far more abundant than regression problems. The basic idea is that we're going to take a target Y that has been formatted as a one-hot vector, meaning one value corresponding to the correct label is set to 1 and the others are set to 0, e.g. ``[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]``. The basic idea of cross-entropy loss is that we only care about how much probability the prediction assigned to the correct label. In other words, for true label 2, we only care about the component of yhat corresponding to 2. Cross-entropy attempts to maximize the log-likelihood given to the correct labels. ``` def cross_entropy(yhat, y): return - nd.sum(y * nd.log(yhat+1e-6)) ``` ## Optimizer For this example we'll be using the same stochastic gradient descent (SGD) optimizer as last time. ``` def SGD(params, lr): for param in params: param[:] = param - lr * param.grad ``` ## Write evaluation loop to calculate accuracy While cross-entropy is nice, differentiable loss function, it's not the way humans usually evaluate performance on multiple choice tasks. More commonly we look at accuracy, the number of correct answers divided by the total number of questions. Let's write an evaluation loop that will take a data iterator and a network, returning the model's accuracy averaged over the entire dataset. ``` def evaluate_accuracy(data_iterator, net): numerator = 0. denominator = 0. for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(model_ctx).reshape((-1,784)) label = label.as_in_context(model_ctx) label_one_hot = nd.one_hot(label, 10) output = net(data) predictions = nd.argmax(output, axis=1) numerator += nd.sum(predictions == label) denominator += data.shape[0] return (numerator / denominator).asscalar() ``` Because we initialized our model randomly, and because roughly one tenth of all examples belong to each of the ten classes, we should have an accuracy in the ball park of .10. ``` evaluate_accuracy(test_data, net) ``` ## Execute training loop ``` epochs = 5 learning_rate = .005 for e in range(epochs): cumulative_loss = 0 for i, (data, label) in enumerate(train_data): data = data.as_in_context(model_ctx).reshape((-1,784)) label = label.as_in_context(model_ctx) label_one_hot = nd.one_hot(label, 10) with autograd.record(): output = net(data) loss = cross_entropy(output, label_one_hot) loss.backward() SGD(params, learning_rate) cumulative_loss += nd.sum(loss).asscalar() test_accuracy = evaluate_accuracy(test_data, net) train_accuracy = evaluate_accuracy(train_data, net) print("Epoch %s. Loss: %s, Train_acc %s, Test_acc %s" % (e, cumulative_loss/num_examples, train_accuracy, test_accuracy)) ``` ## Using the model for prediction Let's make it more intuitive by picking 10 random data points from the test set and use the trained model for predictions. ``` # Define the function to do prediction def model_predict(net,data): output = net(data) return nd.argmax(output, axis=1) # let's sample 10 random data points from the test set sample_data = mx.gluon.data.DataLoader(mnist_test, 10, shuffle=True) for i, (data, label) in enumerate(sample_data): data = data.as_in_context(model_ctx) print(data.shape) im = nd.transpose(data,(1,0,2,3)) im = nd.reshape(im,(28,10*28,1)) imtiles = nd.tile(im, (1,1,3)) plt.imshow(imtiles.asnumpy()) plt.show() pred=model_predict(net,data.reshape((-1,784))) print('model predictions are:', pred) break ``` ## Conclusion Jeepers. We can get nearly 90% accuracy at this task just by training a linear model for a few seconds! You might reasonably conclude that this problem is too easy to be taken seriously by experts. But until recently, many papers (Google Scholar says 13,800) were published using results obtained on this data. Even this year, I reviewed a paper whose primary achievement was an (imagined) improvement in performance. While MNIST can be a nice toy dataset for testing new ideas, we don't recommend writing papers with it. ## Next [Softmax regression with gluon](../chapter02_supervised-learning/softmax-regression-gluon.ipynb) For whinges or inquiries, [open an issue on GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)
github_jupyter
# Pokémon Image Embeddings Can you create image embeddings of Pokémon in order to compare them? Let's find out! ``` import requests import os from tqdm.auto import tqdm from imgbeddings import imgbeddings from PIL import Image import logging import numpy as np import pandas as pd logger = logging.getLogger() logger.setLevel(logging.INFO) ``` Here's a compact script [modified from my AI Generated Pokémon experiments](https://github.com/minimaxir/ai-generated-pokemon-rudalle/blob/master/build_image_dataset.py) to obtain the metadata of all the normal forms of Pokémon, and download the images of the official portraits to `pokemon_images` if not already present. (roughly 30MB total) ``` folder_name = "pokemon_images" size = 224 graphql_query = """ { pokemon_v2_pokemon(where: {id: {_lt: 10000}}, order_by: {id: asc}) { pokemon_v2_pokemontypes { pokemon_v2_type { name } } id name } } """ image_url = ( "https://raw.githubusercontent.com/PokeAPI/sprites/master/" "sprites/pokemon/other/official-artwork/{0}.png" ) r = requests.post( "https://beta.pokeapi.co/graphql/v1beta", json={ "query": graphql_query, }, ) pokemon = r.json()["data"]["pokemon_v2_pokemon"] def encode_pokemon(p): return { "id": p["id"], "name": p["name"].title(), "type_1": p["pokemon_v2_pokemontypes"][0]["pokemon_v2_type"]["name"].title(), } poke_dict = [encode_pokemon(p) for p in pokemon] if os.path.exists(folder_name): print(f"/{folder_name} already exists; skipping downloading images.") else: print(f"Saving Pokemon images to /{folder_name}.") os.makedirs(folder_name) for p in tqdm(pokemon): p_id = p["id"] img = Image.open(requests.get(image_url.format(p_id), stream=True).raw) img = img.resize((size, size), Image.ANTIALIAS) # https://stackoverflow.com/a/9459208 bg = Image.new("RGB", (size, size), (255, 255, 255)) bg.paste(img, mask=img.split()[3]) name = f"{p_id:04d}.png" bg.save(os.path.join(folder_name, name)) ibed = imgbeddings() ``` Now we can generate the 768D imgbeddings for all the Pokémon. ``` # get a list of all the Pokemon image filenames inputs = [os.path.join(folder_name, x) for x in os.listdir(folder_name)] inputs.sort() print(inputs[0:10]) embeddings = ibed.to_embeddings(inputs) embeddings.shape ``` Fit a PCA to the imgbeddings (for simplicity, we won't use any image augmentation as the Pokémon designs are already standardized), and generate the new embeddings. ``` ibed.pca_fit(embeddings, 128) embeddings_pca = ibed.pca_transform(embeddings) embeddings_pca.shape ``` The PCA is automatically saved as `pca.npz`; we can also save the embeddings as a separate `.npy` file and reload them for conveinence. ``` np.save("pokemon_embeddings_pca.npy", embeddings_pca) ``` # Pokémon Similarity Search Let's build a `faiss` index to see which Pokémon are closest to another by visual design! (you can install faiss via `pip3 install faiss-cpu`) This approach find the Pokémon most similar using [cosine similarity](https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances#how-can-i-index-vectors-for-cosine-similarity). First, load the embeddings and build the index. ``` import faiss from sklearn.preprocessing import normalize from IPython.display import HTML from io import BytesIO import base64 index = faiss.index_factory(embeddings_pca.shape[1], "Flat", faiss.METRIC_INNER_PRODUCT) index.add(normalize(embeddings_pca)) index.ntotal ``` Load a Pokémon embedding you already generated, then find the closest Pokémon! `faiss` will return the indices of the corresponding Pokemon. Let's start with Pikachu (id `25`), and find the 10 closest Pokemon and get their similarity. ``` search_id = 25 # faiss results are zero-indexed, so must -1 when searching, +1 after retrieving q_embedding = np.expand_dims(embeddings_pca[search_id - 1, :], 0) # the search will return the query itself, so search for +1 result distances, indices = index.search(normalize(q_embedding), 10 + 1) print(indices + 1) print(distances) # https://www.kaggle.com/code/stassl/displaying-inline-images-in-pandas-dataframe/notebook def get_thumbnail(path): i = Image.open(path) i.thumbnail((64, 64), Image.LANCZOS) return i def image_base64(im): if isinstance(im, str): im = get_thumbnail(im) with BytesIO() as buffer: im.save(buffer, 'jpeg') return base64.b64encode(buffer.getvalue()).decode() def image_formatter(im): return f'<img src="data:image/jpeg;base64,{image_base64(im)}">' def percent_formatter(perc): return f"{perc:.1%}" data = [] for i, idx in enumerate(indices[0]): data.append([idx + 1, poke_dict[idx]["name"], distances[0][i], get_thumbnail(inputs[idx])]) pd.set_option('display.max_colwidth', None) df = pd.DataFrame(data, columns=["ID", "Name", "Similarity", "Image"]) HTML(df.to_html(formatters={"Image": image_formatter, "Similarity": percent_formatter}, escape=False, index=False)) ``` To the eyes of an AI, similarity is not necessairly color; it can be shapes and curves as well. If you check other Pokémon by tweaking the `search_id` above, you'll notice that the similar images tend to have the [same stance and body features](https://twitter.com/minimaxir/status/1507166313281585164). You can use the cell below to run your own images though the index and see what Pokémon they are most similar to! ``` img_path = "/Users/maxwoolf/Downloads/shrek-facts.jpg" img_embedding = ibed.to_embeddings(img_path) distances, indices = index.search(normalize(img_embedding), 10) data = [["—", "Input Image", 1, get_thumbnail(img_path)]] for i, idx in enumerate(indices[0]): data.append([idx + 1, poke_dict[idx]["name"], distances[0][i], get_thumbnail(inputs[idx])]) pd.set_option('display.max_colwidth', None) df = pd.DataFrame(data, columns=["ID", "Name", "Similarity", "Image"]) HTML(df.to_html(formatters={"Image": image_formatter, "Similarity": percent_formatter}, escape=False, index=False)) ```
github_jupyter
# Introduction to Machine Learning (ML) This tutorial aims to get you familiar with the basis of ML. You will go through several tasks to build some basic regression and classification models. ``` #essential imports import sys sys.path.insert(1,'utils') import numpy as np import matplotlib.pyplot as plt # display plots in this notebook %matplotlib nbagg import pandas as pd import ml_utils print np.__version__ print np.__file__ ``` ## 1. Linear regression ### 1. 1. Univariate linear regression Let start with the most simple regression example. Firstly, read the data in a file named "house_price_statcrunch.xls". ``` house_data = pd.ExcelFile('data/house_price_statcrunch.xls').parse(0) ``` Let see what is inside by printing out the first few lines. ``` print " ".join([field.ljust(10) for field in house_data.keys()]) for i in xrange(10): print " ".join([str(house_data[field][i]).ljust(10) for field in house_data.keys()]) TOTALS = len(house_data['House']) print "...\n\nTotal number of samples: {}".format(TOTALS) ``` Let preserve some data for test. Here we extract 10% for testing. ``` np.random.seed(0) idx = np.random.permutation(TOTALS) idx_train = idx[:90] idx_test = idx[90:] house_data_train = {} house_data_test = {} for field in house_data.keys(): house_data_test[field] = house_data[field][idx_test] house_data_train[field] = house_data[field][idx_train] ``` For univariate regression, we are interested in the "size" parameter only. Let's extract necessary data and visualise it. ``` X, Z = ml_utils.extract_data(house_data, ['size'], ['price']) Z = Z/1000.0 #price has unit x1000 USD plt.plot(X[0],Z[0], '.') plt.xlabel('size (feet^2)') plt.ylabel('price (USD x1000)') plt.title('house data scatter plot') plt.show() ``` Our goal is to build a house price prediction model that will approximate the price of a house given its size. To do it, we need to fit a linear line (y = ax + b) to the data above using linear regression. Remember the procedure: 1. Define training set 2. Define hypothesis function. Here $F(x,W) = Wx$ 3. Loss function. Here $L(W) = \frac{1}{2N}{\sum_{i=1}^N{(F(x^{(i)},W)-z)^2}}$ 4. Update procedure (gradient descent). $W = W - k\frac{\partial L}{\partial W}$ To speed up computation, you should avoid using loop when working with scripting languges e.g. Python, Matlab. Try using array/matrix instead. Here you are provided code for step 1 and 2. Your will be asked to implement step 3 and 4. Some skeleton code will be provided for your convenience. ``` """step 1: define training and test set X, Z.""" X_train, Z_train = ml_utils.extract_data(house_data_train, ['size'], ['price']) X_test, Z_test = ml_utils.extract_data(house_data_test, ['size'], ['price']) Z_train = Z_train/1000.0 #price has unit x1000 USD Z_test = Z_test/1000.0 ##normalise data, uncomment for now #X_train, u, scale = ml_utils.normalise_data(X_train) #X_test = ml_utils.normalise_data(X_test, u, scale) N = Z_train.size #number of training samples ones_array = np.ones((1,N),dtype=np.float32) X_train = np.concatenate((X_train, ones_array), axis=0) #why? X_test = np.concatenate((X_test, np.ones((1, Z_test.size), dtype=np.float32)), axis = 0) #same for test data print "size of X_train ", X_train.shape print "size of Z_train ", Z_train.shape """step 2: define hypothesis function""" def F_Regression(X, W): """ Compute the hypothesis function y=F(x,W) in batch. input: X input array, must has size DxN (each column is one sample) W parameter array, must has size 1xD output: linear multiplication of W*X, size 1xN """ return np.dot(W,X) ``` **Task 1.1**: define the loss function for linear regression according to the following formula: $$L = \frac{1}{2N}{\sum_{i=1}^N{(y^{(i)}-z^{(i)})^2}}$$ Please fill in the skeleton code below. Hints: (i) in Python numpy the square operator $x^2$ is implemented as x**2; (ii) try to use matrix form and avoid for loop ``` """step 3: loss function""" def Loss_Regression(Y, Z): """ Compute the loss between the predicted (Y=F(X,W)) and the groundtruth (Z) values. input: Y predicted results Y = F(X,W) with given parameter W, has size 1xN Z groundtruth vector Z, has size 1xN output: loss value, is a scalar """ #enter the code here N = float(Z.size) diff = Y-Z return 1/(2*N)*np.dot(diff, diff.T).squeeze() ``` **Task 1.2**: compute gradient of the loss function w.r.t parameter W according to the following formula:<br> $$\frac{\partial L}{\partial W} = \frac{1}{N}\sum_{i=1}^N{(y^{(i)}-z^{(i)})x^{(i)}}$$ Please fill in the skeleton code below. ``` """step 4: gradient descent - compute gradient""" def dLdW_Regression(X, Y, Z): """ Compute gradient of the loss w.r.t parameter W. input: X input array, each column is one sample, has size DxN Y predicted values, has size 1xN Z groundtruth values, has size 1xN output: gradient, has same size as W """ #enter the code here N = float(Z.size) return 1/N * (Y-Z).dot(X.T) ``` Now we will perform gradient descent update procedure according to the following formula: $$W = W - k\frac{\partial L}{\partial W}$$ Here we use fixed number of iterations and learning rate. ``` """step 4: gradient descent - update loop""" np.random.seed(0) W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 1e-8 #learning rate niters = 160 #number of training iterations #visualisation settings vis_interval = niters/50 loss_collections = [] plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) axis_data = fig.add_subplot(132) for i in xrange(niters): Y_train = F_Regression(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Regression(Y_train, Z_train) #compute loss dLdW = dLdW_Regression(X_train, Y_train, Z_train) #compute gradient W = W - k*dLdW #update loss_collections.append(loss) if (i+1)% vis_interval == 0: ml_utils.plot_loss(axis_loss, range(i+1),loss_collections, "loss = " + str(loss)) ml_utils.plot_scatter_and_line(axis_data, X_train, Z_train, W, "iter #" + str(i)) fig.canvas.draw() print "Learned parameters ", W.squeeze() ``` Now evaluate your learned model using the test set. Measure the total error of your prediction ``` Y_test = F_Regression(X_test, W) error = Loss_Regression(Y_test, Z_test) print "Evaluation error: ", error ``` **Quiz**: you may notice the learning rate k is set to $10^{-8}$. Why is it too small? Try to play with several bigger values of k, you will soon find out that the training is extremely sensitive to the learning rate (the training easily diverges or even causes "overflow" error with large k).<br><br> Answer: It is because both the input (size of house) and output (price) have very large range of values, which result in very large gradient. **Task 1.3**: Test your learned model. Suppose you want to sell a house of size 3000 $feat^2$, how much do you expect your house will cost?<br> Answer: you should get around 260k USD for that house. ``` x = 3000 x = np.array([x,1])[...,None] #make sure feature vector has size 2xN, here N=1 print "Expected price: ", F_Regression(x,W).squeeze() ``` **Task 1.4**: The gradient descent in the code above terminates after 100 iterations. You may want it to terminate when improvement in the loss is below a threshold. $$\Delta L_t = |L_t - L_{t-1}| < \epsilon$$ Edit the code to terminate the loop when the loss improvement is below $\epsilon=10^{-2}$. Re-evaluate your model to see if its performance has improved. ``` """step 4: gradient descent - update loop""" W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 1e-8 #learning rate epsilon = 1e-2 #terminate condition #visualisation settings vis_interval = 10 loss_collections = [] prev_loss = 0 plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) axis_data = fig.add_subplot(132) while(1): Y_train = F_Regression(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Regression(Y_train, Z_train) #compute loss dLdW = dLdW_Regression(X_train, Y_train, Z_train) #compute gradient W = W - k*dLdW #update loss_collections.append(loss) if abs(loss - prev_loss) < epsilon: break prev_loss = loss if (len(loss_collections)+1) % vis_interval==0: #print "Iter #", len(loss_collections) ml_utils.plot_loss(axis_loss, range(len(loss_collections)),loss_collections, "loss = " + str(loss)) ml_utils.plot_scatter_and_line(axis_data, X_train, Z_train, W, "iter #" + str(len(loss_collections))) fig.canvas.draw() print "Learned parameters ", W.squeeze() print "Learning terminates after {} iterations".format(len(loss_collections)) #run the test Y_test = F_Regression(X_test, W) error = Loss_Regression(Y_test, Z_test) print "Evaluation error: ", error ``` Confirm that the error measurement on the test set has improved. ### 1.2 Multivariate regression So far we assume the house price is affected by the size only. Now let consider also other fields "Bedrooms", "Baths", "lot" (location) and "NW" (whether or not the houses face Nothern West direction).<br><br> **Important**: now your feature vector is multi-dimensional, it is crucial to normalise your training set for gradient descent to converge properly. The code below is almost identical to the previous step 1, except it loads more fields and implements data normalisation. ``` """step 1: define training set X, Z.""" selected_fields = ['size', 'Bedrooms', 'Baths', 'lot', 'NW'] X_train, Z_train = ml_utils.extract_data(house_data_train, selected_fields, ['price']) X_test, Z_test = ml_utils.extract_data(house_data_test, selected_fields, ['price']) Z_train = Z_train/1000.0 #price has unit x1000 USD Z_test = Z_test/1000.0 ##normalise X_train, u, scale = ml_utils.normalise_data(X_train) X_test = ml_utils.normalise_data(X_test, u, scale) N = Z_train.size #number of training samples ones_array = np.ones((1,N),dtype=np.float32) X_train = np.concatenate((X_train, ones_array), axis=0) #why? X_test = np.concatenate((X_test, np.ones((1, Z_test.size), dtype=np.float32)), axis = 0) #same for test data print "size of X_train ", X_train.shape print "size of Z_train ", Z_train.shape ``` Now run step 2-4 again. Note the followings: 1. You need not to modify the *Loss_Regression* and *dLdW_Regression* functions. They should generalise enough to work with multi-dimensional data 2. Since your training samples are normalised you can now use much higher learning rate e.g. k = 1e-2 3. Note that the plot function *plot_scatter_and_line* will not work in multivariate regression since it is designed for 1-D input only. Consider commenting it out.<br> **Question**: how many iterations are required to pass the threshold $\Delta L < 10^{-2}$ ?<br> Answer: ~4000 iterations (and it will take a while to complete). **Task 1.5**: (a) evaluate your learned model on the test set. (b) Suppose the house you want to sell has a size of 3000 $feet^2$, has 3 bedrooms, 2 baths, lot number 10000 and in NW direction. How much do you think its price would be? Hints: don't forget to normalise the test sample.<br> Answer: You will get ~150k USD only, much lower than the previous prediction based on size only. Your house has an advantage of size, but other parameters matter too. ``` """step 4: gradient descent - update loop""" """ same code but change k = 1e-2""" W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 1e-2 #learning rate epsilon = 1e-2 #terminate condition #visualisation settings vis_interval = 10 loss_collections = [] prev_loss = 0 plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) #axis_data = fig.add_subplot(132) while(1): Y_train = F_Regression(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Regression(Y_train, Z_train) #compute loss dLdW = dLdW_Regression(X_train, Y_train, Z_train) #compute gradient W = W - k*dLdW #update loss_collections.append(loss) if abs(loss - prev_loss) < epsilon: break prev_loss = loss if (len(loss_collections)+1) % vis_interval==0: #print "Iter #", len(loss_collections) ml_utils.plot_loss(axis_loss, range(len(loss_collections)),loss_collections, "loss = " + str(loss)) #ml_utils.plot_scatter_and_line(axis_data, X_train, Z_train, W, "iter #" + str(len(loss_collections))) fig.canvas.draw() print "Learned parameters ", W.squeeze() print "Learning terminates after {} iterations".format(len(loss_collections)) """apply on the test set""" Y_test = F_Regression(X_test, W) error = Loss_Regression(Y_test, Z_test) print "Evaluation error: ", error """test a single sample""" x = np.array([3000, 3,2, 10000, 1],dtype=np.float32)[...,None] x = ml_utils.normalise_data(x, u, scale) x = np.concatenate((x,np.ones((1,1))),axis=0) print "Price: ", F_Regression(x,W).squeeze() ``` ### 1.3 Gradient descent with momentum In the latest experiment, our training takes ~4000 iterations to converge. Now let try gradient descent with momentum to speed up the training. We will employ the following formula: $$v_t = m*v_{t-1} + k\frac{\partial L}{\partial W}$$ $$W = W - v_t$$ ``` """step 4: gradient descent with momentum - update loop""" W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 1e-2 #learning rate epsilon = 1e-2 #terminate condition m = 0.9 #momentum v = 0 #initial velocity #visualisation settings vis_interval = 10 loss_collections = [] prev_loss = 0 plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) #axis_data = fig.add_subplot(132) while(1): Y_train = F_Regression(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Regression(Y_train, Z_train) #compute loss dLdW = dLdW_Regression(X_train, Y_train, Z_train) #compute gradient v = v*m + k*dLdW W = W - v #update loss_collections.append(loss) if abs(loss - prev_loss) < epsilon: break prev_loss = loss if (len(loss_collections)+1) % vis_interval==0: #print "Iter #", len(loss_collections) ml_utils.plot_loss(axis_loss, range(len(loss_collections)),loss_collections, "loss = " + str(loss)) #ml_utils.plot_scatter_and_line(axis_data, X_train, Z_train, W, "iter #" + str(len(loss_collections))) fig.canvas.draw() print "Learned parameters ", W.squeeze() print "Learning terminates after {} iterations".format(len(loss_collections)) ``` ## 2. Classification In this part you will walk through different steps to implement several basic classification tasks. ### 2.1. Binary classification Imagine you were an USP professor who teaches Computer Science. This year there is 100 year-one students who want to register your module. You examine their performance based on their scores on two exams. You have gone through the records of 80 students and already made admission decisions for them. Now you want to build a model to automatically make admission decisions for the rest 20 students. Your training data will be the exam results and admission decisions for the 80 students that you have assessed.<br><br> Firstly, let load the data. ``` student_data = pd.read_csv('data/student_data_binary_clas.txt', header = None, names=['exam1', 'exam2', 'decision']) student_data #split train/test set X = np.array([student_data['exam1'], student_data['exam2']], dtype=np.float32) Z = np.array([student_data['decision']], dtype = np.float32) #assume the first 80 students have been assessed, use them as the training data X_train = X[:,:80] X_test = X[:,80:] #you later have to manually assess the rest 20 students according to the university policies. # Great, now you have a chance to evaluate your learned model Z_train = Z[:,:80] Z_test = Z[:,80:] #normalise data X_train, u, scale = ml_utils.normalise_data(X_train) X_test = ml_utils.normalise_data(X_test, u, scale) #concatenate array of "1s" to X array X_train = np.concatenate((X_train, np.ones_like(Z_train)), axis = 0) X_test = np.concatenate((X_test, np.ones_like(Z_test)), axis = 0) #let visualise the training set plt.close() plt.ion() fig = plt.figure(1) axis_data = fig.add_subplot(111) ml_utils.plot_scatter_with_label_2d(axis_data, X_train, Z_train,msg="student score scatter plot") ``` **Task 2.1**: your first task is to define the hypothesis function. Do you remember the hypothesis function in a binary classification task? It has form of a sigmoid function: $$F(x,W) = \frac{1}{1+e^{-Wx}}$$ ``` def F_Classification(X, W): """ Compute the hypothesis function given input array X and parameter W input: X input array, must has size DxN (each column is one sample) W parameter array, must has size 1xD output: sigmoid of W*X, size 1xN """ return 1/(1+np.exp(-np.dot(W,X))) ``` **Task 2.2**: define the loss function for binary classification. It is called "negative log loss": $$L(W) = -\frac{1}{N} \sum_{i=1}^N{[z^{(i)} log(F(x^{(i)},W)) + (1-z^{(i)})(log(1-F(x^{(i)},W))]}$$ Next, define the gradient function: $$\frac{\partial L}{\partial W} = \frac{1}{N}(F(X,W) - Z)X^T$$ ``` """step 3: loss function for classification""" def Loss_Classification(Y, Z): """ Compute the loss between the predicted (Y=F(X,W)) and the groundtruth (Z) values. input: Y predicted results Y = F(X,W) with given parameter W, has size 1xN Z groundtruth vector Z, has size 1xN output: loss value, is a scalar """ #enter the code here N = float(Z.size) return -1/N*(np.dot(np.log(Y), Z.T) + np.dot(np.log(1-Y), (1-Z).T)).squeeze() """step 4: gradient descent for classification - compute gradient""" def dLdW_Classification(X, Y, Z): """ Compute gradient of the loss w.r.t parameter W. input: X input array, each column is one sample, has size DxN Y probability of label = 1, has size 1xN Z groundtruth values, has size 1xN output: gradient, has same size as W """ #enter the code here N = float(Z.size) return 1/N * (Y-Z).dot(X.T) W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 0.2 #learning rate epsilon = 1e-6 #terminate condition m = 0.9 #momentum v = 0 #initial velocity #visualisation settings vis_interval = 10 loss_collections = [] prev_loss = 0 plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) axis_data = fig.add_subplot(132) while(1): Y_train = F_Classification(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Classification(Y_train, Z_train) #compute loss dLdW = dLdW_Classification(X_train, Y_train, Z_train) #compute gradient v = v*m + k*dLdW W = W - v #update loss_collections.append(loss) if abs(loss - prev_loss) < epsilon: break prev_loss = loss if (len(loss_collections)+1) % vis_interval==0: ml_utils.plot_loss(axis_loss, range(len(loss_collections)),loss_collections, "loss = " + str(loss)) ml_utils.plot_scatter_with_label_2d(axis_data, X_train, Z_train, W, "student score scatter plot") fig.canvas.draw() print "Learned parameters ", W.squeeze() print "Learning terminates after {} iterations".format(len(loss_collections)) #evaluate Y_test = F_Classification(X_test, W) predictions = Y_test > 0.5 accuracy = np.sum(predictions == Z_test)/float(Z_test.size) print "Test accuracy: ", accuracy ``` We achieve 90% accuracy (only two students have been misclassified). Not too bad, isn't it? **Task 2.3**: regularisation Now we want to add a regularisation term into the loss to prevent overfitting. Regularisation loss is simply magnitude of the parameter vector W after removing the last element (i.e. bias doesn't count to regularisation). $$L_R = \frac{1}{2}|W'|^2$$ where W' is W with the last element truncated.<br> Now the total loss would be: $$L(W) = -\frac{1}{N} \sum_{i=1}^N{[z^{(i)} log(F(x^{(i)},W)) + (1-z^{(i)})(log(1-F(x^{(i)},W))]} + \frac{1}{2}|W'|^2$$ The gradient become: $$\frac{\partial L}{\partial W} = \frac{1}{N}(F(X,W) - Z)X^T + W''$$ where W'' is W with the last element change to 0. Your task is to implement the loss and gradient function with added regularisation. ``` """step 3: loss function with regularisation""" def Loss_Classification_Reg(Y, Z, W): """ Compute the loss between the predicted (Y=F(X,W)) and the groundtruth (Z) values. input: Y predicted results Y = F(X,W) with given parameter W, has size 1xN Z groundtruth vector Z, has size 1xN W parameter vector, size 1xD output: loss value, is a scalar """ #enter the code here N = float(Z.size) W_ = W[:,:-1] return -1/N*(np.dot(np.log(Y), Z.T) + np.dot(np.log(1-Y), (1-Z).T)).squeeze() + 0.5*np.dot(W_,W_.T).squeeze() """step 4: gradient descent with regularisation - compute gradient""" def dLdW_Classification_Reg(X, Y, Z, W): """ Compute gradient of the loss w.r.t parameter W. input: X input array, each column is one sample, has size DxN Y probability of label = 1, has size 1xN Z groundtruth values, has size 1xN W parameter vector, size 1xD output: gradient, has same size as W """ #enter the code here N = float(Z.size) W_ = W W_[:,-1] = 0 return 1/N * (Y-Z).dot(X.T) + W_ ``` Rerun the update loop again with the new loss and gradient functions. Note you may need to change the learning rate accordingly to have proper convergence. Now you have implemented both regularisation and momentum techniques, you can use a standard learning rate value of 0.01 which is widely used in practice. ``` """ gradient descent with regularisation- parameter update loop""" W = np.random.rand(1,X_train.shape[0]).astype(np.float32) #W has size 1xD, randomly initialised k = 0.01 #learning rate epsilon = 1e-6 #terminate condition m = 0.9 #momentum v = 0 #initial velocity #visualisation settings vis_interval = 10 loss_collections = [] prev_loss = 0 plt.close() plt.ion() fig = plt.figure(1,figsize=(16, 4)) axis_loss = fig.add_subplot(131) axis_data = fig.add_subplot(132) for i in range(500): Y_train = F_Classification(X_train,W) #compute hypothesis function aka. predicted values loss = Loss_Classification_Reg(Y_train, Z_train, W) #compute loss dLdW = dLdW_Classification_Reg(X_train, Y_train, Z_train, W) #compute gradient v = v*m + k*dLdW W = W - v #update loss_collections.append(loss) if abs(loss - prev_loss) < epsilon: break prev_loss = loss if (len(loss_collections)+1) % vis_interval==0: ml_utils.plot_loss(axis_loss, range(len(loss_collections)),loss_collections, "loss = " + str(loss)) ml_utils.plot_scatter_with_label_2d(axis_data, X_train, Z_train, W, "student score scatter plot") fig.canvas.draw() print "Learned parameters ", W.squeeze() print "Learning terminates after {} iterations".format(len(loss_collections)) ``` **Question**: Do you see any improvement in accuracy or convergence speed? Why? Answer: Regularisation does help speed up the training (it adds stricter rules to the update procedure). Accuracy is the same (90%) is probably because (i) number of parameters to be trained is small (2-D) and so is the number of training samples; and (ii) the data are well separated. In a learning task which involves large number of parameters (such as neural network), regularisation proves a very efficient technique. ### 2.2 Multi-class classification Here we are working with a very famous dataset. The Iris flower dataset has 150 samples of 3 Iris flower species (Setosa, Versicolour, and Virginica), each sample stores the height and length of its sepal and pedal in cm (4-D in total). Your task is to build a classifier to distinguish these flowers. ``` #read the Iris dataset iris = np.load('data/iris.npz') X = iris['X'] Z = iris['Z'] print "size X ", X.shape print "size Z ", Z.shape #split train/test with ratio 120:30 TOTALS = Z.size idx = np.random.permutation(TOTALS) idx_train = idx[:120] idx_test = idx[120:] X_train = X[:, idx_train] X_test = X[:, idx_test] Z_train = Z[:, idx_train] Z_test = Z[:, idx_test] #normalise data X_train, u, scale = ml_utils.normalise_data(X_train) X_test = ml_utils.normalise_data(X_test, u, scale) #concatenate array of "1s" to X array X_train = np.concatenate((X_train, np.ones_like(Z_train)), axis = 0) X_test = np.concatenate((X_test, np.ones_like(Z_test)), axis = 0) ``` **Task 2.4**: one-vs-all. Train 3 binary one-vs-all classifiers $F_i$ (i=1-3), one for each class. An unknown feture vector x belongs to class i if: $$max_i F(x,W_i)$$ **Task 2.5**: implement one-vs-one and compare the results with one-vs-all.
github_jupyter
# Conditional generation via Bayesian optimization in latent space ## Introduction I recently read [Automatic Chemical Design Using a Data-Driven Continuous Representation of Molecules](https://arxiv.org/abs/1610.02415) by Gómez-Bombarelli et. al.<sup>[1]</sup> and it motivated me to experiment with the approaches described in the paper. Here's a brief summary of the paper. It describes how they use a variational autoencoder<sup>[2]</sup> for generating new chemical compounds with properties that are of interest for drug discovery. For training, they used a large database of chemical compounds whose properties of interest are known. The variational autoencoder can encode compounds into 196-dimensional latent space representations. By sampling from the continuous latent space new compounds can be generated e.g. by sampling near a known compound to generate slight variations of it or by interpolating between more distant compounds. By simply autoencoding chemical compounds, however, they were not able organize latent space w.r.t. properties of interest. To additionally organize latent space w.r.t. these properties they jointly trained the variational autoencoder with a predictor that predicts these properties from latent space representations. Joint training with a predictor resulted in a latent space that reveals a gradient of these properties. This gradient can then be used to drive search for new chemical compounds into regions of desired properties. The following figure, copied from the paper<sup>[1]</sup>, summarizes the approach. ![vae-chem](images/vae-opt/vae-chem.png) For representing compounds in structure space, they use [SMILES](https://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system) strings which can be converted to and from structural representations using standard computational chemistry software. For the encoder network, they experimented with both, 1D-CNNs and RNNs, for the decoder network they used a RNN. Architecure details are described in the paper. The predictor is a small dense neural network. For optimization in latent space i.e. for navigating into regions of desired properties they use a Bayesian optimization approach with Gaussian processes as surrogate model. The authors open-sourced their [chemical variational autoencoder](https://github.com/aspuru-guzik-group/chemical_vae) but didn't publish code related to Bayesian optimization, at least not at the time of writing this article. So I decided to start some experiments but on a toy dataset that is not related to chemistry at all: the [MNIST handwritten digits dataset](https://en.wikipedia.org/wiki/MNIST_database). All methods described in the paper can be applied in this context too and results are easier to visualize and probably easier to grasp for people not familiar with chemistry. The only property associated with the MNIST dataset is the label or value of the digits. In the following, it will be shown how to conditionally generate new digits by following a gradient in latent space. In other words, it will be shown how to navigate into regions of latent space that decode into digit images of desired target label. I'm also going to adress the following questions: - How does joint training with a predictor change the latent space of a variational autoencoder? - How can useful optimization objectives be designed? - How can application of Bayesian optimization methods be justified? - What are possible alternatives to this approach? I'll leave experiments with the chemical compounds dataset and the public chemical VAE for another article. The following assumes some basic familiarity with [variational autoencoders](https://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/autoencoder-applications/variational_autoencoder.ipynb), [Bayesian otpimization](http://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/bayesian-optimization/bayesian_optimization.ipynb) and [Gaussian processes](http://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/gaussian-processes/gaussian_processes.ipynb). For more information on these topics you may want to read the linked articles. ## Architecture The high-level architecture of the joint VAE-predictor model is shown in the following figure. ![model](images/vae-opt/model.png) ### Encoder The encoder is a CNN, identical to the one presented in the the [variational autoencoder](https://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/autoencoder-applications/variational_autoencoder.ipynb) notebook. ![encoder](images/vae-opt/encoder.png) ### Decoder The decoder is a CNN, identical to the one presented in the the [variational autoencoder](https://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/autoencoder-applications/variational_autoencoder.ipynb) notebook. ![decoder](images/vae-opt/decoder.png) ### Predictor The predictor is a dense network with two hidden layers that predicts the probabilities of MNIST image labels 0-9 from the mean i.e. `t_mean` of the variational Gaussian distribution (details below). `t_mean` is one of the encoder outputs. The output layer of the predictor is a softmax layer with 10 units. ![predictor](images/vae-opt/predictor.png) ## Implementation We will use a 2-dimensional latent space for easier visualization. By default, this notebook loads pre-trained models. If you want to train the models yourself set `use_pretrained` to `False`. Expects about 15 minutes on a GPU for training and much longer on a CPU. ``` # Use pre-trained models by default use_pretrained = True # Dimensionality of latent space latent_dim = 2 # Mini-batch size used for training batch_size = 64 ``` Code for the encoder and decoder have already been presented [elsewhere](https://nbviewer.jupyter.org/github/krasserm/bayesian-machine-learning/blob/dev/autoencoder-applications/variational_autoencoder.ipynb), so only code for the predictor is shown here (see [variational_autoencoder_opt_util.py](variational_autoencoder_opt_util.py) for other function definitions): ``` import keras from keras import layers from keras.models import Model def create_predictor(): ''' Creates a classifier that predicts digit image labels from latent variables. ''' predictor_input = layers.Input(shape=(latent_dim,), name='t_mean') x = layers.Dense(128, activation='relu')(predictor_input) x = layers.Dense(128, activation='relu')(x) x = layers.Dense(10, activation='softmax', name='label_probs')(x) return Model(predictor_input, x, name='predictor') ``` The following composes the joint VAE-predictor model. Note that input to the predictor is the mean i.e. `t_mean` of the variational distribution, not a sample from it. ``` from variational_autoencoder_opt_util import * encoder = create_encoder(latent_dim) decoder = create_decoder(latent_dim) sampler = create_sampler() predictor = create_predictor() x = layers.Input(shape=image_shape, name='image') t_mean, t_log_var = encoder(x) t = sampler([t_mean, t_log_var]) t_decoded = decoder(t) t_predicted = predictor(t_mean) model = Model(x, [t_decoded, t_predicted], name='composite') ``` ## Dataset ``` from keras.datasets import mnist from keras.utils import to_categorical (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,)) y_train_cat = to_categorical(y_train) x_test = x_test.astype('float32') / 255. x_test = x_test.reshape(x_test.shape + (1,)) y_test_cat = to_categorical(y_test) ``` ## Training ``` from keras import backend as K from keras.models import load_model def vae_loss(x, t_decoded): ''' Negative variational lower bound used as loss function for training the variational autoencoder on the MNIST dataset. ''' # Reconstruction loss rc_loss = K.sum(K.binary_crossentropy( K.batch_flatten(x), K.batch_flatten(t_decoded)), axis=-1) # Regularization term (KL divergence) kl_loss = -0.5 * K.sum(1 + t_log_var \ - K.square(t_mean) \ - K.exp(t_log_var), axis=-1) return K.mean(rc_loss + kl_loss) if use_pretrained: # Load VAE that was jointly trained with a # predictor returned from create_predictor() model = load_model('models/vae-opt/vae-predictor-softmax.h5', custom_objects={'vae_loss': vae_loss}) else: model.compile(optimizer='rmsprop', loss=[vae_loss, 'categorical_crossentropy'], loss_weights=[1.0, 20.0]) model.fit(x=x_train, y=[x_train, y_train_cat], epochs=15, shuffle=True, batch_size=batch_size, validation_data=(x_test, [x_test, y_test_cat]), verbose=2) ``` ## Results ### Latent space This sections addresses the question > How does joint training with a predictor change the latent space of a variational autoencoder? To answer, three models have been trained: - A VAE as described above but without a predictor (`model_predictor_off`). - A VAE jointly trained with a classifier as predictor (`model_predictor_softmax`). This is the model described above where the predictor predicts the probabilities of labels 0-9 from encoded MNIST images. - A VAE as described above but jointly trained with a regressor as predictor (`model_predictor_linear`). The predictor of this model is trained to predict digit values on a continuous scale i.e. predictions are floating point numbers that can also be less than 0 and greater than 9. See also `create_predictor_linear` in [variational_autoencoder_opt_util.py](variational_autoencoder_opt_util.py). ``` model_predictor_softmax = model model_predictor_linear = load_model('models/vae-opt/vae-predictor-linear.h5', custom_objects={'vae_loss': vae_loss}) model_predictor_off = load_model('models/vae-opt/vae-predictor-off.h5', custom_objects={'vae_loss': vae_loss}) ``` The following plots show the latent spaces of these three models and the distribution of the validation dataset `x_test` in these spaces. Validation data points are colored by their label. ``` import matplotlib.pyplot as plt %matplotlib inline def encode(x, model): return model.get_layer('encoder').predict(x)[0] ts = [encode(x_test, model_predictor_off), encode(x_test, model_predictor_softmax), encode(x_test, model_predictor_linear)] titles = ['VAE latent space without predictor', 'VAE latent space with classifier', 'VAE latent space with regressor'] fig = plt.figure(figsize=(15, 4)) cmap = plt.get_cmap('viridis', 10) for i, t in enumerate(ts): plt.subplot(1, 3, i+1) im = plt.scatter(t[:, 0], t[:, 1], c=y_test, cmap=cmap, vmin=-0.5, vmax=9.5, marker='o', s=0.4) plt.xlim(-4, 4) plt.ylim(-4, 4) plt.title(titles[i]) fig.subplots_adjust(right=0.8) fig.colorbar(im, fig.add_axes([0.82, 0.13, 0.02, 0.74]), ticks=range(10)); ``` One can clearly see that the latent space of models with a predictor (middle and right plot) has more structure i.e. less overlap of regions with different labels than the latent space of the model without a predictor (left plot). Furthermore, when the predictor is a regressor it establishes a gradient in latent space. The right plot clearly shows a gradient from upper-right (lower vaues) to lower-left (higher values). This is exactly what the authors of the paper wanted to achieve: additionally organizing the latent space w.r.t. certain continuous properties so that gradient-based navigation into regions of desired properties becomes possible. If you want to train a model yourself with a regressor as predictor you should make the following modifications to the setup above: ``` # ... predictor = create_predictor_linear(latent_dim) # ... model.compile(optimizer='rmsprop', loss=[vae_loss, 'mean_squared_error'], loss_weights=[1.0, 20.0]) model.fit(x=x_train, y=[x_train, y_train_cat], epochs=15, shuffle=True, batch_size=batch_size, validation_data=(x_test, [x_test, y_test_cat])) ``` Note that in the case of the MNIST dataset the latent space in the left plot is already sufficiently organized to navigate into regions of desired labels. However, this is not the case for the chemical compound dataset (see paper for details) so that further structuring is required. For the MNIST dataset, the goal is merely to demonstrate that further structuring is possible too. In the following we will use the model that uses a classifier as predictor i.e. the model corresponding to the middle plot. ### Optimization objectives > How can useful optimization objectives be designed? First of all, the optimization objective must be a function of the desired target label in addition to latent variable $\mathbf{t}$. For example, if the desired target label is 5 the optimization objective must have an optimum in that region of the latent space where images with a 5 are located. Also remember that the variational distributions i.e. the distributions of codes in latent space have been regularized to be close to the standard normal distribution during model training (see *regularization term* in `vae_loss`). This regularization term should also be considered in the optimization objective to avoid directing search too far from the origin. Hence the optimization objective should not only reflect the probability that a sample corresponds to an image of desired target label but also the standard normal probability distribution. In the following, we will use an optimization objective $f$ that is the negative logarithm of the product of these two terms: $$ f(\mathbf{t}, target) = - \log p(y=target \lvert \mathbf{t}) - \log \mathcal{N}(\mathbf{t} \lvert \mathbf{0}, \mathbf{I}) \tag{1} $$ where $y$ follows a categorical distribution and $p(y=target \lvert \mathbf{t})$ is the probability that $y$ has the desired target value given latent vector $\mathbf{t}$. I'll show two alternatives for computing $p(y=target \lvert \mathbf{t})$. The first alternative simply uses the output of the predictor. The corresponding optimization objective is visualized in the following figure. ``` from matplotlib.colors import LogNorm from scipy.stats import multivariate_normal predictor = model.get_layer('predictor') rx, ry = np.arange(-4, 4, 0.10), np.arange(-4, 4, 0.10) gx, gy = np.meshgrid(rx, ry) t_flat = np.c_[gx.ravel(), gy.ravel()] y_flat = predictor.predict(t_flat) mvn = multivariate_normal(mean=[0, 0], cov=[[1, 0], [0, 1]]) nll_prior = -mvn.logpdf(t_flat).reshape(-1, 1) def nll_predict(i): '''Optimization objective based on predictor output.''' return nll_prior - np.log(y_flat[:,i] + 1e-8).reshape(-1, 1) plot_nll(gx, gy, nll_predict) ``` One can clearly see how the minima in these plots overlap with the different target value regions in the previous figure (see section [Latent space](#Latent-space)). We could now use a gradient-based optimizer for navigating into regions of high log-likelihood i.e. low negative log-likelihood and sample within that region to conditionally generate new digits of the desired target value. Another alternative is to design an optimization objective that can also include "external" results. To explain, let's assume for a moment that we are again in the latent space of chemical compounds. External results in this context can mean experimental results or externally computed results obtained for new compounds sampled from latent space. For example, experimental results can come from expensive drug discovery experiments and externally computed results from computational chemistry software. For working with external results we can use a Gaussian process model (a regression model) initialized with samples from the training set and let a Bayesian optimization algorithm propose new samples from latent space. Then we gather external results for these proposals and update the Gaussian process model with it. Based on the updated model, Bayesian optimization can now propose new samples. A Bayesian optimization approach is especially useful if experimental results are expensive to obtain as it is designed to optimize the objective in a minimum number of steps. This should answer the question > How can application of Bayesian optimization methods be justified? But how can we transfer these ideas to the MNIST dataset? One option is to decode samples from latent space to real images and then let a separate MNIST image classifier compute the probability that a decoded image shows a digit equal to the desired target. For that purpose we use a small CNN that was trained to achieve 99.2% validation accuracy on `x_test`, enough for our purposes. ``` if use_pretrained: classifier = load_model('models/vae-opt/classifier.h5') else: classifier = create_classifier() classifier.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) classifier.fit(x_train, y_train_cat, epochs=5, shuffle=True, batch_size=batch_size, validation_data=(x_test, y_test_cat), verbose=2) ``` If we combine the negative log-likelihood computed with the separate image classifier with the regularization term mentioned before, we obtain the following optimization objective: ``` decoder = model.get_layer('decoder') # Decode latent vector into image d_flat = decoder.predict(t_flat) # Predict probabilities with separate classifier y_flat = classifier.predict(d_flat) def nll_decode_classify(i): '''Optimization objective based on separate image classifier output.''' return nll_prior - np.log(y_flat[:,i] + 1e-8).reshape(-1, 1) plot_nll(gx, gy, nll_decode_classify) ``` The locations of the minima closely match those of the previous optimization objective but the new optimization objective is more fuzzy. It also shows moderately low negative log-likelihood in regions outside of the desired target as well as in regions that are sparsely populated by validation examples. Anyway, let's use it and see if we can achieve reasonable results. ### Bayesian optimization For Bayesian optimization, we use [GPyOpt](http://sheffieldml.github.io/GPyOpt/) with more or less default settings and constrain the the search space as given by `bounds` below. Note that the underlying Gaussian process model is initialized with only two random samples from latent space. ``` import GPyOpt from GPyOpt.methods import BayesianOptimization def nll(t, target): ''' Bayesian optimization objective. ''' # Decode latent vector into image decoded = decoder.predict(t) # Predict probabilities with separate classifier c_probs = classifier.predict(decoded) nll_prior = -mvn.logpdf(t).reshape(-1, 1) nll_pred = -np.log(c_probs[:,target] + 1e-8).reshape(-1, 1) return nll_prior + nll_pred bounds = [{'name': 't1', 'type': 'continuous', 'domain': (-4.0, 4.0)}, {'name': 't2', 'type': 'continuous', 'domain': (-4.0, 4.0)}] def optimizer_for(target): def nll_target(t): return nll(t, target) return BayesianOptimization(f=nll_target, domain=bounds, model_type='GP', acquisition_type ='EI', acquisition_jitter = 0.01, initial_design_numdata = 2, exact_feval=False) ``` We start by running Bayesian optimization for a desired target value of 4 and then visualize the Gaussian process posterior mean, variance and the acquisition function using the built-in `plot_acquisition()` method. ``` optimizer = optimizer_for(target=4) optimizer.run_optimization(max_iter=50) optimizer.plot_acquisition() ``` By comparing with previous figures, we can see that most samples are located around the minimum corresponding to target value 4 (left plot). The acquisition function has high values in this region (right plot). Because Bayesian optimization makes a compromise between *exploration* of regions with high uncertainty and *exploitation* of regions with (locally) optimal values high acquisition function values also exist in regions outside the desired target value. This is also the reason why some samples are broadly scattered across the search space. We finally have to verify that the samples with the lowest optimization objective values actually correspond to images with number 4. ``` def plot_top(optimizer, num=10): top_idx = np.argsort(optimizer.Y, axis=0).ravel() top_y = optimizer.Y[top_idx] top_x = optimizer.X[top_idx] top_dec = np.squeeze(decoder.predict(top_x), axis=-1) plt.figure(figsize=(20, 2)) for i in range(num): plt.subplot(1, num, i + 1) plt.imshow(top_dec[i], cmap='Greys_r') plt.title(f'{top_y[i,0]:.2f}') plt.axis('off') plot_top(optimizer) ``` Indeed, they do! The numbers on top of the images are the optimization objective values of the corresponding points in latent space. To generate more images of desired target value we also could select the top scoring samples and continue sampling in a more or less narrow region around them (not shown here). How does conditional sampling for other desired target values work? ``` optimizer = optimizer_for(target=3) optimizer.run_optimization(max_iter=50) plot_top(optimizer) optimizer = optimizer_for(target=2) optimizer.run_optimization(max_iter=50) plot_top(optimizer) optimizer = optimizer_for(target=5) optimizer.run_optimization(max_iter=50) plot_top(optimizer) optimizer = optimizer_for(target=9) optimizer.run_optimization(max_iter=50) plot_top(optimizer) ``` This looks pretty good! Also note how for targets 3 and 5 the negative log-likelihood significantly increases for images that are hard to be recognized as their desired targets. ## Alternatives > What are possible alternatives to this approach? The approach presented here is one possible approach for conditionally generating images i.e. images with desired target values. In the case of MNIST images, this is actually a very expensive approach. A conditional variational autoencoder<sup>[3]</sup> (CVAE) would be a much better choice here. Anyway, the goal was to demonstrate the approach taken in the paper<sup>[1]</sup> and it worked reasonably well on the MNIST dataset too. Another interesting approach is described in \[4\]. The proposed approach identifies regions in latent space with desired properties without training the corresponding models with these properties in advance. This should help to prevent expensive model retraining and allows post-hoc learning of so-called *latent constraints*, value functions that identify regions in latent space that generate outputs with desired properties. Definitely one of my next papers to read. ## References - \[1\] Rafael Gómez-Bombarelli et. al. [Automatic chemical design using a data-driven continuous representation of molecules](https://arxiv.org/abs/1610.02415). - \[2\] Diederik P Kingma, Max Welling [Auto-Encoding Variational Bayes](https://arxiv.org/abs/1312.6114). - \[3\] Carl Doersch [Tutorial on Variational Autoencoders](https://arxiv.org/abs/1606.05908). - \[4\] Jesse Engel et. al. [Latent Constraints: Learning to Generate Conditionally from Unconditional Generative Models](https://arxiv.org/abs/1711.05772).
github_jupyter
``` from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer, TfidfVectorizer import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from gensim.summarization import summarize from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from nltk.corpus import stopwords import numpy as np import numpy.linalg as LA from nltk.tokenize import sent_tokenize import os import nltk import re import sys from nltk import NaiveBayesClassifier import nltk.classify from nltk.tokenize import wordpunct_tokenize from nltk.corpus import stopwords import re from nltk.tokenize import RegexpTokenizer from nltk.stem.snowball import RussianStemmer from nltk.stem.snowball import SnowballStemmer from gensim.summarization import keywords import warnings warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') df_ans = pd.read_csv("feedbacks_tags.csv", sep='\t') df_ans.head() mob_comment = pd.Series(df_ans['name'].tolist()).astype(str) dist_train = mob_comment.apply(len) dist_train = dist_train[dist_train>10] pal = sns.color_palette() plt.figure(figsize=(10, 5)) plt.hist(dist_train, bins=35, range=[0, 35], normed=True) plt.title('Normalised histogram of character count in questions', fontsize=15) plt.legend() plt.xlabel('Number of characters', fontsize=15) plt.ylabel('Probability', fontsize=15) dist_train = mob_comment.apply(lambda x: len(x.split(' '))) dist_train = dist_train[dist_train>3] plt.figure(figsize=(10, 5)) plt.hist(dist_train, bins=16, range=[1, 6], color=pal[2], normed=True, label='train') plt.title('Normalised histogram of word count', fontsize=15) plt.legend() plt.xlabel('Number of words', fontsize=15) plt.ylabel('Probability', fontsize=15) from wordcloud import WordCloud cloud = WordCloud(width=1440, height=1080).generate(" ".join(mob_comment.astype(str))) plt.figure(figsize=(15, 10)) plt.imshow(cloud) plt.axis('off') stopWords = nltk.corpus.stopwords.words('russian') stopWords.append('все') stopWords.append('очень') stopWords.append('это') stopWords.append('все') stopWords.append('всем') mob_comment = df_ans[['count', 'name']] mob_comment.mobile_app_comment = mob_comment.name.str.lower() mob_comment.name.str.split(expand=True).stack().value_counts()[:10] tokenizer = nltk.word_tokenize mob_comment.mobile_app_comment = mob_comment.mobile_app_comment.str.replace(',', ' ') mob_comment.mobile_app_comment = mob_comment.mobile_app_comment.str.replace('.', ' ') mob_comment.mobile_app_comment = mob_comment.mobile_app_comment.str.replace('!', ' ') mob_comment['name'] = mob_comment['name'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stopWords)])) mob_comment.name.str.split(expand=True).stack().value_counts()[:40] stemmer = SnowballStemmer("russian") def tokenize_and_stem(text): # сначала токенизируем по предложению, потом по словам, чтобы сохранить "особые" слова tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] # удалим все самое плохое, знаки препинания for token in tokens: if re.search('[a-zA-Z0-9А-Яа-я]', token): filtered_tokens.append(token) stems = [stemmer.stem(t) for t in filtered_tokens] return stems def tokenize_only(text): tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] for token in tokens: if re.search('[a-zA-Z0-9А-Яа-я]', token): filtered_tokens.append(token) return filtered_tokens totalvocab_stemmed = [] totalvocab_tokenized = [] for i in mob_comment.mobile_app_comment: allwords_stemmed = tokenize_and_stem(i) totalvocab_stemmed.extend(allwords_stemmed) allwords_tokenized = tokenize_only(i) totalvocab_tokenized.extend(allwords_tokenized) vocab_frame = pd.DataFrame({'words': totalvocab_tokenized}, index = totalvocab_stemmed) print ('Всего ' + str(vocab_frame.shape[0]) + ' слов в словаре') tfidf_vectorizer = TfidfVectorizer( max_features=20000, min_df=1, max_df=0.99, use_idf=True, tokenizer=tokenize_and_stem, ngram_range=(1,5)) tfidf_matrix = tfidf_vectorizer.fit_transform(mob_comment.name) print(tfidf_matrix.shape) print(mob_comment['count'].shape) #mob_comment = mob_comment.reset_index() from sklearn.metrics.pairwise import cosine_similarity dist = 1 - cosine_similarity(tfidf_matrix) # тут не работает from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score range_n_clusters = [ 2 , 5, 7 , 10, 15] # clusters range you want to select best_clusters = 0 previous_silh_avg = 0.0 for n_clusters in range_n_clusters: clusterer = KMeans(n_clusters=n_clusters) cluster_labels = clusterer.fit_predict(tfidf_matrix) silhouette_avg = silhouette_score(tfidf_matrix, cluster_labels) print (silhouette_avg) if silhouette_avg > previous_silh_avg: previous_silh_avg = silhouette_avg best_clusters = n_clusters print (best_clusters) # Final Kmeans for best_clusters ``` ## Кластеризация K-means ``` from sklearn.cluster import KMeans num_clusters = 5 km = KMeans(n_clusters=num_clusters) %time km.fit(tfidf_matrix) clusters = km.labels_.tolist() from sklearn.externals import joblib joblib.dump(km, 'doc_cluster.pkl') #km = joblib.load('doc_cluster.pkl') clusters = km.labels_.tolist() comments = {'np': list(mob_comment['count']), 'comment': list(mob_comment.name), 'cluster': clusters} #frame = pd.DataFrame(films, index = [clusters] , columns = ['rank', 'cluster']) frame = pd.DataFrame(comments) frame['cluster'].value_counts() grouped = frame['np'].groupby(frame['cluster']) #groupby cluster for aggregation purposes grouped.mean() terms = tfidf_vectorizer.get_feature_names() #отсортирует комментарии по близости к кластеру order_centroids = km.cluster_centers_.argsort()[:, ::-1] for i in range(num_clusters): print("Кластер %d:" % i, end='') cust_word = list() for ind in order_centroids[i, :8]: #replace 6 with n words per cluster cust_word.append(vocab_frame.loc[terms[ind].split(' ')].values.tolist()[0][0]) print(set(cust_word)) print() ``` ## Кластеризация дендограммы ``` from scipy.cluster.hierarchy import ward, dendrogram linkage_matrix = ward(dist) #define the linkage_matrix using ward clustering pre-computed distances fig, ax = plt.subplots(figsize=(30, 150)) # set size ax = dendrogram(linkage_matrix, orientation="right", labels=list(frame.comment)); plt.tick_params(\ axis= 'x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') plt.tight_layout() #show plot with tight layout #uncomment below to save figure plt.savefig('ward_clusters.png', dpi=200) #save figure as ward_clusters ``` ## LDA ``` import string def strip_proppers(text): # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent) if word.islower()] return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip() def tokenize_and_stem(text): # сначала токенизируем по предложению, потом по словам, чтобы сохранить "особые" слова tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] # удалим все самое плохое, знаки препинания for token in tokens: if re.search('[a-zA-Z0-9А-Яа-я]', token): filtered_tokens.append(token) stems = [stemmer.stem(t) for t in filtered_tokens] return stems def tokenize_only(text): tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] for token in tokens: if re.search('[a-zA-Z0-9А-Яа-я]', token): filtered_tokens.append(token) return filtered_tokens from gensim import corpora, models, similarities %time preprocess = [strip_proppers(doc) for doc in mob_comment.mobile_app_comment] #tokenize %time tokenized_text = [tokenize_and_stem(text) for text in preprocess] #remove stop words %time texts = tokenized_text #[[word for word in text if word not in stopwords] for text in tokenized_text] from gensim.corpora import Dictionary # to create the bigrams bigram_model = Phrases(texts) import codecs if 1 == 1: with codecs.open('bigram_sentences_all.txt', 'w', encoding='utf_8') as f: for unigram_sentence in texts: bigram_sentence = u' '.join(bigram_model[unigram_sentence]) f.write(bigram_sentence + '\n') from gensim.models.word2vec import LineSentence bigram_sentences = LineSentence('bigram_sentences_all.txt') trigram_model = Phrases(bigram_sentences) triram_sentences = [] for bigram_sentence in bigram_sentences: triram_sentence = u' '.join(trigram_model[bigram_sentence]) triram_sentences.append(triram_sentence) #dictionary = Dictionary(texts) triram_sentences tokenized_text = [tokenize_only(text) for text in triram_sentences] dictionary = Dictionary(tokenized_text) dictionary.filter_extremes(no_below=2, no_above=0.95) corpus = [dictionary.doc2bow(doc) for doc in tokenized_text] print('Number of unique tokens: %d' % len(dictionary)) print('Number of documents: %d' % len(corpus)) num_topics_now = 6 %time lda = models.LdaModel(corpus, num_topics = num_topics_now, id2word=dictionary,\ random_state = 1024, \ update_every=5, \ chunksize=10000, \ passes=100)\ lda.show_topics() topics_matrix = lda.show_topics(formatted=False, num_words=20) #topic_words = topics_matrix[:,:,1] topic_num = 0 for i in range(0,num_topics): print('Топик №', i, end = ': ') for k in range(0,10): print(topics_matrix[i][1][k][0], end=', ') print() topic_num +=1 lda.save('lda_simple_aproach.bin') temp = df_ans[['np_answer', 'mobile_app_comment']][df_ans.mobile_app_comment.isnull() == False] list(temp.iloc[[14]].mobile_app_comment) doc = dictionary.doc2bow(texts[14]) doc_lda = lda.get_document_topics(doc) doc_lda top_topics = lda.top_topics(corpus, topn=20) # Average topic coherence is the sum of topic coherences of all topics, divided by the number of topics. avg_topic_coherence = sum([t[1] for t in top_topics]) / num_topics print('Average topic coherence: %.4f.' % avg_topic_coherence) import pyLDAvis.gensim pyLDAvis.enable_notebook() pyLDAvis.gensim.prepare(lda, corpus, dictionary) ``` ``` trigtam_sen = pd.concat([trigram_sen, df], axis=1) trigtam_sen = trigtam_sen[trigram_sen.sentences.str.strip().str.len() != 0] text = 'Доказа́тельство с нулевы́м разглаше́нием (информа́ции) в криптографии (англ. Zero-knowledge proof) — \ интерактивный криптографический протокол, позволяющий одной из взаимодействующих сторон («The verifier» — проверяющей) убедиться \ в достоверности какого-либо утверждения (обычно математического), не имея при этом никакой другой информации от второй стороны \ («The prover» — доказывающей). Причём последнее условие является необходимым, так как обычно доказать, \ что сторона обладает определёнными сведениями в большинстве случаев тривиально, если она имеет право просто \ раскрыть информацию. Вся сложность состоит в том, чтобы доказать, что у одной из сторон есть информация, \ не раскрывая её содержание. Протокол должен учитывать, что доказывающий сможет убедить проверяющего только \ в случае, если утверждение действительно доказано. В противном случае сделать это будет невозможно,\ или крайне маловероятно из-за вычислительной сложности.\ Под интерактивностью протокола подразумевается непосредственный обмен информацией сторонами[1][2]. \ Таким образом, рассматриваемый протокол требует наличия интерактивных исходных данных (interactive input) \ от проверяющего, как правило, в виде задачи или проблемы. Цель легального доказывающего (имеющего доказательство) \ в этом протоколе — убедить проверяющего в том, что у него есть решение, не выдав при этом даже части «секретного» \ доказательства («нулевое разглашение»). Цель проверяющего же — это удостовериться в том, что доказывающая сторона \ «не лжёт»[2][3].\ Также были разработаны протоколы доказательства с нулевым разглашением[4][5], для которых не требовалось \ наличия интерактивных исходных данных, при этом доказательство которых, как правило, опирается на предположение об \ идеальной криптографической хеш-функции, то есть предполагается, что выход однонаправленной хеш-функции невозможно \ предсказать, если не известен её вход[6]' summarize(text, split= True) keywords(text, ratio=0.05, split=True) %%time from gensim.corpora import Dictionary from gensim.models import Phrases # to create the bigrams bigram_model = Phrases(texts) import codecs if 1 == 1: with codecs.open('bigram_sentences_all.txt', 'w', encoding='utf_8') as f: for unigram_sentence in texts: bigram_sentence = u' '.join(bigram_model[unigram_sentence]) f.write(bigram_sentence + '\n') from gensim.models.word2vec import LineSentence #bigram_sentences = LineSentence('bigram_sentences_all.txt') #bigram_sentences = open('bigram_sentences_all.txt', "r").read().splitlines() import codecs fileObj = codecs.open( 'bigram_sentences_all.txt', "r", "utf_8_sig" ) bigram_sentences = fileObj.read().splitlines() # или читайте по строке fileObj.close() trigram_model = Phrases(bigram_sentences) triram_sentences = [] i =0 for bigram_sentence in bigram_sentences: i += 1 triram_sentence = u' '.join(trigram_model[tokenize_only(bigram_sentence)]) triram_sentences.append(triram_sentence) #if len(triram_sentences) != i: #triram_sentence = u' '.join(' ') print (i, len(triram_sentences)) ```
github_jupyter
``` #https://medium.com/were-are-all-the-ufos-a-in-depth-look-at-ufo-data/where-are-all-the-ufos-a-in-depth-look-at-ufo-data-since-the-early-1900s-94fd3a2e6d95 !pip install plotly==4.8.1 ### load in all csv files ### from google.colab import files uploaded = files.upload() import pandas as pd df1 = pd.read_csv('https://raw.githubusercontent.com/helderc/NUFORC-Data-Scraping/master/ufon_raw_2020-01-18.csv',nrows=38320) !unzip 388_793053_bundle_archive (1).zip df = pd.read_csv('scrubbed.csv') #df1 = pd.read_csv('complete.csv') #from google.colab import drive #drive.mount('/content/drive') ### removes all rows with countrys in them that are not america ### df = df[~df['country'].astype(str).str.contains('gb')] df = df[~df['country'].astype(str).str.contains('ca')] df = df[~df['country'].astype(str).str.contains('au')] df = df[~df['country'].astype(str).str.contains('de')] ### drop unwanted columns and then make some time columns ### df = df.drop(columns=['country','comments']) df = df.drop(columns=['duration (seconds)']) from datetime import timedelta import pandas as pd df['datetime'] = df['datetime'].str.replace('24:00', '0:00') df['datetime'] = pd.to_datetime(df['datetime'], infer_datetime_format=True) df['month'] = df['datetime'].dt.month df['year'] = df['datetime'].dt.year df['hour'] = df['datetime'].dt.hour df1['date'] = pd.to_datetime(df1['Date / Time'], errors='coerce') ### Time columns for the other dataframe ### df1.tail(1) df1['month'] = df1['date'].dt.month df1['year'] = df1['date'].dt.year df1['hour'] = df1['date'].dt.hour df['year'].value_counts() df1['year'].value_counts() ### droped, renamed, and rearanged some columns df1.rename({'date': 'datetime'}, axis=1, inplace=True) df1.drop(['Date / Time'], axis=1) df1 = df1.drop(columns=['Date / Time','Summary']) df1['datetime'] = df1['datetime'].dt.date df['datetime'] = df['datetime'].dt.date df = df.rename(columns={'city': 'City', 'shape': 'Shape', 'duration (hours/min)':'Duration'}) df = df.rename(columns={'state': 'State', 'date posted': 'Date_Posted'}) df = df.rename(columns={'Date_Posted':'Posted'}) df1 = df1.reindex(columns=['datetime','City','State','Shape','Duration','Posted','month','year','hour']) ### uppercased some stuff #### ############################### df['State'] = df['State'].str.upper() df['City'] = df['City'].str.title() #made some subsets in case i wanted them vc = pd.concat([df1, df], axis=0) misc = vc.loc[:, vc.columns.intersection(['Shape','Duration'])] time = vc.loc[:, vc.columns.intersection(['datetime','posted','month','year','hour','Duration'])] df = df[[c for c in df if c not in ['latitude', 'longitude ']] + ['latitude', 'longitude ']] df = df.reindex(index=df.index[::-1]) df.columns ### concated my data frame once everything was perfect ### dfi = pd.concat([df1, df], axis=0) dfi.tail() ### value count snippet ### o = dfi[['City','State']] k = o[o["State"] == 'PA'] p = o[o['State'] == 'AZ'] p.shape kk = k['City'] pp = p['City'] kjk = kk.value_counts().rename_axis('City').reset_index(name='Total') ppo = pp.value_counts().rename_axis('Year').reset_index(name='Total') ppo.head(5) kjk.head(5) Final = pd.concat([ppo, kjk], axis=1) Final.head() Final.rename(index={'Year':'Arizona','City':'Pennslyvania'}) Final = Final.rename(columns={'Year':'Arizona','City':'Pennslyvania'}) Final.head() Final['Total'] = Final['Total'].astype(str).replace('\.0', '', regex=True) Final.head() ### worked out how to get my bar graph for yearly accourences ii = dfi['year'] dfff = ii.value_counts().rename_axis('Year').reset_index(name='Total') print (dfff) dfff = ii.value_counts().rename_axis('Year').reset_index(name='Total') print (dfff) dfff.tail(50) yt = dfff[['Year', 'Total']].sort_values('Year', ascending=False) ## chart studio stuff import plotly.express as px !pip install chart_studio import chart_studio username = 'lnealon21' api_key = 'jYtizvZdhFGQ7sSqiGmn' chart_studio.tools.set_credentials_file(username=username, api_key=api_key) # line 1 import plotly.express as px #df = px.data.gapminder().query("country=='Canada'") fig = px.line(yt, x="Year", y="Total", title='Nation wide sightings by year') fig.show() import chart_studio.plotly as py py.plot(fig, filename = 'Nation wide sightings by year', auto_open=True) # bar 1 import chart_studio.plotly as py py.plot(fig, filename = 'State total', auto_open=True) animals=['California', 'Flordia', 'Washington', 'Texas', 'New York', 'Arizona', 'Pennsylvania'] fig = go.Figure(data=[ go.Bar(name='State Total', x=animals, y=[13531,6832,5804,4825,4565,4117,3975], marker_color='rgb(55, 83, 109)'), go.Bar(name='City Most', x=animals, y=[668,345,648,360,208,651,183], marker_color='rgb(26, 118, 255)') ]) # Change the bar mode fig.update_layout(barmode='group') fig.show() ### all import not mentioned pie charts! ## pie 1/2 labels = ['5 minutes','2 minutes','10 minutes','1 minute','3 minutes','30 seconds', '15 minutes','10 seconds','5 seconds','20 minutes','30 minutes','1 hour','15 seconds', '20 seconds','4 minutes','3 seconds','2 seconds', '2 hours'] values = [7784,5617,5327,4663,4225,3397,3325,2971,2634,2391,2189,1957,1769,1647,1488,1082,955,406] import pandas as pd d = {'Time':labels,'value':values} d = pd.DataFrame(d) labels2 = ['Light', 'Circle', 'Triangle', 'Fireball', 'Unknown', 'Sphere', 'Disk', 'Oval', 'Formation', 'Changing', 'Cigar', 'Flash', 'Rectangle', 'Cylinder', 'Diamond', 'Chevron', 'Teardrop', 'Egg', 'Cone', 'Cross'] values2 = [23562, 11914, 10528, 8913, 7782, 7571, 6260, 4930, 3695, 2769, 2680, 2092, 1908, 1773, 1670, 1364, 979, 941, 440, 360] c = {'Shape':labels2,'Value':values2} c = pd.DataFrame(c) d.head() import plotly.express as px df = d fig = px.pie(d, values='value', names='Time', color_discrete_sequence=px.colors.sequential.RdBu, title='UFO Time Visible') fig.show() import plotly.express as px # This dataframe has 244 lines, but 4 distinct values for `day` #c = px.data.values() fig = px.pie(c, values='Value', names='Shape', title='UFO Shape') fig.show() import chart_studio.plotly as py py.plot(fig, filename = 'df = d', auto_open=True) import chart_studio.plotly as py py.plot(fig, filename = 'UFO Shape', auto_open=True) df.head(1) colors = ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd'] # for colab: def enable_plotly_in_cell(): import IPython from plotly.offline import init_notebook_mode display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>''')) init_notebook_mode(connected=False) g = df[df['datetime'].dt.year == 2013] g.tail(1) import plotly.graph_objects as go import pandas as pd g['text'] = g['city'] + ', ' + g['state']# + ', ' + df['cnt'].astype(str) fig = go.Figure(data=go.Scattergeo( lon = g['longitude '], lat = g['latitude'], text = g['text'], mode='markers', #colorscale = 'teal', #colorbar_title = mycolorbartitle, )) fig.update_layout( title = '2013 Reports', geo_scope='usa', ) fig.show() rt.tail() ```
github_jupyter
``` #예제 4-26 회귀선이 있는 산점도 #라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns #seaborn 제공 데이터셋 가져오기 titanic = sns.load_dataset('titanic') #스타일 테마 설정(5가지: darkgrid, whiteegrid, dark, white, ticks) sns.set_style('darkgrid') #그래프 객체 생성(figure에 2개의 서브 플롯 생성) fig=plt.figure(figsize=(15,5)) ax1 = fig.add_subplot(1,2,1) ax2 = fig.add_subplot(1,2,2) #그래프 그리기()선형회귀선 표시*(fig.reg = ture) sns.regplot(x='age', y='fare', data=titanic, ax=ax1 ) #그래프 그리기 - 선형회귀선 미표시 sns.regplot(x='age', y='fare', data=titanic, ax=ax2, color='orange', fit_reg=False #회귀선 미표시 ) plt.show() #예제 4-27 히스토그램/ 커널밀도함수 #그래프 객체 생성(figure에 3개의 서브 플롯 생성) fig = plt.figure(figsize=(15,5)) ax1 = fig.add_subplot(1, 3, 1 ) ax2 = fig.add_subplot(1, 3, 2) ax3 = fig.add_subplot(1, 3, 3 ) #기본값 sns.distplot(titanic['fare'], ax=ax1) #hist = false sns.distplot(titanic['fare'], hist=False, ax= ax2) #kde = False sns.distplot(titanic['fare'], kde=False, ax= ax3) #차트 제목 표시 ax1.set_title('titanic fare - hist/ked') ax2.set_title('titanic fare -ked') ax3.set_title('titanic fare=hist') plt.show() #예제 4-28 히트맵 #피벗테이블로 범주형 변수를 각각 행, 열로 재구분하여 정리 table = titanic.pivot_table(index=['sex'],columns=['class'], aggfunc='size') table #히트맵 그리기 sns.heatmap(table, #데이터프레임 annot=True, fmt='d', #데이터 값 표시 여부, 정수형 포맷 cmap='YlGnBu', #컬러맵 linewidth = .5, #구분선 cbar=False) # 컬러 바 표시 여부 plt.show() #예제 4-29 범주형 데이터의 산점도 # -*- coding: utf-8 -*- #라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns #seaborn 제공 데이터셋 가져오기 titanic =sns.load_dataset('titanic') #스타일 테마 설정(5가지: darkgrid, whitegrid, dark white, ticks) sns.set_style('whitegrid') #그래프 객체 생성(figure에 2개의 서브 플롯 생성) fig = plt.figure(figsize=(15,5)) ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) #이산형 변수의 분포 - 데이터 분산 미고려(중복표시 o) sns.stripplot(x="class", #x축 변수 y="age", #y축 변수 data=titanic, # 데이터셋 -데이터프레임 ax = ax1 #axe 객체 - 1번쨰 그래프 ) #이산형 변수의 분포 - 데이터 분산 고려(중복 표시 x) sns.swarmplot(x='class', y='age', data=titanic, ax=ax2) #차트 제목 표시 ax1.set_title('Strip Plot') ax2.set_title('Swarm Plot') plt.show() #예제 4-30 막대 그래프 #그래프 객체 생성 (figure 에 3개의 서브 플롯 생성) fig = plt.figure(figsize=(15,5)) ax1 = fig.add_subplot(1,3,1) ax2 = fig.add_subplot(1,3,2) ax3 = fig.add_subplot(1,3,3) #x축 y축에 변수 할당 sns.barplot(x='sex', y='survived', data=titanic, ax= ax1) #x축 y축에 변수 할당하고 hue 옵션 추가 sns.barplot(x='sex', y='survived',hue='class', data=titanic, ax=ax2) #x축 y축에 변수 할당하고 hue 옵션을 추가하여 누적 출력 sns.barplot(x='sex', y='survived', hue='class', dodge=False, data=titanic, ax=ax3) #차트 제목 표시 ax1.set_title('titanic survived -sex') ax2.set_title('titanic survived -sex/class') ax3.set_title('titanic survived -sex/class(staked)') plt.show() # -*- coding: utf-8 -*- # 라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns # Seaborn 제공 데이터셋 가져오기 titanic = sns.load_dataset('titanic') # 스타일 테마 설정 (5가지: darkgrid, whitegrid, dark, white, ticks) sns.set_style('whitegrid') # 그래프 객체 생성 (figure에 3개의 서브 플롯을 생성) fig = plt.figure(figsize=(15, 5)) ax1 = fig.add_subplot(1, 3, 1) ax2 = fig.add_subplot(1, 3, 2) ax3 = fig.add_subplot(1, 3, 3) # 기본값 sns.countplot(x='class', palette='Set1', data=titanic, ax=ax1) # hue 옵션에 'who' 추가 sns.countplot(x='class', hue='who', palette='Set2', data=titanic, ax=ax2) # dodge=False 옵션 추가 (축 방향으로 분리하지 않고 누적 그래프 출력) sns.countplot(x='class', hue='who', palette='Set3', dodge=False, data=titanic, ax=ax3) # 차트 제목 표시 ax1.set_title('titanic class') ax2.set_title('titanic class - who') ax3.set_title('titanic class - who(stacked)') plt.show() #예제 4-32 박스플롯/바이올린 그래프 # -*- coding: utf-8 -*- #라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns #Seaborn 제공 데이터셋 가져오기 titanic = sns.load_dataset('titanic') #스타일 테마 설정(5가지 : darkgrid, whitegrid, dark, white, ticks) sns.set_style('whitegrid') #그래프 객체생성(figure에 4개의 서브플롯 생성) fig = plt.figure(figsize=(15,10)) ax1 = fig.add_subplot(2,2,1) ax2 = fig.add_subplot(2,2,2) ax3 = fig.add_subplot(2,2,3) ax4 = fig.add_subplot(2,2,4) #박스 플롯 - 기본값 sns.boxplot(x='alive', y='age', data=titanic, ax= ax1) #박스플롯 - hue변수 추가 sns.boxplot(x='alive', y='age', hue='sex', data=titanic, ax=ax2) #바이올린그래프 - 기본값 sns.violinplot(x='alive', y='age', data=titanic, ax=ax3) #바이올린그래프- hue변수 추가 sns.violinplot(x='alive', y='age', hue='sex', data=titanic, ax=ax4) plt.show() #예제4-33 조인트 그래프 # -*- coding: utf-8 -*- #라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns #Seaborn 제공 데이터셋 가져오기 titanic =sns.load_dataset('titanic') #스타일 테마 설정(5가지: darkgrid, whitegrid, dark, white, ticks) sns.set_style('whitegrid') #조인트 그래프 -산점도 j1 = sns.jointplot(x='fare', y='age',data=titanic) #조인트 그래프-회귀선 j2=sns.jointplot(x='fare', y='age', kind='reg', data=titanic) #조인트 그래프- 육각 그래프 j3 = sns.jointplot(x='fare', y='age', kind='hex', data=titanic) #조인트 그래프 - 커널 밀집 그래프 j4 = sns.jointplot(x='fare', y='age', kind='kde', data=titanic) #차트 제목 표시 j1.fig_suptitle('titanic fare - scatter', size=15) j2.fig_suptitle('titanic fare - reg', size=15) j3.fig_suptitle('titanic fare - hex', size=15) j4.fig_suptitle('titanic fare - kde', size=15) plt.show() # -*- coding: utf-8 -*- # 라이브러리 불러오기 import matplotlib.pyplot as plt import seaborn as sns # Seaborn 제공 데이터셋 가져오기 titanic = sns.load_dataset('titanic') # 스타일 테마 설정 (5가지: darkgrid, whitegrid, dark, white, ticks) sns.set_style('whitegrid') # 조건에 따라 그리드 나누기 g = sns.FacetGrid(data=titanic, col='who', row='survived') # 그래프 적용하기 g = g.map(plt.hist, 'age') #예제 4-35 이변수 데이터 분포 #titanic 데이터셋중에서 분석 데이터 선택하기 titanic_pair = titanic[['age','pclass','fare']] #조건에 따라 그리드 나누기 g= sns.pairplot(titanic_pair) pip install folium #예제 4-36 지도 만들기 # -*- coding: utf-8 -*- #라이브러리 불러오기 import folium #서울 지도 만들기 seoul_map = folium.Map(location=[37.55, 126.98], zoom_start=12) #지도를 HTML 파일로 저장하기 seoul_map.save('./seoul.html') #예제 4-37 지도 스타일 적용 #-*- coding: utf-8 -*- #라이브러리 불러오기 import folium #서울 지도 만들기 seoul_map2 = folium.Map(location=[37.55, 126.98], tiles='Stamen Terrain', zoom_start=12) seoul_map3 = folium.Map(location=[37.55, 126.98], tiles='Stamen Toner', zoom_start=15) #지도를 HTML파일로 저장하기 seoul_map2.save('./seoul2.html') seoul_map3.save('./seoul3.html') #예제 4-38 지도에 마커 표시하기 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd import folium #대학교 리스트를 데이터 프레임으로 변환 df = pd.read_excel('./서울지역 대학교 위치.xlsx') df.head() #서울 지도 만들기 seoul_map = folium.Map(location=[37.55, 126.98], tiles='Stamen Terrain', zoom_start=12) #대학교 위치 정보를 Markerfh vytl for name, lat, lng in zip(df.index, df.위도, df.경도): folium.Marker([lat,lng], popup = name). add_to(seoul_map) #지도를 HTML 파일로 저장하기 seoul_map.save('./seoul_colleges.html') #예제 4-39 지도에 원형 마커 표시 #대학교 위치 정보를 CircleMarker로 표시 for name, lat, lng in zip(df.index, df.위도, df.경도): folium.CircleMarker( [lat, lng], radius = 10, #원의 반지름 color='brown', #원의 둘레 색상 fill=True, fill_color='coral', #원을 채우는 색 fill_opacity =0.7, #투명도 popup =name ).add_to(seoul_map) #지도를 HTML파일로 저장하기 seoul_map.save('./seoul_collages2.html') #예제 4-40 지도 영역에 단계구분도 표시하기 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd import folium import json #경기도 인구변화 데이터를 불러와서 데이터프레임으로 변환 file_path = './경기도인구데이터.xlsx' df = pd.read_excel(file_path, index_col='구분') df.columns = df.columns.map(str) #경기도 시군구 경계 정보를 가진 geo-json ㅍ ㅏ일 불러오기 geo_path = './경기도행정구역경계.json' try: geo_data = json.load(open(geo_path, encoding='utf-8')) except: geo_data - json.load(open(geo_path, encoding='utf-8-sig')) #경기도 지도 만들기 g_map = folium.Map(location=[37.5502, 126.982], tiles='Stamen Terrain', zoom_start=9) #출력할 연도 선택(2007~2017년 중에서 선택) year='2017' #Choropleth 클래스로 단계구분도 표시하기 folium.Choropleth(geo_data=geo_data, #지도경계 data = df[year], #표시하려는 데이터 columns = [df.index, df[year]], #열지정 fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.3, threshold_scale=[10000, 100000, 300000, 500000, 700000], key_on='feature.properties.name', ).add_to(g_map) #지도를 HTML파일로 저장하기 g_map.save('./gyonggi_population_' + year + '.html') #예제 5-1 누락 데이터 확인 # -*- coding: utf-8 -*- #라이브러리 불러오기 import seaborn as sns #titanic 데이터셋 가져오기 df = sns.load_dataset('titanic') df.head() df.info() #deck 열의 NaN 개수 계산하기 nan_deck = df['deck'].value_counts(dropna=False) print(nan_deck) #isnull() 메소드로 누락 데이터 찾기 print(df.head().isnull()) #notnull()메소드로 누락 데이터 찾기 print(df.head().notnull()) #isnull()메소드로 누락 데이터 개수 구하기 print(df.head().isnull().sum(axis=0)) #예제 5-2 누락 데이터 제거 # -*- coding: utf-8 -*- #라이브러리 불러오기 import seaborn as sns #titanic 데이터셋 가져오기 df = sns.load_dataset('titanic') #for 반복문으로 각 열의 NaN 개수 계산하기 missing_df = df.isnull() for col in missing_df.columns: missing_count = missing_df[col].value_counts() #각 열의 NaN 개수 파악 try: print(col, ':' , missing_count[True]) #NaN값이 있으면 개수 출력 except: print(col,':', 0) #NaN값이 없으면 0개 출력 #예제 5-2 누락 데이터 제거 #NaN 값이 500개 이상인 열을 모두 삭제 - deck 열(891개 중 688개의 NaN 값) df_thresh = df.dropna(axis=1, thresh=500) print(df_thresh.columns) # age 열에 나이 데이터가 없는 모든 행을 삭제 - age 열(891개 중 177개의 NaN 값) df_age = df.dropna(subset=['age'], how='any', axis=0) print(len(df_age)) #평균으로 누학 데이터 바꾸기 # -*- coding: utg -8 #라이브러리 불러오기 import seaborn as sns #titanic 데이터셋 가져오기 df= sns.load_dataset('titanic') #age 열의 첫 10개 데이터 출력 (5행에 값 NaN) print(df['age'].head(10)) print('\n') #age 열의 NaN 값을 다른 나이 데이터의 평균으로 변경하기 mean_age = df['age'].mean(axis=0) #age열의 평균 계산(NaN값 제외) df['age'].fillna(mean_age, inplace=True) #age열의 첫 10개 데이터 출력(5행에 NaN값이 평균으로 대체) print(df['age'].head(10)) #예제 5-4 가장 많이 나타나는 값으로 바꾸기 # -*- coding: utf-8 -*- #라이브러리 불러오기 import seaborn as sns #titanic 데이터셋 가져오기 df = sns.load_dataset('titanic') #embark_town 열의 829행의 NaN 데이터 출력 print(df['embark_town'][825:830]) print('\n') #embark_town 열의 NaN 값을 승선 도시 중에서 가장 많이 출현한 값으로 치환하기 most_freq = df['embark_town'].value_counts(dropna=True).idxmax() print(most_freq) print('\n') df['embark_town'].fillna(most_freq, inplace=True) #embark_town 열 829행의 NaN 데이터 출력(NaN 값이 most_freq 값으로 대체) print(df['embark_town'][825:830]) #예제 5-5 이웃하고 있는 값으로 바꾸기 # -*- coding: utf-8 -*- #라이브러리 불러오기 import seaborn as sns #titanic 데이터셋 가져오기 df = sns.load_dataset('titanic') #embark_town 열 829행의 NaN 데이터 출력 print(df['embark_town'][825:830]) print('\n') #emvark_town 열의 NaN 값을 바로 앞에 있는 828행의 값으로 변경하기 df['embark_town'].fillna(method='ffill', inplace=True) print(df['embark_town'][825:830]) #예제 5-6 중복 데이터 확인 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd #중복 데이터를 갖는 데이터프레임 만들기 df = pd.DataFrame({ 'c1':['a', 'a', 'b', 'a', 'b'], 'c2':[1,1,1,2,2], 'c3':[1,1,2,2,2] }) print(df) print('\n') #데이터프레임 전체 행 데이터 중에서 중복갑 찾기 df_dup = df.duplicated() print(df_dup) print('\n') #예제 5-6 중복 데이터 확인 #데이터프레임의 특정 열 데이터에서 중복값 찾기 col_dup =df['c2'].duplicated() print(col_dup) #예제 5-7 중복 데이터 제거 #라이브러리 불러오기 import pandas as pd #중복 데이터를 갖는 데이터프레임 만들기 df = pd.DataFrame({ 'c1':['a', 'a', 'b', 'a', 'b'], 'c2':[1,1,1,2,2], 'c3':[1,1,2,2,2] }) print(df) print('\n') #데이터프레임에서 중복 행 제거 df2 = df.drop_duplicates() print(df2) #c2, c3 열을 기준으로 중복 행 제거 df3 = df.drop_duplicates(subset=['c2','c3']) print(df3) #예제5-8 단위 환산 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd #read_csv()함수로 df 생성 df = pd.read_csv('./auto-mpg.csv', header=None) df.head() #열 이름 지정 df.columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'name'] print(df.head()) #mpg(mile per gallon)를 kpl(kilometer per liter)로 변환(npg_to_kpl = 0.425) mpg_to_kpl = 1.60934/ 3.78541 #mpg 열에 0.425를 곱한 결과를 새로운 열(kpl)에 추가 df['kpl']=df['mpg'] *mpg_to_kpl print(df.head(3)) print('\n') #kpl 열을 소수점 아래 둘째자리에서 반올림 df['kpl'] = df['kpl'].round(2) print(df.head(3)) #자료형 변환 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd #read_csv()함수로 df 생성 df = pd.read_csv('./auto-mpg.csv', header=None) #열 이름 지정 df.columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'name'] #각 열의 자료형 확인 print(df.dtypes) #horsepower 열의 고유값 확인 print(df['horsepower'].unique()) print('\n') #예제 5-9 자료형 변환 #누락 데이터('?') 삭제 import numpy as np df['horsepower'].replace('?',np.nan, inplace=True) # '?'을 np.nan으로 변경 df.dropna(subset=['horsepower'],axis=0, inplace=True) #누락 데이터 행 삭제 df['horsepower'] = df['horsepower'].astype('float') #문자열을 실수형으로 변환 #horsepower 열의 자료형 확인 print(df['horsepower'].dtype) df['origin'].head() #origin 열의 고유값 확인 print(df['origin'].unique()) #정수형 데이터를 문자열 데이터로 변환 df['origin'].replace({1:'USA', 2:'EU', 3:'JPN'}, inplace=True) #origin 열ㄹ의 고유값과 자료형 확인 print(df['origin'].unique()) print(df['origin'].dtypes) #문자열을 범주형으로 변환 df['origin'] = df['origin'].astype('category') print(df['origin'].dtypes) print() #범주형을 문자열로 다시 변환 df['origin'] = df['origin'].astype('str') print(df['origin'].dtypes) #model year 열의 정수형을 범주형으로 변환 print(df['model year'].sample(3)) df['model year'] = df['model year'].astype('category') print(df['model year'].sample(3)) #예제 5-10 데이터 구간 분활 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd import numpy as np #read_csv() 함수로 df 생성 df = pd.read_csv('./auto-mpg.csv', header=None) #열 이름 지정 df.columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'name'] #horsepower 열의 누락 데이터('?')를 삭제하고 실수형으로 변환 df['horsepower'].replace('?',np.nan, inplace=True) #'?'을 np.nan으로 변경 df.dropna(subset=['horsepower'], axis=0, inplace=True) #누락 데이터 행 삭제 df['horsepower'] = df['horsepower'].astype('float') #문자열을 실수형으로 변환 #np.histogram 함수로 3개의 bin 으로 구분할 경계값 리스트 구하기 count, bin_dividers = np.histogram(df['horsepower'], bins=3) print(bin_dividers) #예제 5-10 데이터 구간 분할 #3개의 bin에 이름 지정 bin_names = ['저출력', '보통출력', '고출력'] #pd.cut 함수로 각 데이터를 3개의 bin 에 할당 df['hp_bin'] = pd.cut(x=df['horsepower'], #데이터 배열 bins=bin_dividers, #경계값 리스트 labels = bin_names, #bin 이름 include_lowest=True) #첫 경계값 포함 #horsepower 열 , hp_bin 열의 첫 15행 출력 print(df[['horsepower', 'hp_bin']].head(15)) #예제 5-11 더미변수 #np.histogram 함수로 3개의 bin으로 구분할 경계값의 리스트 구하기 count, bin_dividers = np.histogram(df['horsepower'], bins=3) #3개의 bin에 이름 저장 bin_names = ['저출력', '보통출력', '고출력'] #pd.cut으로 각 데이터를 3개의 bin 에 할당 df['hp_bin'] = pd.cut(x=df['horsepower'], #데이터배열 bins = bin_dividers, #경계값 리스트 labels=bin_names, #bin 이름 include_lowest=True) #첫 경계값 포함 #hp_bin 열의 범주형 데이터를 더미 변수로 변환 horsepower_dummies = pd.get_dummies(df['hp_bin']) print(horsepower_dummies.head(15)) #예제 5-12 원핫인코딩 #sklearn 라이브러리 불러오기 from sklearn import preprocessing #전처리를 위한 encoder 객체 만들기 label_encoder = preprocessing.LabelEncoder() #label encoder 생성 onehot_encoder = preprocessing.OneHotEncoder() #one hot encoder 생성. df['hp_bin'].head() #label encoder 로 문자열 범주를 숫자형 범주로 변환 onehot_labeled = label_encoder.fit_transform(df['hp_bin'].head(15)) print(onehot_labeled) print(type(onehot_labeled)) #2차원 행렬로 변경 onehot_reshaped = onehot_labeled.reshape(len(onehot_labeled), 1) print(onehot_reshaped) print(type(onehot_reshaped)) #희소행렬로 변환 onehot_fitted = onehot_encoder.fit_transform(onehot_reshaped) print(onehot_fitted) print(type(onehot_fitted)) #예제 5-13 정규화 # -*- coding: utf-8 -*- #라이브러리 불러오기 import pandas as pd import numpy as np #read_csv() 함수로 df 생성 df = pd.read_csv('./auto-mpg.csv', header=None) #열 이름 지정 df.columns = ['mpg','cylinders','displacement','horsepower','weight', 'acceleration', 'model year','origin','name'] #horsepower 열의 누락 데이터('?')를 삭제하고 실수형으로 변환 df['horsepower'].replace('?', np.nan, inplace =True) #'?'을 np.nan으로 댗체 df.dropna(subset=['horsepower'],axis=0, inplace=True) #누락 데이터 행 삭제 df['horsepower'] = df['horsepower'].astype('float') #문자열을 실수형으로 변환 #horsepower 열의 통계 요약 정보로 최대값(max)확인 print(df.horsepower.describe()) print('\n') #horsepower 열의 최대값의 절댇값으로 모든 데이터를 나눠서 저장 df.horsepower = df.horsepower/abs(df.horsepower.max()) print(df.horsepower.head()) print('\n') print(df.horsepower.describe()) ```
github_jupyter
# Analysis of how many mice pass *ephys* and other criteria Luigi Acerbi, Apr 2020 (with inputs from Gaelle Chapuis and Anne Urai) This script performs analyses to check how many mice pass the currenty set criterion for ephys. ``` # Generally useful Python packages import numpy as np import pandas as pd import scipy as sp import os, sys, time # Visualization import matplotlib.pyplot as plt # IBL-specific packages import datajoint as dj dj.config['database.host'] = 'datajoint.internationalbrainlab.org' from ibl_pipeline import subject, acquisition, action, behavior, reference, data from ibl_pipeline.analyses.behavior import PsychResults, SessionTrainingStatus from ibl_pipeline.utils import psychofit as psy from ibl_pipeline.analyses import behavior as behavior_analysis ephys = dj.create_virtual_module('ephys', 'ibl_ephys') # Get list of subjects associated to the repeated site probe trajectory from ONE (original snippet from Gaelle Chapuis) from oneibl.one import ONE one = ONE() traj = one.alyx.rest('trajectories', 'list', provenance='Planned', x=-2243, y=-2000, # repeated site coordinate project='ibl_neuropixel_brainwide_01') sess = [p['session'] for p in traj] first_pass_map_repeated = [(s['subject'],s['start_time'][0:10]) for s in sess] all_ephys_sessions = False # Analyze ALL sessions? if all_ephys_sessions: # Download all ephys sessions from DataJoint sess_ephys = (acquisition.Session * subject.Subject * behavior_analysis.SessionTrainingStatus ) & 'task_protocol LIKE "%ephys%"' # & 'task_protocol LIKE "%biased%"' & 'session_start_time < "2019-09-30"') else: # Download only sessions that have the `brainwide` project + where there are ephys data and probe trajectories present # (code snippet from Anne Urai's; see here: https://github.com/int-brain-lab/analysis/blob/master/python/neuron_yield.ipynb) sess_ephys = acquisition.Session * subject.Subject * subject.SubjectLab \ * (acquisition.SessionProject & 'session_project = "ibl_neuropixel_brainwide_01"') \ * behavior_analysis.SessionTrainingStatus \ & ephys.ProbeInsertion & ephys.DefaultCluster.Metrics sess_ephys = sess_ephys.fetch(format='frame').reset_index() df = pd.DataFrame(sess_ephys) ``` The following code computes how many `ephys` sessions are considered `good_enough_for_brainwide_map`: - across *all* ephys sessions; - across the ephys sessions in the first-pass map for the repeated site. ``` session_dates = df['session_start_time'].apply(lambda x : x.strftime("%Y-%m-%d")) # First, count all mice total = len(df.index) good_enough = np.sum(df['good_enough_for_brainwide_map']) prc = good_enough / total * 100 print('Total # of ephys sessions: '+ str(total)) print('Total # of sessions good_enough_for_brainwide_map: ' + str(good_enough) + ' (' + "{:.1f}".format(prc) + ' %)') # Now, consider only mice in the first pass map, repeated site count = 0 for (mouse_name,session_date) in first_pass_map_repeated: tmp = df[(df['subject_nickname'] == mouse_name) & (session_dates == session_date)] count = count + np.sum(tmp['good_enough_for_brainwide_map']) total = len(first_pass_map_repeated) good_enough = count prc = good_enough / total * 100 print('Total # of ephys sessions in first pass map, repeated site: '+ str(total)) print('Total # of sessions good_enough_for_brainwide_map in first pass map, repeated site: ' + str(good_enough) + ' (' + "{:.1f}".format(prc) + ' %)') ``` The following code computes how many sessions are required for a mouse to reach certain levels of training or protocols, in particular: - from `trained` status to `biased` protocol - from `biased` protocol to `ready4ephys` status ``` mice_list = set(df['subject_nickname']) trained2biased = [] biased2ready4ephys = [] for mouse_name in mice_list: subj_string = 'subject_nickname LIKE "' + mouse_name + '"' sess_mouse = (acquisition.Session * subject.Subject * behavior_analysis.SessionTrainingStatus ) & subj_string df1 = pd.DataFrame(sess_mouse) # Find first session of training trained_start = np.argmax(df1['training_status'].apply(lambda x: 'trained' in x)) if 'trained' not in df1['training_status'][trained_start]: trained_start = None # Find first session of biased protocol biased_start = np.argmax(df1['task_protocol'].apply(lambda x: 'biased' in x)) if 'biased' not in df1['task_protocol'][biased_start]: biased_start = None # Find first session of ephys ready4ephys_start = np.argmax(df1['training_status'].apply(lambda x: 'ready4ephys' in x)) if 'ready4ephys' not in df1['training_status'][ready4ephys_start]: ready4ephys_start = None if ready4ephys_start != None: trained2biased.append(biased_start - trained_start) biased2ready4ephys.append(ready4ephys_start - biased_start) trained2biased = np.array(trained2biased) biased2ready4ephys = np.array(biased2ready4ephys) flag = trained2biased > 0 print('# Mice: ' + str(np.sum(flag))) print('# Sessions from "trained" to "biased": ' + "{:.2f}".format(np.mean(trained2biased[flag])) + ' +/- '+ "{:.2f}".format(np.std(trained2biased[flag]))) print('# Sessions from "biased" to "ready4ephys": ' + "{:.2f}".format(np.mean(biased2ready4ephys[flag])) + ' +/- '+ "{:.2f}".format(np.std(biased2ready4ephys[flag]))) ```
github_jupyter
# labels ``` import vectorbt as vbt import numpy as np import pandas as pd from datetime import datetime, timedelta from numba import njit # Disable caching for performance testing vbt.settings.caching['enabled'] = False close = pd.DataFrame({ 'a': [1, 2, 1, 2, 3, 2], 'b': [3, 2, 3, 2, 1, 2] }, index=pd.Index([ datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5), datetime(2020, 1, 6) ])) pos_ths = [np.array([1, 1 / 2]), np.array([2, 1 / 2]), np.array([3, 1 / 2])] neg_ths = [np.array([1 / 2, 1 / 3]), np.array([1 / 2, 2 / 3]), np.array([1 / 2, 3 / 4])] big_close = pd.DataFrame(np.random.randint(1, 10, size=(1000, 1000)).astype(float)) big_close.index = [datetime(2018, 1, 1) + timedelta(days=i) for i in range(1000)] big_close.shape ``` ## Look-ahead indicators ``` print(vbt.FMEAN.run(close, window=(2, 3), ewm=(False, True), param_product=True).fmean) %timeit vbt.FMEAN.run(big_close, window=2) %timeit vbt.FMEAN.run(big_close, window=np.arange(2, 10).tolist()) print(vbt.FMEAN.run(big_close, window=np.arange(2, 10).tolist()).wrapper.shape) print(vbt.FSTD.run(close, window=(2, 3), ewm=(False, True), param_product=True).fstd) %timeit vbt.FSTD.run(big_close, window=2) %timeit vbt.FSTD.run(big_close, window=np.arange(2, 10).tolist()) print(vbt.FSTD.run(big_close, window=np.arange(2, 10).tolist()).wrapper.shape) print(vbt.FMIN.run(close, window=(2, 3)).fmin) %timeit vbt.FMIN.run(big_close, window=2) %timeit vbt.FMIN.run(big_close, window=np.arange(2, 10).tolist()) print(vbt.FMIN.run(big_close, window=np.arange(2, 10).tolist()).wrapper.shape) print(vbt.FMAX.run(close, window=(2, 3)).fmax) %timeit vbt.FMAX.run(big_close, window=2) %timeit vbt.FMAX.run(big_close, window=np.arange(2, 10).tolist()) print(vbt.FMAX.run(big_close, window=np.arange(2, 10).tolist()).wrapper.shape) ``` ## Label generators ``` print(vbt.FIXLB.run(close, n=(2, 3)).labels) %timeit vbt.FIXLB.run(big_close, n=2) %timeit vbt.FIXLB.run(big_close, n=np.arange(2, 10).tolist()) print(vbt.FIXLB.run(big_close, n=np.arange(2, 10).tolist()).wrapper.shape) vbt.FIXLB.run(close['a'], n=2).plot().show_png() print(vbt.MEANLB.run(close, window=(2, 3), ewm=(False, True), param_product=True).labels) %timeit vbt.MEANLB.run(big_close, window=2) %timeit vbt.MEANLB.run(big_close, window=np.arange(2, 10).tolist()) print(vbt.MEANLB.run(big_close, window=np.arange(2, 10).tolist()).wrapper.shape) vbt.MEANLB.run(close['a'], window=2).plot().show_png() print(vbt.LEXLB.run(close, pos_th=pos_ths, neg_th=neg_ths).labels) %timeit vbt.LEXLB.run(big_close, pos_th=1, neg_th=0.5) print(vbt.LEXLB.run(big_close, pos_th=1, neg_th=0.5).wrapper.shape) vbt.LEXLB.run(close['a'], pos_th=1, neg_th=0.5).plot().show_png() print(vbt.TRENDLB.run(close, pos_th=pos_ths, neg_th=neg_ths, mode='Binary').labels) %timeit vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='Binary') print(vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='Binary').wrapper.shape) vbt.TRENDLB.run(close['a'], pos_th=1, neg_th=0.5, mode='Binary').plot().show_png() print(vbt.TRENDLB.run(close, pos_th=pos_ths, neg_th=neg_ths, mode='BinaryCont').labels) %timeit vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='BinaryCont') print(vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='BinaryCont').wrapper.shape) vbt.TRENDLB.run(close['a'], pos_th=1, neg_th=0.5, mode='BinaryCont').plot().show_png() print(vbt.TRENDLB.run(close, pos_th=pos_ths, neg_th=neg_ths, mode='BinaryContSat').labels) %timeit vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='BinaryContSat') print(vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='BinaryContSat').wrapper.shape) vbt.TRENDLB.run(close['a'], pos_th=1, neg_th=0.5, mode='BinaryContSat').plot().show_png() print(vbt.TRENDLB.run(close, pos_th=pos_ths, neg_th=neg_ths, mode='PctChange').labels) %timeit vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='PctChange') print(vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='PctChange').wrapper.shape) vbt.TRENDLB.run(close['a'], pos_th=1, neg_th=0.5, mode='PctChange').plot().show_png() print(vbt.TRENDLB.run(close, pos_th=pos_ths, neg_th=neg_ths, mode='PctChangeNorm').labels) %timeit vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='PctChangeNorm') print(vbt.TRENDLB.run(big_close, pos_th=1, neg_th=0.5, mode='PctChangeNorm').wrapper.shape) vbt.TRENDLB.run(close['a'], pos_th=1, neg_th=0.5, mode='PctChangeNorm').plot().show_png() print(vbt.BOLB.run(close, window=1, pos_th=pos_ths, neg_th=neg_ths).labels) print(vbt.BOLB.run(close, window=2, pos_th=pos_ths, neg_th=neg_ths).labels) %timeit vbt.BOLB.run(big_close, window=2, pos_th=1, neg_th=0.5) %timeit vbt.BOLB.run(big_close, window=np.arange(2, 10).tolist(), pos_th=1, neg_th=0.5) print(vbt.BOLB.run(big_close, window=np.arange(2, 10).tolist(), pos_th=1, neg_th=0.5).wrapper.shape) vbt.BOLB.run(close['a'], window=2, pos_th=1, neg_th=0.5).plot().show_png() ```
github_jupyter
# Performing the Hyperparameter tuning **Learning Objectives** 1. Learn how to use `cloudml-hypertune` to report the results for Cloud hyperparameter tuning trial runs 2. Learn how to configure the `.yaml` file for submitting a Cloud hyperparameter tuning job 3. Submit a hyperparameter tuning job to Cloud AI Platform ## Introduction Let's see if we can improve upon that by tuning our hyperparameters. Hyperparameters are parameters that are set *prior* to training a model, as opposed to parameters which are learned *during* training. These include learning rate and batch size, but also model design parameters such as type of activation function and number of hidden units. Here are the four most common ways to finding the ideal hyperparameters: 1. Manual 2. Grid Search 3. Random Search 4. Bayesian Optimzation **1. Manual** Traditionally, hyperparameter tuning is a manual trial and error process. A data scientist has some intution about suitable hyperparameters which they use as a starting point, then they observe the result and use that information to try a new set of hyperparameters to try to beat the existing performance. Pros - Educational, builds up your intuition as a data scientist - Inexpensive because only one trial is conducted at a time Cons - Requires alot of time and patience **2. Grid Search** On the other extreme we can use grid search. Define a discrete set of values to try for each hyperparameter then try every possible combination. Pros - Can run hundreds of trials in parallel using the cloud - Gauranteed to find the best solution within the search space Cons - Expensive **3. Random Search** Alternatively define a range for each hyperparamter (e.g. 0-256) and sample uniformly at random from that range. Pros - Can run hundreds of trials in parallel using the cloud - Requires less trials than Grid Search to find a good solution Cons - Expensive (but less so than Grid Search) **4. Bayesian Optimization** Unlike Grid Search and Random Search, Bayesian Optimization takes into account information from past trials to select parameters for future trials. The details of how this is done is beyond the scope of this notebook, but if you're interested you can read how it works here [here](https://cloud.google.com/blog/products/gcp/hyperparameter-tuning-cloud-machine-learning-engine-using-bayesian-optimization). Pros - Picks values intelligenty based on results from past trials - Less expensive because requires fewer trials to get a good result Cons - Requires sequential trials for best results, takes longer **AI Platform HyperTune** AI Platform HyperTune, powered by [Google Vizier](https://ai.google/research/pubs/pub46180), uses Bayesian Optimization by default, but [also supports](https://cloud.google.com/ml-engine/docs/tensorflow/hyperparameter-tuning-overview#search_algorithms) Grid Search and Random Search. When tuning just a few hyperparameters (say less than 4), Grid Search and Random Search work well, but when tunining several hyperparameters and the search space is large Bayesian Optimization is best. ``` # Use the chown command to change the ownership of the repository !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Installing the latest version of the package !pip install --user google-cloud-bigquery==1.25.0 ``` **Note**: Restart your kernel to use updated packages. Kindly ignore the deprecation warnings and incompatibility errors related to google-cloud-storage. ``` # Importing the necessary module import os from google.cloud import bigquery # Change with your own bucket and project below: BUCKET = "<BUCKET>" PROJECT = "<PROJECT>" REGION = "<YOUR REGION>" OUTDIR = "gs://{bucket}/taxifare/data".format(bucket=BUCKET) os.environ['BUCKET'] = BUCKET os.environ['OUTDIR'] = OUTDIR os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION os.environ['TFVERSION'] = "2.5" %%bash # Setting up cloud SDK properties gcloud config set project $PROJECT gcloud config set compute/region $REGION ``` ## Make code compatible with AI Platform Training Service In order to make our code compatible with AI Platform Training Service we need to make the following changes: 1. Upload data to Google Cloud Storage 2. Move code into a trainer Python package 4. Submit training job with `gcloud` to train on AI Platform ## Upload data to Google Cloud Storage (GCS) Cloud services don't have access to our local files, so we need to upload them to a location the Cloud servers can read from. In this case we'll use GCS. ## Create BigQuery tables If you haven not already created a BigQuery dataset for our data, run the following cell: ``` bq = bigquery.Client(project = PROJECT) dataset = bigquery.Dataset(bq.dataset("taxifare")) # Creating a dataset try: bq.create_dataset(dataset) print("Dataset created") except: print("Dataset already exists") ``` Let's create a table with 1 million examples. Note that the order of columns is exactly what was in our CSV files. ``` %%bigquery CREATE OR REPLACE TABLE taxifare.feateng_training_data AS SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_datetime, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, 'unused' AS key FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 1000)) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 ``` Make the validation dataset be 1/10 the size of the training dataset. ``` %%bigquery CREATE OR REPLACE TABLE taxifare.feateng_valid_data AS SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_datetime, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, 'unused' AS key FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 10000)) = 2 AND trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 ``` ## Export the tables as CSV files ``` %%bash echo "Deleting current contents of $OUTDIR" gsutil -m -q rm -rf $OUTDIR echo "Extracting training data to $OUTDIR" bq --location=US extract \ --destination_format CSV \ --field_delimiter "," --noprint_header \ taxifare.feateng_training_data \ $OUTDIR/taxi-train-*.csv echo "Extracting validation data to $OUTDIR" bq --location=US extract \ --destination_format CSV \ --field_delimiter "," --noprint_header \ taxifare.feateng_valid_data \ $OUTDIR/taxi-valid-*.csv # List the files of the bucket gsutil ls -l $OUTDIR # Here, it shows the short header for each object !gsutil cat gs://$BUCKET/taxifare/data/taxi-train-000000000000.csv | head -2 ``` If all ran smoothly, you should be able to list the data bucket by running the following command: ``` # List the files of the bucket !gsutil ls gs://$BUCKET/taxifare/data ``` ## Move code into python package Here, we moved our code into a python package for training on Cloud AI Platform. Let's just check that the files are there. You should see the following files in the `taxifare/trainer` directory: - `__init__.py` - `model.py` - `task.py` ``` # It will list all the files in the mentioned directory with a long listing format !ls -la taxifare/trainer ``` To use hyperparameter tuning in your training job you must perform the following steps: 1. Specify the hyperparameter tuning configuration for your training job by including a HyperparameterSpec in your TrainingInput object. 2. Include the following code in your training application: - Parse the command-line arguments representing the hyperparameters you want to tune, and use the values to set the hyperparameters for your training trial. Add your hyperparameter metric to the summary for your graph. - To submit a hyperparameter tuning job, we must modify `model.py` and `task.py` to expose any variables we want to tune as command line arguments. ### Modify model.py ``` %%writefile ./taxifare/trainer/model.py # Importing the necessary modules import datetime import hypertune import logging import os import shutil import numpy as np import tensorflow as tf from tensorflow.keras import activations from tensorflow.keras import callbacks from tensorflow.keras import layers from tensorflow.keras import models from tensorflow import feature_column as fc logging.info(tf.version.VERSION) CSV_COLUMNS = [ 'fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key', ] LABEL_COLUMN = 'fare_amount' DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']] DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] # Splits features and labels from feature dictionary def features_and_labels(row_data): for unwanted_col in ['key']: row_data.pop(unwanted_col) label = row_data.pop(LABEL_COLUMN) return row_data, label # Loads dataset using the tf.data API from CSV files def load_dataset(pattern, batch_size, num_repeat): dataset = tf.data.experimental.make_csv_dataset( file_pattern=pattern, batch_size=batch_size, column_names=CSV_COLUMNS, column_defaults=DEFAULTS, num_epochs=num_repeat, ) return dataset.map(features_and_labels) # Prefetch overlaps the preprocessing and model execution of a training step def create_train_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=None) return dataset.prefetch(1) def create_eval_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=1) return dataset.prefetch(1) # Parse a string and return a datetime.datetime def parse_datetime(s): if type(s) is not str: s = s.numpy().decode('utf-8') return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S %Z") # Here, tf.sqrt Computes element-wise square root of the input tensor def euclidean(params): lon1, lat1, lon2, lat2 = params londiff = lon2 - lon1 latdiff = lat2 - lat1 return tf.sqrt(londiff*londiff + latdiff*latdiff) # Timestamp.weekday() function return the day of the week represented by the date in the given Timestamp object def get_dayofweek(s): ts = parse_datetime(s) return DAYS[ts.weekday()] # It wraps a python function into a TensorFlow op that executes it eagerly @tf.function def dayofweek(ts_in): return tf.map_fn( lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string), ts_in ) def transform(inputs, NUMERIC_COLS, STRING_COLS, nbuckets): # Pass-through columns transformed = inputs.copy() del transformed['pickup_datetime'] feature_columns = { colname: fc.numeric_column(colname) for colname in NUMERIC_COLS } # Scaling longitude from range [-70, -78] to [0, 1] for lon_col in ['pickup_longitude', 'dropoff_longitude']: transformed[lon_col] = layers.Lambda( lambda x: (x + 78)/8.0, name='scale_{}'.format(lon_col) )(inputs[lon_col]) # Scaling latitude from range [37, 45] to [0, 1] for lat_col in ['pickup_latitude', 'dropoff_latitude']: transformed[lat_col] = layers.Lambda( lambda x: (x - 37)/8.0, name='scale_{}'.format(lat_col) )(inputs[lat_col]) # Adding Euclidean dist (no need to be accurate: NN will calibrate it) transformed['euclidean'] = layers.Lambda(euclidean, name='euclidean')([ inputs['pickup_longitude'], inputs['pickup_latitude'], inputs['dropoff_longitude'], inputs['dropoff_latitude'] ]) feature_columns['euclidean'] = fc.numeric_column('euclidean') # hour of day from timestamp of form '2010-02-08 09:17:00+00:00' transformed['hourofday'] = layers.Lambda( lambda x: tf.strings.to_number( tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32), name='hourofday' )(inputs['pickup_datetime']) feature_columns['hourofday'] = fc.indicator_column( fc.categorical_column_with_identity( 'hourofday', num_buckets=24)) latbuckets = np.linspace(0, 1, nbuckets).tolist() lonbuckets = np.linspace(0, 1, nbuckets).tolist() b_plat = fc.bucketized_column( feature_columns['pickup_latitude'], latbuckets) b_dlat = fc.bucketized_column( feature_columns['dropoff_latitude'], latbuckets) b_plon = fc.bucketized_column( feature_columns['pickup_longitude'], lonbuckets) b_dlon = fc.bucketized_column( feature_columns['dropoff_longitude'], lonbuckets) ploc = fc.crossed_column( [b_plat, b_plon], nbuckets * nbuckets) dloc = fc.crossed_column( [b_dlat, b_dlon], nbuckets * nbuckets) pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4) feature_columns['pickup_and_dropoff'] = fc.embedding_column( pd_pair, 100) return transformed, feature_columns # Here, tf.sqrt Computes element-wise square root of the input tensor def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) def build_dnn_model(nbuckets, nnsize, lr): # input layer is all float except for pickup_datetime which is a string STRING_COLS = ['pickup_datetime'] NUMERIC_COLS = ( set(CSV_COLUMNS) - set([LABEL_COLUMN, 'key']) - set(STRING_COLS) ) inputs = { colname: layers.Input(name=colname, shape=(), dtype='float32') for colname in NUMERIC_COLS } inputs.update({ colname: layers.Input(name=colname, shape=(), dtype='string') for colname in STRING_COLS }) # transforms transformed, feature_columns = transform( inputs, NUMERIC_COLS, STRING_COLS, nbuckets=nbuckets) dnn_inputs = layers.DenseFeatures(feature_columns.values())(transformed) x = dnn_inputs for layer, nodes in enumerate(nnsize): x = layers.Dense(nodes, activation='relu', name='h{}'.format(layer))(x) output = layers.Dense(1, name='fare')(x) model = models.Model(inputs, output) lr_optimizer = tf.keras.optimizers.Adam(learning_rate=lr) model.compile(optimizer=lr_optimizer, loss='mse', metrics=[rmse, 'mse']) return model # Define train and evaluate method to evaluate performance of the model def train_and_evaluate(hparams): batch_size = hparams['batch_size'] eval_data_path = hparams['eval_data_path'] nnsize = hparams['nnsize'] nbuckets = hparams['nbuckets'] lr = hparams['lr'] num_evals = hparams['num_evals'] num_examples_to_train_on = hparams['num_examples_to_train_on'] output_dir = hparams['output_dir'] train_data_path = hparams['train_data_path'] if tf.io.gfile.exists(output_dir): tf.io.gfile.rmtree(output_dir) timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') savedmodel_dir = os.path.join(output_dir, 'savedmodel') model_export_path = os.path.join(savedmodel_dir, timestamp) checkpoint_path = os.path.join(output_dir, 'checkpoints') tensorboard_path = os.path.join(output_dir, 'tensorboard') dnn_model = build_dnn_model(nbuckets, nnsize, lr) logging.info(dnn_model.summary()) trainds = create_train_dataset(train_data_path, batch_size) evalds = create_eval_dataset(eval_data_path, batch_size) steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals) checkpoint_cb = callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1) tensorboard_cb = callbacks.TensorBoard(tensorboard_path, histogram_freq=1) history = dnn_model.fit( trainds, validation_data=evalds, epochs=num_evals, steps_per_epoch=max(1, steps_per_epoch), verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch callbacks=[checkpoint_cb, tensorboard_cb] ) # Exporting the model with default serving function. tf.saved_model.save(dnn_model, model_export_path) # TODO 1 hp_metric = history.history['val_rmse'][num_evals-1] # TODO 1 hpt = hypertune.HyperTune() hpt.report_hyperparameter_tuning_metric( hyperparameter_metric_tag='rmse', metric_value=hp_metric, global_step=num_evals ) return history ``` ### Modify task.py ``` %%writefile taxifare/trainer/task.py # Importing the necessary module import argparse import json import os from trainer import model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--batch_size", help = "Batch size for training steps", type = int, default = 32 ) parser.add_argument( "--eval_data_path", help = "GCS location pattern of eval files", required = True ) parser.add_argument( "--nnsize", help = "Hidden layer sizes (provide space-separated sizes)", nargs = "+", type = int, default=[32, 8] ) parser.add_argument( "--nbuckets", help = "Number of buckets to divide lat and lon with", type = int, default = 10 ) parser.add_argument( "--lr", help = "learning rate for optimizer", type = float, default = 0.001 ) parser.add_argument( "--num_evals", help = "Number of times to evaluate model on eval data training.", type = int, default = 5 ) parser.add_argument( "--num_examples_to_train_on", help = "Number of examples to train on.", type = int, default = 100 ) parser.add_argument( "--output_dir", help = "GCS location to write checkpoints and export models", required = True ) parser.add_argument( "--train_data_path", help = "GCS location pattern of train files containing eval URLs", required = True ) parser.add_argument( "--job-dir", help = "this model ignores this field, but it is required by gcloud", default = "junk" ) args, _ = parser.parse_known_args() hparams = args.__dict__ hparams["output_dir"] = os.path.join( hparams["output_dir"], json.loads( os.environ.get("TF_CONFIG", "{}") ).get("task", {}).get("trial", "") ) print("output_dir", hparams["output_dir"]) model.train_and_evaluate(hparams) ``` ### Create config.yaml file Specify the hyperparameter tuning configuration for your training job Create a HyperparameterSpec object to hold the hyperparameter tuning configuration for your training job, and add the HyperparameterSpec as the hyperparameters object in your TrainingInput object. In your HyperparameterSpec, set the hyperparameterMetricTag to a value representing your chosen metric. If you don't specify a hyperparameterMetricTag, AI Platform Training looks for a metric with the name training/hptuning/metric. The following example shows how to create a configuration for a metric named metric1: ``` %%writefile hptuning_config.yaml # Setting parameters for hptuning_config.yaml trainingInput: scaleTier: BASIC hyperparameters: goal: MINIMIZE maxTrials: 10 # TODO 2 maxParallelTrials: 2 # TODO 2 hyperparameterMetricTag: rmse # TODO 2 enableTrialEarlyStopping: True params: - parameterName: lr # TODO 2 type: DOUBLE minValue: 0.0001 maxValue: 0.1 scaleType: UNIT_LOG_SCALE - parameterName: nbuckets # TODO 2 type: INTEGER minValue: 10 maxValue: 25 scaleType: UNIT_LINEAR_SCALE - parameterName: batch_size # TODO 2 type: DISCRETE discreteValues: - 15 - 30 - 50 ``` #### Report your hyperparameter metric to AI Platform Training The way to report your hyperparameter metric to the AI Platform Training service depends on whether you are using TensorFlow for training or not. It also depends on whether you are using a runtime version or a custom container for training. We recommend that your training code reports your hyperparameter metric to AI Platform Training frequently in order to take advantage of early stopping. TensorFlow with a runtime version If you use an AI Platform Training runtime version and train with TensorFlow, then you can report your hyperparameter metric to AI Platform Training by writing the metric to a TensorFlow summary. Use one of the following functions. You may need to install `cloudml-hypertune` on your machine to run this code locally. ``` # Installing the latest version of the package !pip install cloudml-hypertune ``` Kindly ignore, if you get the version warnings related to pip install command. ``` %%bash # Testing our training code locally EVAL_DATA_PATH=./taxifare/tests/data/taxi-valid* TRAIN_DATA_PATH=./taxifare/tests/data/taxi-train* OUTPUT_DIR=./taxifare-model rm -rf ${OUTDIR} export PYTHONPATH=${PYTHONPATH}:${PWD}/taxifare python3 -m trainer.task \ --eval_data_path $EVAL_DATA_PATH \ --output_dir $OUTPUT_DIR \ --train_data_path $TRAIN_DATA_PATH \ --batch_size 5 \ --num_examples_to_train_on 100 \ --num_evals 1 \ --nbuckets 10 \ --lr 0.001 \ --nnsize 32 8 ls taxifare-model/tensorboard ``` The below hyperparameter training job step will take **upto 45 minutes** to complete. ``` %%bash PROJECT_ID=$(gcloud config list project --format "value(core.project)") BUCKET=$PROJECT_ID REGION="us-central1" TFVERSION="2.4" # Output directory and jobID OUTDIR=gs://${BUCKET}/taxifare/trained_model_$(date -u +%y%m%d_%H%M%S) JOBID=taxifare_$(date -u +%y%m%d_%H%M%S) echo ${OUTDIR} ${REGION} ${JOBID} gsutil -m rm -rf ${OUTDIR} # Model and training hyperparameters BATCH_SIZE=15 NUM_EXAMPLES_TO_TRAIN_ON=100 NUM_EVALS=10 NBUCKETS=10 LR=0.001 NNSIZE="32 8" # GCS paths GCS_PROJECT_PATH=gs://$BUCKET/taxifare DATA_PATH=$GCS_PROJECT_PATH/data TRAIN_DATA_PATH=$DATA_PATH/taxi-train* EVAL_DATA_PATH=$DATA_PATH/taxi-valid* # TODO 3 gcloud ai-platform jobs submit training $JOBID \ --module-name=trainer.task \ --package-path=taxifare/trainer \ --staging-bucket=gs://${BUCKET} \ --config=hptuning_config.yaml \ --python-version=3.7 \ --runtime-version=${TFVERSION} \ --region=${REGION} \ -- \ --eval_data_path $EVAL_DATA_PATH \ --output_dir $OUTDIR \ --train_data_path $TRAIN_DATA_PATH \ --batch_size $BATCH_SIZE \ --num_examples_to_train_on $NUM_EXAMPLES_TO_TRAIN_ON \ --num_evals $NUM_EVALS \ --nbuckets $NBUCKETS \ --lr $LR \ --nnsize $NNSIZE ``` Copyright 2021 Google Inc. 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 http://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
github_jupyter
Unsupervised learning means a lack of labels: we are looking for structure in the data, without having an *a priori* intuition what that structure might be. A great example is clustering, where the goal is to identify instances that clump together in some high-dimensional space. Unsupervised learning in general is a harder problem. Deep learning revolutionized supervised learning and it had made significant advances in unsupervised learning, but there remains plenty of room for improvement. In this notebook, we look at how we can map an unsupervised learning problem to graph optimization, which in turn we can solve on a quantum computer. # Mapping clustering to discrete optimization Assume that we have some points $\{x_i\}_{i=1}^N$ lying in some high-dimensional space $\mathbb{R}^d$. How do we tell which ones are close to one another and which ones are distant? To get some intuition, let's generate a simple dataset with two distinct classes. The first five instances will belong to class 1, and the second five to class 2: ``` import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline n_instances = 4 class_1 = np.random.rand(n_instances//2, 3)/5 class_2 = (0.6, 0.1, 0.05) + np.random.rand(n_instances//2, 3)/5 data = np.concatenate((class_1, class_2)) colors = ["red"] * (n_instances//2) + ["green"] * (n_instances//2) fig = plt.figure() ax = fig.add_subplot(111, projection='3d', xticks=[], yticks=[], zticks=[]) ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors) ``` The high-dimensional space is endowed with some measure of distance, the Euclidean distance being the simplest case. We can calculate all pairwise distances between the data points: ``` import itertools w = np.zeros((n_instances, n_instances)) for i, j in itertools.product(*[range(n_instances)]*2): w[i, j] = np.linalg.norm(data[i]-data[j]) ``` This matrix is sometimes called the Gram or the kernel matrix. The Gram matrix contains a fair bit of information about the topology of the points in the high-dimensional space, but it is not easy to see. We can think of the Gram matrix as the weighted adjacency matrix of a graph: two nodes represent two data instances. Their distance as contained in the Gram matrix is the weight on the edge that connects them. If the distance is zero, they are not connected by an edge. In general, this is a dense graph with many edges -- sparsity can be improved by a distance function that gets exponentially smaller. What can we do with this graph to find the clusters? We could look for the max-cut, that is, the collection of edges that would split the graph in exactly two if removed, while maximizing the total weight of these edges [[1](#1)]. This is a well-known NP-hard problem, but it also very naturally maps to an Ising model. The spin variables $\sigma_i \in \{-1, +1\}$ take on value $\sigma_i = +1$ if a data instance is in cluster 1 (nodes $V_1$ in the graph), and $\sigma_i = -1$ if the data instance is in cluster 2 (nodes $V_2$ in the graph). The cost of a cut is $$ \sum_{i\in V_1, j\in V_2} w_{ij} $$ Let us assume a fully connected graph. Then, accounting for the symmetry of the adjacency matrix, we can expand this as $$ \frac{1}{4}\sum_{i, j} w_{ij} - \frac{1}{4} \sum_{i, j} w_{ij} \sigma_i \sigma_j $$ $$ = \frac{1}{4}\sum_{i, j\in V} w_{ij} (1- \sigma_i \sigma_j). $$ By taking the negative of this, we can directly solve the problem by a quantum optimizer. # Solving the max-cut problem by QAOA Most quantum computing frameworks have convenience functions defined for common graph optimization algorithms, and max-cut is a staple. This reduces our task to importing the relevant functions: ``` from qiskit.aqua import get_aer_backend, QuantumInstance from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import COBYLA from qiskit.aqua.translators.ising import max_cut ``` Setting $p=1$ in the QAOA algorithm, we can initialize it with the max-cut problem. ``` qubit_operators, offset = max_cut.get_max_cut_qubitops(w) p = 1 optimizer = COBYLA() qaoa = QAOA(qubit_operators, optimizer, p, operator_mode='matrix') ``` Here the choice of the classical optimizer `COBYLA` was arbitrary. Let us run this and analyze the solution. This can take a while on a classical simulator. ``` backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=1) result = qaoa.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) graph_solution = max_cut.get_graph_solution(x) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', max_cut.get_graph_solution(x)) print('solution objective:', max_cut.max_cut_value(x, w)) ``` Looking at the solution, the cut matches the clustering structure. # Solving the max-cut problem by annealing Naturally, the same problem can be solved on an annealer. Our only task is to translate the couplings and the on-site fields to match the programming interface: ``` import dimod J, h = {}, {} for i in range(n_instances): h[i] = 0 for j in range(i+1, n_instances): J[(i, j)] = w[i, j] model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) print("Energy of samples:") for solution in response.data(): print("Energy:", solution.energy, "Sample:", solution.sample) ``` If you look at the first sample, you will see that the first five data instances belong to the same graph partition, matching the actual cluster. # References [1] Otterbach, J. S., Manenti, R., Alidoust, N., Bestwick, A., Block, M., Bloom, B., Caldwell, S., Didier, N., Fried, E. Schuyler, Hong, S., Karalekas, P., Osborn, C. B., Papageorge, A., Peterson, E. C., Prawiroatmodjo, G., Rubin, N., Ryan, Colm A., Scarabelli, D., Scheer, M., Sete, E. A., Sivarajah, P., Smith, Robert S., Staley, A., Tezak, N., Zeng, W. J., Hudson, A., Johnson, Blake R., Reagor, M., Silva, M. P. da, Rigetti, C. (2017). [Unsupervised Machine Learning on a Hybrid Quantum Computer](https://arxiv.org/abs/1712.05771). *arXiv:1712.05771*. <a id='1'></a>
github_jupyter
``` '''this is a bit of a silly experiment to see what VGG would do given map data (VGG was probably the most successful image recognition neutal net circa 2017) It seems to somewhat think the earth is a coral reef! or maybe a scuba diver! :D this is not all silliness as we can use VGG for 'transfer learning', wherein we can either (a) train a new model starting from VGG or (b) use the first few layers of VGG to compue some more features which we can use in a classical classifer like gradient boost. ''' # please note I havent done a great job of commenting this yet. # more info at: # https://keras.io/api/applications/vgg/#vgg16-function # https://keras.io/guides/transfer_learning/#do-a-round-of-finetuning-of-the-entire-model # https://ai-pool.com/d/keras-get-layer-of-the-model # https://machinelearningmastery.com/how-to-use-transfer-learning-when-developing-convolutional-neural-network-models/ # https://www.tensorflow.org/api_docs/python/tf/keras/applications/vgg16/preprocess_input from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import preprocess_input import numpy as np Vmodel = VGG16(weights='imagenet', include_top=True) Vmodel.summary() input = Vmodel.get_layer('input_2') layer1 = Vmodel.get_layer('block1_conv1') layer2 = Vmodel.get_layer('block1_conv2') import tensorflow.keras as keras model = keras.Sequential([input, layer1, layer2]) layer1.trainable = False layer2.trainable = False !pip install git+https://github.com/NSCC-COGS/Aestheta.git from aestheta import core a = core.getTile(source='google_sat') # a = core.getTile(xyz=[2.3522,48.8566,10], source='google_sat') # a = core.getTile(xyz=[-63.2,45.8566,10], source='google_sat') print(a.shape) import tensorflow as tf a1=a[0:224,0:224,:] a1 = a1.reshape((1, a1.shape[0], a1.shape[1], a1.shape[2])) a2 = tf.keras.applications.vgg16.preprocess_input(a1) b = Vmodel.predict(a2) label = tf.keras.applications.vgg16.decode_predictions(b) print(label) from matplotlib import pyplot as plt plt.imshow(a) plt.show() for i in label[0]: print(i[1],i[2]) # https://stackoverflow.com/questions/41711190/keras-how-to-get-the-output-of-each-layer from keras.models import Model layer_name = 'block1_conv1' model = Vmodel intermediate_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output) intermediate_output = intermediate_layer_model.predict(a2) # for i in range(intermediate_output.shape[3]): # plt.imshow(intermediate_output[0,:,:,i]) # plt.show() intermediate_output.shape big = intermediate_output[0] big.shape def img2features(img): features = img.reshape(-1, img.shape[2]) return features big_features = img2features(big) big_features # https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60 from sklearn.decomposition import PCA pca = PCA(n_components=3) pca_features = pca.fit_transform(big_features) pca_features.shape def features2img(features): img = features.reshape(224,224,3) return img pca_image = features2img(pca_features) plt.imshow(pca_image[:,:,:]) pca_image.shape map = core.getTile(source='google_map') intermediate_output.shape avgg = intermediate_output[0,:,:,:] map.shape mvgg = map[0:224,0:224,:] amod = core.simpleClassifier(avgg, mvgg) ns = [45.5,-63.5,19] ns = [44.6488, -63.5752,6] ns = [44.247682, -66.355587,10] zoom = core.getTile(ns, 'google_sat') zoom = zoom[0:224,0:224,:] plt.imshow(zoom) z=zoom[0:224,0:224,:] z = z.reshape((1, z.shape[0], z.shape[1], z.shape[2])) z = tf.keras.applications.vgg16.preprocess_input(z) z = intermediate_layer_model.predict(z)[0] z.shape outz = core.classifyImage(z,*amod) plt.imshow(outz) outvgg = core.classifyImage(avgg,*amod) plt.imshow(outvgg) plt.show() ```
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np import pandas as pd import time df_master = pd.read_csv('PGCB_Demand_Data_2021.csv',parse_dates=True,index_col='date') df_master.head(24) df_master.info() def plot_daily_demand(df,y): ''' It returns the daily load demand vs hour for a specific year. df = dataframe y = year ''' monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'} dfx = df.loc[df.year==y] for i,m in enumerate(set(dfx.month)): if m in set(dfx.month): dfxx = dfx.loc[dfx.month==m] #print(monthDict[m],end=' ') for d in range(1,31): if d in set(dfxx.day): #print(d) dfxxx = dfxx.loc[dfxx.day==d] ttl = str('Year: '+str(y)+' Month: '+str(monthDict[m])+' '+str(d)) plt.figure(ttl) plt.plot(dfxxx.hour,dfxxx.demand) #print(dfxxx) plt.title(ttl) # plot_daily_demand(df_master,2018) df_master.shape D_max_daily = df_master.groupby('date').demand.max().to_numpy() D_max_daily #normalizing load value D_max = max(D_max_daily) D_max df = df_master.demand/D_max df Y = np.array(df) Y df_master.head() X = df_master[['month','day','weekday','hour']] X = X.values # add season and festival info to the dataset import datetime iter_date = datetime.date(2018, 1, 1) season = np.zeros((24*1170,)) festival = np.zeros((24*1170,)) for i in range(1170): month = iter_date.month day = iter_date.day for j in range(24): if (month==4) | (month==5) | ((month==3) and (day>7)) | ((month==6) and (day<8)): season[i*24 + j] = 0 #spring elif (month==7) | (month==8) | ((month==6) and (day>7)) | ((month==9) and (day<8)): season[i*24 + j] = 1 #summer elif (month==10) | (month==11) | ((month==9) and (day>7)) | ((month==12) and (day<8)): season[i*24 + j] = 2 #autumn elif (month==1) | (month==2) | ((month==12) and (day>7)) | ((month==3) and (day<8)): season[i*24 + j] = 3 #winter if (month == 7) and (day == 4): festival[i*24 + j] = 1 if (month == 11) and (iter_date.weekday() == 4) and (day + 7 > 30): festival[i*24 + j] = 1 if (month == 12) and (day == 25): festival[i*24 + j] = 1 iter_date = iter_date + datetime.timedelta(1) festival season = np.reshape(season,(season.shape[0],1)) X_data = np.append(X,season,axis=1) X X = np.reshape(X_data,(X_data.shape[0],1,X_data.shape[1])) X.shape # Split the training dataset in 80% / 20% from sklearn.model_selection import train_test_split #dataset splitted into train,val,test as 64%,16%,20% X_train,X_test,Y_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_train,Y_train,test_size=0.2, random_state=42) X_test.shape X_train.shape[1] from keras.models import Sequential from keras.layers import Conv1D, Dropout, Dense, Flatten, LSTM, MaxPooling1D, Bidirectional,GRU from keras.optimizers import Adam from keras.callbacks import EarlyStopping, TensorBoard from keras.layers import TimeDistributed # define LSTM model = Sequential() model.add(LSTM(40, input_shape=(1,5),kernel_initializer='uniform', return_sequences=True)) #input shape (1,5) to (1,6) model.add(LSTM(40,kernel_initializer='uniform', activation='selu')) model.add(Dropout(0.1, input_shape=(40,))) # model.add(Dense(20, activation='selu')) model.add(Dense(1, activation='selu')) opt = Adam(learning_rate=0.001) model.compile(loss='mean_absolute_percentage_error', optimizer=opt, metrics=['accuracy']) model.summary() start_time = time.time() history = model.fit(X_train, Y_train, epochs=100, shuffle=True, batch_size=18,validation_data=(X_val,Y_val)) finish_time = time.time() print("--- %s seconds ---" % (finish_time - start_time)) print((finish_time - start_time)/60,'minutes') loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot([i for i in range(len(loss))],loss) plt.plot([i for i in range(len(val_loss))],val_loss) plt.legend(['train loss','validation loss']) scores = model.evaluate(X_test, Y_test) print("TEST MAPE :",scores[0]) scores def give_daily_demand(df,y): ''' It returns the daily load demand vs hour for a specific year. df = dataframe y = year ''' monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'} dfx = df.loc[df.year==y] for i,m in enumerate(set(dfx.month)): if m in set(dfx.month): dfxx = dfx.loc[dfx.month==m] #print(monthDict[m],end=' ') for d in range(1,31): if d in set(dfxx.day): #print(d) dfxxx = dfxx.loc[dfxx.day==d] ttl = str('Year: '+str(y)+' Month: '+str(monthDict[m])+' '+str(d)) #plt.figure(ttl) #plt.plot(dfxxx.hour,dfxxx.demand) #print(dfxxx) #plt.title(ttl) return dfxxx,ttl dfxxx,ttl = give_daily_demand(df_master,2019) print(dfxxx) print(ttl) test_y = [] true_y = [] for i in range(48,24*3): test = X[i] true_y.append(Y[i]*D_max) test = test.reshape(1,1,5) y = model.predict(test) test_y.append(y[0][0]*D_max) plt.plot(test_y) plt.plot(true_y) plt.legend(['PREDICTED','ACTUAL']) y_pred=model.predict(X_test) y_pred.shape # Y_test.shape y_pred.shape Y_test.shape from sklearn.metrics import accuracy_score y_pred.shape Y_test.shape # Y_test=Y_test.reshape(5616,1) X_test.shape y_pred=model.predict(X_test) y_pred.shape Y_test=Y_test.reshape(5616,1) Y_test.shape plt.plot(y_pred[48:24*3]) plt.plot(Y_test[48:24*3]) plt.legend(['PREDICTED(LSTM with Y_train)','ACTUAL']) nsamples, nx, ny = X_train.shape d2_train_dataset = X_train.reshape((nsamples,nx*ny)) from sklearn.ensemble import RandomForestRegressor cls = RandomForestRegressor( random_state = 0) cls.fit(d2_train_dataset,Y_train) nsamples, nx, ny = X_test.shape d2_test_dataset = X_test.reshape((nsamples,nx*ny)) sk_pred=cls.predict(d2_test_dataset) plt.plot(sk_pred[48:24*3]*D_max) plt.plot(Y_test[48:24*3]*D_max) plt.legend(['PREDICTED(RF)','ACTUAL']) # scores(d2_test_dataset,Y_test) cls.feature_importances_ importance = cls.feature_importances_ # summarize feature importance for i,v in enumerate(importance): print('Feature: %0d, Score: %.5f' % (i,v)) importance.shape from matplotlib import pyplot pyplot.bar([x for x in range(len(importance))], importance) pyplot.show() cls.feature_importances_ import sklearn.metrics MAPE_RF=mean_absolute_percentage_error(Y_test,sk_pred) MAPE_RF cls.score(d2_test_dataset,Y_test) mean_absolute_percentage_error(Y_test,sk_pred) plt.plot(sk_pred[48:24*3]) plt.plot(y_pred[48:24*3]) plt.plot(Y_test[48:24*3]) plt.legend(['PREDICTED(RF)','PREDICTED(LSTM)','ACTUAL']) ```
github_jupyter
# Sesion 4 : ## - Biblioteca de Pandas ## - Dataframes de Pandas ########################################################## ## 1. Biblioteca de Pandas Pandas es una biblioteca de Python de análisis y manipulación de datos de alto rendimiento. Define nuevas estructuras de datos basadas en los arrays de la librería NumPy pero con nuevas funcionalidades. Lo que hace que pandas sea tan atractivo es la potente interfaz para acceder a registros individuales de la tabla, el manejo adecuado de valores perdidos y las operaciones de bases de datos relacionales entre DataFrames. [Biblioteca Pandas](https://pandas.pydata.org/docs/user_guide/10min.html) ``` ### Dos tipos de datos importantes definidos por pandas son Series y DataFrame. Puede pensar en una serie como una “columna” de datos, como una colección de observaciones sobre una sola variable. Un DataFrame es un objeto para almacenar columnas de datos relacionadas. # 1. Importa la biblioteca Pandas import pandas as pd # 2. Lea un archivo de datos de valores separados por comas (CSV) con pd.read_csv # Asigne el resultado a una variable llamada "data" para almacenar los datos que se leyeron. # La variable data sera nuestra DataFrame data = pd.read_csv('data/gapminder_gdp_oceania.csv') print(data) ``` * Si los datos se encuentran en un fichero o base de datos se deben usar las funciones propias como read_csv, read_excel, read_json o read_html segun corresponda. * Las columnas en un dataframe son las variables observadas, y las filas son las observaciones. * Pandas usa la barra invertida \ para mostrar líneas ajustadas cuando la salida es demasiado ancha para caber en la pantalla. ### Archivo no encontrado Estas lecciones almacenan sus archivos de datos en un subdirectorio data, razón por la cual la ruta al archivo es data/gapminder_gdp_oceania.csv. Si olvida incluir data/,**o si lo incluye pero su copia del archivo está en otro lugar**, obtendrá un runtime error que termina con una línea como esta: ``` data = pd.read_csv('gapminder_gdp_oceania.csv') print(data) ``` ### Utiliza index_col para especificar los valores de que columna deben usarse como fila de encabezado. * Los encabezados de fila son números (0 y 1 en este caso). * Indexar por país. ``` # 3. Pase el nombre de la columna a read_csv como su parámetro index_col (el indice de la tabla) data = pd.read_csv('data/gapminder_gdp_oceania.csv', index_col='country') print(data) ``` ### Utiliza DataFrame.info para obtener más información sobre un dataframe. * Para crear un DataFrame se usa la función constructora DataFrame() a la que se le proporciona una lista o diccionario con los datos a introducir. ``` # 4. Obtinene informacion del DataFrame "data" usando DataFrame.info data.info() ``` * Este es un DataFrame * Dos filas llamadas 'Australia' y 'Nueva Zelanda' * Doce columnas, cada una de las cuales tiene dos valores de punto flotante de 64 bits. * Más adelante hablaremos de valores nulos, que se utilizan para representar observaciones faltantes. * Utiliza 208 bytes de memoria. ### El atributo DataFrame.shape muestra la forma de la matriz: ``` # Mostrar el numero de filas y columnas que tiene el DataFrame "data' data.shape ``` ### El atributo DataFrame.columns registra información sobre las columnas del dataframe. ``` # 5. Mostrar las informaciones de columnas y de indice. data.columns # data.index # valor vinculado a una fila ``` * Ten en cuenta que se trata de datos, no de un método. * Por lo tanto, no uses () para intentar llamarlo. ### Utiliza DataFrame.T para transponer el dataframe. * A veces se quiere tratar las columnas como filas y viceversa. * La transposición (escrita como .T) no copia los datos, solo cambia la vista del programa. * Al igual que columns, es una variable miembro. ``` # 6. Transpone el DataFrame con DataFrame.T print(data.T) ``` ### Utiliza DataFrame.describe para obtener estadísticas resumidas sobre los datos. * DataFrame.describe() obtiene las estadísticas de resumen de solo las columnas que tienen datos numéricos. Todas las demás columnas se ignoran, a menos que use el argumento include = 'all'. * No es particularmente útil con solo dos registros, pero muy útil cuando hay miles. ``` # 7. Obtiene estadisticas resumidas de america con DataFrame.describe print(data.describe()) ``` ### Ejercicio: Lectura de otros datos Lea los datos en gapminder_gdp_americas.csv (que debe estar en el mismo directorio que gapminder_gdp_oceania.csv) en una variable llamada americas y muestra sus estadísticas de resumen. ``` # 1. import pandas as pd import pandas as pd # 2. Lea un archivo de datos de valores separados por comas (CSV) con pd.read_csv('data/gapminder_gdp_americas.csv') # Asigne el resultado a una variable "america" para almacenar los datos que se leyeron # 3. Pase el nombre de la columna a read_csv como su parámetro index_col='country' # 4. Obtinene informacion del DataFrame america con DataFrame.info() # Muestra la forma de america usando DataFrame.shape # 5. Muestra las informaciones de columnas y de indice. # 6. Transpone el DataFrame usando DataFrame.T # 7. Obtiene estadisticas resumidas de america usando DataFrame.describe ``` ### DataFrame.head() * Podemos ver las primeras cinco filas de america ejecutando americas.head(). Podemos especificar el número de filas que deseamos ver especificando el parámetro n en nuestra llamada a americas.head(). ``` # 8. Ejecute las primeras tres filas de america usando dataframe.head(n=3) america.head(n=3) ``` ### DataFrame.tail() * Para ver las últimas tres filas de america, usaríamos el comando americas.tail (n = 3) , análogo a head () usado anteriormente. Sin embargo, aquí queremos ver las últimas tres columnas, que necesitamos para cambiar nuestra vista y luego usar tail(). Para hacerlo, creamos un nuevo DataFrame en el que las filas y las columnas se cambian. ``` # 9. Ejecute las ultimas tres filas del DataFrame dataframe.head(n=3) # Creamos un nuevo DataFrame en el que las filas y las columnas se cambian usando DataFrame.T america_volteado = america.T america_volteado.T.tail(n=3) ``` ### Ejercicio Los datos de su proyecto actual se almacenan en un archivo llamado microbes.csv, que se encuentra en una carpeta llamada field_data. Estás haciendo un análisis en un cuaderno llamado analysis.ipynb en una carpeta llamada tesis: ¿Qué valor(es) debe pasar a read_csv para leer microbes.csv en analysis.ipynb? ## 2. DataFrames de Pandas ### DataFrame * Un DataFrame es una colección de Series; es una estructura de datos tabulares que se compone de columnas y filas ordenadas. * El DataFrame es la manera en que pandas representa una tabla y una Serie es la estructura de datos que usa Pandas para representar una columna. * Representa, ni más ni menos, a la típica tabla de datos de dos dimensiones, con filas y columnas. Además, cada fila y cada columna puede tener, opcionalmente, su nombre o etiqueta. ### Seleccionando valores Para acceder a un valor en la posición [i, j] de un DataFrame, tenemos dos opciones, dependiendo de cuál es el significado de i en uso. Recuerda que un DataFrame proporciona un índex como una forma para identificar las filas de la tabla; Una fila, entonces, tiene una posición dentro de la tabla, así como una etiqueta, que identifica de forma única su entrada en el DataFrame. ### Usa DataFrame.iloc[..., ...] para seleccionar valores por su (entrada) posición. * Puedes identificar la posicion por un indice numerico ``` # import pandas as pd data = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') print(data) print(data.iloc[0, 0]) print(data.iloc[0, 0]) ``` ### Usa DataFrame.loc[.., ..] para seleccionar valores por su (entrada) etiqueta. * Puedes especificar la posición por el nombre de la fila. ``` data = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') print(data.loc["Albania", "gdpPercap_1952"]) ``` ### Usa : para referirte a todas las columnas o todos los renglones. * Al igual que la notación de segmentación habitual de Python. ``` print(data.loc["Albania", :]) # Podría dar el mismo resultado imprimiendo data.loc["Albania"] # Otro ejemplo print(data.loc[:, "gdpPercap_1952"]) #Podría dar el mismo resultado imprimiendo data["gdpPercap_1952"] # También puede dar el mismo resultado imprimiendo data.gdpPercap_1952 # No recomendado, porque es fácil confundir con la notación . ``` ### Selecciona multiples columnas o filas usando DataFrame.loc y un segmento con nombre. ``` data = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country') print(data) print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972']) ``` ### El Resultado de los cortes pueden ser usados en otras operaciones. * Usualmente no solo imprimimos un corte. * Todos los operadores estadísticos que trabajan sobre DataFrames completos. trabajan de igual manera sobre los cortes. ``` # Por ejemplo, calcular el max de un corte print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'].max()) # Calcular el min de un corte print(data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'].min()) ``` ### Usa compariciones para seleccionar datos basados en el valor. * La comparación es aplicada elemento por elemento. * Regresa un DataFrame con una forma similar de True y False. ``` # Usa un subconjunto de datos para mantener la salida legible. subset = data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972'] print('Subconjunto de datos:\n', subset) # Cuales valores son más grandes que 10000 ? print('\nDonde están los valores grandes?\n', subset > 10000) #Operador Logico ``` * Verdadero se refiere a los elementos que satisfacen la condición (mayores de 10000), y Falso se refiere a los elementos que no satisfacen la condición. ### Selecciona valores o NaN usando una máscara Booleana. * Mask, Básicamente, funciona con una lista de valores booleanos (verdadero / falso), que cuando se aplica a la matriz original devuelve los elementos de interés. * Obtendras el valor donde la máscara es verdadera y NaN (no es un número) donde es falsa * Esto es útil porque los NaNs son ignorados por operadores como max, min, average, etc. ``` mask = subset > 10000 print(subset[mask]) #resumen stadistico print(subset[subset > 10000].describe()) ``` ## Group By: cortar-aplicar-combinar * Los métodos de vectorización de pandas y las operaciones de agrupación son características que brindan a los usuarios mucha flexibilidad para analizar sus datos. * Por ejemplo, supongamos que queremos tener una visión más clara de cómo los países europeos se dividen según su PIB (GDP). 1. Podemos echar un vistazo dividiendo los países en dos grupos durante los años encuestados, aquellos que presentaron un PIB más alto que el promedio europeo y aquellos con un PIB más bajo. 2. Luego estimamos un puntaje de Riqueza basado en los valores históricos (de 1962 a 2007), donde contamos cuántas veces un país ha participado en los grupos de PIB más bajo o más alto ``` # Crea mask _higher para otorgar un valor falso o verdadero # para aquellos paises que presentaron un PIB más alto que el promedio europeo # y aquellos con un PIB más bajo. mask_higher = data > data.median() print(mask_higher) pd.Series([True, True, False, False]).count() pd.Series([True, True, False, False]).aggregate("sum") # Crea la variable wealth_score para estimar un puntaje de Riqueza basado en los valores históricos (de 1962 a 2007) # donde contamos cuántas veces un país ha participado en los grupos de PIB más bajo o más alto. wealth_score = mask_higher.aggregate("sum", axis=1) / len(data.columns) print(wealth_score) ``` * El resultado muestra el Promedio de cuantas veces el pais observado ha estado en el grupo de los paises mas ricos * Donde 1 significa que ha estado todas las veces y 0 ni una sola vez. Finalmente, para cada grupo en la tabla wealth_score , nosotros sumamos sus contribuciones (financieras) a través de los años encuestados: ``` """ for x in data.groupby(wealth_score): print(x) print("="*80) """; data.groupby(wealth_score).sum() ``` * Se ha agrupado los datos segun el score de riqueza. ### Puntos claves * Biblioteca Pandas * Usa DataFrame.iloc[...,...]para seleccionar valores por su localización entera * Usa : solo, para referirte a todas las columnas o a todos los renglones * Selecciona múltiples columnas o filas usando DataFrame.loc y un segmento con nombre. * El resultado de cortar puede ser usado en operaciones adicionales * Usa comparaciones para seleccionar datos basados en un valor * Selecciona valores de NaN usando mascaras booleanas
github_jupyter
As this is currently still in a proof-of-concept phase, only a subset of Vital data structures and algorithms are available via the Python interface, and yet also limited in functionality within Python (e.g. only simple data accessors and manipuators are available. ## Setting up the environment In order to access and use the Vital python interface: * When configuring the Kwiver build with CMake, enable `KWIVER_ENABLE_C_BINDINGS`, `KWIVER_ENABLE_PYTHON`, and `KWIVER_BUILD_SHARED`. * Source the setup_KWIVER.sh file in the build or installation directory, whichever is relevant. The module find_vital_library.py uses LD_LIBRARY_PATH to search for the vital_c library. # Introduction Vital now supports an initial Python interface via a C interface library. This iPython notebook intends to introduce this interface and provide a simple demonstration of its use and capability in its current state. Before interacting with the Vital python bindings, the Vital common setup script should be sourced. When working with the bindings while in the source tree, a setup script may be sourced in <SOURCE>/vital/bindings/python/setup_vital_python.sh This simply adds that containing directory to the PYTHON_PATH. A Windows equivalent batch script will be provided in the future. ### Unit Tests Tests for the python interface are available in <SOURCE>/vital/bindings/python/vital/tests/ and require the `nose` python package. To run: $ nosetests ./vital/bindings/python/vital/tests ## Using the Vital Python Interface The Vital Python interface is very similar to the C++ interface, with a slight difference in how algorithms are treated. Altogether, the Vital Python module primarily consists of a collection of data structures and a collection of algorithms types. ### Importing Vital Once the environment is setup Vital is imported under the name `vital` ``` # Importing Vital Python module import vital print vital ``` ### Data structures The data structures provided in the Python interface are intended to provide the same functions as their C++ counter parts but maintain pythonic design and interaction. Most data structures are importable, for convenience, in the root vital module. **NOTE:** Currently, the only data structure that is 100% implemented (compared to the source data structure in C++) is the config_block structue (the VitalConfigBlock class in Python). Other data structures in the Python interface are only partially implemented in support of the currently implemented algorithms. Currently implemented data structures (in whole or part): * algorithm_plugin_manager * camera * camera_map * config_block (complete interface) * image * image_container * track * track_set #### Example: Using the ConfigBlock ``` # ConfigBlock is imported during the vital import. # Creating an empyty config block: cb = vital.ConfigBlock("SomeNameNotRequired") print "empty ConfigBlock keys", cb.available_keys() # an empty list cb.set_value('foobar', 'true') print "updated ConfigBlock keys", cb.available_keys() # Now has one element, 'foobar' print "value of 'foobar':", cb.get_value('foobar') # Get string value # This happens to be a valid boolean string, so we can get it as a boolean value, too if cb.get_value_bool('foobar'): print "foobar is on (%s)" % cb.get_value_bool('foobar') else: print "foobar is off (%s)" % cb.get_value_bool('foobar') ``` ### Error Handling The C interface implements an error handle structure, which many functions take in and set, in case an exception is thrown in the C++ code. When an exception is detected, a non-zero error code is set. The Python interface uses these handles to propagate any errors that occur in the C/C++ code (aside from unavoidable things like segfaults) as raised exceptions in Python. While there is a catch-all return code and Python exception class for generic errors, specific Python exception classes may be associated to specific return codes on a per-function basis for more fine-grained exception handling. #### Example: C++ exceptions translated to Python Config blocks may be read from file. If constructed from a file that doesn't exist, the C++ interface would throw an exception. This is also the case in the Python interface due to automatic error propagation, which happens to be a specific exception class due to the Python implementation knowing that the C interface will return different error codes for specific errors. ``` from vital import ConfigBlock from vital.exceptions.config_block_io import VitalConfigBlockIoFileNotFoundException try: cb = ConfigBlock.from_file("/This/is/probably/not/a/file/on/your/disk.lalalalala") except VitalConfigBlockIoFileNotFoundException as err: print "Exception caught:", err ``` Other functions may only throw the generic base VITAL Python exception due to a current lack of implementation on the Python side, or the C interface does not yet return fine-grained error codes. ``` from vital.types import TrackSet from vital.exceptions.base import VitalBaseException # An empty track set ts = TrackSet() try: ts.write_tracks_file("not_enough_tracks.txt") except VitalBaseException as err: print "Exception caught:", err ``` ### Plugin Management Just as in C++, we need to load the dynamic plugins before we can instantiate abstract algorithms with concrete instances. In Python this is done via the `vital.apm` module. In order for plugins to be picked up, the environment variable ``KWIVER_PLUGIN_PATH`` should be set to a colon separated sequence of directories to look in. In the below example, we set the path to point to a build of MAP-Tk's built plugin libraries. ``` import os from vital import apm # os.environ['KWIVER_PLUGIN_PATH'] = '/home/purg/dev/maptk/build-dev_ocv_3.x/lib/maptk' # OR apm.add_search_path( '/home/purg/dev/maptk/build-dev_ocv_3.x/lib/maptk' ) # Nothing registered initially: print "Initially registered modlues:", apm.registered_module_names() # Register an invalid specific module: apm.register_plugins("vital_core") print "Single module registration:", apm.registered_module_names() # Register a valid specific module: apm.register_plugins("maptk_core_plugin") print "Single module registration:", apm.registered_module_names() # Register all available modules (recommended, thread-safe): print "Reg all once:", apm.register_plugins_once() print "All available modules:", apm.registered_module_names() ``` **NOTE:** It is possible to compile the VITAL system statically, but the C interface libraray dynamically. In this case, dynamic plugins are not supported. It is still required to call `VitalAlgorithmPluginManager.register_plugins` to register available algorithm implementations, however the system will only register those implementations that have been baked into the libraries at compile time. Be aware that in this case no modules will be reported as registered via the ` VitalAlgorithmPluginManager.registered_module_names()` method even when algorithm implementations are actually registered. ### Algorithms In the C++ interface, abstract algorithms are defined, but need to be instantiated with concrete derived algorithms provided by the plugins. Static member functions on abstract base class for each algorithm can list the loaded algorithm implementations by name and create an instance of any implementaiton by string name. In the Python interface, each algorithm class represents one of the C++ declared algorithm definition types. They act like a shared pointer would in the C++ interface. #### Undefined Algorithm Instances All algorithm instances must be named (a configuration requirement) and can be initially created with an undefined implementation type, or with a specific implementation. Valid implementation names (types) are determined by what plugins are loaded at the time of instance construction. When undefined, a call to the `impl_name()` instance method returns None, and calls to implementation methods raise an exception stating that we cannot operate on a null pointer. ``` from vital.algo import ImageIo from vital.exceptions.base import VitalBaseException iio = ImageIo('algo_name') print "iio implementation name:", iio.impl_name() try: iio.load('foo.jpg') except VitalBaseException as err: print err ``` #### Instantiating Algorithm Implementations When using algorithm instances interactively, available implementations can be viewed via the `registered_names()` class method. ``` ImageIo.registered_names() ``` If a specific implementation is known, it may be initialized via the ` create(...)` class method, or by VitalConfigBlock configuration. ``` # Directly creating a new algorithm via implementation name iio_ocv = ImageIo.create("iio_ocv", "ocv") print "Created Implementation type:", iio_ocv.impl_name() ``` #### Configuring an Algorithm via ConfigBlock ``` iio = ImageIo('iio') # and unconfigured image_io algorithm cb = iio.get_config() # get the configuration # iio.impl_name() == None print cb.as_string() # To see the current configuration cb.set_value('iio:type', 'ocv') iio.set_config(cb) print "Using Image IO implementation:", iio.impl_name() print iio.get_config().as_string() ``` #### A More Interesting Configuration Example ``` from vital.algo import TrackFeatures tracker = TrackFeatures.create("tracker", "core") print tracker.get_config().as_string() cb = tracker.get_config() cb.set_value("tracker:core:descriptor_extractor:type", "ocv_SURF") tracker.set_config(cb) print tracker.get_config().as_string() cb = tracker.get_config() surf_cb = cb.subblock_view("tracker:core:descriptor_extractor:ocv_SURF") print "Before:" print surf_cb.as_string() print "----------------" surf_cb.set_value("upright", True) surf_cb.set_value("hessian_threshold", 750) print "After:" print surf_cb.as_string() print "----------------" tracker.set_config(cb) print tracker.get_config().as_string() ``` ## Future Work Going forward, the following should be achieved: * Finish interfacing remaining Vital data structures and structure APIs * Allow further access to underlying data, including using Numpy to represent data arrays and matricies. * Allow algorithm implementations in Python that are then generally usable within the Vital system via a Python algorithm plugin.
github_jupyter
# SGDRegressor with StandardScaler & Power Transformer This Code template is for regression analysis using the SGDRegressor where rescaling method used is StandardScaler and feature transformation is done using PowerTransformer. ### Required Packages ``` import warnings import numpy as np import pandas as pd import seaborn as se import matplotlib.pyplot as plt from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler, PowerTransformer from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error from sklearn.linear_model import SGDRegressor warnings.filterwarnings('ignore') ``` ### Initialization Filepath of CSV file ``` #filepath file_path= "" ``` List of features which are required for model training. ``` #x_values features=[] ``` Target feature for prediction. ``` #y_value target='' ``` ### Data Fetching Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. ``` df=pd.read_csv(file_path) df.head() ``` ### Feature Selections It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model. We will assign all the required input features to X and target/outcome to Y. ``` X=df[features] Y=df[target] ``` ### Data Preprocessing Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. ``` def NullClearner(df): if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])): df.fillna(df.mean(),inplace=True) return df elif(isinstance(df, pd.Series)): df.fillna(df.mode()[0],inplace=True) return df else:return df def EncodeX(df): return pd.get_dummies(df) ``` Calling preprocessing functions on the feature and target set. ``` x=X.columns.to_list() for i in x: X[i]=NullClearner(X[i]) X=EncodeX(X) Y=NullClearner(Y) X.head() ``` #### Correlation Map In order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. ``` f,ax = plt.subplots(figsize=(18, 18)) matrix = np.triu(X.corr()) se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix) plt.show() ``` ### Data Splitting The train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data. ``` x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) ``` ### Model Stochastic Gradient Descent (SGD) is a simple yet very efficient approach to fitting linear classifiers and regressors under convex loss functions such as (linear) Support Vector Machines and Logistic Regression. SGD is merely an optimization technique and does not correspond to a specific family of machine learning models. It is only a way to train a model. Often, an instance of SGDClassifier or SGDRegressor will have an equivalent estimator in the scikit-learn API, potentially using a different optimization technique. For example, using SGDRegressor(loss='squared_loss', penalty='l2') and Ridge solve the same optimization problem, via different means. #### Model Tuning Parameters > - **loss** -> The loss function to be used. The possible values are ‘squared_loss’, ‘huber’, ‘epsilon_insensitive’, or ‘squared_epsilon_insensitive’ > - **penalty** -> The penalty (aka regularization term) to be used. Defaults to ‘l2’ which is the standard regularizer for linear SVM models. ‘l1’ and ‘elasticnet’ might bring sparsity to the model (feature selection) not achievable with ‘l2’. > - **alpha** -> Constant that multiplies the regularization term. The higher the value, the stronger the regularization. Also used to compute the learning rate when set to learning_rate is set to ‘optimal’. > - **l1_ratio** -> The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. Only used if penalty is ‘elasticnet’. > - **tol** -> The stopping criterion > - **learning_rate** -> The learning rate schedule,possible values {'optimal','constant','invscaling','adaptive'} > - **eta0** -> The initial learning rate for the ‘constant’, ‘invscaling’ or ‘adaptive’ schedules. > - **power_t** -> The exponent for inverse scaling learning rate. > - **epsilon** -> Epsilon in the epsilon-insensitive loss functions; only if loss is ‘huber’, ‘epsilon_insensitive’, or ‘squared_epsilon_insensitive’. ### Standard Scaler Standardize features by removing the mean and scaling to unit variance The standard score of a sample x is calculated as: z = (x - u) / s where u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False. ### Power Transformer Power transforms are a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to heteroscedasticity (non-constant variance), or other situations where normality is desired. Currently, PowerTransformer supports the Box-Cox transform and the Yeo-Johnson transform. The optimal parameter for stabilizing variance and minimizing skewness is estimated through maximum likelihood. Apply a power transform featurewise to make data more Gaussian-like. ``` model=make_pipeline(StandardScaler(), PowerTransformer(), SGDRegressor(random_state=123)) model.fit(x_train,y_train) ``` #### Model Accuracy We will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model. score: The score function returns the coefficient of determination R2 of the prediction. ``` print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) ``` > **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. > **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ``` y_pred=model.predict(x_test) print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100)) print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred))) print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) ``` #### Prediction Plot First, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. ``` n=len(x_test) if len(x_test)<20 else 20 plt.figure(figsize=(14,10)) plt.plot(range(n),y_test[0:n], color = "green") plt.plot(range(n),model.predict(x_test[0:n]), color = "red") plt.legend(["Actual","prediction"]) plt.title("Predicted vs True Value") plt.xlabel("Record number") plt.ylabel(target) plt.show() ``` #### Creator: Ayush Gupta , Github: [Profile](https://github.com/guptayush179)
github_jupyter
![imagen](../../imagenes/ejercicios.png) # Ejercicio SQL Para este ejercicio usaremos una base de datos del FIFA 20. **Asegúrante que tienes el CSV "FIFA20.csv" en la misma carpeta donde está este Notebook**. Realiza los siguientes apartados: 1. Obtén una tabla con todos los campos 2. Obtén una tabla con los campos "short_name", "club", "team_position" 3. Obtén la misma tabla que el apartado anterior, pero en este caso renombrando los campos al castellano. 4. ¿Cuáles son todos los "team_position" diferentes? 5. ¿Cuáles son todos los "team_position" y "preferred_foot" diferentes? 6. ¿Cuáles son los jugadores diestros? ("preferred_foot" = "Right") 7. Obtén una tabla con los jugadores influencers 8. Obtén una tabla con los extremos izquierda ('team_position' = 'LW') influencers 9. Obtén una tabla con los jugadores cuyo nombre empieze por "W" y tenga una puntuación ('overall') mayor de 80 puntos. 1. ¿Y si ponemos el límite de la puntuación en mayor de 90 puntos? 10. Saca una tabla con los jugadores del Real Madrid, que NO sean diestros y tengan un potencial superior a 85 11. ¿Cuál es el jugador con la puntuación ('overall') más alta? 12. ¿Cuál es la media del valor (value_eur) de todos los jugadores, en millones de euros, sabiendo que las unidades del valor de la tabla son euros? 13. ¿Cuál es la media del salario por equipo? 14. Calcula la máxima puntuación ('overall') por "'preferred_foot' **NOTA**: se recomienda añadir un `LIMIT 5` en la mayoría de apartados para evitar grandes outputs de las queries. ``` # Importamos paquetes import pandas as pd import sqlite3 cnx = sqlite3.connect(':memory:') # Importamos datos de un CSV df = pd.read_csv('FIFA20.csv') df.head() # Pasamos el DataFrame de Pandas a SQL df.to_sql('fifa20', con=cnx, if_exists='replace', index=False) # Definimos la función para hacer queries. def sql_query(query): return pd.read_sql(query, cnx) # 1. Obten una tabla con todos los campos query = ''' SELECT * FROM fifa20 LIMIT 5 ''' sql_query(query) # 2. Obtén una tabla con los campos "short_name", "club", "team_position" query = ''' SELECT "short_name", "club", "team_position" FROM fifa20 LIMIT 5 ''' sql_query(query) # 3. Obtén la misma tabla que el apartado anterior, pero en este caso renombrando los campos al castellano. query = ''' SELECT "short_name" as "Nombre corto", "club" as "Equipo", "team_position" as "Posición en el equipo" FROM fifa20 LIMIT 5 ''' sql_query(query) # 4. ¿Cuáles son todos los "team_position" diferentes? query = ''' SELECT DISTINCT "team_position" FROM fifa20 ''' sql_query(query) # 5. ¿Cuáles son todos los "team_position" y "preferred_foot" diferentes? query = ''' SELECT DISTINCT "team_position", "preferred_foot" FROM fifa20 ''' sql_query(query) # 6. ¿Cuáles son los jugadores diestros? ("preferred_foot" = "Right") query = ''' SELECT * FROM fifa20 WHERE "preferred_foot" = "Right" LIMIT 5 ''' sql_query(query) # 7. Obtén una tabla con los jugadores influencers query = ''' SELECT DISTINCT "influencer" FROM fifa20 ''' sql_query(query) query = ''' SELECT * FROM fifa20 WHERE influencer = True ''' sql_query(query) # 8. Obtén una tabla con los extremos izquierda ('team_position' = 'LW') influencers query = ''' SELECT * FROM fifa20 WHERE "team_position" = "LW" and influencer = 1 ''' sql_query(query) # 9. Obtén una tabla con los jugadores cuyo nombre empieze por "W" y tenga una puntuación ('overall') mayor de 80 puntos query = ''' SELECT * FROM fifa20 WHERE long_name like "W%" and overall > 80 ''' sql_query(query) # 9. ¿Y si en lugar de 80, buscamos que la puntuación sea mayor de 90? query = ''' SELECT * FROM fifa20 WHERE long_name like "W%" and overall > 90 ''' sql_query(query) ``` Correcto. Ninguno lo cumple ``` # 10. Saca una tabla con los jugadores del Real Madrid, que NO sean diestros y tengan un potencial superior a 85 query = ''' SELECT * FROM fifa20 WHERE club = "Real Madrid" and "preferred_foot" <> "Right" and potential > 85 ''' sql_query(query) # 11. ¿Cuál es el jugador con la puntuación ('overall') más alta? query = ''' SELECT short_name, MAX(overall) as "Puntuación más alta" FROM fifa20 ''' sql_query(query) # 12. ¿Cuál es la media del valor (value_eur) de todos los jugadores, en millones de euros, sabiendo que las unidades del valor de la tabla son euros? query = ''' SELECT AVG(value_eur)/1000000 as "Media valor (M€)" FROM fifa20 ''' sql_query(query) # 13. ¿Cuál es la media del salario por equipo? Ordena el resultado de mayor a menor salario query = ''' SELECT club, AVG(wage_eur) as "Media Salario (€)" FROM fifa20 GROUP BY club order by "Media Salario (€)" desc ''' sql_query(query) # 14. Calcula la máxima puntuación ('overall') por club. ORdena el resultado de menor a mayor puntuación query = ''' SELECT "club", MAX(overall) as "Max Puntuación" FROM fifa20 GROUP BY "club" ORDER BY "Max Puntuación" ''' sql_query(query) ```
github_jupyter
# Introduction to Planning for Self Driving Vehicles In this notebook you are going to train your own ML policy to fully control an SDV. You will train your model using the Lyft Prediction Dataset and [L5Kit](https://github.com/woven-planet/l5kit). **Before starting, please download the [Lyft L5 Prediction Dataset 2020](https://self-driving.lyft.com/level5/prediction/) and follow [the instructions](https://github.com/woven-planet/l5kit#download-the-datasets) to correctly organise it.** The policy will be a deep neural network (DNN) which will be invoked by the SDV to obtain the next command to execute. More in details, you will be working with a CNN architecture based on ResNet50. ![model](../../docs/images/planning/model.svg) #### Inputs The network will receive a Bird's-Eye-View (BEV) representation of the scene surrounding the SDV as the only input. This has been rasterised in a fixed grid image to comply with the CNN input. L5Kit is shipped with various rasterisers. Each one of them captures different aspects of the scene (e.g. lanes or satellite view). This input representation is very similar to the one used in the [prediction competition](https://www.kaggle.com/c/lyft-motion-prediction-autonomous-vehicles/overview). Please refer to our [competition baseline notebook](../agent_motion_prediction/agent_motion_prediction.ipynb) and our [data format notebook](../visualisation/visualise_data.ipynb) if you want to learn more about it. #### Outputs The network outputs the driving signals required to fully control the SDV. In particular, this is a trajectory of XY and yaw displacements which can be used to move and steer the vehicle. After enough training, your model will be able to drive an agent along a specific route. Among others, it will do lane-following while respecting traffic lights. Let's now focus on how to train this model on the available data. ### Training using imitation learning The model is trained using a technique called *imitation learning*. We feed examples of expert driving experiences to the model and expect it to take the same actions as the driver did in those episodes. Imitation Learning is a subfield of supervised learning, in which a model tries to learn a function f: X -> Y describing given input / output pairs - one prominent example of this is image classification. This is also the same concept we use in our [motion prediction notebook](../agent_motion_prediction/agent_motion_prediction.ipynb), so feel free to check that out too. ##### Imitation learning limitations Imitation Learning is powerful, but it has a strong limitation. It's not trivial for a trained model to generalise well on out-of-distribution data. After training the model, we would like it to take full control and drive the AV in an autoregressive fashion (i.e. by following its own predictions). During evaluation it's very easy for errors to compound and make the AV drift away from the original distribution. In fact, during training our model has seen only good examples of driving. In particular, this means **almost perfect midlane following**. However, even a small constant displacement during evaluation can accumulate enough error to lead the AV completely out of its distribution in a matter of seconds. ![drifting](../../docs/images/planning/drifting.svg) This is a well known issue in SDV control and simulation discussed, among others, in [this article](https://ri.cmu.edu/pub_files/2010/5/Ross-AIStats10-paper.pdf). # Adding perturbations to the mix One of the simplest techniques to ensure a good generalisation is **data augmentation**, which exposes the network to different versions of the input and helps it to generalise better to out-of-distribution situations. In our setting, we want to ensure that **our model can recover if it ends up slightly off the midlane it is following**. Following [the noteworthy approach from Waymo](https://arxiv.org/pdf/1812.03079.pdf), we can enrich the training set with **online trajectory perturbations**. These perturbations are kinematically feasible and affect both starting angle and position. A new ground truth trajectory is then generated to link this new starting point with the original trajectory end point. These starting point will be slightly rotated and off the original midlane, and the new trajectory will teach the model how to recover from this situation. ![perturbation](../../docs/images/planning/perturb.svg) In the following cell, we load the training data and leverage L5Kit to add these perturbations to our training set. We also plot the same example with and without perturbation. During training, our model will see also those examples and learn how to recover from positional and angular offsets. ``` from tempfile import gettempdir import matplotlib.pyplot as plt import numpy as np import torch from torch import nn, optim from torch.utils.data import DataLoader from tqdm import tqdm from l5kit.configs import load_config_data from l5kit.data import LocalDataManager, ChunkedDataset from l5kit.dataset import EgoDataset from l5kit.rasterization import build_rasterizer from l5kit.geometry import transform_points from l5kit.visualization import TARGET_POINTS_COLOR, draw_trajectory from l5kit.planning.rasterized.model import RasterizedPlanningModel from l5kit.kinematic import AckermanPerturbation from l5kit.random import GaussianRandomGenerator import os ``` ## Prepare data path and load cfg By setting the `L5KIT_DATA_FOLDER` variable, we can point the script to the folder where the data lies. Then, we load our config file with relative paths and other configurations (rasteriser, training params...). ``` # set env variable for data os.environ["L5KIT_DATA_FOLDER"] = open("../dataset_dir.txt", "r").read().strip() dm = LocalDataManager(None) # get config cfg = load_config_data("./config.yaml") perturb_prob = cfg["train_data_loader"]["perturb_probability"] # rasterisation and perturbation rasterizer = build_rasterizer(cfg, dm) mean = np.array([0.0, 0.0, 0.0]) # lateral, longitudinal and angular std = np.array([0.5, 1.5, np.pi / 6]) perturbation = AckermanPerturbation( random_offset_generator=GaussianRandomGenerator(mean=mean, std=std), perturb_prob=perturb_prob) # ===== INIT DATASET train_zarr = ChunkedDataset(dm.require(cfg["train_data_loader"]["key"])).open() train_dataset = EgoDataset(cfg, train_zarr, rasterizer, perturbation) # plot same example with and without perturbation for perturbation_value in [1, 0]: perturbation.perturb_prob = perturbation_value data_ego = train_dataset[0] im_ego = rasterizer.to_rgb(data_ego["image"].transpose(1, 2, 0)) target_positions = transform_points(data_ego["target_positions"], data_ego["raster_from_agent"]) draw_trajectory(im_ego, target_positions, TARGET_POINTS_COLOR) plt.imshow(im_ego) plt.axis('off') plt.show() # before leaving, ensure perturb_prob is correct perturbation.perturb_prob = perturb_prob model = RasterizedPlanningModel( model_arch="resnet50", num_input_channels=rasterizer.num_channels(), num_targets=3 * cfg["model_params"]["future_num_frames"], # X, Y, Yaw * number of future states, weights_scaling= [1., 1., 1.], criterion=nn.MSELoss(reduction="none") ) print(model) ``` # Prepare for training Our `EgoDataset` inherits from PyTorch `Dataset`; so we can use it inside a `Dataloader` to enable multi-processing. ``` train_cfg = cfg["train_data_loader"] train_dataloader = DataLoader(train_dataset, shuffle=train_cfg["shuffle"], batch_size=train_cfg["batch_size"], num_workers=train_cfg["num_workers"]) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=1e-3) print(train_dataset) ``` # Training loop Here, we purposely include a barebone training loop. Clearly, many more components can be added to enrich logging and improve performance. Still, the sheer size of our dataset ensures that a reasonable performance can be obtained even with this simple loop. ``` tr_it = iter(train_dataloader) progress_bar = tqdm(range(cfg["train_params"]["max_num_steps"])) losses_train = [] model.train() torch.set_grad_enabled(True) for _ in progress_bar: try: data = next(tr_it) except StopIteration: tr_it = iter(train_dataloader) data = next(tr_it) # Forward pass data = {k: v.to(device) for k, v in data.items()} result = model(data) loss = result["loss"] # Backward pass optimizer.zero_grad() loss.backward() optimizer.step() losses_train.append(loss.item()) progress_bar.set_description(f"loss: {loss.item()} loss(avg): {np.mean(losses_train)}") ``` ### Plot the train loss curve We can plot the train loss against the iterations (batch-wise) to check if our model has converged. ``` plt.plot(np.arange(len(losses_train)), losses_train, label="train loss") plt.legend() plt.show() ``` # Store the model Let's store the model as a torchscript. This format allows us to re-load the model and weights without requiring the class definition later. **Take note of the path, you will use it later to evaluate your planning model!** ``` to_save = torch.jit.script(model.cpu()) path_to_save = f"{gettempdir()}/planning_model.pt" to_save.save(path_to_save) print(f"MODEL STORED at {path_to_save}") ``` # Congratulations in training your first ML policy for planning! ### What's Next Now that your model is trained and safely stored, you can evaluate how it performs in two very different situations using our dedicated notebooks: ### [Open-loop evaluation](./open_loop_test.ipynb) In this setting the model **is not controlling the AV**, and predictions are used to compute metrics only. ### [Closed-loop evaluation](./closed_loop_test.ipynb) In this setting the model **is in full control of the AV** future movements. ## Pre-trained models we provide a collection of pre-trained models for the planning task: - [model](https://lyft-l5-datasets-public.s3-us-west-2.amazonaws.com/models/planning_models/planning_model_20201208.pt) trained on train.zarr for 15 epochs; - [model](https://lyft-l5-datasets-public.s3-us-west-2.amazonaws.com/models/planning_models/planning_model_20201208_early.pt) trained on train.zarr for 2 epochs; - [model](https://lyft-l5-datasets-public.s3-us-west-2.amazonaws.com/models/planning_models/planning_model_20201208_nopt.pt) trained on train.zarr with perturbations disabled for 15 epochs; - [model](https://lyft-l5-datasets-public.s3-us-west-2.amazonaws.com/models/planning_models/planning_model_20201208_nopt_early.pt) trained on train.zarr with perturbations disabled for 2 epochs; We include two partially trained models to emphasise the important role of perturbations during training, especially during the first stage of training. To use one of the models simply download the corresponding `.pt` file and load it in the evaluation notebooks.
github_jupyter
# Download the Dataset Download the dataset from this link: https://www.kaggle.com/shanwizard/modest-museum-dataset ## Dataset Description Description of the contents of the dataset can be found here: https://shan18.github.io/MODEST-Museum-Dataset ### Mount Google Drive (Works only on Google Colab) For running the notebook on Google Colab, upload the dataset into you Google Drive and execute the two cells below ``` from google.colab import drive drive.mount('/content/gdrive') ``` Unzip the data from Google Drive into Colab ``` !unzip -qq '/content/gdrive/My Drive/modest_museum_dataset.zip' -d . ``` ### Check GPU ``` !nvidia-smi ``` # Install Packages ``` !pip install -r requirements.txt ``` # Import Packages ``` %matplotlib inline import random import matplotlib.pyplot as plt import torch from tensornet.data import MODESTMuseum from tensornet.utils import initialize_cuda, plot_metric from tensornet.model import DSResNet from tensornet.model.optimizer import sgd from tensornet.engine import LRFinder from tensornet.engine.ops import ModelCheckpoint, TensorBoard from tensornet.engine.ops.lr_scheduler import reduce_lr_on_plateau from loss import RmseBceDiceLoss, SsimDiceLoss from learner import ModelLearner ``` # Set Seed and Get GPU Availability ``` # Initialize CUDA and set random seed cuda, device = initialize_cuda(1) ``` # Data Fetch ``` DATASET_PATH = 'modest_museum_dataset' # Common parameter values for the dataset dataset_params = dict( cuda=cuda, num_workers=16, path=DATASET_PATH, hue_saturation_prob=0.25, contrast_prob=0.25, ) %%time # Create dataset dataset = MODESTMuseum( train_batch_size=256, val_batch_size=256, resize=(96, 96), **dataset_params ) # Create train data loader train_loader = dataset.loader(train=True) # Create val data loader val_loader = dataset.loader(train=False) ``` # Model Architecture and Summary ``` %%time model = DSResNet().to(device) model.summary({ k: v for k, v in dataset.image_size.items() if k in ['bg', 'bg_fg'] }) ``` # Find Initial Learning Rate Multiple LR Range Test are done on the model to find the best initial learning rate. ## Range Test 1 ``` model = DSResNet().to(device) # Create model optimizer = sgd(model, 1e-7, 0.9) # Create optimizer criterion = RmseBceDiceLoss() # Create loss function # Find learning rate lr_finder = LRFinder(model, optimizer, criterion, device=device) lr_finder.range_test(train_loader, 400, learner=ModelLearner, start_lr=1e-7, end_lr=5, step_mode='exp') # Get best initial learning rate initial_lr = lr_finder.best_lr # Print learning rate and loss print('Learning Rate:', initial_lr) print('Loss:', lr_finder.best_metric) # Plot learning rate vs loss lr_finder.plot() # Reset graph lr_finder.reset() ``` ## Range Test 2 ``` model = DSResNet().to(device) # Create model optimizer = sgd(model, 1e-5, 0.9) # Create optimizer criterion = RmseBceDiceLoss() # Create loss function # Find learning rate lr_finder = LRFinder(model, optimizer, criterion, device=device) lr_finder.range_test(train_loader, 400, learner=ModelLearner, start_lr=1e-5, end_lr=1, step_mode='exp') # Get best initial learning rate initial_lr = lr_finder.best_lr # Print learning rate and loss print('Learning Rate:', initial_lr) print('Loss:', lr_finder.best_metric) # Plot learning rate vs loss lr_finder.plot() # Reset graph lr_finder.reset() ``` ## Range Test 3 ``` model = DSResNet().to(device) # Create model optimizer = sgd(model, 1e-4, 0.9) # Create optimizer criterion = RmseBceDiceLoss() # Create loss function # Find learning rate lr_finder = LRFinder(model, optimizer, criterion, device=device) lr_finder.range_test(train_loader, 200, learner=ModelLearner, start_lr=1e-4, end_lr=10, step_mode='exp') # Get best initial learning rate initial_lr = lr_finder.best_lr # Print learning rate and loss print('Learning Rate:', initial_lr) print('Loss:', lr_finder.best_metric) # Plot learning rate vs loss lr_finder.plot() # Reset graph lr_finder.reset() ``` ## Range Test 4 ``` model = DSResNet().to(device) # Create model optimizer = sgd(model, 1e-5, 0.9) # Create optimizer criterion = RmseBceDiceLoss() # Create loss function # Find learning rate lr_finder = LRFinder(model, optimizer, criterion, device=device) lr_finder.range_test(train_loader, 100, learner=ModelLearner, start_lr=1e-5, end_lr=2, step_mode='exp') # Get best initial learning rate initial_lr = lr_finder.best_lr # Print learning rate and loss print('Learning Rate:', initial_lr) print('Loss:', lr_finder.best_metric) # Plot learning rate vs loss lr_finder.plot() # Reset graph lr_finder.reset() ``` ## Range Test 5 ``` model = DSResNet().to(device) # Create model optimizer = sgd(model, 1e-7, 0.9) # Create optimizer criterion = RmseBceDiceLoss() # Create loss function # Find learning rate lr_finder = LRFinder(model, optimizer, criterion, device=device) lr_finder.range_test(train_loader, 400, learner=ModelLearner, start_lr=1e-7, end_lr=10, step_mode='exp') # Get best initial learning rate initial_lr = lr_finder.best_lr # Print learning rate and loss print('Learning Rate:', initial_lr) print('Loss:', lr_finder.best_metric) # Plot learning rate vs loss lr_finder.plot() # Reset graph lr_finder.reset() ```
github_jupyter
``` import os import urllib import random import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn as sns from sklearn import preprocessing, grid_search from sklearn.cross_validation import train_test_split from sklearn.metrics import roc_auc_score, roc_curve from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest from sklearn import neighbors from sklearn.neighbors import NearestNeighbors from statsmodels.robust.scale import mad param_grid = { 'n_neighbors': [5, 10, 20, 30, 40, 50], 'weights': ['uniform'], } %matplotlib inline plt.style.use('seaborn-notebook') # We're going to be building a 'TP53' classifier GENE = 'TP53' if not os.path.exists('data'): os.makedirs('data') url_to_path = { # X matrix 'https://ndownloader.figshare.com/files/5514386': os.path.join('data', 'expression.tsv.bz2'), # Y Matrix 'https://ndownloader.figshare.com/files/5514389': os.path.join('data', 'mutation-matrix.tsv.bz2'), } for url, path in url_to_path.items(): if not os.path.exists(path): urllib.request.urlretrieve(url, path) %%time path = os.path.join('data', 'expression.tsv.bz2') X = pd.read_table(path, index_col=0) %%time path = os.path.join('data', 'mutation-matrix.tsv.bz2') Y = pd.read_table(path, index_col=0) y = Y[GENE] # The Series now holds TP53 Mutation Status for each Sample y.head(6) # top samples X.head(6) # Here are the percentage of tumors with NF1 y.value_counts(True) ``` # Set aside 10% of the data for testing ``` # Typically, this can only be done where the number of mutations is large enough # limit X and y for faster testing; I ran out of memory without the limit # X_train, X_test, y_train, y_test = train_test_split(X[:4000], y[:4000], test_size=0.1, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0) 'Size: {:,} features, {:,} training samples, {:,} testing samples'.format(len(X.columns), len(X_train), len(X_test)) ``` ## Create a pipeline to do the prediction ``` clf = neighbors.KNeighborsClassifier() # joblib is used to cross-validate in parallel by setting `n_jobs=-1` in GridSearchCV # Supress joblib warning. See https://github.com/scikit-learn/scikit-learn/issues/6370 warnings.filterwarnings('ignore', message='Changing the shape of non-C contiguous array') clf_grid = grid_search.GridSearchCV(estimator=clf, param_grid=param_grid, n_jobs=-1, scoring='roc_auc') pipeline = make_pipeline( StandardScaler(), # Feature scaling clf_grid) %%time # Fit the model (the computationally intensive part) pipeline.fit(X=X_train, y=y_train) best_clf = clf_grid.best_estimator_ #feature_mask = feature_select.get_support() # Get a boolean array indicating the selected features print (clf_grid.best_params_) def grid_scores_to_df(grid_scores): """ Convert a sklearn.grid_search.GridSearchCV.grid_scores_ attribute to a tidy pandas DataFrame where each row is a hyperparameter-fold combinatination. """ rows = list() for grid_score in grid_scores: for fold, score in enumerate(grid_score.cv_validation_scores): row = grid_score.parameters.copy() row['fold'] = fold row['score'] = score rows.append(row) df = pd.DataFrame(rows) return df cv_score_df = grid_scores_to_df(clf_grid.grid_scores_) facet_grid = sns.factorplot(x='n_neighbors', y='score', data=cv_score_df, kind='violin', size=4, aspect=1) facet_grid.set_ylabels('AUROC'); %%time y_pred_train = pipeline.predict_proba(X_train)[:, 1] y_pred_test = pipeline.predict_proba(X_test)[:, 1] def get_threshold_metrics(y_true, y_pred): roc_columns = ['fpr', 'tpr', 'threshold'] roc_items = zip(roc_columns, roc_curve(y_true, y_pred)) roc_df = pd.DataFrame.from_items(roc_items) auroc = roc_auc_score(y_true, y_pred) return {'auroc': auroc, 'roc_df': roc_df} metrics_train = get_threshold_metrics(y_train, y_pred_train) metrics_test = get_threshold_metrics(y_test, y_pred_test) # Plot ROC plt.figure() for label, metrics in ('Training', metrics_train), ('Testing', metrics_test): roc_df = metrics['roc_df'] plt.plot(roc_df.fpr, roc_df.tpr, label='{} (AUROC = {:.1%})'.format(label, metrics['auroc'])) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Predicting TP53 mutation from gene expression (ROC curves)') plt.legend(loc='lower right'); ```
github_jupyter
``` import pickle import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from sklearn.model_selection import RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier import librosa from sklearn.utils.multiclass import unique_labels #directory to training data and json file train_dir='/Users/nadimkawwa/Desktop/Udacity/MLEND/Capstone/nsynth-train/audio/' #directory to training data and json file valid_dir='/Users/nadimkawwa/Desktop/Udacity/MLEND/Capstone/nsynth-valid/audio/' #directory to training data and json file test_dir='/Users/nadimkawwa/Desktop/Udacity/MLEND/Capstone/nsynth-test/audio/' ``` ## Feature Extract ``` def feature_extract(file): """ Define function that takes in a file an returns features in an array """ #get wave representation y, sr = librosa.load(file) #determine if instruemnt is harmonic or percussive by comparing means y_harmonic, y_percussive = librosa.effects.hpss(y) if np.mean(y_harmonic)>np.mean(y_percussive): harmonic=1 else: harmonic=0 #Mel-frequency cepstral coefficients (MFCCs) mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13) #temporal averaging mfcc=np.mean(mfcc,axis=1) #get the mel-scaled spectrogram spectrogram = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128,fmax=8000) #temporally average spectrogram spectrogram = np.mean(spectrogram, axis = 1) #compute chroma energy chroma = librosa.feature.chroma_cens(y=y, sr=sr) #temporally average chroma chroma = np.mean(chroma, axis = 1) #compute spectral contrast contrast = librosa.feature.spectral_contrast(y=y, sr=sr) contrast = np.mean(contrast, axis= 1) return [harmonic, mfcc, spectrogram, chroma, contrast] def instrument_code(filename): """ Function that takes in a filename and returns instrument based on naming convention """ class_names=['bass', 'brass', 'flute', 'guitar', 'keyboard', 'mallet', 'organ', 'reed', 'string', 'synth_lead', 'vocal'] for name in class_names: if name in filename: return class_names.index(name) else: return None #get the training with open('DataWrangling/filenames_train.pickle', 'rb') as f: filenames_train = pickle.load(f) #load the json files df_train= pd.read_json('/Users/nadimkawwa/Desktop/Udacity/MLEND/Capstone/nsynth-train/examples.json', orient='index') #exclude all files in training dataset df_train_mod = df_train[~df_train.index.isin(filenames_train)] df_train_mod.shape #Sample n files df_train_sample=df_train_mod.groupby('instrument_family', as_index=False, #group by instrument family group_keys=False).apply(lambda df: df.sample(1000)) #number of samples #drop the synth_lead from the training dataset df_train_sample= df_train_sample[df_train_sample['instrument_family']!=9] df_train_sample.shape #save the train file index as list filenames = df_train_sample.index.tolist() #create dictionary to store all test features dict_test = {} #loop over every file in the list for file in filenames: #extract the features features = feature_extract(train_dir+ file + '.wav') #specify directory and .wav #add dictionary entry dict_test[file] = features #convert dict to dataframe features_test = pd.DataFrame.from_dict(dict_test, orient='index', columns=['harmonic', 'mfcc', 'spectro', 'chroma', 'contrast']) targets_test = [] for name in features_test.index.tolist(): targets_test.append(instrument_code(name)) features_test['targets'] = targets_test #extract mfccs mfcc_test = pd.DataFrame(features_test.mfcc.values.tolist(),index=features_test.index) mfcc_test = mfcc_test.add_prefix('mfcc_') #extract spectro spectro_test = pd.DataFrame(features_test.spectro.values.tolist(),index=features_test.index) spectro_test = spectro_test.add_prefix('spectro_') #extract chroma chroma_test = pd.DataFrame(features_test.chroma.values.tolist(),index=features_test.index) chroma_test = chroma_test.add_prefix('chroma_') #extract contrast contrast_test = pd.DataFrame(features_test.contrast.values.tolist(),index=features_test.index) contrast_test = chroma_test.add_prefix('contrast_') #drop the old columns features_test = features_test.drop(labels=['mfcc', 'spectro', 'chroma', 'contrast'], axis=1) #concatenate df_features_test=pd.concat([features_test, mfcc_test, spectro_test, chroma_test, contrast_test], axis=1, join='inner') df_features_test.head() #save the dataframe to a pickle file with open('DataWrangling/df_features_test_sensitive.pickle', 'wb') as f: pickle.dump(df_features_test, f) ``` # Test The New Data ``` #get the classifier with open('SavedModels/random_search_RF.pickle', 'rb') as f: clf_rf = pickle.load(f) def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data classes = classes[unique_labels(y_true, y_pred)] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots(figsize=(10,10)) im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") #fig.tight_layout() return ax class_names=np.array(['bass', 'brass', 'flute', 'guitar', 'keyboard', 'mallet', 'organ', 'reed', 'string', 'synth_lead', 'vocal']) X_test = df_features_test.drop(labels=['targets'], axis=1) y_test = df_features_test['targets'] y_pred_RF = clf_rf.predict(X_test) accuracy_RF = np.mean(y_pred_RF == y_test) print("The accuracy of Random Forest is {0:.2%}".format(accuracy_RF)) plot_confusion_matrix(y_test, y_pred_RF, classes=class_names, normalize=True, title='Normalized confusion matrix for Random Forest - Sensitivity Test') plt.savefig('ConfusionMatrix/RF_Normalized_sensitive.png') ```
github_jupyter
# Chapter 10 - Bet Sizing ## Introduction Your ML algorithm can achieve high accuracy, but if you do not size your bets properly, your investment strategy will inevitably lose money. This notebook contains the worked exercises from the end of chapter 10 of "Advances in Financial Machine Learning" by Marcos López de Prado. The questions are restated here in this notebook, with the accompanying code solutions following directly below each question. All code in this notebook can be run as is and requires no external data, with the exception of the EF3M algorithm used in exercise 10.4 which can be found in `mlfinlab.bet_sizing.ef3m.py`. ## Conclusion This notebook demonstrates different bet sizing algorithms in the sample case of a *long-only* trading strategy. Simply counting and averaging the number of open bets at any given time led to a more aggressive bet sizing than the algorithm based on fit Gaussians to the distribution of open bets, as discussed in exercise 10.4. The EF3M algorithm implemented in `mlfinlab.bet_sizing.ef3m.py` and applied in exercise 10.4 provides a scalable and accurate way to determine the parameters of a distribution under the assumption that it is a mixture of two Gaussian distributions. ## Next Steps While the examples in these exercises were relatively simple, it could be useful to be able to determine the parameters of a distribution under the assumption that it is a mixture of $n$ Gaussian distributions. Generalizing the currently implemented EF3M algorithm to fit to any number of distributions is seen as possible future work. ---- ---- ## Exercises Below are the worked solutions to the exercises. All code can be run as is in this notebook, with the exception of exercise 10.4 which requires functions from ´ef3m.py´ (included in this repository). We begin with importing relavant packages and functions to this notebook. ``` # imports import numpy as np from scipy.stats import norm, moment import pandas as pd from sklearn.neighbors import KernelDensity import matplotlib.pyplot as plt from matplotlib import cm import seaborn as sns import datetime as dt from mlfinlab.bet_sizing.ef3m import M2N, raw_moment ``` ---- #### EXERCISE 10.1 Using the formulation in Section 10.3, plot the bet size ($m$) as a function of the maximum predicted probability ($\tilde{p}$) when $||X|| = 2, 3, ..., 10$. ``` num_classes_list = [i for i in range(2, 11, 1)] # array of number of classes, 2 to 10 n = 10_000 # number of points to plot colors = iter(cm.coolwarm(np.linspace(0,1,len(num_classes_list)))) fig_10_1, ax_10_1 = plt.subplots(figsize=(16, 10)) for num_classes in num_classes_list: min_prob, max_prob = 1 / num_classes, 1 # possible range for maximum predicted probability, [1/||X||, 1] P = np.linspace(min_prob, max_prob, n, endpoint=False) # range of maximum predicted probabilities to plot z = (P - min_prob) / (P*(1-P))**0.5 m = 2 * norm.cdf(z) - 1 ax_10_1.plot(P, m, label=f"||X||={num_classes}", linewidth=2, alpha=1, color=colors.__next__()) ax_10_1.set_ylabel("Bet Size $m=2Z[z]-1$", fontsize=16) ax_10_1.set_xlabel(r"Maximum Predicted Probability $\tilde{p}=max_i${$p_i$}", fontsize=16) ax_10_1.set_title("Figure 10.1: Bet Size vs. Maximum Predicted Probability", fontsize=18) ax_10_1.set_xticks([0.1*i for i in range(11)]) ax_10_1.set_yticks([0.1*i for i in range(11)]) ax_10_1.legend(loc="upper left", fontsize=14, title="Number of bet size labels", title_fontsize=12) ax_10_1.set_ylim((0,1.05)) ax_10_1.set_xlim((0, 1.05)) ax_10_1.grid(linewidth=1, linestyle=':') plt.show() ``` **Figure 10.1** shows the bet size vs. the maximum predicted probability given the number of discrete bet size labels. The left-side of each line represents the case in which the maximum probability across the size labels is $\frac{1}{||X||}$ and all probabilities are equal, leading to a bet size of zero. Note the bet size reaches the limiting value $1.0$ faster at greater values of $||X||$, since the greater number of alternative bets spreads the remaining probability much thinner, leading to a greater confidence in that with the maximum predicted probability. ---- #### EXERCISE 10.2 Draw 10,000 random numbers from a uniform distribution with bounds U[.5, 1.]. (Author's note: These exercises are intended to simulate dynamic bet sizing of a long-only strategy.) __(a)__ Compute bet sizes _m_ for $||X||=2$. __(b)__ Assign 10,000 consecutive calendar days to the bet sizes. __(c)__ Draw 10,000 random numbers from a uniform distribution with bounds U[1, 25]. __(d)__ Form a `pandas.Series` indexed by the dates in 2.b, and with values equal to the index shifted forward the number of days in 2.c. This is a `t1` object similar to the ones we used in Chapter 3. __(e)__ Compute the resulting average active bets, following Section 10.4. ``` # draw random numbers from a uniform distribution (all bets are long) np.random.seed(0) sample_size = 10_000 P_t = np.random.uniform(.5, 1., sample_size) # array of random from uniform dist. # 10.2(a) Compute bet sizes for ||X||=2 z = (P_t - 0.5) / (P_t*(1-P_t))**0.5 m = 2 * norm.cdf(z) - 1 # bet sizes, x=1 # 10.2(b) Assign 10,000 consecutive calendar days start_date = dt.datetime(2000, 1, 1) # starting at 01-JAN-2000 date_step = dt.timedelta(days=1) dates = np.array([start_date + i*date_step for i in range(sample_size)]) bet_sizes = pd.Series(data=m, index=dates) # 10.2(c) Draw 10,000 random numbers from a uniform distribution shift_list = np.random.uniform(1., 25., sample_size) shift_dt = np.array([dt.timedelta(days=d) for d in shift_list]) # 10.2(d) Create a pandas.Series object dates_shifted = dates + shift_dt t1 = pd.Series(data=dates_shifted, index=dates) # Collect the series into a single DataFrame. df_events = pd.concat(objs=[t1, bet_sizes], axis=1) df_events = df_events.rename(columns={0: 't1', 1: 'bet_size_prob'}) df_events['p'] = P_t df_events = df_events[['t1', 'p', 'bet_size_prob']] # 10.2(e) Compute the average active bets (sizes). avg_bet = pd.Series() active_bets = pd.Series() for idx, val in t1.iteritems(): active_idx = t1[(t1.index<=idx)&(t1>idx)].index num_active = len(active_idx) active_bets[idx] = num_active avg_bet[idx] = bet_sizes[active_idx].mean() df_events['num_active_bets'] = active_bets df_events['avg_active_bet_size'] = avg_bet print("The first 10 rows of the resulting DataFrame from Exercise 10.2:") display(df_events.head(10)) print("Summary statistics on the bet size columns:") display(df_events[['bet_size_prob', 'num_active_bets', 'avg_active_bet_size']].describe()) ``` ---- #### EXERCISE 10.3 Using the `t1` object from exercise 2.d: __(a)__ Determine the maximum number of concurrent long bets, $\bar{c_l}$. __(b)__ Determine the maximum number of concurrent short bets, $\bar{c_s}$. __(c)__ Derive the bet size as $m_t = c_{t,l}\frac{1}{\bar{c_l}} - c_{t,s}\frac{1}{\bar{c_s}}$, where $c_{t,l}$ is the number of concurrent long bets at time $t$, and $c_{t,s}$ is the number of concurrent short bets at time $t$. ``` # 10.3(a) max number of concurrent long bets df_events2 = df_events.copy() active_long = pd.Series() active_short = pd.Series() for idx in df_events2.index: # long bets are defined as having a prediction probability greater than or equal to 0.5 df_long_active_idx = set(df_events2[(df_events2.index<=idx) & (df_events2.t1>idx) & (df_events2.p>=0.5)].index) active_long[idx] = len(df_long_active_idx) # short bets are defined as having a prediction probability less than 0.5 df_short_active_idx = set(df_events2[(df_events2.index<=idx) & (df_events2.t1>idx) & (df_events2.p<0.5)].index) active_short[idx] = len(df_short_active_idx) print(f" 10.3(a) Maximum number of concurrent long bets: {active_long.max()}") # 10.3(b) max number of concurrent short bets # p[x=1]: U[0.5, 1], thus all bets are long, and the # number of concurrent short bets is always zero in this exercise. print(f" 10.3(b) Maximum number of concurrent short bets: {active_short.max()}") # 10.3(c) bet size as difference between fractions of concurrent long and short bets # Handle possible division by zero. avg_active_long = active_long/active_long.max() if active_long.max() > 0 else active_long avg_active_short = active_short/active_short.max() if active_short.max() > 0 else active_short bet_sizes_2 = avg_active_long - avg_active_short df_events2 = df_events2.assign(active_long=active_long, active_short=active_short, bet_size_budget=bet_sizes_2) display(df_events2.head(10)) # plot the frequency of different bet sizes fig_10_3, ax_10_3 = plt.subplots(figsize=(16, 8)) colors = iter(cm.coolwarm(np.linspace(0,1,3))) n_bins = 50 for i, col in enumerate(['bet_size_prob', 'avg_active_bet_size', 'bet_size_budget']): ax_10_3.hist(df_events2[col], bins=n_bins, alpha=0.75, color=colors.__next__(), label=col) ax_10_3.set_xticks([i/10 for i in range(11)]) ax_10_3.set_xlabel("Column value", fontsize=12) ax_10_3.set_ylabel("Value count", fontsize=12) ax_10_3.set_title("Figure 10.3: Visualization of distribution of values from exercise 10.3", fontsize=16) ax_10_3.legend(loc="upper left", fontsize=14, title="Column distribution", title_fontsize=12) fig_10_3.tight_layout() plt.show() ``` **Figure 10.3** visualizes the distributions of bet sizes found in the DataFrame as of exercise 10.3. `bet_size_prob` is the bet size calculated from predicted probilities, $m=2Z[z]-1$, as in section 10.3, and runs between $[0, 1]$ as seen in **Figure 10.1**. `avg_active_bet_size` is the average of the values of active bets in `bet_size_prob` at any given time. Values for `bet_size_budget` are calculated as described in section 10.2, and take on 20 discrete values since the maximum number of concurrent bets is 20 and the minimum is 1 (there is always at least one active bet). ---- #### EXERCISE 10.4 Using the `t1` object from exercise 2.d: __(a)__ Compute the series $c_t = c_{t,l} - c_{t,s}$, where $c_{t,l}$ is the number of concurrent long bets at time $t$, and $c_{t,s}$ is the number of concurrent short bets at time $t$. __(b)__ Fit a mixture of two Gaussians on {$c_t$}. You may want to use the method described in López de Prado and Foreman (2014). __(c)__ Derive the bet size as $$m_t = \begin{cases} \frac{F[c_t]-F[0]}{1-F[0]}, & \text{if } c_t\geq 0\\\ \frac{F[c_t]-F[0]}{F[0]}, & \text{if } c_t\le 0 \end{cases}$$ where $F[x]$ is the CDF of the fitted mixture of two Gaussians for a value of $x$. __(d)__ Explain how this series ${m_t}$ differ from the bet size computed in exercise 3. ``` # 10.4(a) compute the series c_t = c_{t,l} (all bets are long) # ====================================================== df_events2['c_t'] = df_events2.active_long - 0 # number of short bets is always zero fig_10_4, ax_10_4 = plt.subplots(figsize=(10,6)) ax_10_4a = sns.distplot(df_events2['c_t'], bins=20, kde=True, kde_kws={"bw":0.6}, norm_hist=False, ax=ax_10_4) ax_10_4a.set_xlabel('$c_t$', fontsize=12) ax_10_4.set_ylabel("Value counts", fontsize=12) ax_10_4a.set_title("Figure 10.4(a): Distribution of series $c_t$", fontsize=14) plt.show() ``` **Figure 10.4(a)** shows the distribution of the number of concurrent long bets at any given time $t$. Note the slightly longer tail to the left due to the maximum number of bets being limiting in the start of the sequence. ``` # 10.4(b) fit a mixture of 2 Gaussians # compute the first 5 centered moments # ====================================================== print(f"Mean (first raw moment): {df_events2.c_t.mean()}") print("First 5 centered moments") mmnts = [moment(df_events2.c_t.to_numpy(), moment=i) for i in range(1, 6)] for i, mnt in enumerate(mmnts): print(f"E[r^{i+1}] = {mnt}") ``` The EF3M algorithm that we plan to implment uses the first 5 raw moments, so we must convert the centered moments (just previously calculated) to raw moments using the `raw_moment` function from `ef3m.py`. ``` # Calculate raw moments from centered moments # ====================================================== raw_mmnts = raw_moment(central_moments=mmnts, dist_mean=df_events2.c_t.mean()) for i, mnt in enumerate(raw_mmnts): print(f"E_Raw[r^{i+1}]={mnt}") ``` Now that we have the first 5 raw moments, we can apply the EF3M algorithm. We use variant 2 since we have the 5th moment, and it converges faster in practice. While the first 3 moments are fit exactly, there is not a unqiue solution to this, so we have to make multple runs to find the most likely value. We visualize the results of the fitted parameters in histograms, and use a kernel density estimate to identify the most likely value for each parameter. ``` # On an Intel i7-7700K with 32GB RAM, execution times are as follows: # 10 runs will take approximately 6 minutes # 100 runs will take approximately 1 hour # 1000 runs will take approximately 9 hours # ====================================================== n_runs = 50 m2n = M2N(raw_mmnts, epsilon=10**-5, factor=5, n_runs=n_runs, variant=2, max_iter=10_000_000) df_10_4 = m2n.mp_fit() # Visualize results and determine the most likely values from a KDE plot # ====================================================== fig_10_4b, ax_10_4b = plt.subplots(nrows=5, ncols=1, figsize=(8,12)) cols = ['mu_1', 'mu_2', 'sigma_1', 'sigma_2', 'p_1'] bins = int(n_runs / 4) # to minimize number of bins without results, choose at own discretion fit_parameters = [] print(f"=== Values chosen based on the mode of the distribution of results from EF3M ({n_runs} runs) ===") for col_i, ax in enumerate(ax_10_4b.flatten()): col = cols[col_i] df = df_10_4.copy() df[col+'_bin'] = pd.cut(df[col], bins=bins) df = df.groupby([col+'_bin']).count() ax = sns.distplot(df_10_4[col], bins=bins, kde=True, ax=ax) dd = ax.get_lines()[0].get_data() most_probable_val = dd[0][np.argmax(dd[1])] fit_parameters.append(most_probable_val) ax.set_ylabel("Value count") ax.set_xlabel(f"Estimated value of parameter: {col}") ax.axvline(most_probable_val, color='red', alpha=0.6) ax.set_title(f"{col}: {round(most_probable_val,3)}", color='red') print(f"Most probable estimate for parameter '{col}':", round(dd[0][np.argmax(dd[1])], 3)) fig_10_4b.suptitle(f"Figure 10.4(b): Results of running {n_runs} EF3M fitting rounds", fontsize=14) fig_10_4b.tight_layout(pad=3.5) plt.show() ``` **Figure 10.4(b)** shows the distribution of the parameter estimates from the fitting rounds. The red vertical line indicates the most likely value for each parameter according to the KDE, with the estimated value stated above the subplot in red. The CDF of a [mixture of $n$ distributions](https://en.wikipedia.org/wiki/Mixture_distribution), $F_{mixture}(x)$, can be represented as the weighted sum of the individual distributions: $$ F_{mixture}(x) = \sum_{i=1}^{n}{w_i F_{i, norm}(x)}$$ Where $w_i$ are the weights corresponding to each of the individual cumulative distribution functions of a normal distribution, $F_{i,norm}(x)$. Thus, for the mixture of $n=2$ distributions in this question, the CDF of the mixture, $F(x)$, is: $$ F(x) = p_1 F_{norm}(x, \mu_1, \sigma_1) + (1-p_1) F_{norm}(x, \mu_2, \sigma_2) $$ Where $F_{norm}(x, \mu_i, \sigma_i)$ is the cumulative distribution evaluated at $x$ of a Normal distribution with parameters $\mu_i$ and $\sigma_i$, and $p_1$ is the probability of a given random sample being drawn from the first distribution. ``` # 10.4(c) Calculating the bet size using the mixture of 2 Gaussians # ====================================================== def cdf_mixture(x, parameters): # the CDF of a mixture of 2 normal distributions, evaluated at x # :param x: (float) x-value # :param parameters: (list) mixture parameters, [mu1, mu2, sigma1, sigma2, p1] # :return: (float) CDF of the mixture # =================================== mu1, mu2, sigma1, sigma2, p1 = parameters # for clarity return p1*norm.cdf(x, mu1, sigma1) + (1-p1)*norm.cdf(x, mu2, sigma2) def bet_size_mixed(c_t, parameters): # return the bet size based on the description provided in # question 10.4(c). # :param c_t: (int) different of the number of concurrent long bets minus short bets # :param parameters: (list) mixture parameters, [mu1, mu2, sigma1, sigma2, p1] # :return: (float) bet size # ========================= if c_t >= 0: return ( cdf_mixture(c_t, parameters) - cdf_mixture(0, parameters) ) / ( 1 - cdf_mixture(0, parameters) ) else: ( cdf_mixture(c_t, parameters) - cdf_mixture(0, parameters) ) / cdf_mixture(0, parameters) df_events2['bet_size_reserve'] = df_events2.c_t.apply(lambda c: bet_size_mixed(c, fit_parameters)) fig_10_4c, ax_10_4c = plt.subplots(figsize=(10,6)) for c in ['bet_size_prob', 'avg_active_bet_size', 'bet_size_budget', 'bet_size_reserve']: ax_10_4c.hist(df_events2[c].to_numpy(), bins=100, label=c, alpha=0.7) ax_10_4c.legend(loc='upper left', fontsize=12, title="Bet size type", title_fontsize=10) ax_10_4c.set_xlabel("Bet Size, $m_t$", fontsize=12) ax_10_4c.set_ylabel("Value count", fontsize=12) ax_10_4c.set_title("Figure 10.4(c): Bet Size distributions from exercises 10.3 and 10.4", fontsize=14) display(df_events2[['c_t', 'bet_size_prob', 'avg_active_bet_size', 'bet_size_budget', 'bet_size_reserve']].describe()) ``` **Figure 10.4(c)** shows the distribution of bet sizes as calculated in exercises 10.2, 10.3 and 10.4. `bet_size_budget` is the number of active bets divided by the maximum number of active bets, while `bet_size_reserve` is the bet sizes calculated using the fit mixture of 2 Gaussian distributions. Note that both are 20 discrete values due to the underlying data as previously discussed. **10.4(d) Discussion** The bet size distribution calculated in exercise 3, `bet_size_budget`, and exercise 4, `bet_size_reserve`, are both made up of discrete values. Since the series $\{c_t\}$ is made up of integers between 1 and 20, the bet size from exercise 3, $m_t=c_{t,l}\frac{1}{\tilde{c_l}}$, is also a set of discrete values bounded by $[\frac{1}{\tilde{c_l}}, 1]$ (since there is always at least 1 active bet for any given $t$). However, $98\%$ of all bet sizes fall between $[0.45, 0.9]$, with a mean at $0.67$. In exercise 4 the bet size is calculated using $c_t$ as an input, which results in the bet sizes being a series composed of 20 unique values. Here the bet size values are bounded by $(0, 1)$ but are spread out more evenly across the range than in exercise 3; here $98\%$ of the bet sizes fall between $[0.014, 0.998]$, with a lower mean of $0.50$. Even though we are examining a *long-only* betting strategy, the bet sizes calculated in exercise 4 typically get much closer to zero (i.e. not placing the bet at all), whereas in exercise 3 $99\%$ of all bet sizes are at least $0.45$. ``` print("Quantiles of the bet size values as calculated in the previous exercises:") display(pd.concat([df_events2.quantile([0.001, 0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99, 0.999]), df_events2.mean().to_frame(name='Mean').transpose()])) ``` ---- #### EXERCISE 10.5 Repeat exercise 1, where you discretize $m$ with a `stepSize=.01`, `setpSize=.05`, and `stepSize=.1`. ``` num_classes_list = [i for i in range(2, 11, 1)] # array of number of classes, 2 to 10 n = 10000 # number of points to plot fig_10_5, ax_10_5 = plt.subplots(2, 2, figsize=(20, 16)) ax_10_5 = fig_10_5.get_axes() d_list = [None, 0.01, 0.05, 0.1] d = d_list[2] sub_fig_num = ['i', 'ii', 'iii', 'iv'] for i, axi in enumerate(ax_10_5): colors = iter(cm.coolwarm(np.linspace(0,1,len(num_classes_list)))) for num_classes in num_classes_list: d = d_list[i] min_prob, max_prob = 1 / num_classes, 1 # possible range for maximum predicted probability, [1/||X||, 1] P = np.linspace(min_prob, max_prob, n, endpoint=False) # range of maximum predicted probabilities to plot z = (P - min_prob) / (P*(1-P))**0.5 m = 2 * norm.cdf(z) - 1 if not isinstance(d, type(None)): m = (m/d).round()*d axi.plot(P, m, label=f"||X||={num_classes}", linewidth=2, alpha=1, color=colors.__next__()) axi.set_ylabel("Bet Size $m=2Z[z]-1$", fontsize=14) axi.set_xlabel(r"Maximum Predicted Probability $\tilde{p}=max_i${$p_i$}", fontsize=14) axi.set_xticks([0.1*i for i in range(11)]) axi.set_yticks([0.1*i for i in range(11)]) axi.legend(loc="upper left", fontsize=10, title="Number of bet size labels", title_fontsize=11) axi.set_ylim((0,1.05)) axi.set_xlim((0, 1.05)) if not isinstance(d, type(None)): axi.set_title(f"({sub_fig_num[i]}) Discretized Bet Size, d={d}", fontsize=16) else: axi.set_title(f"({sub_fig_num[i]}) Continuous Bet Size", fontsize=16) axi.grid(linewidth=1, linestyle=':') fig_10_5.suptitle("Figure 10.5: Plots where bet size $m$ is discretized", fontsize=18) fig_10_5.tight_layout(pad=4) plt.show() ``` **Figure 10.5** shows the bet size calculated from predicted probabilities using (i) a continuous bet size, as well as bet sizes discretized by step sizes of (ii) $d=0.01$, (iii) $d=0.05$, and (iv) $d=0.1$. ---- #### EXERCISE 10.6 Rewrite the equations in Section 10.6, so that the bet size is determined by a power function rather than a sigmoid function. We can substitute a power function to calculate bet size, $\tilde{m}$: $$\tilde{m}[\omega, x] = sgn[x]|x|^\omega$$ $L[f_i, \omega, \tilde{m}]$, the inverse function of $\tilde{m}[\omega, x]$ with respect to the market price $p_t$, can be rewritten as: $$L[f_i, \omega, \tilde{m}] = f_i - sgn[\tilde{m}]|\tilde{m}|^{1/\omega}$$ The inverse of $\tilde{m}[\omega, x]$ with respect to $\omega$ can be rewritten as: $$\omega = \frac{log[\frac{\tilde{m}}{sgn(x)}]}{log[|x|]}$$ Where $x = f_i - p_t$ is still the divergence between the current market price, $p_t$, and the price forecast, $f_i$. ---- #### EXERCISE 10.7 Modify Snippet 10.4 so that in implements the equations you derived in exercise 6. ``` # Snippet 10.4, modified to use a power function for the Bet Size # =============================================================== # pos : current position # tPos : target position # w : coefficient for regulating width of the bet size function (sigmoid, power) # f : forecast price # mP : market price # x : divergence, f - mP # maxPos : maximum absolute position size # =============================================================== def betSize_power(w, x): # returns the bet size given the price divergence sgn = np.sign(x) return sgn * abs(x)**w def getTPos_power(w, f, mP, maxPos): # returns the target position size associated with the given forecast price return int( betSize_power(w, f-mP)*maxPos ) def invPrice_power(f, w, m): # inverse function of bet size with respect to the market price sgn = np.sign(m) return f - sgn*abs(m)**(1/w) def limitPrice_power(tPos, pos, f, w, maxPos): # returns the limit price given forecast price sgn = np.sign(tPos-pos) lP = 0 for j in range(abs(pos+sgn), abs(tPos+1)): lP += invPrice_power(f, w, j/float(maxPos)) lP = lP / (tPos-pos) return lP def getW_power(x, m): # inverse function of the bet size with respect to the 'w' coefficient return np.log(m/np.sign(x)) / np.log(abs(x)) # a short script to check calculations forwards and backwards # =============================================================== mP, f, wParams = 100, 115, {'divergence': 10, 'm': 0.95} w = getW_power(wParams['divergence'], wParams['m']) # calibrate w # checking forward and backward calculations m_test = betSize_power(w, f-mP) mP_test = invPrice_power(f, w, m_test) w_test = getW_power(f-mP, m_test) print(f"Market price: {mP}; Result of inverse price: {mP_test}; Diff: {abs(mP-mP_test)}") print(f"w: {w}; Result of inverse w: {w_test}; Diff: {abs(w-w_test)}") # setup data for replicating Figure 10.3 mP, f, wParams = 100, 115, {'divergence': 10, 'm': 0.95} n_points = 1000 X = np.linspace(-1.0, 1.0, n_points) w = 2 bet_sizes_power = np.array([betSize_power(w, xi) for xi in X]) # plotting fig_10_7, ax_10_7 = plt.subplots(figsize=(10,8)) ax_10_7.plot(X, bet_sizes_power, label='$f[x]=sgn[x]|x|^2$', color='blue', linestyle='-') ax_10_7.set_xlabel("$x$", fontsize=16) ax_10_7.set_ylabel("$f[x]$", fontsize=16) ax_10_7.set_xlim((-1, 1)) ax_10_7.set_ylim((-1, 1)) fig_10_7.suptitle("Figure 10.7: Bet Sizes vs. Price Divergence", fontsize=18) plt.legend(loc='upper left', fontsize=16) fig_10_7.tight_layout(pad=3) plt.show() ``` **Figure 10.7** shows a plot of bet size vs. price divergence using the same parameters as Figure 10.3 on page 148 of "Advances in Financial Machine Learning".
github_jupyter
# English - French Translation In second week of inzva Applied AI program, we are going to create English-French translator. We will create models in different complexity levels. Althought our dataset is not a big one (our corpus is little than a standart storybook) it takes some time to train the models. For this reason it is highly recommended to use GPU for this notebook. Google Translate will be our greatest friend during our work on this notebook. It would be great to have someone who knows French! By the end of this notebook you will have hands-on-experience on - Tokenization - Embeddings - Padding - RNN - BRNN - GRU and LSTM - Keras based implementation tricks Reference: This notebook uses the data from Udacity Artificial Intelligence Nanodegree. ``` import collections import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Model, Sequential from keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional, Dropout, LSTM from keras.layers.embeddings import Embedding from keras.optimizers import Adam from keras.losses import sparse_categorical_crossentropy from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) ``` # The Architecture Rather than writing our code line by line without using any functions, we will use functions to write our code in a more structured way. It makes our code more readable and cleaner. If we are to apply the same operation twice, it is worth to write a seperate function for that operation. Coding details are one of the most underrated aspects of data related software development. Being able to understand your code months after you wrote it is critical. Besides, in order to work collaboratively you have to write good quality readable code. ### Load Data ``` import os def load_data(path): """ Load dataset """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data.split('\n') # Load English data english_sentences = load_data('.../machine_translation/data/small_vocab_en') # Load French data french_sentences = load_data('.../Users/Scoutium/Desktop/inzva/machine_translation/data/small_vocab_fr') ``` ### Files & Structure of Our Data Each line in `small_vocab_en` contains an English sentence with the respective translation in each line of `small_vocab_fr`. Some examples are ``` for sample_i in range(5): print('English sample {}: {}'.format(sample_i + 1, english_sentences[sample_i])) print('French sample {}: {}\n'.format(sample_i + 1, french_sentences[sample_i])) ``` From looking at the sentences, you can see they have been preprocessed already. The puncuations have been delimited using spaces. All the text have been converted to lowercase. ### Vocabulary The complexity of the problem is determined by the complexity of the vocabulary. A more complex vocabulary is a more complex problem. Let's look at the complexity of the dataset we'll be working with. ``` english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()]) french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()]) print('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()]))) print('{} unique English words.'.format(len(english_words_counter))) print('10 Most common words in the English dataset:') print('"' + '" "'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '"') print() print('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()]))) print('{} unique French words.'.format(len(french_words_counter))) print('10 Most common words in the French dataset:') print('"' + '" "'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '"') ``` For comparison, _Alice's Adventures in Wonderland_ contains 2,766 unique words of a total of 15,500 words. ## Preprocess 1. Tokenize the words into ids - Why do we need it? 2. Add padding to make all the sequences the same length. - Why do we need it? ``` def tokenize(x): """ Tokenize x :param x: List of sentences/strings to be tokenized :return: Tuple of (tokenized x data, tokenizer used to tokenize x) """ # TODO: Implement tokenizer = Tokenizer() tokenizer.fit_on_texts(x) return tokenizer.texts_to_sequences(x), tokenizer #tests.test_tokenize(tokenize) # Tokenize Example output text_sentences = [ 'The quick brown fox jumps over the lazy dog .', 'By Jove , my quick study of lexicography won a prize .', 'This is a short sentence .'] text_tokenized, text_tokenizer = tokenize(text_sentences) print(text_tokenizer.word_index) print() for sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)): print('Sequence {} in x'.format(sample_i + 1)) print(' Input: {}'.format(sent)) print(' Output: {}'.format(token_sent)) ``` ### Tokenize For a neural network to predict on text data, it first has to be turned into data it can understand. Text data like "dog" is a sequence of ASCII character encodings. Since a neural network is a series of multiplication and addition operations, the input data needs to be number(s). We can turn each character into a number or each word into a number. These are called character and word ids, respectively. Character ids are used for character level models that generate text predictions for each character. A word level model uses word ids that generate text predictions for each word. #### Word level models tend to learn better, since they are lower in complexity, so we'll use those. ### Padding When batching the sequence of word ids together, each sequence needs to be the same length. Since sentences are dynamic in length, we can add padding to the end of the sequences to make them the same length #### Why do we need to add padding to end of the each sentence? What happens if we add them to the beginning? ``` def pad(x, length=None): """ Pad x :param x: List of sequences. :param length: Length to pad the sequence to. If None, use length of longest sequence in x. :return: Padded numpy array of sequences """ # TODO: Implement return pad_sequences(x, maxlen=length, padding='post') #tests.test_pad(pad) # Pad Tokenized output test_pad = pad(text_tokenized) for sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)): print('Sequence {} in x'.format(sample_i + 1)) print(' Input: {}'.format(np.array(token_sent))) print(' Output: {}'.format(pad_sent)) ``` ### Preprocess Pipeline We have written functions for tokenization and padding but we didn't call them yet. Now, we are going to write a 'preprocess' function to wrap these functions and apply them. ``` def preprocess(x, y): """ Preprocess x and y :param x: Feature List of sentences :param y: Label List of sentences :return: Tuple of (Preprocessed x, Preprocessed y, x tokenizer, y tokenizer) """ preprocess_x, x_tk = tokenize(x) preprocess_y, y_tk = tokenize(y) preprocess_x = pad(preprocess_x) preprocess_y = pad(preprocess_y) # Keras's sparse_categorical_crossentropy function requires the labels to be in 3 dimensions preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1) return preprocess_x, preprocess_y, x_tk, y_tk preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer =\ preprocess(english_sentences, french_sentences) max_english_sequence_length = preproc_english_sentences.shape[1] max_french_sequence_length = preproc_french_sentences.shape[1] english_vocab_size = len(english_tokenizer.word_index) french_vocab_size = len(french_tokenizer.word_index) print('Data Preprocessed') print("Max English sentence length:", max_english_sequence_length) print("Max French sentence length:", max_french_sequence_length) print("English vocabulary size:", english_vocab_size) print("French vocabulary size:", french_vocab_size) ``` ## Models We will implement following models - Model 1 is a simple RNN - Model 2 is a RNN with Embedding - Model 3 is a Bidirectional RNN - Model 4 is an optional Encoder-Decoder RNN ### Ids Back to Text The neural network will be translating the input to words ids, which isn't the final form we want. We want the French translation. The function `logits_to_text` will bridge the gab between the logits from the neural network to the French translation. ``` def logits_to_text(logits, tokenizer): """ Turn logits from a neural network into text using the tokenizer :param logits: Logits from a neural network :param tokenizer: Keras Tokenizer fit on the labels :return: String that represents the text of the logits """ index_to_words = {id: word for word, id in tokenizer.word_index.items()} index_to_words[0] = '<PAD>' return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)]) print('`logits_to_text` function loaded.') ``` ### Model 1: RNN A basic RNN model is a good baseline for sequence data. In this model, we will build a RNN that translates English to French. We are using - LSTM - TimeDistributed of Keras A good explanation of TimeDistributed function: https://stackoverflow.com/questions/53107126/what-are-the-uses-of-timedistributed-wrapper-for-lstm-or-any-other-layers ``` def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a basic RNN on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the dataset :param french_vocab_size: Number of unique French words in the dataset :return: Keras model built, but not trained """ # Hyperparameters learning_rate = 0.005 # TODO: Build the layers model = Sequential() model.add(GRU(256, input_shape=input_shape[1:], return_sequences=True)) model.add(TimeDistributed(Dense(1024, activation='relu'))) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax'))) # Compile model model.compile(loss=sparse_categorical_crossentropy, optimizer=Adam(learning_rate), metrics=['accuracy']) return model #tests.test_simple_model(simple_model) # Reshaping the input to work with a basic RNN tmp_x = pad(preproc_english_sentences, max_french_sequence_length) tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1)) # Train the neural network simple_rnn_model = simple_model( tmp_x.shape, preproc_french_sentences.shape[1], len(english_tokenizer.word_index)+1, len(french_tokenizer.word_index)+1) print(simple_rnn_model.summary()) simple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=2, validation_split=0.2) # Print prediction(s) print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) # Print prediction(s) print("Prediction:") print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) print("\nCorrect Translation:") print(french_sentences[:1]) print("\nOriginal text:") print(english_sentences[:1]) ``` ### Model 2: Embedding You've turned the words into ids, but there's a better representation of a word. This is called word embeddings. An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors. In this model, you'll create a RNN model using embedding. ``` def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a RNN model using word embedding on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the dataset :param french_vocab_size: Number of unique French words in the dataset :return: Keras model built, but not trained """ # TODO: Implement # Hyperparameters learning_rate = 0.005 # TODO: Build the layers model = Sequential() model.add(Embedding(english_vocab_size, 256, input_length=input_shape[1], input_shape=input_shape[1:])) model.add(GRU(256, return_sequences=True)) model.add(TimeDistributed(Dense(1024, activation='relu'))) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax'))) # Compile model model.compile(loss=sparse_categorical_crossentropy, optimizer=Adam(learning_rate), metrics=['accuracy']) return model # TODO: Reshape the input tmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1]) tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2])) # TODO: Train the neural network embed_rnn_model = embed_model( tmp_x.shape, preproc_french_sentences.shape[1], len(english_tokenizer.word_index)+1, len(french_tokenizer.word_index)+1) embed_rnn_model.summary() embed_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=2, validation_split=0.2) # TODO: Print prediction(s) print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) # Print prediction(s) print("Prediction:") print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) print("\nCorrect Translation:") print(french_sentences[:1]) print("\nOriginal text:") print(english_sentences[:1]) ``` ### Model 3: Bidirectional RNNs One restriction of a RNN is that it can't see the future input, only the past. This is where bidirectional recurrent neural networks come in. They are able to see the future data. ``` def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a bidirectional RNN model on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the dataset :param french_vocab_size: Number of unique French words in the dataset :return: Keras model built, but not trained """ # TODO: Implement # Hyperparameters learning_rate = 0.003 # TODO: Build the layers model = Sequential() model.add(Bidirectional(GRU(128, return_sequences=True), input_shape=input_shape[1:])) model.add(TimeDistributed(Dense(1024, activation='relu'))) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax'))) # Compile model model.compile(loss=sparse_categorical_crossentropy, optimizer=Adam(learning_rate), metrics=['accuracy']) return model # TODO: Reshape the input tmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1]) tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2])) # TODO: Train and Print prediction(s) embed_rnn_model = embed_model( tmp_x.shape, preproc_french_sentences.shape[1], len(english_tokenizer.word_index)+1, len(french_tokenizer.word_index)+1) embed_rnn_model.summary() embed_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=2, validation_split=0.2) print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) # Print prediction(s) print("Prediction:") print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) print("\nCorrect Translation:") print(french_sentences[:1]) print("\nOriginal text:") print(english_sentences[:1]) ``` ### Model 4: Encoder-Decoder Time to look at encoder-decoder models. This model is made up of an encoder and decoder. The encoder creates a matrix representation of the sentence. The decoder takes this matrix as input and predicts the translation as output. Create an encoder-decoder model in the cell below. ``` def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train an encoder-decoder model on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the dataset :param french_vocab_size: Number of unique French words in the dataset :return: Keras model built, but not trained """ # OPTIONAL: Implement # Hyperparameters learning_rate = 0.001 # Build the layers model = Sequential() # Encoder model.add(GRU(256, input_shape=input_shape[1:], go_backwards=True)) model.add(RepeatVector(output_sequence_length)) # Decoder model.add(GRU(256, return_sequences=True)) model.add(TimeDistributed(Dense(1024, activation='relu'))) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax'))) # Compile model model.compile(loss=sparse_categorical_crossentropy, optimizer=Adam(learning_rate), metrics=['accuracy']) return model tests.test_encdec_model(encdec_model) # Reshape the input tmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1]) tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1)) # Train and Print prediction(s) encdec_rnn_model = encdec_model( tmp_x.shape, preproc_french_sentences.shape[1], len(english_tokenizer.word_index)+1, len(french_tokenizer.word_index)+1) encdec_rnn_model.summary() encdec_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2) # Print prediction(s) print("Prediction:") print(logits_to_text(encdec_rnn_model.predict(tmp_x[:1])[0], french_tokenizer)) print("\nCorrect Translation:") print(french_sentences[:1]) print("\nOriginal text:") print(english_sentences[:1]) ``` ### Model 5: Custom Using BRNN with Embeddings. ``` def model_final(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train a model that incorporates embedding, encoder-decoder, and bidirectional RNN on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English words in the dataset :param french_vocab_size: Number of unique French words in the dataset :return: Keras model built, but not trained """ # TODO: Implement # Hyperparameters learning_rate = 0.003 # Build the layers model = Sequential() # Embedding model.add(Embedding(english_vocab_size, 128, input_length=input_shape[1], input_shape=input_shape[1:])) # Encoder model.add(Bidirectional(GRU(128))) model.add(RepeatVector(output_sequence_length)) # Decoder model.add(Bidirectional(GRU(128, return_sequences=True))) model.add(TimeDistributed(Dense(512, activation='relu'))) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax'))) model.compile(loss=sparse_categorical_crossentropy, optimizer=Adam(learning_rate), metrics=['accuracy']) return model tests.test_model_final(model_final) print('Final Model Loaded') ``` ## Prediction ``` def final_predictions(x, y, x_tk, y_tk): """ Gets predictions using the final model :param x: Preprocessed English data :param y: Preprocessed French data :param x_tk: English tokenizer :param y_tk: French tokenizer """ # TODO: Train neural network using model_final model = model_final(x.shape,y.shape[1], len(x_tk.word_index)+1, len(y_tk.word_index)+1) model.summary() model.fit(x, y, batch_size=1024, epochs=25, validation_split=0.2) ## DON'T EDIT ANYTHING BELOW THIS LINE y_id_to_word = {value: key for key, value in y_tk.word_index.items()} y_id_to_word[0] = '<PAD>' sentence = 'he saw a old yellow truck' sentence = [x_tk.word_index[word] for word in sentence.split()] sentence = pad_sequences([sentence], maxlen=x.shape[-1], padding='post') sentences = np.array([sentence[0], x[0]]) predictions = model.predict(sentences, len(sentences)) print('Sample 1:') print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]])) print('Il a vu un vieux camion jaune') print('Sample 2:') print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[1]])) print(' '.join([y_id_to_word[np.max(x)] for x in y[0]])) final_predictions(preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer) ```
github_jupyter
# Discrimination Threshold Analysis This is a discrimination threshold analysis on selected better performing decision trees. This was determined in the notebook "Classification Report Selected Decision Trees.ipynb" The data is from the team's "MLTable1" Using Yellowbrick's discrimination threshold. Link: https://www.scikit-yb.org/en/latest/api/classifier/threshold.html ``` #imports import pandas as pd import boto3 from sklearn.tree import DecisionTreeClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from yellowbrick.classifier import ClassificationReport pd.set_option('display.max_columns', 200) %matplotlib inline from yellowbrick.classifier import DiscriminationThreshold from yellowbrick.classifier.threshold import discrimination_threshold ``` ## Load the Data ``` #load in the csvs #TODO For Team: enter the credentails below to run S3_Key_id='' S3_Secret_key='' def pull_data(Key_id, Secret_key, file): """ Function which CJ wrote to pull data from S3 """ BUCKET_NAME = "gtown-wildfire-ds" OBJECT_KEY = file client = boto3.client( 's3', aws_access_key_id= Key_id, aws_secret_access_key= Secret_key) obj = client.get_object(Bucket= BUCKET_NAME, Key= OBJECT_KEY) file_df = pd.read_csv(obj['Body']) return (file_df) #Pull in the firms and scan df file = 'MLTable1.csv' df = pull_data(S3_Key_id, S3_Secret_key, file) df.head() #unnamed seems to be a column brought in that we dont want. drop it. df = df.drop(['Unnamed: 0'], axis=1) df.head() df.shape df['FIRE_DETECTED'].value_counts() ``` ## ML Prep ``` #seperate data sets as labels and features X = df.drop('FIRE_DETECTED', axis=1) y = df['FIRE_DETECTED'] #train test splitting of data #common syntax here is to use X_train, X_test, y_train, y_test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) #create our scalar to get optimized result sc = StandardScaler() #runs the standard scalar with default settings. you can refine this, see docs #transform the feature data by using the fit_transform X_train = sc.fit_transform(X_train) X_test = sc.fit_transform(X_test) ``` ## Discrimination Threshold Start with discrimination threshold from highest "Fire" recall score with a (relatively) higher F1 score from the "Classisfication Report Selected Decision Trees.ipynb" ``` #start with the model below model = DecisionTreeClassifier(criterion='entropy', splitter='random') visualizer = DiscriminationThreshold(model) visualizer.fit(X, y) # Fit the data to the visualizer visualizer.show() # Finalize and render the figure #try another model? model = DecisionTreeClassifier(splitter='random') visualizer = DiscriminationThreshold(model) visualizer.fit(X, y) # Fit the data to the visualizer visualizer.show() # Finalize and render the figure ```
github_jupyter
<a href="https://colab.research.google.com/github/gptix/DS-Unit-2-Applied-Modeling/blob/master/module2/Follow_LS_DS10_232.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 3, Module 2* --- # Wrangle ML datasets 🍌 In today's lesson, we’ll work with a dataset of [3 Million Instacart Orders, Open Sourced](https://tech.instacart.com/3-million-instacart-orders-open-sourced-d40d29ead6f2)! ### Setup ``` # Download data import requests def download(url): filename = url.split('/')[-1] print(f'Downloading {url}') r = requests.get(url) with open(filename, 'wb') as f: f.write(r.content) print(f'Downloaded {filename}') download('https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz') # Uncompress data import tarfile tarfile.open('instacart_online_grocery_shopping_2017_05_01.tar.gz').extractall() # Change directory to where the data was uncompressed %cd instacart_2017_05_01 # Print the csv filenames from glob import glob for filename in glob('*.csv'): print(filename) ``` ### For each csv file, look at its shape & head ``` import pandas as pd from IPython.display import display def preview(): for filename in glob('*.csv'): df = pd.read_csv(filename) print(filename, df.shape) display(df.head()) print('\n') preview() ``` ## The original task was complex ... [The Kaggle competition said,](https://www.kaggle.com/c/instacart-market-basket-analysis/data): > The dataset for this competition is a relational set of files describing customers' orders over time. The goal of the competition is to predict which products will be in a user's next order. > orders.csv: This file tells to which set (prior, train, test) an order belongs. You are predicting reordered items only for the test set orders. Each row in the submission is an order_id from the test set, followed by product_id(s) predicted to be reordered. > sample_submission.csv: ``` order_id,products 17,39276 29259 34,39276 29259 137,39276 29259 182,39276 29259 257,39276 29259 ``` ## ... but we can simplify! Simplify the question, from "Which products will be reordered?" (Multi-class, [multi-label](https://en.wikipedia.org/wiki/Multi-label_classification) classification) to **"Will customers reorder this one product?"** (Binary classification) Which product? How about **the most frequently ordered product?** # Questions: - What is the most frequently ordered product? - How often is this product included in a customer's next order? - Which customers have ordered this product before? - How can we get a subset of data, just for these customers? - What features can we engineer? We want to predict, will these customers reorder this product on their next order? ## What was the most frequently ordered product? ``` prior = pd.read_csv('order_products__prior.csv') prior['product_id'].mode() prior['product_id'].value_counts() train = pd.read_csv('order_products__train.csv') train['product_id'].mode() train['product_id'].value_counts() products = pd.read_csv('products.csv') products[products['product_id']==24852] prior = pd.merge(prior, products, on='product_id') ``` ## How often are bananas included in a customer's next order? There are [three sets of data](https://gist.github.com/jeremystan/c3b39d947d9b88b3ccff3147dbcf6c6b): > "prior": orders prior to that users most recent order (3.2m orders) "train": training data supplied to participants (131k orders) "test": test data reserved for machine learning competitions (75k orders) Customers' next orders are in the "train" and "test" sets. (The "prior" set has the orders prior to the most recent orders.) We can't use the "test" set here, because we don't have its labels (only Kaggle & Instacart have them), so we don't know what products were bought in the "test" set orders. So, we'll use the "train" set. It currently has one row per product_id and multiple rows per order_id. But we don't want that. Instead we want one row per order_id, with a binary column: "Did the order include bananas?" Let's wrangle! ## Technique #1 ``` df = train.head(16).copy() df['bananas'] = df['product_id'] == 24852 df.groupby('order_id')['bananas'].any() train['bananas'] = train['product_id'] == 24852 train.groupby('order_id')['bananas'].any() train_wrangled = train.groupby('order_id')['bananas'].any().reset_index() target = 'bananas' train_wrangled[target].value_counts(normalize=True) ``` ## Technique #2 ``` df # Group by order_id, get a list of product_ids for that order df.groupby('order_id')['product_id'].apply(list) # Group by order_id, get a list of product_ids for that order, check if that list includes bananas def includes_bananas(product_ids): return 24852 in list(product_ids) df.groupby('order_id')['product_id'].apply(includes_bananas) train = (train .groupby('order_id') .agg({'product_id': includes_bananas}) .reset_index() .rename(columns={'product_id': 'bananas'})) target = 'bananas' train[target].value_counts(normalize=True) ``` ## Which customers have ordered this product before? - Customers are identified by `user_id` - Products are identified by `product_id` Do we have a table with both these id's? (If not, how can we combine this information?) ``` preview() ``` Answer: No, we don't have a table with both these id's. But: - `orders.csv` has `user_id` and `order_id` - `order_products__prior.csv` has `order_id` and `product_id` - `order_products__train.csv` has `order_id` and `product_id` too ``` # In the order_products__prior table, which orders included bananas? BANANAS = 24852 prior[prior.product_id==BANANAS] banana_prior_order_ids = prior[prior.product_id==BANANAS].order_id # Look at the orders table, which orders included bananas? orders = pd.read_csv('orders.csv') orders.sample(n=5) # In the orders table, which orders included bananas? orders[orders.order_id.isin(banana_prior_order_ids)] # Check this order id, confirm that yes it includes bananas prior[prior.order_id==738281] banana_orders = orders[orders.order_id.isin(banana_prior_order_ids)] # In the orders table, which users have bought bananas? banana_user_ids = banana_orders.user_id.unique() ``` ## How can we get a subset of data, just for these customers? We want *all* the orders from customers who have *ever* bought bananas. (And *none* of the orders from customers who have *never* bought bananas.) ``` # orders table, shape before getting subset orders.shape # orders table, shape after getting subset orders = orders[orders.user_id.isin(banana_user_ids)] orders.shape # IDs of *all* the orders from customers who have *ever* bought bananas subset_order_ids = orders.order_id.unique() # order_products__prior table, shape before getting subset prior.shape # order_products__prior table, shape after getting subset prior = prior[prior.order_id.isin(subset_order_ids)] prior.shape # order_products__train table, shape before getting subset train.shape # order_products__train table, shape after getting subset train = train[train.order_id.isin(subset_order_ids)] train.shape # In this subset, how often were bananas reordered in the customer's most recent order? train[target].value_counts(normalize=True) ``` ## What features can we engineer? We want to predict, will these customers reorder bananas on their next order? - Other fruit they buy - Time between banana orders - Frequency of banana orders by a customer - Organic or not - Time of day ``` preview() train.shape train.head() # Merge user_id, order_number, order_dow, order_hour_of_day, and days_since_prior_order # with the training data train = pd.merge(train, orders) train.head() ``` - Frequency of banana orders - % of orders - Every n days on average - Total orders - Recency of banana orders - n of orders - n days ``` USER = 61911 prior = pd.merge(prior, orders[['order_id', 'user_id']]) prior['bananas'] = prior.product_id == BANANAS # This user has ordered 196 products, df = prior[prior.user_id==USER] df # This person has ordered bananas six times df['bananas'].sum() df[df['bananas']] # How many unique orders for this user? df['order_id'].nunique() df['bananas'].sum() / df['order_id'].nunique() ```
github_jupyter
# Keyboard shortcuts In this notebook, you'll get some practice using keyboard shortcuts. These are key to becoming proficient at using notebooks and will greatly increase your work speed. First up, switching between edit mode and command mode. Edit mode allows you to type into cells while command mode will use key presses to execute commands such as creating new cells and openning the command palette. When you select a cell, you can tell which mode you're currently working in by the color of the box around the cell. In edit mode, the box and thick left border are colored green. In command mode, they are colored blue. Also in edit mode, you should see a cursor in the cell itself. By default, when you create a new cell or move to the next one, you'll be in command mode. To enter edit mode, press Enter/Return. To go back from edit mode to command mode, press Escape. > **Exercise:** Click on this cell, then press Enter + Shift to get to the next cell. Switch between edit and command mode a few times. ``` # mode practice ``` ## Help with commands If you ever need to look up a command, you can bring up the list of shortcuts by pressing `H` in command mode. The keyboard shortcuts are also available above in the Help menu. Go ahead and try it now. ## Creating new cells One of the most common commands is creating new cells. You can create a cell above the current cell by pressing `A` in command mode. Pressing `B` will create a cell below the currently selected cell. > **Exercise:** Create a cell above this cell using the keyboard command. > **Exercise:** Create a cell below this cell using the keyboard command. ## Switching between Markdown and code With keyboard shortcuts, it is quick and simple to switch between Markdown and code cells. To change from Markdown to a code cell, press `Y`. To switch from code to Markdown, press `M`. > **Exercise:** Switch the cell below between Markdown and code cells. ``` ## Practice here def fibo(n): # Recursive Fibonacci sequence! if n == 0: return 0 elif n == 1: return 1 return fibo(n-1) + fibo(n-2) ``` ## Line numbers A lot of times it is helpful to number the lines in your code for debugging purposes. You can turn on numbers by pressing `L` (in command mode of course) on a code cell. > **Exercise:** Turn line numbers on and off in the above code cell. ## Deleting cells Deleting cells is done by pressing `D` twice in a row so `D`, `D`. This is to prevent accidently deletions, you have to press the button twice! > **Exercise:** Delete the cell below. ``` # DELETE ME ``` ## Saving the notebook Notebooks are autosaved every once in a while, but you'll often want to save your work between those times. To save the book, press `S`. So easy! ## The Command Palette You can easily access the command palette by pressing Shift + Control/Command + `P`. > **Note:** This won't work in Firefox and Internet Explorer unfortunately. There is already a keyboard shortcut assigned to those keys in those browsers. However, it does work in Chrome and Safari. This will bring up the command palette where you can search for commands that aren't available through the keyboard shortcuts. For instance, there are buttons on the toolbar that move cells up and down (the up and down arrows), but there aren't corresponding keyboard shortcuts. To move a cell down, you can open up the command palette and type in "move" which will bring up the move commands. > **Exercise:** Use the command palette to move the cell below down one position. ``` # Move this cell down # below this cell ``` ## Finishing up There is plenty more you can do such as copying, cutting, and pasting cells. I suggest getting used to using the keyboard shortcuts, you’ll be much quicker at working in notebooks. When you become proficient with them, you'll rarely need to move your hands away from the keyboard, greatly speeding up your work. Remember, if you ever need to see the shortcuts, just press `H` in command mode.
github_jupyter
``` import os import torch import torch.nn as nn from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision.datasets import MNIST from torchvision import transforms import pytorch_lightning as pl class ConvNet(pl.LightningModule): def __init__(self): super(ConvNet, self).__init__() self.cn1 = nn.Conv2d(1, 16, 3, 1) self.cn2 = nn.Conv2d(16, 32, 3, 1) self.dp1 = nn.Dropout2d(0.10) self.dp2 = nn.Dropout2d(0.25) self.fc1 = nn.Linear(4608, 64) # 4608 is basically 12 X 12 X 32 self.fc2 = nn.Linear(64, 10) def forward(self, x): x = self.cn1(x) x = F.relu(x) x = self.cn2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dp1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dp2(x) x = self.fc2(x) op = F.log_softmax(x, dim=1) return op def training_step(self, batch, batch_num): train_x, train_y = batch y_pred = self(train_x) training_loss = F.cross_entropy(y_pred, train_y) # optional self.log('train_loss', training_loss, on_epoch=True, prog_bar=True) return training_loss def validation_step(self, batch, batch_num): # optional val_x, val_y = batch y_pred = self(val_x) val_loss = F.cross_entropy(y_pred, val_y) # optional self.log('val_loss', val_loss, on_step=True, on_epoch=True, prog_bar=True) return val_loss def validation_epoch_end(self, outputs): # optional avg_loss = torch.stack(outputs).mean() return avg_loss def test_step(self, batch, batch_num): # optional test_x, test_y = batch y_pred = self(test_x) test_loss = F.cross_entropy(y_pred, test_y) # optional self.log('test_loss', test_loss, on_step=True, on_epoch=True, prog_bar=True) return test_loss def test_epoch_end(self, outputs): # optional avg_loss = torch.stack(outputs).mean() return avg_loss def configure_optimizers(self): return torch.optim.Adadelta(self.parameters(), lr=0.5) def train_dataloader(self): return DataLoader(MNIST(os.getcwd(), train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1302,), (0.3069,))])), batch_size=32, num_workers=4) def val_dataloader(self): # optional return DataLoader(MNIST(os.getcwd(), train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1302,), (0.3069,))])), batch_size=32, num_workers=4) def test_dataloader(self): # optional return DataLoader(MNIST(os.getcwd(), train=False, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1302,), (0.3069,))])), batch_size=32, num_workers=4) model = ConvNet() trainer = pl.Trainer(progress_bar_refresh_rate=20, max_epochs=10) trainer.fit(model) trainer.test() # Start tensorboard. %reload_ext tensorboard %tensorboard --logdir lightning_logs/ ```
github_jupyter
## Python script used to scrape vehicle complaints information from [www.carcomplaints.com](http://www.carcomplaints.com) website. ``` from collections import OrderedDict from bs4 import BeautifulSoup import urllib.request as request import re url_Honda = 'http://www.carcomplaints.com/Honda/' html_Honda = request.urlopen(url_Honda) soup_Honda = BeautifulSoup(html_Honda) ``` ### Honda Models Overall Complaint Counts (http://www.carcomplaints.com/Honda/) ``` ul = soup_Honda.find_all('ul', class_='column bar',id=re.compile('c*')) ul ``` As you can see from above, the data I want (the model name and # of complaints are in the &lt;li&gt; tags). I will make a Python dict of this data: ``` honda_model_counts_dict = {} num_column_data = len(ul) # The data is divided up in arbitrary number of columns per HTML page source for i in range(num_column_data): # For each column of data... for row in ul[i].find_all('li'): honda_model_counts_dict[row.a.get_text()] = int(row.span.get_text().replace(",","")) honda_model_counts_dict ``` ### Acura Models Overall Complaint Counts Using the same procedure I did for Honda, I will get the Acura models and their respective complaint counts. ``` from collections import OrderedDict from bs4 import BeautifulSoup from IPython.display import HTML import urllib.request as request import re url_Acura = 'http://www.carcomplaints.com/Acura/' html_Acura = request.urlopen(url_Acura) soup_Acura = BeautifulSoup(html_Acura) ul = soup_Acura.find_all('ul', class_='column bar',id=re.compile('c*')) acura_model_counts_dict = {} num_column_data = len(ul) # The data is divided up in arbitrary number of columns for i in range(num_column_data): # For each column of data... for row in ul[i].find_all('li'): acura_model_counts_dict[row.a.get_text()] = int(row.span.get_text().replace(",","")) OD_Acura = OrderedDict(sorted(acura_model_counts_dict.items(), key=lambda t: t[1], reverse=True)) s_header = '<table border="1"><tr><th>Model Name</th><th># of Complaints</th></tr>' s_data = '' for key in OD_Acura.keys(): s_data = s_data + '<tr><td align="center">' + key + '</td>' + '<td align="center">' + str(OD_Acura[key]) + '</td></tr>' s_footer = "</table>" h = HTML(s_header+s_data+s_footer);h ``` #### Honda version executed all in one cell ``` from collections import OrderedDict from bs4 import BeautifulSoup from IPython.display import HTML import urllib.request as request import re url_Honda = 'http://www.carcomplaints.com/Honda/' html_Honda = request.urlopen(url_Honda) soup_Honda = BeautifulSoup(html_Honda) ul = soup_Honda.find_all('ul', class_='column bar',id=re.compile('c*')) honda_model_counts_dict = {} num_column_data = len(ul) # The data is divided up in arbitrary number of columns per HTML page source for i in range(num_column_data): # For each column of data... for row in ul[i].find_all('li'): honda_model_counts_dict[row.a.get_text()] = int(row.span.get_text().replace(",","")) OD_Honda = OrderedDict(sorted(honda_model_counts_dict.items(), key=lambda t: t[1], reverse=True)) s_header = '<table border="1"><tr><th>Model Name</th><th># of Complaints</th></tr>' s_data = '' for key in OD_Honda.keys(): s_data = s_data + '<tr><td align="center">' + key + '</td>' + '<td align="center">' + str(OD_Honda[key]) + '</td></tr>' s_footer = "</table>" h = HTML(s_header+s_data+s_footer);h ``` #### OK, now that I've shown how to obtain the number of complaints for each model in a step-by-step manner, it is time to make a function out of this so we can re-use all this code ``` from bs4 import BeautifulSoup import urllib.request as request import re def getCountsByModel(make): """Method that returns the number of complaints for each model based on vehicle make Applicable make values are: 'Honda','Acura','Ford','GM',etc Method returns a dictionary where the key is the model, value is the qty of complaints""" url = 'http://www.carcomplaints.com/' url_make = url+make+'/' html_make = request.urlopen(url_make) soup = BeautifulSoup(html_make) ul = soup.find_all('ul', class_='column bar',id=re.compile('c*')) make_model_counts_dict = OrderedDict() num_column_data = len(ul) # The data is divided up in arbitrary number of columns per HTML page source for i in range(num_column_data): # For each column of data... for row in ul[i].find_all('li'): make_model_counts_dict[row.a.get_text()] = int(row.span.get_text().replace(",","")) return make_model_counts_dict getCountsByModel('Honda') ``` #### I also made a function to get all available makes at carcomplaints.com ``` from bs4 import BeautifulSoup import urllib.request as request import re def getMakes(): """Function to get all the makes available at carcomplaints.com""" url = 'http://www.carcomplaints.com/' html = request.urlopen(url) soup = BeautifulSoup(html) sections = soup.find_all('section', id=re.compile('makes')) make_list = [] for section in range(len(sections)): for li in sections[section].find_all('li'): make_list.append(li.get_text()) return make_list getMakes() ``` #### Function to get available model years and complaint qty from a give model ``` from bs4 import BeautifulSoup import urllib.request as request import re def getYearCounts(make, model): """Function that returns a Python dict that contains model years and their complaint qty""" url = 'http://www.carcomplaints.com/'+make+'/'+model+'/' html = request.urlopen(url) soup = BeautifulSoup(html) li = soup.find_all('li', id=re.compile('bar*')) year_counts_dict = {} for item in li: year_counts_dict[int(item.find('span',class_='label').get_text())]=int(item.find('span',class_='count').get_text().replace(",","")) return year_counts_dict getYearCounts('Honda','Accord') ``` #### Function to get Top Systems by Qty ``` from bs4 import BeautifulSoup from collections import OrderedDict import urllib.request as request import re def getTopSystemsQty(make, model, year): """Function that returns an OrderedDict containing system problems and their complaint qty""" url = 'http://www.carcomplaints.com/'+make+'/'+model+'/'+str(year)+'/' html = request.urlopen(url) soup = BeautifulSoup(html) li = soup.find_all('li', id=re.compile('bar*')) problem_counts_dict = OrderedDict() # We want to maintain insertion order for item in li: try: problem_counts_dict[item.a['href'][:-1]]=int(item.span.get_text().replace(",","")) except: pass return problem_counts_dict getTopSystemsQty(year=2012, make='Honda', model='CR-V') getTopSystemsQty(year=2001, make='Nissan', model='Altima') ``` #### Function to get number of corresponding qty of NHTSA complaints for each system category ``` from bs4 import BeautifulSoup from collections import OrderedDict import urllib.request as request import re def getNhtsaSystemsQty(make, model, year): """Function that returns an OrderedDict containing qty of NHTSA complaints by system""" url = 'http://www.carcomplaints.com/'+make+'/'+model+'/'+str(year)+'/' html = request.urlopen(url) soup = BeautifulSoup(html) nhtsa = soup.find_all('em', class_='nhtsa') nhtsa_counts = [] for item in nhtsa: try: # There are 3 string tokens separated by whitespace, i want the 3rd token which is the qty nhtsa_counts.append(int(item.span.get_text().split()[2])) except: # Unfortunately, some only have 2 tokens nhtsa_counts.append(int(item.span.get_text().split()[1])) systems = soup.find_all('li', id=re.compile('bar*')) systems_list = [] for item in systems: systems_list.append(item.a['href'][:-1]) # Remove the ending forward slash nhtsa_systems_counts = list(zip(systems_list,nhtsa_counts)) nhtsa_systems_qty_dict = OrderedDict() for item in nhtsa_systems_counts: nhtsa_systems_qty_dict[item[0]]=item[1] return nhtsa_systems_qty_dict getNhtsaSystemsQty('Honda','Accord','2001') ``` #### Function to get qty of complaints by sub-system ``` from bs4 import BeautifulSoup from collections import OrderedDict import urllib.request as request import re make = 'Honda' model = 'Civic' year = 2001 system = 'transmission' def getSubSystemsQty(make, model, year, system): """Function that will return an OrderedDict of # of complaints by sub-system""" url = 'http://www.carcomplaints.com/'+make+'/'+model+'/'+str(year)+'/'+system+'/' html = request.urlopen(url) soup = BeautifulSoup(html) li = soup.find_all('li', id=re.compile('bar*')) subsystem_counts_dict = OrderedDict() # We want to maintain insertion order for item in li: subsystem_counts_dict[item.a['href'].split(".")[0]]=int(item.span.get_text().replace(",","")) return subsystem_counts_dict getSubSystemsQty('Honda','Accord','2000','transmission') ``` #### Function to get the review text for a specific system failure ``` from bs4 import BeautifulSoup import urllib.request as request import re def getReviews(make, model, year, system, subsystem): """Function that returns a list of customer reviews""" url = 'http://www.carcomplaints.com/'+make+'/'+model+'/'+str(year)+'/'+system+'/'+subsystem+'.shtml' html = request.urlopen(url) soup = BeautifulSoup(html) reviews = soup.find_all('div', itemprop="reviewBody") complaints = [] for complaint in reviews: complaints.append(complaint.p.get_text()) return complaints for complaint in getReviews('Honda','Civic','2001','transmission','pops_out_of_gear'): print(complaint) print('*'*120) ```
github_jupyter
## General information This kernel is a fork of my Keras kernel. But this one will use Pytorch. I'll gradually introduce more complex architectures. ![](https://pbs.twimg.com/profile_images/1013607595616038912/pRq_huGc_400x400.jpg) ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from nltk.tokenize import TweetTokenizer import datetime import lightgbm as lgb from scipy import stats from scipy.sparse import hstack, csr_matrix from sklearn.model_selection import train_test_split, cross_val_score from wordcloud import WordCloud from collections import Counter from nltk.corpus import stopwords from nltk.util import ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.multiclass import OneVsRestClassifier import time pd.set_option('max_colwidth',400) from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.preprocessing import OneHotEncoder import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch.autograd import Variable import torch.utils.data import random import warnings warnings.filterwarnings("ignore", message="F-score is ill-defined and being set to 0.0 due to no predicted samples.") import re from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, CosineAnnealingLR def seed_torch(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True train = pd.read_csv("../input/train.csv") test = pd.read_csv("../input/test.csv") sub = pd.read_csv('../input/sample_submission.csv') ``` ## Data overview This is a kernel competition, where we can't use external data. As a result we can use only train and test datasets as well as embeddings which were provided by organizers. ``` import os print('Available embeddings:', os.listdir("../input/embeddings/")) train["target"].value_counts() ``` We have a seriuos disbalance - only ~6% of data are positive. No wonder the metric for the competition is f1-score. ``` train.head() ``` In the dataset we have only texts of questions. ``` print('Average word length of questions in train is {0:.0f}.'.format(np.mean(train['question_text'].apply(lambda x: len(x.split()))))) print('Average word length of questions in test is {0:.0f}.'.format(np.mean(test['question_text'].apply(lambda x: len(x.split()))))) print('Max word length of questions in train is {0:.0f}.'.format(np.max(train['question_text'].apply(lambda x: len(x.split()))))) print('Max word length of questions in test is {0:.0f}.'.format(np.max(test['question_text'].apply(lambda x: len(x.split()))))) print('Average character length of questions in train is {0:.0f}.'.format(np.mean(train['question_text'].apply(lambda x: len(x))))) print('Average character length of questions in test is {0:.0f}.'.format(np.mean(test['question_text'].apply(lambda x: len(x))))) ``` As we can see on average questions in train and test datasets are similar, but there are quite long questions in train dataset. ``` puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', '+', '\\', '•', '~', '@', '£', '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] def clean_text(x): x = str(x) for punct in puncts: x = x.replace(punct, f' {punct} ') return x def clean_numbers(x): x = re.sub('[0-9]{5,}', '#####', x) x = re.sub('[0-9]{4}', '####', x) x = re.sub('[0-9]{3}', '###', x) x = re.sub('[0-9]{2}', '##', x) return x mispell_dict = {"aren't" : "are not", "can't" : "cannot", "couldn't" : "could not", "didn't" : "did not", "doesn't" : "does not", "don't" : "do not", "hadn't" : "had not", "hasn't" : "has not", "haven't" : "have not", "he'd" : "he would", "he'll" : "he will", "he's" : "he is", "i'd" : "I would", "i'd" : "I had", "i'll" : "I will", "i'm" : "I am", "isn't" : "is not", "it's" : "it is", "it'll":"it will", "i've" : "I have", "let's" : "let us", "mightn't" : "might not", "mustn't" : "must not", "shan't" : "shall not", "she'd" : "she would", "she'll" : "she will", "she's" : "she is", "shouldn't" : "should not", "that's" : "that is", "there's" : "there is", "they'd" : "they would", "they'll" : "they will", "they're" : "they are", "they've" : "they have", "we'd" : "we would", "we're" : "we are", "weren't" : "were not", "we've" : "we have", "what'll" : "what will", "what're" : "what are", "what's" : "what is", "what've" : "what have", "where's" : "where is", "who'd" : "who would", "who'll" : "who will", "who're" : "who are", "who's" : "who is", "who've" : "who have", "won't" : "will not", "wouldn't" : "would not", "you'd" : "you would", "you'll" : "you will", "you're" : "you are", "you've" : "you have", "'re": " are", "wasn't": "was not", "we'll":" will", "didn't": "did not", "tryin'":"trying"} def _get_mispell(mispell_dict): mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) return mispell_dict, mispell_re mispellings, mispellings_re = _get_mispell(mispell_dict) def replace_typical_misspell(text): def replace(match): return mispellings[match.group(0)] return mispellings_re.sub(replace, text) # Clean the text train["question_text"] = train["question_text"].apply(lambda x: clean_text(x.lower())) test["question_text"] = test["question_text"].apply(lambda x: clean_text(x.lower())) # Clean numbers train["question_text"] = train["question_text"].apply(lambda x: clean_numbers(x)) test["question_text"] = test["question_text"].apply(lambda x: clean_numbers(x)) # Clean speelings train["question_text"] = train["question_text"].apply(lambda x: replace_typical_misspell(x)) test["question_text"] = test["question_text"].apply(lambda x: replace_typical_misspell(x)) max_features = 120000 tk = Tokenizer(lower = True, filters='', num_words=max_features) full_text = list(train['question_text'].values) + list(test['question_text'].values) tk.fit_on_texts(full_text) train_tokenized = tk.texts_to_sequences(train['question_text'].fillna('missing')) test_tokenized = tk.texts_to_sequences(test['question_text'].fillna('missing')) train['question_text'].apply(lambda x: len(x.split())).plot(kind='hist'); plt.yscale('log'); plt.title('Distribution of question text length in characters'); ``` We can see that most of the questions are 40 words long or shorter. Let's try having sequence length equal to 70 for now. ``` max_len = 72 maxlen = 72 X_train = pad_sequences(train_tokenized, maxlen = max_len) X_test = pad_sequences(test_tokenized, maxlen = max_len) ``` ### Preparing data for Pytorch One of main differences from Keras is preparing data. Pytorch requires special dataloaders. I'll write a class for it. At first I'll append padded texts to original DF. ``` y_train = train['target'].values def sigmoid(x): return 1 / (1 + np.exp(-x)) from sklearn.model_selection import StratifiedKFold splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=10).split(X_train, y_train)) embed_size = 300 embedding_path = "../input/embeddings/glove.840B.300d/glove.840B.300d.txt" def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore')) # all_embs = np.stack(embedding_index.values()) # emb_mean,emb_std = all_embs.mean(), all_embs.std() emb_mean,emb_std = -0.005838499, 0.48782197 word_index = tk.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words + 1, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector embedding_path = "../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt" def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore') if len(o)>100) # all_embs = np.stack(embedding_index.values()) # emb_mean,emb_std = all_embs.mean(), all_embs.std() emb_mean,emb_std = -0.0053247833, 0.49346462 embedding_matrix1 = np.random.normal(emb_mean, emb_std, (nb_words + 1, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embedding_index.get(word) if embedding_vector is not None: embedding_matrix1[i] = embedding_vector embedding_matrix = np.mean([embedding_matrix, embedding_matrix1], axis=0) del embedding_matrix1 ``` ### Model ``` class Attention(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(Attention, self).__init__(**kwargs) self.supports_masking = True self.bias = bias self.feature_dim = feature_dim self.step_dim = step_dim self.features_dim = 0 weight = torch.zeros(feature_dim, 1) nn.init.xavier_uniform_(weight) self.weight = nn.Parameter(weight) if bias: self.b = nn.Parameter(torch.zeros(step_dim)) def forward(self, x, mask=None): feature_dim = self.feature_dim step_dim = self.step_dim eij = torch.mm( x.contiguous().view(-1, feature_dim), self.weight ).view(-1, step_dim) if self.bias: eij = eij + self.b eij = torch.tanh(eij) a = torch.exp(eij) if mask is not None: a = a * mask a = a / torch.sum(a, 1, keepdim=True) + 1e-10 weighted_input = x * torch.unsqueeze(a, -1) return torch.sum(weighted_input, 1) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self).__init__() hidden_size = 128 self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout2d(0.1) self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size*2, hidden_size, bidirectional=True, batch_first=True) self.lstm_attention = Attention(hidden_size*2, maxlen) self.gru_attention = Attention(hidden_size*2, maxlen) self.linear = nn.Linear(1024, 16) self.relu = nn.ReLU() self.dropout = nn.Dropout(0.1) self.out = nn.Linear(16, 1) def forward(self, x): h_embedding = self.embedding(x) h_embedding = torch.squeeze(self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) h_lstm, _ = self.lstm(h_embedding) h_gru, _ = self.gru(h_lstm) h_lstm_atten = self.lstm_attention(h_lstm) h_gru_atten = self.gru_attention(h_gru) avg_pool = torch.mean(h_gru, 1) max_pool, _ = torch.max(h_gru, 1) conc = torch.cat((h_lstm_atten, h_gru_atten, avg_pool, max_pool), 1) conc = self.relu(self.linear(conc)) conc = self.dropout(conc) out = self.out(conc) return out m = NeuralNet() def train_model(model, x_train, y_train, x_val, y_val, validate=True): optimizer = torch.optim.Adam(model.parameters()) # scheduler = CosineAnnealingLR(optimizer, T_max=5) # scheduler = StepLR(optimizer, step_size=3, gamma=0.1) train = torch.utils.data.TensorDataset(x_train, y_train) valid = torch.utils.data.TensorDataset(x_val, y_val) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) loss_fn = torch.nn.BCEWithLogitsLoss(reduction='mean').cuda() best_score = -np.inf for epoch in range(n_epochs): start_time = time.time() model.train() avg_loss = 0. for x_batch, y_batch in tqdm(train_loader, disable=True): y_pred = model(x_batch) loss = loss_fn(y_pred, y_batch) optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() / len(train_loader) model.eval() valid_preds = np.zeros((x_val_fold.size(0))) if validate: avg_val_loss = 0. for i, (x_batch, y_batch) in enumerate(valid_loader): y_pred = model(x_batch).detach() avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) valid_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] search_result = threshold_search(y_val.cpu().numpy(), valid_preds) val_f1, val_threshold = search_result['f1'], search_result['threshold'] elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t val_f1={:.4f} best_t={:.2f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, val_f1, val_threshold, elapsed_time)) else: elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, elapsed_time)) valid_preds = np.zeros((x_val_fold.size(0))) avg_val_loss = 0. for i, (x_batch, y_batch) in enumerate(valid_loader): y_pred = model(x_batch).detach() avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) valid_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] print('Validation loss: ', avg_val_loss) test_preds = np.zeros((len(test_loader.dataset))) for i, (x_batch,) in enumerate(test_loader): y_pred = model(x_batch).detach() test_preds[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # scheduler.step() return valid_preds, test_preds#, test_preds_local x_test_cuda = torch.tensor(X_test, dtype=torch.long).cuda() test = torch.utils.data.TensorDataset(x_test_cuda) batch_size = 512 test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) seed=1029 def threshold_search(y_true, y_proba): best_threshold = 0 best_score = 0 for threshold in tqdm([i * 0.01 for i in range(100)], disable=True): score = f1_score(y_true=y_true, y_pred=y_proba > threshold) if score > best_score: best_threshold = threshold best_score = score search_result = {'threshold': best_threshold, 'f1': best_score} return search_result def seed_everything(seed=1234): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything() train_preds = np.zeros(len(train)) test_preds = np.zeros((len(test), len(splits))) n_epochs = 5 from tqdm import tqdm from sklearn.metrics import f1_score for i, (train_idx, valid_idx) in enumerate(splits): x_train_fold = torch.tensor(X_train[train_idx], dtype=torch.long).cuda() y_train_fold = torch.tensor(y_train[train_idx, np.newaxis], dtype=torch.float32).cuda() x_val_fold = torch.tensor(X_train[valid_idx], dtype=torch.long).cuda() y_val_fold = torch.tensor(y_train[valid_idx, np.newaxis], dtype=torch.float32).cuda() train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) print(f'Fold {i + 1}') seed_everything(seed + i) model = NeuralNet() model.cuda() valid_preds_fold, test_preds_fold = train_model(model, x_train_fold, y_train_fold, x_val_fold, y_val_fold, validate=False) train_preds[valid_idx] = valid_preds_fold test_preds[:, i] = test_preds_fold search_result = threshold_search(y_train, train_preds) sub['prediction'] = test_preds.mean(1) > search_result['threshold'] sub.to_csv("submission.csv", index=False) ```
github_jupyter
# Distribution Strategy Design Pattern This notebook demonstrates how to use distributed training with Keras. ``` import datetime import os import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow import feature_column as fc # Determine CSV, label, and key columns # Create list of string column headers, make sure order matches. CSV_COLUMNS = ["weight_pounds", "is_male", "mother_age", "plurality", "gestation_weeks", "mother_race"] # Add string name for label column LABEL_COLUMN = "weight_pounds" # Set default values for each CSV column as a list of lists. # Treat is_male and plurality as strings. DEFAULTS = [[0.0], ["null"], [0.0], ["null"], [0.0], ["null"]] def features_and_labels(row_data): """Splits features and labels from feature dictionary. Args: row_data: Dictionary of CSV column names and tensor values. Returns: Dictionary of feature tensors and label tensor. """ label = row_data.pop(LABEL_COLUMN) return row_data, label def load_dataset(pattern, batch_size=1, mode=tf.estimator.ModeKeys.EVAL): """Loads dataset using the tf.data API from CSV files. Args: pattern: str, file pattern to glob into list of files. batch_size: int, the number of examples per batch. mode: tf.estimator.ModeKeys to determine if training or evaluating. Returns: `Dataset` object. """ # Make a CSV dataset dataset = tf.data.experimental.make_csv_dataset( file_pattern=pattern, batch_size=batch_size, column_names=CSV_COLUMNS, column_defaults=DEFAULTS) # Map dataset to features and label dataset = dataset.map(map_func=features_and_labels) # features, label # Shuffle and repeat for training if mode == tf.estimator.ModeKeys.TRAIN: dataset = dataset.shuffle(buffer_size=1000).repeat() # Take advantage of multi-threading; 1=AUTOTUNE dataset = dataset.prefetch(buffer_size=1) return dataset ``` Build model as before. ``` def create_input_layers(): """Creates dictionary of input layers for each feature. Returns: Dictionary of `tf.Keras.layers.Input` layers for each feature. """ inputs = { colname: tf.keras.layers.Input( name=colname, shape=(), dtype="float32") for colname in ["mother_age", "gestation_weeks"]} inputs.update({ colname: tf.keras.layers.Input( name=colname, shape=(), dtype="string") for colname in ["is_male", "plurality", "mother_race"]}) return inputs ``` And set up feature columns. ``` def categorical_fc(name, values): cat_column = fc.categorical_column_with_vocabulary_list( key=name, vocabulary_list=values) return fc.indicator_column(categorical_column=cat_column) def create_feature_columns(): feature_columns = { colname : fc.numeric_column(key=colname) for colname in ["mother_age", "gestation_weeks"] } feature_columns["is_male"] = categorical_fc( "is_male", ["True", "False", "Unknown"]) feature_columns["plurality"] = categorical_fc( "plurality", ["Single(1)", "Twins(2)", "Triplets(3)", "Quadruplets(4)", "Quintuplets(5)", "Multiple(2+)"]) feature_columns["mother_race"] = fc.indicator_column( fc.categorical_column_with_hash_bucket( "mother_race", hash_bucket_size=17, dtype=tf.dtypes.string)) feature_columns["gender_x_plurality"] = fc.embedding_column( fc.crossed_column(["is_male", "plurality"], hash_bucket_size=18), dimension=2) return feature_columns def get_model_outputs(inputs): # Create two hidden layers of [64, 32] just in like the BQML DNN h1 = layers.Dense(64, activation="relu", name="h1")(inputs) h2 = layers.Dense(32, activation="relu", name="h2")(h1) # Final output is a linear activation because this is regression output = layers.Dense(units=1, activation="linear", name="weight")(h2) return output def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean((y_pred - y_true) ** 2)) ``` ## Build the model and set up distribution strategy Next, we'll combine the components of the model above to build the DNN model. Here is also where we'll define the distribution strategy. To do that, we'll place the building of the model inside the scope of the distribution strategy. Notice the output after excuting the cell below. We'll see ``` INFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0', '/job:localhost/replica:0/task:0/device:GPU:1', '/job:localhost/replica:0/task:0/device:GPU:2', '/job:localhost/replica:0/task:0/device:GPU:3') ``` This indicates that we're using the MirroredStrategy on 4 GPUs. That is because my machine has 4 GPUs. Your output may look different depending on how many GPUs you have on your device. ``` def build_dnn_model(): """Builds simple DNN using Keras Functional API. Returns: `tf.keras.models.Model` object. """ # Create input layer inputs = create_input_layers() # Create feature columns feature_columns = create_feature_columns() # The constructor for DenseFeatures takes a list of numeric columns # The Functional API in Keras requires: LayerConstructor()(inputs) dnn_inputs = layers.DenseFeatures( feature_columns=feature_columns.values())(inputs) # Get output of model given inputs output = get_model_outputs(dnn_inputs) # Build model and compile it all together model = tf.keras.models.Model(inputs=inputs, outputs=output) model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"]) return model # Create the distribution strategy mirrored_strategy = tf.distribute.MirroredStrategy() with mirrored_strategy.scope(): model = build_dnn_model() print("Here is our DNN architecture so far:\n") print(model.summary()) ``` To see how many GPU devices you have attached to your machine, run the cell below. As mentioned above, I have 4. ``` print('Number of devices: {}'.format(mirrored_strategy.num_replicas_in_sync)) ``` Copyright 2020 Google Inc. 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 http://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
github_jupyter
``` import jupyter_addons as ja ja.set_css() ``` ## Network Design with PypeFlow API - Example 3 # Adding Balancing Valves & Control Valves to a Closed Network ## 1. Setting up the `Designer` We will continue to work with the network from the design examples 1 and 2, but now we have modified it into a closed network. Look at the scheme [here](../resources/ex3_scheme.pdf). In the cross-overs of the riser we have added a balancing valve and a control valve. The csv network configuration file now looks as shown below. It describes the pipe sections in the network without any fittings, balancing valves or control valves. ``` import pandas as pd df = pd.read_csv('../projects/config2_bal_pressure.csv') ja.display_table(df) ``` In row 8 up to and including row 15 of the network configuration the cross-overs are added to the network configuration. These sections have a nominal diameter (DN) of 20 mm. We also modified the flow rates in the sections. Each cross-over has an equal flow rate of 0.212 L/s. The flow rates in the pipe sections of the riser follow from the law of continuity applied to the nodes. We start by setting up the `Designer` like we did in design example 2: ``` from pypeflow.design import Designer Designer.set_units({ 'length': 'm', 'diameter': 'mm', 'flow_rate': 'L/s', 'pressure': 'bar', 'velocity': 'm/s' }) Designer.create_network( start_node_id='n1', end_node_id='n0', fluid='water', fluid_temperature=10.0, pipe_schedule='pipe_schedule_40' ) Designer.configure_network('../projects/config2_bal_pressure.csv') ``` Unlike the previous example, we haven't add any fittings in this case. Let's have a look already at the flow paths in the network: ``` df_paths = Designer.get_paths() ja.display_table(df_paths) ``` Notice that the velocity head and elevation head will always be zero in a closed network. ## 2. Adding Balancing Valves to the Cross-overs Make a list with the ids of the cross-over sections in which the balancing valves and control valves will be inserted: ``` cross_overs = ['s22*', 's33*', 's44*', 's55*', 's66*', 's77*', 's88*', 's99*'] ``` ### 2.1 Determining Preliminary Kvs-values of the Balancing Valves For each balancing valve we set a design pressure drop across the fully open balancing valve. The value of the design pressure drop must be expressed in the measuring units that were passed to the `Designer` when setting it up (see step 1 above). When the balancing valves are added to the network, the `Designer` will calculate a preliminary Kvs-value for each balancing valve, based on the given design pressure drop. Take a look at the API documentation to see how to use the `Designer`'s method `add_balancing_valves` in the module `pypeflow.design.design`. ``` import quantities as qty dp_design = qty.Pressure(3.0, 'kPa') Kvs_pre_list = Designer.add_balancing_valves([(cross_over, dp_design('bar')) for cross_over in cross_overs]) d = { 'section id': [t[0] for t in Kvs_pre_list], 'preliminary Kvs': [round(t[1], 3) for t in Kvs_pre_list] } df_bal_preKvs = pd.DataFrame(d) ja.display_table(df_bal_preKvs) ``` In order to obtain the chosen design pressure drop across the balancing valve, we should select a balancing valve with a Kvs-value of 4.4. ### 2.2 Selecting Commercially Available Balancing Valves Based on the preliminary Kvs-values and the nominal diameters of the cross-overs we can search for a commercially available balancing valve. In a catalogue we find a balancing valve DN20 with a Kvs-value of 6.5. We will initialize the balancing valves with this value: ``` Designer.init_balancing_valves([(cross_over, 6.5) for cross_over in cross_overs]) ``` Let's take a look again at the flow paths in the network after inserting the balancing valves: ``` df_paths = Designer.get_paths() ja.display_table(df_paths) ``` ## 3. Adding Control Valves to the Cross-Overs ### 3.1 Determining Preliminary Kvs-values of the Control Valves The calculated Kvs-value of a control valve is determined based on a target valve authority the user must enter and the pressure loss along the critical path of the network; this is the pressure loss to which the other paths will be balanced and that will also determine the necessary pump feed pressure to establish the design flow rates. Usually an initial valve authority of 0.5 is chosen to size a control valve. When the control valves are added to the network, the `Designer` will calculate a preliminary Kvs-value for each control valve, based on this target valve authority. Take a look at the API documentation to see how to use the `Designer`'s method `add_control_valves` in the module `pypeflow.design.design`. ``` Kvs_pre_list = Designer.add_control_valves([(cross_over, 0.5) for cross_over in cross_overs]) d = { 'section id': [t[0] for t in Kvs_pre_list], 'preliminary Kvs': [round(t[1], 3) for t in Kvs_pre_list] } df_ctrl_preKvs = pd.DataFrame(d) ja.display_table(df_ctrl_preKvs) ``` ### 3.2 Selecting Commercially Available Control Valves Based on the preliminary Kvs-values and the nominal diameters of the cross-overs we can search for a commercially available control valve. From a catalogue we find a control valve DN15 with a Kvs-value of 1.6. ``` Designer.set_control_valves([(cross_over, 1.6) for cross_over in cross_overs]) ``` At this stage we have added fully open balancing valves and fully open control valves to the cross-overs. ## 4. Flow Balancing the Network ### 4.1 Situation Before Balancing Let's take a look at the **flow paths** before balancing the network: ``` df_paths = Designer.get_paths() ja.display_table(df_paths) ``` From the last column in the table we can see how much pressure must be dissipated by the balancing valves in each cross-over. This amount is determined by the required static head of the critical path, which passes through cross-over `s99*`. It is the difference between the required static head of the critical path and the required static head of the path under consideration. Also have a look at the dynamic pressure losses in the **pipe sections**: ``` df_sections = Designer.get_sections() ja.display_table(df_sections) ``` We can see that the design flow rate in the cross-overs with fully open balancing valve and control valve would produce a pressure loss of 0.272 bar. Also let us take a look at the **control valve authority** before balancing the network: ``` df_ctrl = Designer.get_control_valves() ja.display_table(df_ctrl) ``` We can see that the valve authority is a bit less than the target value of 0.5. This is because we had to select a greater available Kvs-value than the calculated value. ### 4.2 Flow Balancing To let the `Designer` balance the network, we call its `set_balancing_valves` method: ``` Designer.set_balancing_valves() df_bal = Designer.get_balancing_valves() ja.display_table(df_bal) ``` The balancing valve in the cross-over `s99*` of the critical path remains fully open: its Kvr setting is equal to the Kvs value. The balancing valves in the other cross-overs are turned in a more closed position, so that all flow paths will obtain the same required static head while at the same time the design flow rates through each cross-over are maintained. ### 4.3 Situation After Balancing Let's take a look again at the **flow paths**: ``` df_paths = Designer.get_paths() ja.display_table(df_paths) ``` We can see that the required static head for all flow paths is the same now and equal to the required static head of the critical path. Next, let's also have a look again at the dynamic pressure losses in the **pipe sections**: ``` df_sections = Designer.get_sections() ja.display_table(df_sections) ``` We see that by closing the balancing valves in the cross-overs in order to set their Kvr setting right, the pressure drop across all cross-overs has increased, except of course the pressure drop across the cross-over in the critical path, so that all flow paths have obtained the same required static head, i.e. the required static head of the critical path. Also, let us take a look again at the authorities of the control valves after flow balancing: ``` df_ctrl = Designer.get_control_valves() ja.display_table(df_ctrl) ``` We see that the control valves have kept their original authorities after flow balancing, as these are determined based on the static head that is required for the critical path. It is recommended that the authority of a modulating control valve under actual working conditions does not fall below 0.25 in order to maintain good flow controllability, regardless of the flow conditions through the other cross-overs in the network. As control valves in the network under actual working conditions get more closed, the feed pressure across the cross-over with the fully open control valve might rise, which would lead to a flow rate that exceeds the design value, unless a constant pressure controlled pump should be used. ## 5. Drawing the System Curve of the Balanced Network ### 5.1 Hydraulic Resistance of the Balanced Network The relationship between the feed pressure applied to the network and the resulting flow rate that enters and leaves the network can be expressed as: $$ \Delta {p} = R * V^2 $$ where $R$ is called the hydraulic resistance of the network. The hydraulic resistance of the balanced network can be retrieved using: ``` R = Designer.network.hydraulic_resistance ja.display_item(f'The hydraulic resistance of the balanced network = <b>{R:.3e}</b>') ``` It should be noticed that the returned value of the hydraulic resistance is based on flow rate and pressure expressed in their basic SI-units (m³/s and Pa). ### 5.2 The System Curve of the Balanced Network The system curve of the network can easily be drawn using the class `SystemCurve` in sub-package `pypeflow.utils`. Have a look in the API-documentation for more information about its usage. ``` from pypeflow.utils import SystemCurve sys_curve = SystemCurve( R, src_units={'flow_rate': 'm^3/s', 'pressure': 'Pa'}, dest_units={'flow_rate': 'L/s', 'pressure': 'bar'} ) graph = sys_curve.draw_system_curve( V_initial=qty.VolumeFlowRate(0.0, 'L/s'), V_final=qty.VolumeFlowRate(2.5, 'L/s'), V_max=qty.VolumeFlowRate(2.5, 'L/s'), V_step=qty.VolumeFlowRate(0.1, 'L/s'), p_max=qty.Pressure(1, 'bar'), p_step=qty.Pressure(0.1, 'bar'), fig_size=(8, 6) ) graph.show() ```
github_jupyter
# Packaging an Overlay This notebook will demonstrate how to package an Overlay. This notebook depends on the previous three notebooks: 2. [Creating a Vivado HLS Core](2-Creating-A-Vivado-HLS-Core.ipynb) 3. [Building a Vivado Bitstream](3-Building-A-Bitstream.ipynb) 4. [Using an HLS core in PYNQ](4-Using-an-HLS-core-in-PYNQ.ipynb) In this notebook you will generate the following file inside the `tutorial` directory: - `setup.py` This will allow you to install your PYNQ Overlays as Python packages using Pip, and distribute them on GitHub (Like this tutorial was delivered) ## Outputs from Previous Steps The first two critical components of a PYNQ overlay are a `.tcl` script file and a `.bit`. These files should have been created in **[Creating a FPGA Bitstream](2-Creating-A-Bitstream.ipynb)** and with the names `io.tcl` and `io.bit`. In addition, you will need the `__init__.py` and `io.py` python files created in **[Using an HLS core in PYNQ](4-Using-an-HLS-core-in-PYNQ.ipynb)**. These files are necessary for communcation between the ARM Processing System and FPGA Programmable Logic. Verify that the following files are in the `/home/xilinx/PYNQ-HLS/tutorial/pynqhls/io` directory of your PYNQ board. 1. `io.tcl` 2. `io.bit` 3. `io.py` 4. `__init__.py` ``` !ls /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/io.tcl !ls /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/io.bit !ls /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/io.py !ls /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/__init__.py ``` ## Notebooks Folder Finally, we need to create a `notebooks` folder and populate its contents. Inside of `notebooks` we need to create a `pictures` folder. The following cell will perform this operation: ``` !mkdir /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/notebooks !mkdir /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/notebooks/pictures ``` You can create your own notebooks inside of this folder, or you can copy the existing demonstration notebook: ``` !cp -r /home/xilinx/PYNQ-HLS/pynqhls/io/notebooks/*.ipynb /home/xilinx/PYNQ-HLS/tutorial/pynqhls/io/notebooks ``` ## Automating Installation The next step is to automate the installation using [PIP](https://pip.pypa.io). In the previous notebook you added your `ioOverlay` class to the Python Search path. By creating a `setup.py` file and running `pip3.6` you will be able to run your overlay from any Python shell without modifying the search path. To do this, we will create a `setup.py` script in the repository. You cannot skip this step, but fortunately, we provide working code for you. ### Creating a `setup.py` file A `setup.py` file is the central part of distributing a python package using PIP. In this step we will create a simple `setup.py` script that executes the following steps: 1. Installs the notebooks folder as a folder with the name `HLS-Tutorial-Output` in the Jupyter Home directory (`/home/xilinx/jupyter_notebooks` on a PYNQ board) 2. Installs the overlay (`io.bit` file, `io.tcl` file, `__init__.py`, and `io.py`) from the previous step into the python `site-packages` folder. More documentation regarding `setup.py` and setup scripts can be found on the [distutils documentation page](https://docs.python.org/3/distutils/setupscript.html). Copy and paste the following cell into `setup.py` inside `/home/xilinx/PYNQ-HLS/tutorial/` on your PYNQ board: ``` from setuptools import setup import os jupyter_dest = '/home/xilinx/jupyter_notebooks' # Find all of the tutorial notebooks in the notebooks_src path notebooks_src = 'pynqhls/io/notebooks/' notebooks_dest = os.path.join(jupyter_dest, 'HLS-Tutorial-Output') notebooks = [os.path.join(notebooks_src, f) for f in os.listdir(notebooks_src)] # Find all of the tutorial notebook pictures in the pictures_src path notebooks_pictures_src = os.path.join(notebooks_src, 'pictures') notebooks_pictures_dest = os.path.join(notebooks_dest, 'pictures') notebooks_pictures = [os.path.join(notebooks_pictures_src, f) for f in os.listdir(notebooks_pictures_src)] notebooks.remove(notebooks_pictures_src) setup(name='pynq-hls-tutorial', version='0.1', description="A simple package describing how to create a PYNQ \ bitstream with HLS cores", author='Your Name', author_email='youremail@yourinstitution.edu', license='BSD-3', data_files = [(notebooks_dest, notebooks), (notebooks_pictures_dest, notebooks_pictures)], package_dir = {'pynqhls_tutorial': './pynqhls'}, packages=['pynqhls_tutorial', 'pynqhls_tutorial.io'], package_data={'':['*.bit', '*.tcl']}, install_requires=['pynq'], dependency_links=['http://github.com/xilinx/PYNQ.git@v2.0#egg=pynq'], ) ``` The `setup.py` file starts with a set of variable declarations: - The variable `jupyter_dest` defines the path of the Jupyter Notebooks directory on the PYNQ board. - The variable `notebooks` defines the location of the `.ipynb` notebook files for delivery, and `notebooks_dest` defines the destination. Likewise for `notebooks_pictures_src` and `notebooks_pictures_dest`. Inside the call to `setup()` we pass the arguments [`data_files`](https://docs.python.org/3.6/distutils/setupscript.html#installing-additional-files), [`packages` and `package_dir`](https://docs.python.org/3.6/distutils/setupscript.html#listing-whole-packages), and [`package_data`](https://docs.python.org/3.6/distutils/setupscript.html#installing-package-data). - `data_files` is a list of Relative-Source and Destination-Path tuples used to install non-python files (like notebooks and pictures) - `packages` is a list of Python packages to install - `package_dir` is a dictonary mapping package names to directory locations - `package_data` is a dictionary containing a package and list of relative files that should be included in that package In order to install this as a PYNQ package using `setup.py` we need to modify all four variables, as shown above Once you have saved `setup.py` in `/home/xilinx/PYNQ-HLS/tutorial` you will be able to install the IO Overlay you have created on your PYNQ board using the cell below: ``` !pip3.6 install /home/xilinx/PYNQ-HLS/tutorial/ ``` When the command has completed reload this notebook and run the following cell. Note how the package name has changed from `pynqhls` to `pynqhls_tutorial` to avoid conflicts in the Python package namespace: ``` from pynqhls_tutorial.io import ioOverlay overlay = ioOverlay('io.bit') ``` If you are successful, you can re-run the same tests from the previous notebook: ``` import time overlay.launch() time.sleep(10) buttons = overlay.land() for i in range(4): if(buttons & (1<<i)): print(f"Button {i} is pressed!") ``` ## Installing from Git The steps we have shown above install a Python package from a local directory. To install a Python Package from Git you must provide a `setup.py` file in the root directory. These tutorials demonstrate one example of using a `setup.py` file to distribute a PYNQ Pver;ay. The `setup.py` file we use is shown below: ``` from setuptools import setup import os jupyter_dest = '/home/xilinx/jupyter_notebooks' # We provide three tutorials: tutorials = ["stream", "sharedmem", "io"] # Find all of the tutorial notebooks in the tutorials_base path tutorials_base = 'tutorial/notebooks/' tutorials_dest_base = os.path.join(jupyter_dest, 'HLS-Tutorial') data_files = [] # For each tutorial, install the notebooks and pictures for the tutorial. for tut in tutorials: nbsource = os.path.join(tutorials_base, tut) notebooks = [os.path.join(nbsource, f) for f in os.listdir(nbsource)] nbdest = os.path.join(tutorials_dest_base, tut) picsource = os.path.join(nbsource, 'pictures') pictures = [os.path.join(picsource, f) for f in os.listdir(picsource)] picdest = os.path.join(nbdest, 'pictures') notebooks.remove(picsource) data_files.append((nbdest, notebooks)) data_files.append((picdest, pictures)) demo_base = 'pynqhls/' demo_dest_base = os.path.join(jupyter_dest, 'HLS-Demo') # For each tutorial, install the demo notebook and pictures for tut in tutorials: nbsource = os.path.join(demo_base, tut, 'notebooks') notebooks = [os.path.join(nbsource, f) for f in os.listdir(nbsource)] nbdest = os.path.join(demo_dest_base, tut) picsource = os.path.join(nbsource, 'pictures') pictures = [os.path.join(picsource, f) for f in os.listdir(picsource)] picdest = os.path.join(nbdest, 'pictures') notebooks.remove(picsource) data_files.append((nbdest, notebooks)) data_files.append((picdest, pictures)) setup(name='pynq-hls', version='0.1', description="A simple package describing how to create a PYNQ\ bitstream with HLS cores", author='Dustin Richmond', author_email='drichmond@eng.ucsd.edu', url='https://github.com/drichmond/PYNQ-HLS/', license='BSD-3', data_files = data_files, packages=['pynqhls', 'pynqhls.stream', 'pynqhls.io', 'pynqhls.sharedmem'], package_data={'':['*.bit', '*.tcl']}, install_requires=['pynq'], dependency_links=['http://github.com/xilinx/PYNQ.git@v2.0#egg=pynq'], ) ```
github_jupyter
``` import VGG19 from importlib import reload import matplotlib.pyplot as plt # from PatchMatchMxnet import init_nnf, upSample_nnf, avg_vote, propagate, reconstruct_avg,tran_shape import mxnet as mx import copy from utils import * import numpy as np %matplotlib inline # reload(VGG19) # model = VGG19.VGG19() img_A = load_image("./data/ava.jpg", 0.5) img_BP = load_image("./data/mona.jpg", 0.5) plt.subplot(1, 2, 1) plt.imshow(img_A[:, :, (2, 1, 0)]) plt.subplot(1, 2, 2) plt.imshow(img_BP[:, :, (2, 1, 0)]) plt.show() # mxnet 中使用的图片数据的格式应该与opencv中还是类似的 params = { 'layers': [29, 20, 11, 6, 1], 'iter': 10, } rangee = [32, 6, 6, 4, 4, 2] sizes = [3, 3, 3, 5, 5, 3] lr = [0.1, 0.005, 0.005, 0.00005] weights= [1.0, 0.8, 0.7, 0.6, 0.1, 0.0] data_A,data_A_size = model.get_features(img_tensor=img_A, layers=params['layers']) data_B,data_B_size = model.get_features(img_tensor=img_BP, layers=params['layers']) for layer_size in data_A_size: print("size_idx:", layer_size) data_AP = copy.deepcopy(data_A) # 若data_A 已经是GPU上的数组,那么data_A经过deepcopy之后得到的依旧在GPU上 curr_layer = 0 ctx = mx.gpu(0) ann_AB = init_nnf(data_A_size[curr_layer][2:], data_A_size[curr_layer][2:]) # type == array next_layer = curr_layer + 2 ann_AB_upnnf2 = upSample_nnf(ann_AB, data_A_size[next_layer][2:]) target_BP_np = avg_vote(ann_AB, data_A[curr_layer], sizes[curr_layer], data_A_size[curr_layer][2:], data_A_size[curr_layer][2:]) Ndata_A, response_A = normalize(data_A[curr_layer]) Ndata_B, response_B= normalize(data_B[curr_layer]) ann_AB, _ = propagate(ann_AB, Ndata_A, Ndata_A, Ndata_B, Ndata_B, sizes[curr_layer], params['iter'], rangee[curr_layer]) ann_AB ann_AB_upnnf2 = upSample_nnf(ann_AB, data_A_size[next_layer][2:]) data_AP[curr_layer] = blend(response_A, data_A[curr_layer], data_AP[curr_layer], weights[curr_layer]) data_B_np = avg_vote(ann_AB_upnnf2, ts2np(data_A[next_layer]), sizes[next_layer], data_A_size[next_layer][2:], data_A_size[next_layer][2:]) print(data_B_np.shape) target_BP_np = avg_vote(ann_AB, ts2np(data_A[curr_layer]), sizes[curr_layer], data_A_size[curr_layer][2:], data_A_size[curr_layer][2:]) print(target_BP_np.shape) print(ann_AB.shape) data_AP[curr_layer + 1] = model.get_deconvoluted_feat(target_BP_np, curr_layer, data_AP[next_layer], lr=lr[curr_layer], iters=400, display=False) from mxnet import nd import numpy as np A= nd.array([1,2,3,4,5]) print(A.clip(3,5)) from mxnet import optimizer optimizer.Adam(A,1) A = [1,2,3,4,5] plt.plot(A) import cv2 import matplotlib.pyplot as plt %matplotlib inline import numpy as np Img = cv2.imread("./results/good_one.png")[:, :, (2, 1, 0)]/255.0 Img = Img.astype(np.float32) plt.figure(figsize=(100,100)) plt.imshow(Img) blur = cv2.bilateralFilter(Img,3,15,15) plt.figure(figsize=(100,100)) plt.imshow(blur) from main import * config = get_config("data/2/1.jpg", "data/2/2.jpg", 2) # load images img_A = load_image(config['img_A_path']) img_BP = load_image(config['img_BP_path']) plt.figure(figsize=(10,10)) output_img(img_A[:, :, (2, 1, 0)], img_BP[:, :, (2, 1, 0)]) # # Deep-Image-Analogy tic = time() img_AP, img_B = analogy(img_A, img_BP, config) print("all_analogy_time_is:{}".format(time() - tic)) i plt.figure(figsize=(20,20)) output_img(img_AP, img_B) for i in range(6): print(i) ```
github_jupyter
``` # Duplicate of python wrapper tests but going through a trivial reference frame. from jp_doodle import dual_canvas from IPython.display import display from jp_proxy_widget import notebook_test_helpers from canvas_test_helpers import ColorTester validators = notebook_test_helpers.ValidationSuite() c = dual_canvas.DualCanvasWidget(width=220, height=220) display(c) def two_rects(c): # trivial reference frame frame = c.rframe(1,1) r1 = frame.rect(x=0, y=0, w=100, h=100, color="rgb(123,34,222)", events=False, name=True) r2 = frame.rect(x=0, y=0, w=100, h=100, color="rgb(234,222,111)", events=True) return (r1, r2) (cr1, cr2) = two_rects(c) cr2.change(color="rgb(111,222,222)") c.fit() # should be light cyan after change c_tester = ColorTester(c, "change", height=220) c_tester.add_check(100, 100, [111,222,222, 255]) validators.add_validation(c, c_tester.validate) #c_tester.validate() f = dual_canvas.DualCanvasWidget(width=220, height=220) display(f) (fr1, fr2) = two_rects(f) fr2.forget() f.fit() f_tester = ColorTester(f, "forget", height=220) f_tester.add_check(100, 100, [123,34,222, 255]) validators.add_validation(f, f_tester.validate) #f_tester.validate() v = dual_canvas.DualCanvasWidget(width=220, height=220) display(v) (vr1, vr2) = two_rects(v) vr2.visible(False) v.fit() v_tester = ColorTester(v, "visible", height=220) v_tester.add_check(100, 100, [123,34,222, 255]) validators.add_validation(v, v_tester.validate) #v_tester.validate() t = dual_canvas.DualCanvasWidget(width=220, height=220) display(t) (tr1, tr2) = two_rects(t) done_callback_called = False def done_callback(): global done_callback_called done_callback_called = True def check_done_callback_called(): assert done_callback_called, "Done callback was not called" print("Done callback was called!") tr2.transition(color="rgb(111,222,222)", seconds_duration=0.01, done_callback=done_callback) t.fit() #check_done_callback_called() t_tester = ColorTester(t, "transition", height=220) t_tester.add_check(100, 100, [111,222,222, 255]) validators.add_validation(t, t_tester.validate) validators.add_validation(t, check_done_callback_called) done_callback_called #t_tester.position_to_color_found = {} #t_tester.validate() #t.js_debug() #t.element.request_redraw() n = dual_canvas.DualCanvasWidget(width=220, height=220) display(n.debugging_display()) (nr1, nr2) = two_rects(n) n_info = [] def n_callback(event): print("called back " + repr(event.get("canvas_name"))) assert event["canvas_name"] == nr2.name, (event["canvas_name"], nr2.name) n_info.append(event) nr2.change(color="rgb(111,222,222)") nr2.on("click", n_callback) n.fit() n_tester = ColorTester(n, "on event", height=220) n_tester.spoof_event("click", 100, 100) n_tester.add_check(100, 100, [111,222,222, 255]) validators.add_validation(n, n_tester.validate) #n_tester.validate() n_info ff = dual_canvas.DualCanvasWidget(width=220, height=220) display(ff.debugging_display()) (ffr1, ffr2) = two_rects(ff) ff_info = [] def ff_callback(event): print("called back " + repr(event.get("canvas_name"))) assert event["canvas_name"] == ffr2.name ff_info.append(event) ffr2.change(color="rgb(111,222,222)") ffr2.on("click", n_callback) ffr2.off("click") ff.fit() ff_tester = ColorTester(ff, "off event", height=220) ff_tester.spoof_event("click", 100, 100) ff_tester.add_check(100, 100, [234,222,111, 255]) validators.add_validation(ff, ff_tester.validate) #ff_tester.validate() do_validations = True if do_validations: delay_ms = 5000 display(validators.run_all_in_widget(delay_ms=delay_ms)) ```
github_jupyter
``` import pandas as pd import numpy as np df = pd.read_csv('amazon_baby.csv', dtype={"name": str, "review": str, "rating": np.int32}) df.head() ``` # Build word count vector for each view ``` from sklearn.feature_extraction.text import CountVectorizer df.dropna(inplace=True) vectorizer = CountVectorizer() def word_count(s): try: x = vectorizer.fit_transform([s]) res = {} voc = vectorizer.get_feature_names() for index, count in enumerate(x.toarray()[0]): if count > 0: res[voc[index]] = count except: return '' return res df['word_count'] = df['review'].apply(word_count) df.head() giraffe_reviews = df[df['name']=='Vulli Sophie the Giraffe Teether'] len(giraffe_reviews) import matplotlib.pyplot as plt %matplotlib notebook plt.figure() giraffe_reviews['rating'].value_counts(ascending=True).plot(kind='bar') plt.xticks(rotation=0) df.rating.value_counts() df = df[df.rating != 3] df['sentiment'] = df['rating'] >= 4 df.head() from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression X_train, X_test, y_train, y_test = train_test_split(df['review'], df['sentiment'], random_state=0, train_size=0.8) sentiment_model = LogisticRegression() X_train = vectorizer.fit_transform(X_train) sentiment_model.fit(X_train, y_train) sentiment_model.score(X_train, y_train) X_test = vectorizer.transform(X_test) sentiment_model.score(X_test, y_test) from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt %matplotlib notebook def metric_roc_curve(fpr,tpr,roc_auc): plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Sentiment Analyzing') plt.legend(loc="lower right") plt.show() y_pred = sentiment_model.predict_proba(X_test) fpr, tpr, _ = roc_curve(y_test, y_pred[:, 1]) roc_auc = auc(fpr, tpr) metric_roc_curve(fpr, tpr, roc_auc) ``` # Question 1 ``` selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] index = {} for word in selected_words: index[word] = 0 def f(s): for word in selected_words: if word in s: index[word] += s[word] _ = df.word_count.apply(f) index max(index.items(), key=lambda x: x[1]) ``` # Question two ``` min(index.items(), key=lambda x: x[1]) def selected_count(dic, word): if word in dic: return dic[word] return 0 for word in selected_words: df[word] = df.word_count.apply(selected_count, args=(word,)) X_train, X_test, y_train, y_test = train_test_split(df[selected_words], df['sentiment'], random_state=0, train_size=0.8) model = LogisticRegression() model.fit(X_train, y_train) coeff = pd.DataFrame({'name': selected_words, 'value': model.coef_[0]}) coeff.sort_values('value') model.score(X_test, y_test) np.sum(y_test)/len(list(y_test)) df[df['name'] == 'Baby Trend Diaper Champ'] Baby_df = df[df['name']=='Baby Trend Diaper Champ'] X_train = Baby_df['review'] y_train = Baby_df['sentiment'] vectorize = CountVectorizer() X_train = vectorize.fit_transform(X_train) baby_model = LogisticRegression() baby_model.fit(X_train, y_train) Baby_df['pred'] = baby_model.predict_proba(X_train)[:, 1] Baby_df['pred1'] = model.predict_proba(Baby_df[selected_words])[:, 1] Baby_df.sort_values('pred', ascending=False) Baby_df.sort_values('pred', ascending=False).iloc[0, 1] ```
github_jupyter
[View in Colaboratory](https://colab.research.google.com/github/AnujArora23/FlightDelayML/blob/master/DTFlightDelayDataset.ipynb) # Flight Delay Prediction (Regression) **NOTE: THIS IS A CONTINUATION OF THE *SGDFlightDelayDataset.ipynb* NOTEBOOK WHICH USES STOCHASTIC GRADIENT DESCENT REGRESSION. THIS PART ONLY CONTAINS THE BOOSTED DECISION TREE PREDICTION AND COMPARISON BETWEEN THE TWO. FOR DATA CLEANING AND EXPLORATION, PLEASE SEE THE PREVIOUS NOTEBOOK.** These datasets are taken from Microsoft Azure Machine Learning Studio's sample datasets. It contains flight delay data for various airlines for the year 2013. There are two files uploaded as a compressed archive on my GitHub page: 1) **Flight_Delays_Data.csv** : This contains arrival and departure details for various flights operated by 16 different airlines. The schema is pretty self explanatory but I will mention the important and slightly obscure columns: *OriginAirportID/DestAirportID* : The unique 5 digit integer identifier for a particular airport. *CRSDepTime/CRSArrTime* : Time in 24 hour format (e.g. 837 is 08:37AM) *ArrDel15/DepDel15* : Binary columns where *1* means that the flight was delayed beyond 15 minutes and *0* means it was not. *ArrDelay/DepDelay* : Time (in minutes) by which flight was delayed. 2) **Airport_Codes_Dataset.csv** : This file gives the city, state and name of the airport along with the unique 5 digit integer identifier. ### Goals: **1. Clean the data, and see which features may be important and which might be redundant.** **2. Do an exploratory analysis of the data to identify where most of the flight delays lie (e.g. which carrier, airport etc.).** **3. Choose and build an appropriate regression model for this dataset to predict *ArrDelay* time in minutes.** **4. Choose and build alternative models and compare all models with various accuracy metrics.** ## Install and import necessary libraries ``` !pip install -U -q PyDrive #Only if you are loading your data from Google Drive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import preprocessing from sklearn.linear_model import SGDRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import AdaBoostRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import cross_val_score, cross_val_predict from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV from sklearn import grid_search from sklearn import metrics ``` ## Authorize Google Drive (if your data is stored in Drive) ``` %%capture auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) ``` ## Data Ingestion I have saved the two files in my personal drive storage and read them from there into a pandas data frame. Please modify the following cells to read the CSV files into a Pandas dataframe as per your storage location. ``` %%capture downloaded = drive.CreateFile({'id':'1VxxZFZO7copAM_AHHF42zjO7rlGR1aPm'}) # replace the id with id of file you want to access downloaded.GetContentFile('Airport_Codes_Dataset.csv') downloaded = drive.CreateFile({'id':'1owzv86uWVRace_8xvRShFrDTRXSljp3I'}) # replace the id with id of file you want to access downloaded.GetContentFile('Flight_Delays_Data.csv') airpcode = pd.read_csv('Airport_Codes_Dataset.csv') flightdel = pd.read_csv('Flight_Delays_Data.csv') ``` ## Data Cleanup ### Remove NULL /NaN rows and drop redundant columns ``` flightdel.dropna(inplace=True) #Drop NaNs. We will still have enough data flightdel.drop(['Year','Cancelled'],axis=1,inplace=True) #There is only 1 unique value for both (2013 and 0 respectively) flightdel.reset_index(drop=True,inplace=True) ``` ###Join the 2 CSV files to get airport code details for origin and destination ``` result=pd.merge(flightdel,airpcode,left_on='OriginAirportID',right_on='airport_id',how='left') result.drop(['airport_id'],axis=1,inplace=True) #result.reset_index(drop=True,inplace=True) result.rename(columns={'city':'cityor','state':'stateor','name':'nameor'},inplace=True) result=pd.merge(result,airpcode,left_on='DestAirportID',right_on='airport_id',how='left') result.drop(['airport_id'],axis=1,inplace=True) result.reset_index(drop=True,inplace=True) result.rename(columns={'city':'citydest','state':'statedest','name':'namedest'},inplace=True) flightdelfin=result ``` ### Perform Feature Conversion (to categorical dtype) ``` cols=['Carrier','DepDel15','ArrDel15','OriginAirportID','DestAirportID','cityor','stateor','nameor','citydest','statedest','namedest'] flightdelfin[cols]=flightdelfin[cols].apply(lambda x: x.astype('category')) ``` ###Drop duplicate observations ``` flightdelfin.drop_duplicates(keep='first',inplace=True) flightdelfin.reset_index(drop=True,inplace=True) ``` ###Drop columns that are unnecessary for analysis **In particular, we drop ArrDel15 and DepDel15 columns as they add no extra information from the ArrDel and DepDel columns respectively.** ``` flightdelan=flightdelfin.iloc[:,0:11] flightdelan.drop('DepDel15',axis=1,inplace=True) flightdelan.head() ``` ###Final check before analysis ** We check if our data types are correct and do a general scan of the dataframe information. It looks good! Everything is as it should be.** ``` flightdelan.info() #flightdelan[['Month','DayofMonth','DayOfWeek']]=flightdelan[['Month','DayofMonth','DayOfWeek']].apply(lambda x: x.astype(np.int64)) ``` ## Prediction ### Convert Categorical Variables to Indicator Variables **To do any sort of prediction, we need to convert the categorical variables to dummy (indicator) variables and drop one group in for each categorical column in the original table, so as to get a baseline to compare to. If we do not drop one group from each categorical variable, our regression will fail due to multicollinearity.** **The choice of which group(s) to drop is complete arbitrary but in our case, we will drop the carrier with the least number of flights i.e. Hawaiian Airlines (HA), and we will choose an arbitrary city pair with just 1 flight frequency to drop. As of now I have chosen the OriginAirportID as 14771 and the DestAirportID as 13871 to be dropped.** ``` flightdeldum=pd.get_dummies(flightdelan) flightdeldum.drop(['Carrier_HA','OriginAirportID_14771','DestAirportID_13871'],axis=1,inplace=True) flightdeldum.head() ``` **As one can see above, each cateogrical column has been converted to 'n' binary columns where n was the number of groups in that particular categorical column. For example, the carrier column has been split into 16 indicator columns (number of unique carriers) and one has been dropped ('Carrier_HA').** **Similar logic can be applied to the DestAirportID and OriginAirportID categorical columns.** **NOTE: The Month, DayofMonth and DayofWeek columns have not been converted to indicator variables because they are ORDINAL cateogorical variables and not nominal. There is a need to retain their ordering because the 2nd month comes after the 1st and so on. Hence, since their current form retains their natural ordering, we do not need to touch these columns.** ### Decision Tree Regression **To predict the arrival delays for various combinations of the input variables and future unseen data, we need to perform a regression since the output variable (ArrDelay) is a continuous one.** **Decision trees are an alternative algorithm for prediction (both classification and regression). SGD regression, is after all, a form of multiple linear regression, which assumes linearity between features, whereas decision trees do not assume linearity between features. Hence, it is a good idea to run a decision tree regressor on our data set to see if we get any imporvement.** ``` scaler = preprocessing.StandardScaler() flightdeldum[['CRSDepTime','CRSArrTime','DepDelay']]=scaler.fit_transform(flightdeldum[['CRSDepTime','CRSArrTime','DepDelay']]) y=flightdeldum.ArrDelay X=flightdeldum.drop('ArrDelay',axis=1) ``` **In the cell above, we have scaled the relevant columns (Z score) that had values that were dissimilar to the rest of the features, as the regularization strategy we are going to use, requires features to be in a similar range.** **We now split the data into training and testing data and in this case, we are going to use 80% of the data for training and the remaining for testing.** ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123) ``` **We use the min_samples_split parameter in the sklearn decision tree package, as a stopping criteria. ** ``` # Fit regression model regr_1 = DecisionTreeRegressor(min_samples_split=100) regr_1.fit(X_train,y_train) ``` **In the above cell, we trained the model using the DecisionTreeRegressor and now it is time to predict using the test data.** ``` y_pred=regr_1.predict(X_test) # The coefficients #print('Coefficients: \n', reg.coef_) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test.values, y_pred)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % r2_score(y_test.values, y_pred)) plt.scatter(y_test.values, y_pred) plt.xlabel("True Values") plt.ylabel("Predictions") plt.show() ``` **As we can see from the above cells, 88% of the variance (R^2 score) in the data has been captured and the model is predicting well. The trend line in the graph would be very close to the ideal 45 degree trend line (expected line if the model predicted with 100% accuracy).** **However, we do not want to overfit our model because we want it to perform well on new untested data. To check if our model overfits, we can run a 6 fold cross validation and analyze the variance (R^2 scores) on each fold ,as shown below.** ``` # Perform 6-fold cross validation kfold = KFold(n_splits=6) scores = cross_val_score(regr_1, X, y, cv=kfold) print 'Cross-validated scores:', scores print 'Average Cross-validated score:', np.mean(scores) ``` ###Grid Search (Hyperparameter Tuning) (Optional and Computationally Expensive) **The following function performs a search over the entire parameter grid (as specified below) for the minimum number of samples to split (minimum number of observations required for node to be split), and returns the optimal parameters, after an n fold cross validation.** ``` #https://medium.com/@aneesha/svm-parameter-tuning-in-scikit-learn-using-gridsearchcv-2413c02125a0 def dectree_param_selection(X, y, nfolds): min_samples_splits = [60,80,100] param_grid = {'min_samples_split': min_samples_splits} grid_search = GridSearchCV(DecisionTreeRegressor(), param_grid, cv=nfolds) grid_search.fit(X, y) grid_search.best_params_ return grid_search.best_params_ dectree_param_selection(X_train,y_train,5) ``` **As we can see above, the grid search has yielded the optimal parameters for the min_samples_split parameter. This process took about 40 minutes to execute as it is very computationally expensive.** **Since, we received the same parameter as our initial estimate, we can conclude our decision tree regressor here.** ##Comparison **We have seen that, after running a 6 fold cross validation (to eliminate overfitting), we have the following results for each of the predictors:** **1) SGD Regression (with gridsearch parameters) : MSE = ~164, R^2=~89%** **2) Decision Tree Regression: MSE= ~184, R^2=~86%** **Since both results involve at least a 5 fold cross validation, we can be assured that the models are not overfit. Hence, given the above figures, we can clearly see that the Stochastic Gradient Descent Regression is a better algorithm for this problem.** **FINAL CHOICE: Stochastic Gradient Descent Regression.**
github_jupyter
``` import sys sys.path.append('../..') import torchdyn; from torchdyn.models import *; from torchdyn.datasets import * from pytorch_lightning.loggers import WandbLogger data = ToyDataset() n_samples = 1 << 16 n_gaussians = 7 X, yn = data.generate(n_samples // n_gaussians, 'gaussians', n_gaussians=7, std_gaussians=0.1, dim=2, radius=2) X = (X - X.mean())/X.std() import matplotlib.pyplot as plt plt.figure(figsize=(3, 3)) plt.scatter(X[:,0], X[:,1], c='orange', alpha=0.3, s=4) import torch import torch.utils.data as data device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") X_train = torch.Tensor(X).to(device) y_train = torch.LongTensor(yn).long().to(device) train = data.TensorDataset(X_train, y_train) trainloader = data.DataLoader(train, batch_size=512, shuffle=True) ``` ## Model ``` from torch.distributions import MultivariateNormal, Uniform, TransformedDistribution, SigmoidTransform, Categorical prior = MultivariateNormal(torch.zeros(2).to(device), torch.eye(2).to(device)) f = nn.Sequential( nn.Linear(2, 32), nn.Softplus(), DataControl(), nn.Linear(32+2, 2) ) # cnf wraps the net as with other energy models noise_dist = MultivariateNormal(torch.zeros(2).to(device), torch.eye(2).to(device)) cnf = nn.Sequential(CNF(f)) nde = NeuralDE(cnf, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-6, rtol=1e-6, sensitivity='adjoint') model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1), nde).to(device) ``` ## Learner ``` def cnf_density(model): with torch.no_grad(): npts = 200 side = np.linspace(-2., 2., npts) xx, yy = np.meshgrid(side, side) memory= 100 x = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)]) x = torch.from_numpy(x).type(torch.float32).to(device) z, delta_logp = [], [] inds = torch.arange(0, x.shape[0]).to(torch.int64) for ii in torch.split(inds, int(memory**2)): z_full = model(x[ii]).cpu().detach() z_, delta_logp_ = z_full[:, 1:], z_full[:, 0] z.append(z_) delta_logp.append(delta_logp_) z = torch.cat(z, 0) delta_logp = torch.cat(delta_logp, 0) logpz = prior.log_prob(z.cuda()).cpu() # logp(z) logpx = logpz - delta_logp px = np.exp(logpx.cpu().numpy()).reshape(npts, npts) plt.imshow(px); plt.xlabel([]) plt.ylabel([]) class Learner(pl.LightningModule): def __init__(self, model:nn.Module): super().__init__() self.model = model self.lr = 1e-3 def forward(self, x): return self.model(x) def training_step(self, batch, batch_idx): # plot logging if batch_idx == 0: cnf_density(self.model) self.logger.experiment.log({"chart": plt}) plt.close() nde.nfe = 0 x, _ = batch x += 1e-2*torch.randn_like(x).to(x) xtrJ = self.model(x) logprob = prior.log_prob(xtrJ[:,1:]).to(x) - xtrJ[:,0] loss = -torch.mean(logprob) nfe = nde.nfe nde.nfe = 0 metrics = {'loss': loss, 'nfe':nfe} self.logger.experiment.log(metrics) return {'loss': loss} def configure_optimizers(self): return torch.optim.AdamW(self.model.parameters(), lr=self.lr, weight_decay=1e-5) def train_dataloader(self): self.loader_l = len(trainloader) return trainloader logger = WandbLogger(project='torchdyn-toy_cnf-bench') learn = Learner(model) trainer = pl.Trainer(min_steps=45000, max_steps=45000, gpus=1, logger=logger) trainer.fit(learn); sample = prior.sample(torch.Size([1<<15])) # integrating from 1 to 0, 8 steps of rk4 model[1].s_span = torch.linspace(0, 1, 2) new_x = model(sample).cpu().detach() cnf_density(model) plt.figure(figsize=(12, 4)) plt.subplot(121) plt.scatter(new_x[:,1], new_x[:,2], s=0.3, c='blue') #plt.scatter(boh[:,0], boh[:,1], s=0.3, c='black') plt.subplot(122) plt.scatter(X[:,0], X[:,1], s=0.3, c='red') def cnf_density(model): with torch.no_grad(): npts = 200 side = np.linspace(-2., 2., npts) xx, yy = np.meshgrid(side, side) memory= 100 x = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)]) x = torch.from_numpy(x).type(torch.float32).to(device) z, delta_logp = [], [] inds = torch.arange(0, x.shape[0]).to(torch.int64) for ii in torch.split(inds, int(memory**2)): z_full = model(x[ii]).cpu().detach() z_, delta_logp_ = z_full[:, 1:], z_full[:, 0] z.append(z_) delta_logp.append(delta_logp_) z = torch.cat(z, 0) delta_logp = torch.cat(delta_logp, 0) logpz = prior.log_prob(z.cuda()).cpu() # logp(z) logpx = logpz - delta_logp px = np.exp(logpx.cpu().numpy()).reshape(npts, npts) plt.imshow(px, cmap='inferno', vmax=px.mean()); a = cnf_density(model) ```
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import featuretools as ft import lightgbm as lgb import seaborn as sns from sklearn.model_selection import GridSearchCV from sklearn.model_selection import KFold from sklearn.metrics import roc_auc_score from random import sample import pickle import eli5 from eli5.sklearn import PermutationImportance from lightgbm import LGBMClassifier from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA import math %matplotlib inline RSEED = 50 ``` # Load Original Features ``` feat_num = 439 # 取出feature文件 with open('./data/features%s_na.pickle'%(feat_num), 'rb') as handle: df_total_raw = pickle.load(handle) # 取出要删掉的列 with open('./data/feat%s_rm_pm_importance100.pickle'%(437), 'rb') as handle: to_drop = pickle.load(handle) # 删掉不用的feature df_total = df_total_raw.drop(list(to_drop),axis=1) print(df_total.shape) df_total.head() # 把train和test文件分开 df_train = df_total[df_total['isFraud'].notnull()] features_test = df_total[df_total['isFraud'].isnull()] features_test_new = features_test.drop(columns = ['isFraud', 'TransactionID']) # 区分train文件中的正例和负例 train_pos = df_train[df_train['isFraud']==1] train_neg = df_train[df_train['isFraud']==0] print(train_pos.shape,train_neg.shape) train_neg_sfd = train_neg.sample(frac=1) train_neg_sfd.head() size = math.floor(train_neg.shape[0] * 0.2) print(size) ``` # Prepare Model ``` categorical = ['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 = categorical + ids categorical = list(set(categorical).intersection(df_total.columns)) 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",#'goss' "bagging_seed": 11, "metric": 'auc', "verbosity": -1, 'reg_alpha': 0.3899927210061127, 'reg_lambda': 0.6485237330340494, 'random_state': 47 #'num_threads':10 #'device' :'gpu', #'is_unbalance':True #'scale_pos_weight':9 } ``` # Train Model ``` predictions = np.zeros(len(features_test_new)) ave_auc = 0 splits = 5 for k in range(0,splits): print("Fold {}".format(k)) # 生成采样数据集 print('Generate Train Data') train_neg_sample = train_neg_sfd.iloc[size*k:size*(k+1)] df_train_sample = pd.concat([train_pos,train_neg_sample]).sort_index() # 定义label和feature labels_train = df_train_sample['isFraud'] features_train = df_train_sample.drop(columns = ['isFraud', 'TransactionID']) valid_num = math.floor(features_train.shape[0]*0.8) print(features_train.shape,labels_train.shape,valid_num) print('Training Begin') # 训练数据 train_set = lgb.Dataset(features_train.iloc[0:valid_num,:], label=labels_train.values[0:valid_num],categorical_feature=categorical)# valid_set = lgb.Dataset(features_train.iloc[valid_num:,:], label=labels_train.values[valid_num:],categorical_feature=categorical)# valid_results = {} model = lgb.train(params,train_set,num_boost_round = 10000, valid_sets = [train_set, valid_set], verbose_eval=500, early_stopping_rounds = 500, evals_result=valid_results) print('Training Finish,Predicting') pred = model.predict(features_train.iloc[valid_num:,:]) auc_score = roc_auc_score(labels_train.values[valid_num:], pred) ave_auc += auc_score / splits predictions += model.predict(features_test_new) / splits ave_auc # feat438 ave_auc # feat439 drop transactionDT ave_auc # feat439 baseline ave_auc id_test = features_test['TransactionID'] submission = pd.DataFrame({'TransactionID': id_test, 'isFraud': predictions}) submission.to_csv('./data/sub_feat%s_easyensemble.csv'%(feat_num), index = False) ```
github_jupyter
## Exercise 3.8 MLE for the uniform distribution (Source: Kaelbling.) Consider a uniform distribution centered on 0 with width $2a$. The density function is given by $$ p(x)= \frac{1}{2a}I(x\in[-a, a]) $$ - a. Given a data set $x_1,\ldots,x_n$, what is the maximum likelihood estimate of $a$ (call it $\hat{a}$)? - b. What probability would the model assign to a new data point $x_{n+1}$ using $\hat{a}$? - c. Do you see any problem with the above approach? Briefly suggest (in words) a better approach. ### Solution #### (a) Let's calculate the maximum likelihood estimator of the uniform distribution on the dataset $D=\{x_1, x_2, \ldots, x_n\}$ \begin{aligned} p(D|a) & = \prod_{i=1}^N p(x_i|a) = \prod_{i=1}^N\frac{1}{2a}I(x_i\in [-a, a])\\ & = \frac{1}{(2a)^N}\prod_{i=1}^N I(x_i \in [-a, a]) \end{aligned} From this we see that the likelihood is a combination of two terms. The first term $\frac{1}{(2a)^N}$ is a monotonic decreasing function in $a$. Thus, as we decrease $a$ we get larger likelihoods. The second term is $\prod_{i=1}^N I(x_i\in[-a, a])$, which is equal to 0 if any of the points of the dataset are outside the interval $[-a, ]$, and equal to 1 otherwise. So in order to have the maximum likelihood, we have to take the minimum value $\hat{a}$ such that $D\subset[-\hat{a}, \hat{a}]$. Let's define $D_{\mathrm{abs}} = \{|x_1|, |x_2|, \ldots, |x_n|\}$. Thus the maximum likelihood estimator is given by $$ \hat{a} = \mathrm{sup}(D_{\mathrm{abs}}) = \max(|x_i|). $$ #### (b) Given a new datapoint $x_{n+1}$, the model would assign it the following probability: $$ p(x_{n+1}) = \frac{1}{2\hat{a}}I(x_{n+1}\in[-\hat{a}, \hat{a}]) = \left\{\begin{array}{ll}\frac{1}{2\hat{a}} & if \hat{a}\ge|x_n+1| \\ 0 & \mathrm{otherwise}\end{array}\right. $$ #### (c) The problem exposed in $(b)$ is the zero count problem, where we have an unreliable MLE, given the nature of our dataset. The MLE is unreliable because it gives 0 probability for every data point greater than $\mathrm{sup}(D_{\mathrm{abs}})$. This becomes even more unreliable when we have small datasets. The MLE is given by $\mathrm{sup}(D_{\mathrm{abs}})$, which makes sense, after all, the MLE is all about maximizing the chance of our dataset to occur. Let's carry out a deeper analysis of our result. Since all datapoints were sampled from the uniform distribution that we are trying to infer, it is reasonable to assume that $a\ge \mathrm{sup}(D_{\mathrm{abs}})$. In order words, if $x_i$ was sampled from a uniform distribution, then $p(x_i)\ne 0$ and $x_i\in[-a, a]$. This result has nothing to do with MLE yet. Now if we want to maximize the chance of our data to occurr, we already saw in (a) that we need to minimize the parameter $a$ given the restrictions above. The problem with this assumption as we saw in (b) and (c) is that it cannot explain the appearance of any new sample greater than $\mathrm{sup}(D_{\mathrm{abs}})$, which consist of the zero count problem. The Bayesian analysis of the uniform distribution infers a distribution for the parameter $a$ that gives zero probability to values $a < \mathrm{sup}(D_{\mathrm{abs}})$ and gives decreasing probabilities for values $a \ge \mathrm{sup}(D_{\mathrm{abs}})$.
github_jupyter
# Tutorial: Introduction to Altair This tutorial is based off the [Altair Tutorial](https://github.com/altair-viz/altair_notebooks). ## Review - The Grammar of Graphics *The Grammar of Graphics*, Wilkinson (2005) uses the following specification: * Data/Variables * Geometry and Aesthetics ## Translating to Altair/Vege-Lite Altair and Vega-Lite use different language. * Geometry $\rightarrow$ **mark** * *Data/Variables* and *Aethetics* $\rightarrow$ **encoding** ## Importing `altair` ``` import altair as alt # Uncomment/run this line to enable Altair in the notebook (not JupyterLab): # alt.renderers.enable('notebook') ``` ## The data Data is specified in two ways. * A `pandas` data frame * Interactive * Use `pandas` tools * A string of a `url` to a csv/JSON data set * Best for posting to the web * see [Defining Data](https://altair-viz.github.io/user_guide/data.html). ## Small `pandas` Data Set ``` import pandas as pd data = pd.DataFrame({'a': ['C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'], 'b': [2, 7, 4, 1, 2, 6, 8, 4, 7]}) data ``` ## The `Chart` object * The fundamental object * Takes a dataframe as an argument ``` chart = alt.Chart(data) ``` At this point the specification contains only the data, and no visualization specification. ## Specifying the Geometry - Chart Marks * Use a `mark` method to specify a geometry * **Example** We can map to points using `mark_point` <img src="../images/1_1_point.png"> ``` chart = alt.Chart(data).mark_point() chart ``` <font color="red"> <b>Question:</b> </font> Why do we get exactly one point? ## Other Mark Types Here are some commonly used `mark_*()` methods; see [Markings](https://altair-viz.github.io/documentation/marks.html) in the Altair documentation: <table> <tr> <th>Method</th><th>Method</th> </tr> <tr> <td><code>mark_area()</code></td> <td><code>mark_point()</code></td> </tr> <tr> <td><code>mark_bar()</code></td> <td><code>mark_rule()</code></td> </tr> <tr> <td><code>mark_circle()</code></td> <td><code>mark_square()</code></td> </tr> <tr> <td><code>mark_line()</code></td> <td><code>mark_text()</code></td> </tr> <tr> <td><code>mark_tick()</code></td> </tr> </table> ## Data encodings To assign information to a mark, we use an **encoding**. A visual encoding specifies * How data should be mapped onto the visual properties. * Can include * Binning * Aggregation * Scaling ## Adding an Encoding to a Chart Object Use the `encode()` method of the `Chart` object. ``` chart = alt.Chart(data).mark_point().encode(y='a') chart ``` ## Common encodings Some of the more frequency used visual encodings are listed here: * **X**: x-axis value * **Y**: y-axis value * **Color**: color of the mark * **Shape**: shape of the mark * **Size**: size of the mark ## Other encodings Here are some other encodings * **Opacity**: transparency/opacity of the mark * **Row**: row within a grid of facet plots * **Column**: column within a grid of facet plots For a complete list of these encodings, see the [Encodings](https://altair-viz.github.io/documentation/encoding.html) . ## Explicit Variable Types * Altair guessed the data type (nominal). * Explicitly specify with a colon ``` chart = alt.Chart(data).mark_point().encode(y='a:N') chart ``` ## Available data types Altair supports four primitive data types: <table> <tr> <th>Data Type</th> <th>Code</th> <th>Description</th> </tr> <tr> <td>quantitative</td> <td>Q</td> <td>Numerical quantity (real-valued)</td> </tr> <tr> <td>nominal</td> <td>N</td> <td>Name / Unordered categorical</td> </tr> <tr> <td>ordinal</td> <td>O</td> <td>Ordered categorial</td> </tr> <tr> <td>temporal</td> <td>T</td> <td>Date/time</td> </tr> </table> ## Mapping 2 Dimension Let's encode column `b` as the `x` position: ``` alt.Chart(data).mark_point().encode( y='a', x='b' ) ``` ## Two Ways to Specify Variables * First method: `y = 'a'` * Short and easy to read * Second method: `alt.Y('a')` * Allows extra features. You will see many example in the next notebook. ``` alt.Chart(data).mark_point().encode( y=alt.Y('a'), x=alt.X('b') ) ``` ## Changing the mark type A different mark type can be chosen using a different `mark_*()` method, such as `mark_bar()`: ``` alt.Chart(data).mark_bar().encode( alt.Y('a'), alt.X('b') ) ``` ## Order Doesn't Matter We can specify the `mark` and `encoding` in any order. ``` alt.Chart(data).encode( alt.Y('a'), alt.X('b') ).mark_bar() ``` ## More than one encoding call We can also split the `encode` into multiple parts ``` alt.Chart(data).mark_bar().encode(y = 'a').encode(x = "b") ``` ## Under-the-hood Details To make a visualization * Altair creates a JSON specification * Vega-lite renders this in the browser ``` chart = alt.Chart(data).mark_point().encode(y='a', x='b') chart.to_dict() ``` ## Publishing a visualization online Because Altair produces Vega-Lite specifications, it is easy to export and post charts on the web. * Light-weight specification. * Vega-lite does all the work (in JavaScript). * No server needed. Use the ``savechart()`` method to save any chart to HTML. ``` chart.savechart('chart.html') !cat chart.html ``` ## View the Resulting Page in a Notebook ``` # Display IFrame in IPython from IPython.display import IFrame IFrame('chart.html', width=400, height=200) ``` Alternatively, you can use your web browser to open the file manually to confirm that it works: [chart.html](chart.html). ## Customizing your visualization For fast data exploration, Altair (via Vega-Lite) has * many default properties, but * provides an API to customize the visualization. ``` alt.Chart(data).mark_bar().encode( y='a', x=alt.X('b', axis=alt.Axis(title='New Label')) ) ``` ## Changing Mark Properties ``` alt.Chart(data).mark_bar(color='firebrick').encode( y='a', x=alt.X('b', axis=alt.Axis(title='New Label')) ) ``` ## Changing Other Properties Set other properties using the ``properties()`` method. ``` chart = alt.Chart(data).mark_bar().encode( y='a', x=alt.X('average(b)', axis=alt.Axis(title='Average of b')) ).properties( width=400, height=300 ) chart ``` ## Learning More For more information on Altair, please refer to Altair's online documentation: http://altair-viz.github.io/
github_jupyter
# Display objects A `striplog` depends on a hierarchy of objects. This notebook shows the objects related to display: - [Decor](#Decor): One element from a legend — describes how to display a Rock. - [Legend](#Legend): A set of Decors — describes how to display a set of Rocks or a Striplog. <hr /> ## Decor ``` from striplog import Decor ``` A Decor attaches a display style to a Rock. ``` print(Decor.__doc__) ``` We are going to need a `Component` to make a `Decor`. ``` from striplog import Component r = {'colour': 'grey', 'grainsize': 'vf-f', 'lithology': 'sand', 'porosity': 0.123 } rock = Component(r) rock d = {'color': '#267022', 'component': rock, 'width': 3} decor = Decor(d) decor from striplog import Component r = {'colour': 'grey', 'grainsize': 'vf-f', 'lithology': 'sand', 'porosity': 0.123 } rock = Component(r) rock ``` Like `Rock`s, we instantiate `Decor`s with a `dict` of properties: ``` d = {'color': '#267022', 'component': rock, 'width': 3} decor = Decor(d) decor ``` Or instantiate with keyword parameters: ``` Decor(colour='#86f0b6', component=Component({'colour': 'grey', 'grainsize': 'vf-f', 'porosity': 0.123, 'lithology': 'sand'}), width=3.0) ``` You can access its attributes. It has two ways to understand colour: ``` print("Hex: {}... and RGB: {}".format(decor.colour, decor.rgb)) print(decor) %matplotlib inline decor.plot() decor.hatch = '+' decor.plot() ``` There are the standard `matplotlib` hatch patterns: ``` hatches = "\/|+x-.o*" for h in hatches: Decor({'component': Component({'hatch':h}), 'hatch': h, 'colour': '#eeeeee'}).plot() ``` And there are some custom ones. These really need to be reconciled and implemented in a more flexible way, perhaps even going as far as a redesign of the mpl implementation. ``` hatches = "pctLbs!=v^" for h in hatches: Decor({'component': Component({'hatch':h}), 'hatch': h, 'colour': '#eeeeee'}).plot(fmt="{hatch}") ``` We can disaply hatches in a single plot for quick reference: ``` import matplotlib.pyplot as plt hatches = ['.', '..', 'o', 'p', 'c', '*', '-', '--', '=', '==', '|', '||', '!', '!!', '+', '++', '/', '\\', '//', '\\\\', '///', '\\\\\\', 'x', 'xx', '^', 'v', 't', 'l', 'b', 's'] fig, axs = plt.subplots(figsize=(16,5.25), ncols=10, nrows=3) fig.subplots_adjust(hspace=0.5) for ax, h in zip(axs.flatten(), hatches): ax.set_title(h) Decor(colour='#eeeeee', component=Component({'hatch': h}), hatch=h).plot(fmt='', ax=ax) ``` <hr /> ## Legend ``` from striplog import Legend print(Legend.__doc__) ``` We'll define a legend in a CSV file. I can't think of a better way for now. It would be easy to make a web form to facilitate this with, for example, a colour picker. It may not be worth it, though; I imagine one would create one and then leave it alone most of the time. ``` l = u"""colour, width, component lithology, component colour, component grainsize #F7E9A6, 3, Sandstone, Grey, VF-F #FF99CC, 2, Anhydrite, , #DBD6BC, 3, Heterolithic, Grey, #FF4C4A, 2, Volcanic, , #86F0B6, 5, Conglomerate, , #FF96F6, 2, Halite, , #F2FF42, 4, Sandstone, Grey, F-M #DBC9BC, 3, Heterolithic, Red, #A68374, 2, Siltstone, Grey, #A657FA, 3, Dolomite, , #FFD073, 4, Sandstone, Red, C-M #A6D1FF, 3, Limestone, , #FFDBBA, 3, Sandstone, Red, VF-F #FFE040, 4, Sandstone, Grey, C-M #A1655A, 2, Siltstone, Red, #363434, 1, Coal, , #664A4A, 1, Mudstone, Red, #666666, 1, Mudstone, Grey, """ legend = Legend.from_csv(text=l) legend[:5] ``` Duplicate lithologies will result in a warning. To avoid strange results, you should fix the problem by removing duplicates. ``` l = u"""colour, component lithology #F7E9A6, Sandstone #F2FF42, Sandstone #FF99CC, Anhydrite #DBD6BC, Heterolithic #FF4C4A, Volcanic #86F0B6, Conglomerate #FFD073, Sandstone """ Legend.from_csv(text=l) ``` We can also export a legend as CSV text: ``` print(legend.to_csv()) ``` ## Builtin legends There are several: 'nsdoe': Nova Scotia Dept. of Energy 'nagmdm__6_2': USGS N. Am. Geol. Map Data Model 6.2 <<< default 'nagmdm__6_1': USGS N. Am. Geol. Map Data Model 6.1 'nagmdm__4_3': USGS N. Am. Geol. Map Data Model 4.3 'sgmc': USGS State Geologic Map Compilation ``` legend = Legend.builtin('nsdoe') legend ``` There is also a default legend, which you can call with `Legend.default()` (no arguments). ``` Legend.default() ``` There are also default timescales: ``` time = Legend.default_timescale() time[:10] ``` ## Legend from image ``` from IPython.display import Image Image('z_Lithology_legend_gapless2.png', width=15) liths = [ 'Conglomerate', 'Sandstone', 'Sandstone', 'Sandstone', 'Sandstone', 'Sandstone', 'Siltstone', 'Siltstone', 'Heterolithic', 'Heterolithic', 'Mudstone', 'Mudstone', 'Limestone', 'Dolomite', 'Anhydrite', 'Halite', 'Coal', 'Volcanic', 'NULL', ] colours = [ None, 'Grey', 'Red', 'Grey', 'Grey', 'Red', 'Grey', 'Red', 'Grey', 'Red', 'Grey', 'Red', None, None, None, None, None, None, None, ] components = [Component({'lithology': l, 'colour': c}) for l, c in zip(liths, colours)] Legend.from_image('z_Lithology_legend_gapless2.png', components).plot() ``` ## Querying a legend The legend is basically a query table. We can ask the Legend what colour to use for a given Rock object: ``` legend.get_colour(rock) rock3 = Component({'colour': 'red', 'grainsize': 'vf-f', 'lithology': 'sandstone'}) legend.get_colour(rock3) Legend.random(rock3) ``` Sometimes we also want to use a width for a given lithology: ``` legend.get_width(rock3) ``` We can also ask the legend which Rock is represented by a particular colour. (I doubt you'd ever really need to do this, but I had to implement this to allow you to make a `Striplog` from an image: it looks up the rocks to use by colour.) ``` legend.get_component('#f7e9a6') ``` The `Legend` behaves more or less like a list, so we can index into it: ``` legend[3:5] ``` `Legend`s can plot themselves. ``` legend.plot() ``` Sometimes you don't want to have to make a legend, so you can use a random one. Just pass a list of `Component`s... ``` # We'll scrape a quick list of 7 components from the default legend: c = [d.component for d in legend[:7]] l = Legend.random(c) l.plot() ``` There is a default colour table for geological timescales too... it's based on the Wikipedia's colour scheme for the geological timetable. ``` time[74:79].plot(fmt="{age!t}") # Pass a format for proper case ``` ## Hatch patterns ``` hatchy = """colour,width,hatch,component colour,component grainsize,component lithology #dddddd,1,+,,,siltstone, #dddddd,1,+++,,,greywacke, #dddddd,2,x,,,anhydrite, #dddddd,2,xxx,,,gypsum, #dddddd,3,/,,,missing, #dddddd,4,..,,,sandstone, #dddddd,5,o,,,conglomerate, #dddddd,5,0,,,till, #dddddd,6,---,,,mudstone, #dddddd,7,,,,limestone, """ Legend.from_csv(text=hatchy).plot() ``` ## Bugs ### Decor plots with axes These should plot as square patches, not rectangles. The text actually flows off the right-hand edge of the plot. ``` import matplotlib.pyplot as plt fig = plt.figure(figsize=(3, 10)) for i, d in enumerate(l): ax = fig.add_subplot(len(l), 1, i+1) ax = d.plot(ax=ax) ``` <hr /> <p style="color:gray">©2015 Agile Geoscience. Licensed CC-BY. <a href="https://github.com/agile-geoscience/striplog">striplog.py</a></p>
github_jupyter
# 1. Pandas - 구조화된 데이터의 처리를 지원하는 Python 라이브러리. Python계의 엑셀! ## Pandas란? - 구조화된 데이터의 처리를 지원하는 Python 라이브러리 - 고성능 Array 계산 라이브러리인 Numpy와 통합하여, 강력한 “스프레드시트” 처리 기능을 제공 - Pandas는 Numpy의 wapper. 즉, Numpy의 데이터 타입을 그대로 불러와서 사용할 수 있다. - 인덱싱, 연산용 함수, 전처리 함수 등을 제공함 ``` from pandas import Series, DataFrame import pandas as pd import numpy as np ``` 위의 세 줄은 고정으로 import 시켜놓고 가자. ## 데이터 로딩 ``` data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data' # Data URL ``` Boston housing 문제의 데이터는 다음과 같이 되어있다. <img src="../../img/Screen Shot 2019-03-17 at 5.06.15 PM.png" width="700"> ``` df_data = pd.read_csv(data_url, sep='\s+', header = None) # csv 타입 데이터 로드, separate는 빈공간으로 지정하고, Column은 없음 ``` '\s+'의 경우, '\s'는 정규 표현식으로서 공백문자(space)를 의미한다. 따라서 '\s+'는 "빈 칸으로 나눠서 띄워져 있는 것들은 다 가져와라." 라는 뜻으로 이해하면 된다. 그리고 header는 첫 줄에 column 이름들이 들어가 있는 지를 보는 paremeter이다. 없으면 None을 주면 된다. ``` df_data.head() # 처음 다섯줄 출력 ``` head를 찍으면 처음 5칸을 보여준다. column들이 없었으니 column을 따로 설정해보자. ``` df_data.columns = [ 'CRIM','ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO' ,'B', 'LSTAT', 'MEDV'] # Column Header 이름 지정 df_data.head() ``` --- # 2. Series ## Pandas의 구성 <img src="../../img/Screen Shot 2019-03-17 at 5.24.59 PM.png" width="700"> Pandas는 기본적으로 Series와 DataFrame이라고 하는 두 가지 Object로 구성되어 있다. Series라는 것은 간단하게 말해서 numpy에서의 하나의 vector ## 일반적인 pandas의 활용 <img src="../../img/Screen Shot 2019-03-17 at 5.28.58 PM.png" width="800"> ## Series - Column Vector를 표현하는 object ~~~python example_obj = Series() ~~~ <img src="../../img/Screen Shot 2019-03-17 at 5.34.43 PM.png" width="700"> ``` list_data = [1,2,3,4,5] example_obj = Series(data = list_data) # data에는 dict도 가능 print(example_obj) ``` - index & values(data) <img src="../../img/Screen Shot 2019-03-17 at 5.38.19 PM.png" width="500"> Series에서는 index를 신경쓰지 않아도 되지만 나중에 DataFrame에서 index를 신경쓰면 되고 DataFrame에서는 index가 중복이 가능하다. ``` list_name = ["a","b","c","d","e"] list_data = [1,2,3,4,5] example_obj = Series(data = list_data, index=list_name) # index 이름을 지정 print(example_obj) ``` 다음과 같이 직접적으로 접근도 가능하다. ``` print(example_obj.index) print(example_obj.values) print(type(example_obj.values)) ``` 다음과 같이 dictionary도 가능하다. ``` dict_data = {"a":1, "b":2, "c":3, "d":4, "e":5} example_obj = Series(dict_data, dtype=np.float32, name="example_data") # name - series 이름 설정. 쉽게 말해 하나의 column 이름 설정. print(example_obj) ``` - Series의 인덱싱 ``` print(example_obj["a"]) # numpy와 다른점 ``` 다음과 같이 직접적으로 접근해서 값을 변경할 수도 있다. ``` example_obj["a"] = 3.2 print(example_obj) ``` 다음과 같은 것들도 가능하다. ``` print(example_obj[example_obj > 2]) print(example_obj * 2) ``` - Data에 대한 정보 저장 ``` example_obj.name = "number" # series 이름 변경 example_obj.index.name = "alphabet" # index 이름 변경 print(example_obj) ``` - index 값을 기준으로 series 생성 ``` dict_data_1 = {"a":1, "b":2, "c":3, "d":4, "e":5} indexes = ["a","b","c","d","e","f","g","h"] series_obj_1 = Series(dict_data_1, index=indexes) print(series_obj_1) ``` --- # 3. Dataframe - Series를 모아서 만든 Data Table = **기본 2차원** <img src="../../img/Screen Shot 2019-03-17 at 6.46.23 PM.png" width="600"> DataFrame에서는 index와 columns 두 가지로 data를 찾을 수 있다. ~~~python DataFrame() ~~~ <img src="../../img/Screen Shot 2019-03-17 at 7.52.22 PM.png" width="650"> ``` # Example from - https://chrisalbon.com/python/pandas_map_values_to_values.html raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'], 'age': [42, 52, 36, 24, 73], 'city': ['San Francisco', 'Baltimore', 'Miami', 'Douglas', 'Boston']} df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'city']) print(df) ``` 대부분 csv파일을 이용해서 불러오기 때문에 위와 같이 dict 타입으로는 잘 쓰지 않는다. - column 선택 (numpy와 다른점) ``` df = DataFrame(raw_data, columns = ["age", "city"]) print(df) ``` - 새로운 column 추가 ``` df = DataFrame(raw_data, columns = ["first_name","last_name", "age", "city", "debt"]) print(df) ``` - column 선택 - series 추출 property를 아래와 같이 두 가지 방식으로 쓸 수 있다. ``` print(df.first_name) print(df["first_name"]) ``` - loc & iloc - loc(index location) - index 이름 - iloc(index position) - index number 대체적으로 loc은 잘 안씀 ``` print(df.loc[2:]) # row values print(df["first_name"].iloc[2:]) # column values ``` df["first_name"]만 하게 되면 series가 튀어나온다. 다른 것으로 비교해보자. ``` # Example from - https://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation s = pd.Series(np.nan, index=[49,48,47,46,45, 1, 2, 3, 4, 5]) print(s.loc[:3]) # index의 이름이 3이라는 것까지 실행해라. ``` loc은 위와 같이 index의 이름이 3인 것까지 출력하는 것을 볼 수 있다. ``` print(s.iloc[:3]) ``` iloc은 위와 같이 0, 1, 2 즉, index의 number가 3번째 전까지 출력하는 것을 볼 수 있다. - column에 새로운 data 할당 (많이 사용하는 기법) ``` df.debt = df.age > 40 print(df) ``` - transpose ``` df = df.T print(df) ``` - DataFrame에 들어가있는 값 출력 ``` print(df.values) ``` - csv로 변환 ``` df_csv = df.to_csv() print(df_csv) ``` - column 삭제 ``` df = df.T print(df) del df["debt"] print(df) ``` --- # 4. Selection & Drop - 가져올 것들은 가져오고, 지울 것들은 지우고 하는 방법 소개 ``` !pip install xlrd df = pd.read_excel("./excel_comp_data.xlsx") print(df) ``` ## Selection with column names - 1개의 column name 선택 series 객체를 가져온다. ``` df["account"].head(3) ``` - 1개 이상의 column names 선택 여러 개의 column name을 가져오고 싶을 때는 반드시 [ ]으로 묶어서 넣어주어야 한다. 그리고 위와 다르게 dataframe 객체를 가져온다. ``` df[["account", "street", "state"]].head(3) ``` ## Selection with index number - column 이름 없이 사용하는 index number는 row를 기준 가져옴 ``` df[:3] ``` - column이름과 함께 row index 사용시, 해당 column만 ``` df["account"][:3] ``` 앞에 column을 지정해주었기 때문에 series data로 변했다. ## Series selection ``` account_serires = df["account"] account_serires[:3] ``` - 1개 이상의 index ``` account_serires[[1,5,2]] ``` - Boolean index ``` account_serires[account_serires < 250000] ``` ## Index 변경 - 고유한 번호가 있는 경우, 따로 index를 두기 보다 그 값을 index로 해서 쓰고 싶은 경우도 있다. 그럴 경우 다음과 같이 하면 된다. - del을 해주는 것은 원래의 account가 남기 때문이다. ``` df.index = df["account"] del df["account"] df.head() ``` ## Basic, loc, iloc selection - Column과 index number (column의 숫자가 많을 경우 쓰는 방법) ``` df[["name","street"]][:2] ``` - Column과 index name (거의 안쓰는 방법) ``` df.loc[[211829,320563],["name","street"]] ``` - Column number와 index number (제일 많이 쓰는 방법) column이 몇 개 없을 떄는 iloc이 제일 편하다. ``` df.iloc[:2,:2] ``` 개인적으로 iloc을 많이 쓸 것 같다. column에 대해서도 슬라이싱을 할 때 다음과 같이 쓰면 편하다. ``` df["name"].iloc[2:] ``` ## index 재설정 ``` df.index = list(range(0,15)) df.head() ``` index 이름만 account로 돌려놓자. (values들은 사라짐..) ``` df.index.name = "account" df.head() ``` ## Data drop - index number로 drop - column 단위로 없애줄 때는 del을 이용 ex) del df["debt"] - row 단위로 없앨 때 사용 - drop을 쓰는 경우는 크게 없음 - 잘 못 들어온 data를 날릴 때 주로 사용 ``` df.drop(1) ``` - 한개 이상의 Index number로 drop ``` df.drop([0,1,2,3]) ``` - axis 지정으로 축을 기준으로 drop -> column 중에 “city” 그냥 del이 더 편하다. ``` df.drop("city", axis=1) ``` 실제로 데이터가 사라지지는 않는다. pandas에서는 원본 데이터를 삭제를 쉽게 안한다. 원본 데이터를 변환해주고 싶으면 반드시 inplace=True를 추가로 적어주어야한다. inplace=False를 하면 copy본을 따로 만든다. 그리고 그 copy본에서 삭제를 한다. 이부분은 밑에 Replace function에서 다시 보자. 참고로 axis는 0이 항상 가장 큰 차원(축)이고, 숫자가 크면 클수록 작은 차원(축)이 된다. --- # 5. Dataframe Operations ## Series operation - index을 기준으로 연산수행 - 겹치는 index가 없을 경우 NaN값으로 반환 ``` s1 = Series(range(1,6), index=list("abced")) print(s1) s2 = Series(range(5,11), index=list("bcedef")) print(s2) s1.add(s2) print(s1 + s2) ``` ## Dataframe operation - df는 column과 index를 모두 고려 - add operation을 쓰면 NaN값 0으로 변환 - Operation types: add, sub, div, mul ``` df1 = DataFrame(np.arange(9).reshape(3,3), columns=list("abc")) print(df1) df2 = DataFrame(np.arange(16).reshape(4,4), columns=list("abcd")) print(df2) print(df1 + df2) df1.add(df2, fill_value=0) ``` ## Series + Dataframe - column을 기준으로 broadcasting이 발생함 ``` df = DataFrame(np.arange(16).reshape(4,4), columns=list("abcd")) print(df) s = Series(np.arange(10,14), index=list("abcd")) print(s) print(df + s) ``` 반대로 row를 기준으로 broadcasting을 할 수도 있다. ``` s2 = Series(np.arange(10,14)) print(df) print(s2) df.add(s2, axis=0) ``` --- # 6. Lambda, Map, Apply - 실제로 상당히 실용적인 내용! - Map이나 Replace를 써서 데이터를 변경해줄 때 많이 쓴다. - Map - series 추가, 데이터 변환 / Replace - 데이터 변환만 - Apply는 element 단위가 아니라 series 단위로 min, max, mean, sum 등을 구할 때 많이 사용. 통계 데이터 구할 때 많이 사용 - Applymap for dataframe은 전체적으로 element 단위에 적용할 때 사용 ## Lambda 함수 - 한 줄로 함수를 표현하는 익명 함수 기법 - Lisp 언어에서 시작된 기법으로 오늘날 현대언어에 많이 사용 - **lambda** argument : expression ``` f = lambda x,y: x + y print(f(1,4)) ``` 이름을 할당하지 않고도 가능하다. ``` (lambda x: x +1)(5) ``` ## Map 함수 - 함수와 sequence형 데이터를 인자로 받아 - **각 element마다** 입력받은 함수를 적용하여 list로 반환 - 일반적으로 함수를 lambda형태로 표현함 - **map** (function, sequence) ``` ex = [1,2,3,4,5] f = lambda x: x ** 2 print(list(map(f, ex))) ``` 두 개이상의 argument가 있을 때는 두 개의 sequence형을 써야한다. ``` f = lambda x, y: x + y print(list(map(f, ex, ex))) ``` lambda와 같이 익명 함수 그대로 사용할 수도 있다. ``` list(map(lambda x: x+x, ex)) ``` ## Map for series - Pandas의 series type의 데이터에도 map 함수 사용가능 - function 대신 dict, sequence형 자료등으로 대체 가능 - 실제로 많이 사용 - 데이터를 직접적으로 추가하거나 변환해줄 때 사용 ``` s1 = Series(np.arange(10)) s1.head(5) s1.map(lambda x: x**2).head(5) ``` - dict type으로 데이터 교체. 없는 값은 NaN 10대, 20대, 30대를 구분한다거나 할 때 유용하게 **데이터를 변환** 해줄 수 있다. ``` z = {1: 'A', 2: 'B', 3: 'C'} s1.map(z).head(5) ``` - 같은 위치의 데이터를 s2로 전환 ``` s2 = Series(np.arange(10,20)) s1.map(s2).head(5) ``` ## Example - map for series - 제일 많이 쓰는 일반적인 테크닉 ``` df = pd.read_csv("wages.csv") df.head() df.sex.unique() ``` map을 통해 sex_code이라는 **series를 추가** 해보자. ``` df["sex_code"] = df.sex.map({"male":0, "female":1}) df.head() ``` ## Replace function - Map함수의 기능 중 **데이터 변환 기능만** 담당 - 데이터 변환 시 많이 사용하는 함수 ``` df.sex.replace({"male":0, "female":1}).head() df.sex.replace(["male", "female"], # Target list [0,1], # Conversion list inplace=True) # 데이터 변환 결과를 적용 df.head() ``` ## Apply for dataframe - map에서 했던 element 단위가 아닌, series **전체(column)에 해당** 함수를 적용 - 입력값이 series 데이터로 입력받아 handling 가능 - 통계 데이터를 뽑을 때 유용하게 사용 ``` df = pd.read_csv("wages.csv") df.head() df_info = df[["earn", "height","age"]] df_info.head() f = lambda x : x.max() - x.min() ``` 아래와 같이 각 column 별로 결과값 반환된다. ``` df_info.apply(f) ``` - 내장 연산 함수를 사용할 때도 똑같은 효과를 거둘 수 있음 - mean, std 등 사용가능 ``` df_info.sum() df_info.apply(sum) ``` - scalar 값 이외에 series값의 반환도 가능함 ``` f = lambda x : Series([x.min(), x.max(), x.mean()], index=["min", "max", "mean"]) df_info.apply(f) ``` ## Applymap for dataframe - series 단위가 아닌 전체 dataframe의 **element 단위로** 함수를 적용함 - series 단위에 apply를 적용시킬 때와 같은 효과 ``` f = lambda x : -x df_info.applymap(f).head(5) ``` 아래와 같이 apply를 이용하여 해당 series에 적용한 것과 동일한 효과를 볼 수 있다. ``` df_info["earn"].apply(f).head(5) ``` --- # 7. Pandas Built-in functions ## describe - Numeric type 데이터의 요약 정보를 보여줌 - 각 column들마다 통계자료들을 싹 다 뽑아준다. 제일 많이 쓰는 것 중에 하나! ``` df = pd.read_csv("./wages.csv") df.head() df.describe() ``` ## unique - series data의 유일한 값을 list를 반환함. 다시 말해 series data의 category set을 보여준다. - 유일한 인종의 값 list 출력 category형 데이터가 몇 개가 있는 지 모를 때 많이 사용한다. ``` df.race.unique() ``` ## label str - > index 값으로 변환 - dict type으로 index ``` np.array(dict(enumerate(sorted(df["race"].unique())))) ``` - label index 값과 label 값 각각 추출 ``` value = list(map(int, np.array(list(enumerate(df["race"].unique())))[:, 0].tolist())) key = np.array(list(enumerate(df["race"].unique())), dtype=str)[:, 1].tolist() ``` int로 변환해주기 위해 map 사용. map 앞에는 무조건 list가 붙어야함. ``` print(value) print(key) ``` - label str - > index 값으로 변환 ``` df["race"].head() df["race"].replace(to_replace=key, value=value, inplace=True) df.head() ``` 위와 같이 labeling coding을 할 때 pandas를 이용해서 쉽게 변환해줄 수 있다. string값들을 다 int로 바꿔줘서 label을 만드는 것. 위에서 배웠던 replace로도 가능하다. - 성별에 대해서도 동일하게 적용 ``` value = list(map(int, np.array(list(enumerate(df["sex"].unique())))[:, 0].tolist())) key = np.array(list(enumerate(df["sex"].unique())), dtype=str)[:, 1].tolist() print(value) print(key) ``` - ”sex”와 “race” column의 index labelling ``` df["sex"].head() df["sex"].replace(to_replace=key, value=value, inplace=True) df.head() ``` ## sum - 기본적인 column 또는 row 값의 연산을 지원 - sub, mean, min, max, count, median, mad, var 등 ``` df.sum(axis=0) # axis - 아래 화살표를 손으로 표시하고 오른쪽으로 이동 df.sum(axis=1).head() # axis - 오른쪽 화살표를 손으로 표시하고 아래로 이동 ``` ## isnull - column 또는 row 값의 NaN (null) 값의 index를 반환함 ``` df.isnull().head() ``` - Null인 값의 합 ``` df.isnull().sum() ``` ## sort_values - column 값을 기준으로 데이터를 sorting ``` df.sort_values(["age", "earn"], ascending=False).head(10) # ascending=Ture 하면 오름차순 ``` --- 지금까지는 pandas로 데이터들을 불러오고 계산하는 것들을 했다면, 여기서부터는 feature라는 거대한 모판을 만들기 위해 데이터들을 나누고 붙이는 것들을 할 것이다. 일반적으로 우리가 생각하는 toy 데이터들은 굉장히 깨끗한 형태로 올라오지만 실제로 DB에 있는 데이터들을 가져오면 굉장히 지저분하기 때문에 전처리를 많이 해주어야한다. DB에 있는 데이터들이 너무 크면 전처리 시간이 너무 오래 걸리기 때문에 이러한 시간을 줄이기 위해서 Pandas라는 것을 통해 깨끗한 형태로 바꾸어 보고자 하는 것이다. # 8. Groupby ## Groupby - SQL groupby 명령어와 같음 - split -> apply -> combine - 과정을 거쳐 연산함 - 일반적으로 통계치를 낼 때 많이 사용한다. <img src="../../img/Screen Shot 2019-03-18 at 6.14.35 PM.png" width="400"> ``` ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'Kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print(df) ``` <img src="../../img/Screen Shot 2019-03-18 at 6.19.40 PM.png" width="600"> ``` df.groupby("Team")["Points"].sum() ``` - 한 개 이상의 column을 묶을 수도 있음 ``` df.groupby(["Team", "Year"])["Points"].sum() ``` ## Hierarchical index - Groupby 명령의 결과물도 결국은 dataframe - 두 개의 column으로 groupby를 할 경우, index가 두개 생성 - **index가 두개 이상 생성** 될 때 어떻게 다룰 것이냐 ``` h_index = df.groupby(["Team", "Year"])["Points"].sum() print(h_index) h_index.index h_index["Devils":"Kings"] ``` ## Hierarchical index – unstack() - Group으로 묶여진 데이터를 matrix 형태로 전환해줌 - Groupby를 쓰고 unstack()을 해서 matrix로 만들어 주는 것. 많이 쓰는 패턴 중 하나 - DB에 있는 값들을 feature를 생성할 때 사용하는 패턴 ``` h_index.unstack() # row - Team, column - Year, values - Points ``` ## Hierarchical index – swaplevel() - Index level을 변경할 수 있음 ``` h_index h_index.swaplevel() h_index.swaplevel().sort_index() ``` ## Hierarchical index – operations - Index level을 기준으로 기본 연산 수행 가능 - 별로 많이 쓰진 않음 ``` h_index h_index.sum(level=0) # level=0이면 첫 번째 column을 기준 h_index.sum(level=1) # level=1이면 두 번째 column을 기준 ``` 아래부터는 Groupby 중에서 이러한 것들이 있다 정도로만 알면 된다. 잘 쓰이진 않는다. ## Groupby – gropued - Groupby에 의해 Split된 상태를 추출 가능함 - Tuple 형태로 그룹의 key 값 Value값이 추출됨 ``` df grouped = df.groupby("Team") grouped for name, group in grouped: print(name) print(group) ``` - 특정 key값을 가진 그룹의 정보만 추출 가능 ``` grouped.get_group("Devils") ``` - 추출된 group 정보에는 세 가지 유형의 apply가 가능함 - Aggregation: 요약된 통계정보를 추출해 줌 - Transformation: 해당 정보를 변환해줌 - Filtration: 특정 정보를 제거 하여 보여주는 필터링 기능 - 일반적으로 데이터 분석보다는 데이터에 대해서 통계치를 뽑을 때 가끔 사용한다. ## Groupby – aggregation - 요약된 통계정보를 추출해 줌 ``` grouped.agg(sum) grouped.agg(np.mean) ``` - 특정 컬럼에 여러개의 function을 Apply 할 수도 있음 ``` grouped['Points'].agg([np.sum, np.mean, np.std]) ``` ## Groupby – transformation - 해당 정보를 변환해줌 - Aggregation과 달리 key값 별로 요약된 정보가 아님 - 개별 데이터의 변환을 지원함 $z_i = \frac{x_i-\mu}{\sigma}$ ``` score = lambda x: (x - x.mean()) / x.std() grouped.transform(score) ``` ## Groupby – filter - 특정 정보를 제거 하여 보여주는 필터링 기능 - 특정 조건으로 데이터를 검색할 때 사용 - 그나마 검색할 때 많이 쓸일이 있다. ``` df.groupby('Team') for name, group in grouped: print(name) print(group) df.groupby('Team').filter(lambda x: len(x) >= 3) ``` filter안에는 boolean 조건이 존재해야하고, len(x)는 grouped된 dataframe 개수이다. ``` df.groupby('Team').filter(lambda x: x["Points"].max() > 800) ``` --- # 9. Case study ## Data - 시간과 데이터 종류가 정리된 통화량 데이터 - https://www.shanelynn.ie/wp-content/uploads/2015/06/phone_data.csv ``` import dateutil ``` dateutil 패키지의 parse 명령을 쓰면 자동으로 형식 문자열을 찾아 datetime.datetime 클래스 객체를 만들어 준다. ``` df_phone = pd.read_csv("./phone_data.csv") df_phone.head() df_phone['date'] = df_phone['date'].apply(dateutil.parser.parse, dayfirst=True) df_phone.head() df_phone.groupby('month')['duration'].sum() df_phone[df_phone['item'] == 'call'].groupby('month')['duration'].sum() df_phone.item.unique() df_phone.groupby(['month', 'item'])['duration'].sum() df_phone.groupby(['month', 'item'])['date'].count().unstack() ``` 여기서부터는 잘 안쓰이는 것들이지만 한번 연습삼아 해보고 넘어가자. ``` df_phone.groupby('month', as_index=False).agg(sum) ``` index는 필요없으므로 다음과 같이 해보자. ``` df_phone.groupby('month', as_index=False).agg({"duration": "sum"}) # duration column을 sum해준다. ``` as_index=True로 하면 다음과 같이 된다. ``` df_phone.groupby('month').agg({"duration": "sum"}) ``` 쿼리문제 1 - Find the sum of the durations for each group - Find the number of network type entries - Get the first date per group ``` df_phone.groupby(['month', 'item']).agg({'duration': sum, 'network_type': "count", 'date': 'first'}) ``` 쿼리문제 2 - Find the min, max, and sum of the duration column - Find the number of network type entries - Get the min, first, and number of nunique dates ``` df_phone.groupby(['month', 'item']).agg({'duration': min, 'network_type': "count", 'date': [min, 'first', 'nunique']}) # nunique - nunber of unique # nunique - 하나만 있는 것이 아니라 2개 이상인 것들의 갯수 ``` --- # 10. Pivot table & Crosstab - 기본적으로 groupby로 다 가능하다. 특수한 경우에만 Pivot table이나 Crosstab을 사용한다. - 앞에서 배웠던 unstack()과 동일하다. ## Pivot Table - 우리가 Excel에서 보던 그 것! - Index 축은 groupby와 동일함 - Column에 추가로 labelling 값을 추가하여, - Value에 numeric type 값을 aggregation 하는 형태 ``` df_phone = pd.read_csv("./phone_data.csv") df_phone['date'] = df_phone['date'].apply(dateutil.parser.parse, dayfirst=True) df_phone.head() df_phone.pivot_table(["duration"], index=[df_phone.month, df_phone.item], columns=df_phone.network, aggfunc="sum", fill_value=0) ``` ## Crosstab - 두 column에 교차 빈도, 비율, 덧셈 등을 구할 때 사용 - Pivot table의 특수한 형태 - User-Item Rating Matrix 등을 만들 때 사용가능함 ``` df_movie = pd.read_csv("./movie_rating.csv") df_movie pd.crosstab(index=df_movie.critic, columns=df_movie.title, values=df_movie.rating, aggfunc="first").fillna(0) df_movie.pivot_table(["rating"], index=df_movie.critic, columns=df_movie.title, aggfunc="sum", fill_value=0) df_movie.groupby(["critic","title"]).agg({"rating":"first"}).unstack().fillna(0) ``` --- # 11. Merge & Concat ## Merge - SQL에서 많이 사용하는 Merge와 같은 기능 - 두 개의 데이터를 하나로 합침 - 많이 사용 ``` raw_data = {'subject_id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'], 'test_score': [51, 15, 15, 61, 16, 14, 15, 1, 61, 16]} df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'test_score']) df_a raw_data = {'subject_id': ['4', '5', '6', '7', '8'], 'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], 'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']} df_b = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name']) df_b ``` - subject_id 기준으로 merge (inner join) ``` pd.merge(df_a, df_b, on='subject_id') ``` - 두 dataframe이 column이름이 다를 때 (inner join) ``` pd.merge(df_a, df_b, left_on='subject_id', right_on='subject_id') ``` ## Join method <img src="../../img/Screen Shot 2019-03-18 at 8.36.18 PM.png" width="500"> ## Left join ``` pd.merge(df_a, df_b, on='subject_id', how='left') ``` ## Right join ``` pd.merge(df_a, df_b, on='subject_id', how='right') ``` ## Full(outer) join ``` pd.merge(df_a, df_b, on='subject_id', how='outer') ``` ## Inner join ``` pd.merge(df_a, df_b, on='subject_id', how='inner') pd.merge(df_a, df_b, on='subject_id') pd.merge(df_a, df_b, left_on='subject_id', right_on='subject_id') ``` 다 같은 값이 나온다. ## Index based join - index를 둘 다 살리고 싶을 때 사용 - subject_id로 하는 것이 아니라 맨 왼쪽에 있는 index가지고 합칠 때 사용 - 거의 잘 안씀 ``` pd.merge(df_a, df_b, left_index=True, right_index=True) ``` ## Concat - 같은 형태의 데이터를 붙이는 연산작업 ``` raw_data = {'subject_id': ['1', '2', '3', '4', '5'], 'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']} df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name']) df_a raw_data = {'subject_id': ['4', '5', '6', '7', '8'], 'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], 'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']} df_b = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name']) df_b df_new = pd.concat([df_a, df_b]) df_new.reset_index() df_a.append(df_b) df_new = pd.concat([df_a, df_b], axis=1) df_new.reset_index() ``` --- # 12. Persistence - 혼자 사용할 때 말고 여러명이서 작업할 경우 데이터를 넘겨주고 넘겨받을 때, 데이터를 파일 형태로 만들어주는 작업들 - 세 가지 형태가 있음 - Database persistence - XLS persistence - Pickle persistence ## DB persistence - Data loading시 db connection 기능을 제공함 - https://www.dataquest.io/blog/python-pandas-databases/ ``` !pip install pymysql import sqlite3 # pymysql <- 설치 # Database 연결 코드 conn = sqlite3.connect("./flights.db") cur = conn.cursor() cur.execute("select * from airlines limit 5;") results = cur.fetchall() results ``` - db 연결 conn을 사용하여 dataframe 생성 ``` df_airplines = pd.read_sql_query("select * from airlines;", conn) df_airplines.head() df_routes = pd.read_sql_query("select * from routes;", conn) df_routes.head() ``` ## XLS persistence - Dataframe의 엑셀 추출 코드 - Xls 엔진으로 openpyxls 또는 XlsxWrite 사용 - https://xlsxwriter.readthedocs.io/working_with_pandas.html ``` !pip install openpyxl !pip install XlsxWriter writer = pd.ExcelWriter('./df_routes.xlsx', engine='xlsxwriter') df_routes.to_excel(writer, sheet_name='Sheet1') writer.save() ``` ## Pickle persistence - 가장 일반적인 python 파일 persistence - to_pickle, read_pickle 함수 사용 - 제일 편한 방법. 제일 많이 쓰는 방법 ``` df_routes.to_pickle("./df_routes.pickle") df_routes_pickle = pd.read_pickle("./df_routes.pickle") df_routes_pickle.head() df_routes_pickle.describe() # Numeric type 데이터의 요약 정보를 보여줌 ```
github_jupyter
<a id='contents'></a> # Running QCVV Protocols The main purpose of pyGSTi is to implement QCVV techniques that analyze some, often specific, experimental data to learn about a quantum processor. Each such technique is called a "protocol" in pyGSTi, and this term roughly corresponds to its use in the literature. To run a protocol on some data in pyGSTi, here's the general workflow: 1. Create an `ExperimentDesign` object. An "experiment design" is just a description of a set of experiments. It tells you **what circuits you need to run on your quantum processor**. Most protocols require a certain structure to their circuits, or knowledge that their circuits have been drawn from a certain distribution, and thus have a corresponding experiment design type suited to them, e.g. `StandardGSTDesign` and `CliffordRBDesign`. 2. Run or simulate the circuits demanded by the experiment design, and package the resulting data counts with the experiment design in a `ProtocolData` object. This object constitutes the input to a protocol. 3. Create a `Protocol` object, usually corresponding to the type of experiment design, and pass your data object to its `run()` method. The result is a `ProtocolResults` object containing the results of running the protocol along with all the inputs that went in to generating those results. 4. Look at the results object. It can be used to make plots, generate reports, etc. Below are examples of how to run some of the protocols within pyGSTi. You'll notice how, for the most part, they follow the same pattern given above. Here's a list of the protocols for easy reference: ## Contents - [running Gate Set Tomography (GST)](#gate_set_tomography) - [running Randomized Benchmarking (RB)](#randomized_benchmarking) - [testing how well a model describes a set of data](#model_testing) - [running Robust Phase Estimation (RPE)](#robust_phase_estimation) - [drift characterization](#drift_characterization) We'll begin by setting up a `Workspace` so we can display pretty interactive figures inline (see the [intro to Workspaces tutorial](reporting/Workspace.ipynb) for more details) within this notebook. ``` import pygsti import numpy as np ws = pygsti.report.Workspace() ws.init_notebook_mode(autodisplay=True) ``` <a id='gate_set_tomography'></a> ## Gate set tomography The most common reason to use pyGSTi is to run gate set tomography (GST). The GST protocol uses sets of periodic circuits to probe, to a precision *linear* in the maximum-circuit length (i.e. depth), the gates on one or more of the qubits in a quantum processor. For common gate sets with "model packs" that are built into pyGSTi, you only need to specify the maximum circuit length to construct an experiment design for GST. In the example below, data is then simulated using a model with simple depolarizing errors. The standard GST protocol is then run to produce a results object and then generate a report. To learn more about GST, see the [GST Overview](algorithms/GST-Overview.ipynb) and [GST Protocols](algorithms/GST-Protocols.ipynb) tutorials. ``` from pygsti.modelpacks import smq1Q_XYI # get experiment design exp_design = smq1Q_XYI.create_gst_experiment_design(max_max_length=32) # write an empty data object (creates a template to fill in) pygsti.io.write_empty_protocol_data('tutorial_files/test_gst_dir', exp_design, clobber_ok=True) # fill in the template with simulated data (you would run the experiment and use actual data) pygsti.io.fill_in_empty_dataset_with_fake_data( "tutorial_files/test_gst_dir/data/dataset.txt", smq1Q_XYI.target_model().depolarize(op_noise=0.01, spam_noise=0.001), num_samples=1000, seed=1234) # load the data object back in, now with the experimental data data = pygsti.io.read_data_from_dir('tutorial_files/test_gst_dir') # run the GST protocol on the data results = pygsti.protocols.StandardGST().run(data) # create a report report = pygsti.report.construct_standard_report( results, title="GST Overview Tutorial Example Report") report.write_html("tutorial_files/gettingStartedReport") ``` <a href='#contents' style="text-decoration: none;">Back to contents</a> <a id='randomized_benchmarking'></a> ## Randomized benchmarking Randomized benchmarking (RB) can be used to estimate the average per-Clifford error rate by fitting a simple curve to the data from randomized circuits of different depths. To create the experiment design, the user specifies a `QubitProcessorSpec` object that describes the quantum processor (see the [ProcessorSpec tutorial](objects/ProcessorSpec.pynb), the depths (in number of Clifford gates) to use, and the number of circuits at each depth. The results from running the protocol are then used to create a plot of the RB decay curve along with the data. For more information, see the [RB Overview tutorial](algorithms/RB-Overview.ipynb). ``` # define the quantum processor (or piece of a processor) we'll be doing RB on qubit_labels = ['Q1'] gate_names = ['Gxpi2', 'Gxmpi2', 'Gypi2', 'Gympi2'] pspec = pygsti.processors.QubitProcessorSpec(len(qubit_labels), gate_names, qubit_labels=qubit_labels) depths = [0, 10, 20, 30] circuits_per_depth = 50 # Create compilation rules from native gates to Cliffords from pygsti.processors import CliffordCompilationRules as CCR compilations = {'absolute': CCR.create_standard(pspec, 'absolute', ('paulis', '1Qcliffords'), verbosity=0), 'paulieq': CCR.create_standard(pspec, 'paulieq', ('1Qcliffords', 'allcnots'), verbosity=0)} # create an experiment design exp_design = pygsti.protocols.CliffordRBDesign(pspec, compilations, depths, circuits_per_depth) # write an empty data object (creates a template to fill in) pygsti.io.write_empty_protocol_data('tutorial_files/test_rb_dir', exp_design, clobber_ok=True) # fill in the template with simulated data (you would run the experiment and use actual data) # Use a model with 1% depolarization on all gates mdl_datagen = pygsti.models.create_crosstalk_free_model(pspec, depolarization_strengths={ 'Gxpi2': 0.01, 'Gxmpi2': 0.01, 'Gypi2': 0.01, 'Gympi2': 0.01 }, simulator="map") pygsti.io.fill_in_empty_dataset_with_fake_data( "tutorial_files/test_rb_dir/data/dataset.txt", mdl_datagen, num_samples=1000, seed=1234) # load the data object back in, now with the experimental data data = pygsti.io.read_data_from_dir('tutorial_files/test_rb_dir') #Run RB protocol proto = pygsti.protocols.RB() rbresults = proto.run(data) #Create a RB plot ws.RandomizedBenchmarkingPlot(rbresults) ``` <a href='#contents' style="text-decoration: none;">Back to contents</a> <a id='model_testing'></a> ## Model testing (see whether data agrees with a model) GST fits a parameterized model to a data set (see above), which can require many circuits to be run, and take a long time to analyze. It is also possible to create a model in pyGSTi and test how well that model fits a set of data. The circuits used to make this comparison don't need to have any special structure, and the time required to perform the analysis it greatly reduce. In the example below we create a simple 2-qubit model and test it against the output of five hand-selected sequences. For more information on model testing, see the [model testing tutorial](algorithms/ModelTesting.ipynb). For more information about creating explicit models, see the [explicit model tutorial](objects/ExplicitModel.ipynb). ``` # create a dataset file that is just a list of circuits run and their outcomes dataset_txt = \ """## Columns = 00 count, 01 count, 10 count, 11 count {}@(0,1) 100 0 0 0 Gx:0@(0,1) 55 5 40 0 Gx:0Gy:1@(0,1) 20 27 23 30 Gx:0^4@(0,1) 85 3 10 2 Gx:0Gcnot:0:1@(0,1) 45 1 4 50 """ with open("tutorial_files/Example_Short_Dataset.txt","w") as f: f.write(dataset_txt) ds = pygsti.io.read_dataset("tutorial_files/Example_Short_Dataset.txt") # package the dataset into a data object, using the default experiment design # that has essentially no structure. data = pygsti.protocols.ProtocolData(None, ds) # create a model to test pspec = pygsti.processors.QubitProcessorSpec(num_qubits=2, gate_names=['Gx', 'Gy', 'Gcnot'], geometry='line') mdl_to_test = pygsti.models.create_explicit_model(pspec, ideal_gate_type='full TP') mdl_to_test = mdl_to_test.depolarize(op_noise=0.01) # a guess at what the noise is... mdl_to_test.num_modeltest_params = 1 # treat as a model with one adjustable parameter (instead of .num_params) # run the ModelTest protocol on the data proto = pygsti.protocols.ModelTest(mdl_to_test) results = proto.run(data) print("Number of std-deviations away from expected = ", results.estimates['ModelTest'].misfit_sigma()) ``` <a href='#contents' style="text-decoration: none;">Back to contents</a> <a id='robust_phase_estimation'></a> ## RPE Robust Phase Estimation (RPE) determines the phase of a target gate U by iterated action of that gate on a superposition of eigenstates of U. Upwards of 30% error in counts can be tolerated, due to any cause (e.g., statistical noise or calibration error). In this example, the π/2 phase of an X rotation is determined using only noisy X_pi/2 gates (and SPAM). Additional modelpacks for characterizing different phases of different gates will be made available in the future. In the meantime, if you wish to characterize, using RPE, the phase of a gate that is neither X_pi/2 nor Y_pi/2, please email either pygsti@sandia.gov or kmrudin@sandia.gov. ``` # An experiment design from pygsti.modelpacks import smq1Q_Xpi2_rpe, smq1Q_XYI exp_design = smq1Q_Xpi2_rpe.create_rpe_experiment_design(max_max_length=64) # write an empty data object (creates a template to fill in) pygsti.io.write_empty_protocol_data(exp_design, 'tutorial_files/test_rpe_dir', clobber_ok=True) # fill in the template with simulated data (you would run the experiment and use actual data) pygsti.io.fill_in_empty_dataset_with_fake_data( "tutorial_files/test_rpe_dir/data/dataset.txt", smq1Q_XYI.target_model().depolarize(op_noise=0.01, spam_noise=0.1), num_samples=1000, seed=1234) # read the data object back in, now with the experimental data data = pygsti.io.read_data_from_dir('tutorial_files/test_rpe_dir/') # Run the RPE Protocol results = pygsti.protocols.rpe.RobustPhaseEstimation().run(data) print(results.angle_estimate) ``` <a href='#contents' style="text-decoration: none;">Back to contents</a> <a id='drift_characterization'></a> ## Drift Characterization Time-series data can be analyzed for significant indications of drift (time variance in circuit outcome probabilities). See the [tutorial on drift characterization](algorithms/DriftCharacterization.ipynb) for more details. ``` from pygsti.modelpacks import smq1Q_XYI exp_design = smq1Q_XYI.create_gst_experiment_design(max_max_length=4) pygsti.io.write_empty_protocol_data('tutorial_files/test_drift_dir', exp_design, clobber_ok=True) # Simulate time dependent data (right now, this just uses a time-independent model so this is uninteresting) datagen_model = smq1Q_XYI.target_model().depolarize(op_noise=0.05, spam_noise=0.1) datagen_model.sim = "map" # only map-type can generate time-dep data # can also construct this as target_model(simulator="map") above pygsti.io.fill_in_empty_dataset_with_fake_data('tutorial_files/test_drift_dir/data/dataset.txt', datagen_model, num_samples=10, seed=2020, times=range(10)) gst_data = pygsti.io.read_data_from_dir('tutorial_files/test_drift_dir') stability_protocol = pygsti.protocols.StabilityAnalysis() results = stability_protocol.run(gst_data) report = pygsti.report.create_drift_report(results, title='Demo Drift Report') report.write_html('tutorial_files/DemoDriftReport') ``` <a href='#contents' style="text-decoration: none;">Back to contents</a> <a id='timedep_tomography'></a> # What's next? This concludes our overview of how to use some of the major protocols implemented by pyGSTi. The high-level objects involved in this workflow, namely `ExperimentDesign`, `ProtocolData`, `Protocol`, and `ProtocolResults`, are essentially convenient ways of working with pyGSTi's lower-level objects. In the [next tutorial](01-Essential-Objects.ipynb) we look at several of the most important of these, and proceed to show how to use them independently of the high-level objects in the [using essential objects tutorial](02-Using-Essential-Objects.ipynb). If there's something you want to do with pyGSTi that isn't covered here, you should take a look through the table of contents in the latter tutorial.
github_jupyter
``` import numpy as np import pandas as pd from matplotlib import pyplot as plt from tqdm import tqdm %matplotlib inline from torch.utils.data import Dataset, DataLoader import torch import torchvision import torch.nn as nn import torch.optim as optim from torch.nn import functional as F device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) m = 100 # 5, 50, 100, 500, 1000, 2000 desired_num = 1000 tr_i = 0 tr_j = int(desired_num/2) tr_k = desired_num tr_i, tr_j, tr_k ``` # Generate dataset ``` np.random.seed(12) y = np.random.randint(0,10,5000) idx= [] for i in range(10): print(i,sum(y==i)) idx.append(y==i) x = np.zeros((5000,2)) np.random.seed(12) x[idx[0],:] = np.random.multivariate_normal(mean = [5,5],cov=[[0.1,0],[0,0.1]],size=sum(idx[0])) x[idx[1],:] = np.random.multivariate_normal(mean = [-6,7],cov=[[0.1,0],[0,0.1]],size=sum(idx[1])) x[idx[2],:] = np.random.multivariate_normal(mean = [-5,-4],cov=[[0.1,0],[0,0.1]],size=sum(idx[2])) x[idx[3],:] = np.random.multivariate_normal(mean = [-1,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[3])) x[idx[4],:] = np.random.multivariate_normal(mean = [0,2],cov=[[0.1,0],[0,0.1]],size=sum(idx[4])) x[idx[5],:] = np.random.multivariate_normal(mean = [1,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[5])) x[idx[6],:] = np.random.multivariate_normal(mean = [0,-1],cov=[[0.1,0],[0,0.1]],size=sum(idx[6])) x[idx[7],:] = np.random.multivariate_normal(mean = [0,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[7])) x[idx[8],:] = np.random.multivariate_normal(mean = [-0.5,-0.5],cov=[[0.1,0],[0,0.1]],size=sum(idx[8])) x[idx[9],:] = np.random.multivariate_normal(mean = [0.4,0.2],cov=[[0.1,0],[0,0.1]],size=sum(idx[9])) x[idx[0]][0], x[idx[5]][5] for i in range(10): plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) bg_idx = [ np.where(idx[3] == True)[0], np.where(idx[4] == True)[0], np.where(idx[5] == True)[0], np.where(idx[6] == True)[0], np.where(idx[7] == True)[0], np.where(idx[8] == True)[0], np.where(idx[9] == True)[0]] bg_idx = np.concatenate(bg_idx, axis = 0) bg_idx.shape np.unique(bg_idx).shape x = x - np.mean(x[bg_idx], axis = 0, keepdims = True) np.mean(x[bg_idx], axis = 0, keepdims = True), np.mean(x, axis = 0, keepdims = True) x = x/np.std(x[bg_idx], axis = 0, keepdims = True) np.std(x[bg_idx], axis = 0, keepdims = True), np.std(x, axis = 0, keepdims = True) for i in range(10): plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) foreground_classes = {'class_0','class_1', 'class_2'} background_classes = {'class_3','class_4', 'class_5', 'class_6','class_7', 'class_8', 'class_9'} fg_class = np.random.randint(0,3) fg_idx = np.random.randint(0,m) a = [] for i in range(m): if i == fg_idx: b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1) a.append(x[b]) print("foreground "+str(fg_class)+" present at " + str(fg_idx)) else: bg_class = np.random.randint(3,10) b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1) a.append(x[b]) print("background "+str(bg_class)+" present at " + str(i)) a = np.concatenate(a,axis=0) print(a.shape) print(fg_class , fg_idx) np.reshape(a,(2*m,1)) mosaic_list_of_images =[] mosaic_label = [] fore_idx=[] for j in range(desired_num): np.random.seed(j) fg_class = np.random.randint(0,3) fg_idx = np.random.randint(0,m) a = [] for i in range(m): if i == fg_idx: b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1) a.append(x[b]) # print("foreground "+str(fg_class)+" present at " + str(fg_idx)) else: bg_class = np.random.randint(3,10) b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1) a.append(x[b]) # print("background "+str(bg_class)+" present at " + str(i)) a = np.concatenate(a,axis=0) mosaic_list_of_images.append(np.reshape(a,(2*m,1))) mosaic_label.append(fg_class) fore_idx.append(fg_idx) mosaic_list_of_images = np.concatenate(mosaic_list_of_images,axis=1).T mosaic_list_of_images.shape mosaic_list_of_images.shape, mosaic_list_of_images[0] for j in range(m): print(mosaic_list_of_images[0][2*j:2*j+2]) def create_avg_image_from_mosaic_dataset(mosaic_dataset,labels,foreground_index,dataset_number, m): """ mosaic_dataset : mosaic_dataset contains 9 images 32 x 32 each as 1 data point labels : mosaic_dataset labels foreground_index : contains list of indexes where foreground image is present so that using this we can take weighted average dataset_number : will help us to tell what ratio of foreground image to be taken. for eg: if it is "j" then fg_image_ratio = j/9 , bg_image_ratio = (9-j)/8*9 """ avg_image_dataset = [] cnt = 0 counter = np.zeros(m) #np.array([0,0,0,0,0,0,0,0,0]) for i in range(len(mosaic_dataset)): img = torch.zeros([2], dtype=torch.float64) np.random.seed(int(dataset_number*10000 + i)) give_pref = foreground_index[i] #np.random.randint(0,9) # print("outside", give_pref,foreground_index[i]) for j in range(m): if j == give_pref: img = img + mosaic_dataset[i][2*j:2*j+2]*dataset_number/m #2 is data dim else : img = img + mosaic_dataset[i][2*j:2*j+2]*(m-dataset_number)/((m-1)*m) if give_pref == foreground_index[i] : # print("equal are", give_pref,foreground_index[i]) cnt += 1 counter[give_pref] += 1 else : counter[give_pref] += 1 avg_image_dataset.append(img) print("number of correct averaging happened for dataset "+str(dataset_number)+" is "+str(cnt)) print("the averaging are done as ", counter) return avg_image_dataset , labels , foreground_index avg_image_dataset_1 , labels_1, fg_index_1 = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[0:tr_j], mosaic_label[0:tr_j], fore_idx[0:tr_j] , 1, m) test_dataset , labels , fg_index = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[tr_j : tr_k], mosaic_label[tr_j : tr_k], fore_idx[tr_j : tr_k] , m, m) avg_image_dataset_1 = torch.stack(avg_image_dataset_1, axis = 0) # avg_image_dataset_1 = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0) # print(torch.mean(avg_image_dataset_1, keepdims= True, axis = 0)) # print(torch.std(avg_image_dataset_1, keepdims= True, axis = 0)) print("=="*40) test_dataset = torch.stack(test_dataset, axis = 0) # test_dataset = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0) # print(torch.mean(test_dataset, keepdims= True, axis = 0)) # print(torch.std(test_dataset, keepdims= True, axis = 0)) print("=="*40) x1 = (avg_image_dataset_1).numpy() y1 = np.array(labels_1) plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0') plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1') plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2') plt.legend() plt.title("dataset4 CIN with alpha = 1/"+str(m)) x1 = (test_dataset).numpy() / m y1 = np.array(labels) plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0') plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1') plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2') plt.legend() plt.title("test dataset4") test_dataset[0:10]/m test_dataset = test_dataset/m test_dataset[0:10] class MosaicDataset(Dataset): """MosaicDataset dataset.""" def __init__(self, mosaic_list_of_images, mosaic_label): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.mosaic = mosaic_list_of_images self.label = mosaic_label #self.fore_idx = fore_idx def __len__(self): return len(self.label) def __getitem__(self, idx): return self.mosaic[idx] , self.label[idx] #, self.fore_idx[idx] avg_image_dataset_1[0].shape avg_image_dataset_1[0] batch = 200 traindata_1 = MosaicDataset(avg_image_dataset_1, labels_1 ) trainloader_1 = DataLoader( traindata_1 , batch_size= batch ,shuffle=True) testdata_1 = MosaicDataset(avg_image_dataset_1, labels_1 ) testloader_1 = DataLoader( testdata_1 , batch_size= batch ,shuffle=False) testdata_11 = MosaicDataset(test_dataset, labels ) testloader_11 = DataLoader( testdata_11 , batch_size= batch ,shuffle=False) class Whatnet(nn.Module): def __init__(self): super(Whatnet,self).__init__() self.linear1 = nn.Linear(2,3) # self.linear2 = nn.Linear(50,10) # self.linear3 = nn.Linear(10,3) torch.nn.init.xavier_normal_(self.linear1.weight) torch.nn.init.zeros_(self.linear1.bias) def forward(self,x): # x = F.relu(self.linear1(x)) # x = F.relu(self.linear2(x)) x = (self.linear1(x)) return x def calculate_loss(dataloader,model,criter): model.eval() r_loss = 0 with torch.no_grad(): for i, data in enumerate(dataloader, 0): inputs, labels = data inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = model(inputs) loss = criter(outputs, labels) r_loss += loss.item() return r_loss/(i+1) def test_all(number, testloader,net): correct = 0 total = 0 out = [] pred = [] with torch.no_grad(): for data in testloader: images, labels = data images, labels = images.to("cuda"),labels.to("cuda") out.append(labels.cpu().numpy()) outputs= net(images) _, predicted = torch.max(outputs.data, 1) pred.append(predicted.cpu().numpy()) total += labels.size(0) correct += (predicted == labels).sum().item() pred = np.concatenate(pred, axis = 0) out = np.concatenate(out, axis = 0) print("unique out: ", np.unique(out), "unique pred: ", np.unique(pred) ) print("correct: ", correct, "total ", total) print('Accuracy of the network on the %d test dataset %d: %.2f %%' % (total, number , 100 * correct / total)) def train_all(trainloader, ds_number, testloader_list): print("--"*40) print("training on data set ", ds_number) torch.manual_seed(12) net = Whatnet().double() net = net.to("cuda") criterion_net = nn.CrossEntropyLoss() optimizer_net = optim.Adam(net.parameters(), lr=0.001 ) #, momentum=0.9) acti = [] loss_curi = [] epochs = 1000 running_loss = calculate_loss(trainloader,net,criterion_net) loss_curi.append(running_loss) print('epoch: [%d ] loss: %.3f' %(0,running_loss)) for epoch in range(epochs): # loop over the dataset multiple times ep_lossi = [] running_loss = 0.0 net.train() for i, data in enumerate(trainloader, 0): # get the inputs inputs, labels = data inputs, labels = inputs.to("cuda"),labels.to("cuda") # zero the parameter gradients optimizer_net.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion_net(outputs, labels) # print statistics running_loss += loss.item() loss.backward() optimizer_net.step() running_loss = calculate_loss(trainloader,net,criterion_net) if(epoch%200 == 0): print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss)) loss_curi.append(running_loss) #loss per epoch if running_loss<=0.05: print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss)) break print('Finished Training') correct = 0 total = 0 with torch.no_grad(): for data in trainloader: images, labels = data images, labels = images.to("cuda"), labels.to("cuda") outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %.2f %%' % (total, 100 * correct / total)) for i, j in enumerate(testloader_list): test_all(i+1, j,net) print("--"*40) return loss_curi train_loss_all=[] testloader_list= [ testloader_1, testloader_11] train_loss_all.append(train_all(trainloader_1, 1, testloader_list)) %matplotlib inline for i,j in enumerate(train_loss_all): plt.plot(j,label ="dataset "+str(i+1)) plt.xlabel("Epochs") plt.ylabel("Training_loss") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) ```
github_jupyter
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/5.1_Text_classification_examples_in_SparkML_SparkNLP.ipynb) # Text Classification with Spark NLP ``` %%capture # This is only to setup PySpark and Spark NLP on Colab !wget https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/colab_setup.sh -O - | bash # for Spark 2.4.x and Spark NLP 2.x.x, do the following # !wget https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/colab_setup.sh # !bash colab_setup.sh -p 2.4.x -s 2.x.x ``` <b> if you want to work with Spark 2.3 </b> ``` import os # Install java ! apt-get update -qq ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null !wget -q https://archive.apache.org/dist/spark/spark-2.3.0/spark-2.3.0-bin-hadoop2.7.tgz !tar xf spark-2.3.0-bin-hadoop2.7.tgz !pip install -q findspark os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"] os.environ["SPARK_HOME"] = "/content/spark-2.3.0-bin-hadoop2.7" ! java -version import findspark findspark.init() from pyspark.sql import SparkSession ! pip install --ignore-installed -q spark-nlp==2.7.5 import sparknlp spark = sparknlp.start(spark23=True) ``` ``` import os import sys from pyspark.sql import SparkSession from pyspark.ml import Pipeline from sparknlp.annotator import * from sparknlp.common import * from sparknlp.base import * import pandas as pd import sparknlp spark = sparknlp.start() print("Spark NLP version: ", sparknlp.version()) print("Apache Spark version: ", spark.version) ! wget https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/tutorials/Certification_Trainings/Public/data/news_category_train.csv ! wget https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/tutorials/Certification_Trainings/Public/data/news_category_test.csv # newsDF = spark.read.parquet("data/news_category.parquet") >> if it is a parquet newsDF = spark.read \ .option("header", True) \ .csv("news_category_train.csv") newsDF.show(truncate=50) newsDF.take(2) from pyspark.sql.functions import col newsDF.groupBy("category") \ .count() \ .orderBy(col("count").desc()) \ .show() ``` ## Building Classification Pipeline ### LogReg with CountVectorizer Tokenizer: Tokenization stopwordsRemover: Remove Stop Words countVectors: Count vectors (“document-term vectors”) ``` from pyspark.ml.feature import CountVectorizer, HashingTF, IDF, OneHotEncoder, StringIndexer, VectorAssembler, SQLTransformer %%time document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) stemmer = Stemmer() \ .setInputCols(["cleanTokens"]) \ .setOutputCol("stem") finisher = Finisher() \ .setInputCols(["stem"]) \ .setOutputCols(["token_features"]) \ .setOutputAsArray(True) \ .setCleanAnnotations(False) countVectors = CountVectorizer(inputCol="token_features", outputCol="features", vocabSize=10000, minDF=5) label_stringIdx = StringIndexer(inputCol = "category", outputCol = "label") nlp_pipeline = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, stemmer, finisher, countVectors, label_stringIdx]) nlp_model = nlp_pipeline.fit(newsDF) processed = nlp_model.transform(newsDF) processed.count() processed.select('description','token_features').show(truncate=50) processed.select('token_features').take(2) processed.select('features').take(2) processed.select('description','features','label').show() # set seed for reproducibility (trainingData, testData) = processed.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) trainingData.printSchema() from pyspark.ml.classification import LogisticRegression lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0) lrModel = lr.fit(trainingData) predictions = lrModel.transform(testData) predictions.filter(predictions['prediction'] == 0) \ .select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) from pyspark.ml.evaluation import MulticlassClassificationEvaluator evaluator = MulticlassClassificationEvaluator(predictionCol="prediction") evaluator.evaluate(predictions) from sklearn.metrics import confusion_matrix, classification_report, accuracy_score y_true = predictions.select("label") y_true = y_true.toPandas() y_pred = predictions.select("prediction") y_pred = y_pred.toPandas() y_pred.prediction.value_counts() cnf_matrix = confusion_matrix(list(y_true.label.astype(int)), list(y_pred.prediction.astype(int))) cnf_matrix print(classification_report(y_true.label, y_pred.prediction)) print(accuracy_score(y_true.label, y_pred.prediction)) ``` ### LogReg with TFIDF ``` from pyspark.ml.feature import HashingTF, IDF hashingTF = HashingTF(inputCol="token_features", outputCol="rawFeatures", numFeatures=10000) idf = IDF(inputCol="rawFeatures", outputCol="features", minDocFreq=5) #minDocFreq: remove sparse terms nlp_pipeline_tf = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, stemmer, finisher, hashingTF, idf, label_stringIdx]) nlp_model_tf = nlp_pipeline_tf.fit(newsDF) processed_tf = nlp_model_tf.transform(newsDF) processed_tf.count() # set seed for reproducibility processed_tf.select('description','features','label').show() (trainingData, testData) = processed_tf.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) lrModel_tf = lr.fit(trainingData) predictions_tf = lrModel_tf.transform(testData) predictions_tf.select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) y_true = predictions_tf.select("label") y_true = y_true.toPandas() y_pred = predictions_tf.select("prediction") y_pred = y_pred.toPandas() print(classification_report(y_true.label, y_pred.prediction)) print(accuracy_score(y_true.label, y_pred.prediction)) ``` ### Random Forest with TFIDF ``` from pyspark.ml.classification import RandomForestClassifier rf = RandomForestClassifier(labelCol="label", \ featuresCol="features", \ numTrees = 100, \ maxDepth = 4, \ maxBins = 32) # Train model with Training Data rfModel = rf.fit(trainingData) predictions_rf = rfModel.transform(testData) predictions_rf.select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) y_true = predictions_rf.select("label") y_true = y_true.toPandas() y_pred = predictions_rf.select("prediction") y_pred = y_pred.toPandas() print(classification_report(y_true.label, y_pred.prediction)) print(accuracy_score(y_true.label, y_pred.prediction)) ``` ## LogReg with Spark NLP Glove Word Embeddings ``` document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) glove_embeddings = WordEmbeddingsModel().pretrained() \ .setInputCols(["document",'cleanTokens'])\ .setOutputCol("embeddings")\ .setCaseSensitive(False) embeddingsSentence = SentenceEmbeddings() \ .setInputCols(["document", "embeddings"]) \ .setOutputCol("sentence_embeddings") \ .setPoolingStrategy("AVERAGE") embeddings_finisher = EmbeddingsFinisher() \ .setInputCols(["sentence_embeddings"]) \ .setOutputCols(["finished_sentence_embeddings"]) \ .setOutputAsVector(True)\ .setCleanAnnotations(False) explodeVectors = SQLTransformer(statement= "SELECT EXPLODE(finished_sentence_embeddings) AS features, * FROM __THIS__") label_stringIdx = StringIndexer(inputCol = "category", outputCol = "label") nlp_pipeline_w2v = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, glove_embeddings, embeddingsSentence, embeddings_finisher, explodeVectors, label_stringIdx]) nlp_model_w2v = nlp_pipeline_w2v.fit(newsDF) processed_w2v = nlp_model_w2v.transform(newsDF) processed_w2v.count() processed_w2v.columns processed_w2v.show(5) processed_w2v.select('finished_sentence_embeddings').take(1) # IF SQLTransformer IS NOT USED INSIDE THE PIPELINE, WE CAN EXPLODE OUTSIDE from pyspark.sql.functions import explode # processed_w2v= processed_w2v.withColumn("features", explode(processed_w2v.finished_sentence_embeddings)) processed_w2v.select("features").take(1) processed_w2v.select("features").take(1) processed_w2v.select('description','features','label').show() # set seed for reproducibility (trainingData, testData) = processed_w2v.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) from pyspark.sql.functions import udf @udf("long") def num_nonzeros(v): return v.numNonzeros() testData = testData.where(num_nonzeros("features") != 0) lrModel_w2v = lr.fit(trainingData) predictions_w2v = lrModel_w2v.transform(testData) predictions_w2v.select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) y_true = predictions_w2v.select("label") y_true = y_true.toPandas() y_pred = predictions_w2v.select("prediction") y_pred = y_pred.toPandas() print(classification_report(y_true.label, y_pred.prediction)) print(accuracy_score(y_true.label, y_pred.prediction)) processed_w2v.select('description','cleanTokens.result').show(truncate=50) ``` ## LogReg with Spark NLP Bert Embeddings ``` document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) bert_embeddings = BertEmbeddings\ .pretrained('bert_base_cased', 'en') \ .setInputCols(["document",'cleanTokens'])\ .setOutputCol("bert")\ .setCaseSensitive(False)\ embeddingsSentence = SentenceEmbeddings() \ .setInputCols(["document", "bert"]) \ .setOutputCol("sentence_embeddings") \ .setPoolingStrategy("AVERAGE") embeddings_finisher = EmbeddingsFinisher() \ .setInputCols(["sentence_embeddings"]) \ .setOutputCols(["finished_sentence_embeddings"]) \ .setOutputAsVector(True)\ .setCleanAnnotations(False) label_stringIdx = StringIndexer(inputCol = "category", outputCol = "label") nlp_pipeline_bert = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, bert_embeddings, embeddingsSentence, embeddings_finisher, label_stringIdx]) nlp_model_bert = nlp_pipeline_bert.fit(newsDF) processed_bert = nlp_model_bert.transform(newsDF) processed_bert.count() from pyspark.sql.functions import explode processed_bert= processed_bert.withColumn("features", explode(processed_bert.finished_sentence_embeddings)) processed_bert.select('description','features','label').show() # set seed for reproducibility (trainingData, testData) = processed_bert.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) from pyspark.ml.classification import LogisticRegression lr = LogisticRegression(maxIter=20, regParam=0.3, elasticNetParam=0) lrModel = lr.fit(trainingData) from pyspark.sql.functions import udf @udf("long") def num_nonzeros(v): return v.numNonzeros() testData = testData.where(num_nonzeros("features") != 0) predictions = lrModel.transform(testData) predictions.select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import pandas as pd df = predictions.select('description','category','label','prediction').toPandas() print(classification_report(df.label, df.prediction)) print(accuracy_score(df.label, df.prediction)) ``` ## LogReg with ELMO Embeddings ``` document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) elmo_embeddings = ElmoEmbeddings.pretrained()\ .setPoolingLayer("word_emb")\ .setInputCols(["document",'cleanTokens'])\ .setOutputCol("elmo") embeddingsSentence = SentenceEmbeddings() \ .setInputCols(["document", "elmo"]) \ .setOutputCol("sentence_embeddings") \ .setPoolingStrategy("AVERAGE") embeddings_finisher = EmbeddingsFinisher() \ .setInputCols(["sentence_embeddings"]) \ .setOutputCols(["finished_sentence_embeddings"]) \ .setOutputAsVector(True)\ .setCleanAnnotations(False) label_stringIdx = StringIndexer(inputCol = "category", outputCol = "label") nlp_pipeline_elmo = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, elmo_embeddings, embeddingsSentence, embeddings_finisher, label_stringIdx]) nlp_model_elmo = nlp_pipeline_elmo.fit(newsDF) processed_elmo = nlp_model_elmo.transform(newsDF) processed_elmo.count() (trainingData, testData) = newsDF.randomSplit([0.7, 0.3], seed = 100) processed_trainingData = nlp_model_elmo.transform(trainingData) processed_trainingData.count() processed_testData = nlp_model_elmo.transform(testData) processed_testData.count() processed_trainingData.columns processed_testData= processed_testData.withColumn("features", explode(processed_testData.finished_sentence_embeddings)) processed_trainingData= processed_trainingData.withColumn("features", explode(processed_trainingData.finished_sentence_embeddings)) from pyspark.sql.functions import udf @udf("long") def num_nonzeros(v): return v.numNonzeros() processed_testData = processed_testData.where(num_nonzeros("features") != 0) %%time from pyspark.ml.classification import LogisticRegression lr = LogisticRegression(maxIter=20, regParam=0.3, elasticNetParam=0) lrModel = lr.fit(processed_trainingData) processed_trainingData.columns predictions = lrModel.transform(processed_testData) predictions.select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) df = predictions.select('description','category','label','prediction').toPandas() df.shape df.head() from sklearn.metrics import classification_report, accuracy_score print(classification_report(df.label, df.prediction)) print(accuracy_score(df.label, df.prediction)) ``` ## LogReg with Universal Sentence Encoder ``` useEmbeddings = UniversalSentenceEncoder.pretrained()\ .setInputCols("document")\ .setOutputCol("use_embeddings") document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") loaded_useEmbeddings = UniversalSentenceEncoder.load('/root/cache_pretrained/tfhub_use_en_2.4.0_2.4_1587136330099')\ .setInputCols("document")\ .setOutputCol("use_embeddings") embeddings_finisher = EmbeddingsFinisher() \ .setInputCols(["use_embeddings"]) \ .setOutputCols(["finished_use_embeddings"]) \ .setOutputAsVector(True)\ .setCleanAnnotations(False) label_stringIdx = StringIndexer(inputCol = "category", outputCol = "label") use_pipeline = Pipeline( stages=[ document_assembler, loaded_useEmbeddings, embeddings_finisher, label_stringIdx] ) use_df = use_pipeline.fit(newsDF).transform(newsDF) use_df.select('finished_use_embeddings').show(3) from pyspark.sql.functions import explode use_df= use_df.withColumn("features", explode(use_df.finished_use_embeddings)) use_df.show(2) # set seed for reproducibility (trainingData, testData) = use_df.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import pandas as pd from pyspark.ml.classification import LogisticRegression lr = LogisticRegression(maxIter=20, regParam=0.3, elasticNetParam=0) lrModel = lr.fit(trainingData) predictions = lrModel.transform(testData) predictions.filter(predictions['prediction'] == 0) \ .select("description","category","probability","label","prediction") \ .orderBy("probability", ascending=False) \ .show(n = 10, truncate = 30) df = predictions.select('description','category','label','prediction').toPandas() #df['result'] = df['result'].apply(lambda x: x[0]) df.head() print(classification_report(df.label, df.prediction)) print(accuracy_score(df.label, df.prediction)) ``` ### train on entire dataset ``` lr = LogisticRegression(maxIter=20, regParam=0.3, elasticNetParam=0) lrModel = lr.fit(use_df) test_df = spark.read.parquet("data/news_category_test.parquet") test_df = use_pipeline.fit(test_df).transform(test_df) test_df= test_df.withColumn("features", explode(test_df.finished_use_embeddings)) test_df.show(2) predictions = lrModel.transform(test_df) df = predictions.select('description','category','label','prediction').toPandas() df['label'] = df.category.replace({'World':2.0, 'Sports':3.0, 'Business':0.0, 'Sci/Tech':1.0}) df.head() print(classification_report(df.label, df.prediction)) print(accuracy_score(df.label, df.prediction)) ``` ## Spark NLP Licensed DocClassifier ``` from sparknlp_jsl.annotator import * # set seed for reproducibility (trainingData, testData) = newsDF.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) stemmer = Stemmer() \ .setInputCols(["cleanTokens"]) \ .setOutputCol("stem") logreg = DocumentLogRegClassifierApproach()\ .setInputCols(["stem"])\ .setLabelCol("category")\ .setOutputCol("prediction") nlp_pipeline = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, stemmer, logreg]) nlp_model = nlp_pipeline.fit(trainingData) processed = nlp_model.transform(testData) processed.count() processed.select('description','category','prediction.result').show(truncate=50) processed.select('description','prediction.result').show(truncate=50) from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import pandas as pd df = processed.select('description','category','prediction.result').toPandas() df.head() df.result[0][0] df = processed.select('description','category','prediction.result').toPandas() df['result'] = df['result'].apply(lambda x: x[0]) df.head() df = processed.select('description','category','prediction.result').toPandas() df['result'] = df['result'].apply(lambda x: x[0]) print(classification_report(df.category, df.result)) print(accuracy_score(df.category, df.result)) ``` # ClassifierDL ``` # actual content is inside description column document = DocumentAssembler()\ .setInputCol("description")\ .setOutputCol("document") use = UniversalSentenceEncoder.load('/root/cache_pretrained/tfhub_use_en_2.4.4_2.4_1583158595769')\ .setInputCols(["document"])\ .setOutputCol("sentence_embeddings") # the classes/labels/categories are in category column classsifierdl = ClassifierDLApproach()\ .setInputCols(["sentence_embeddings"])\ .setOutputCol("class")\ .setLabelColumn("category")\ .setMaxEpochs(5)\ .setEnableOutputLogs(True) pipeline = Pipeline( stages = [ document, use, classsifierdl ]) # set seed for reproducibility (trainingData, testData) = newsDF.randomSplit([0.7, 0.3], seed = 100) print("Training Dataset Count: " + str(trainingData.count())) print("Test Dataset Count: " + str(testData.count())) pipelineModel = pipeline.fit(trainingData) from sklearn.metrics import classification_report, accuracy_score df = pipelineModel.transform(testDataset).select('category','description',"class.result").toPandas() df['result'] = df['result'].apply(lambda x: x[0]) print(classification_report(df.category, df.result)) print(accuracy_score(df.category, df.result)) ``` ## Loading the trained classifier from disk ``` classsifierdlmodel = ClassifierDLModel.load('classifierDL_model_20200317_5e') import sparknlp sparknlp.__path__ .setInputCols(["sentence_embeddings"])\ .setOutputCol("class")\ .setLabelColumn("category")\ .setMaxEpochs(5)\ .setEnableOutputLogs(True) trainDataset = spark.read \ .option("header", True) \ .csv("data/news_category_train.csv") trainDataset.count() trainingData.count() document = DocumentAssembler()\ .setInputCol("description")\ .setOutputCol("document") sentence = SentenceDetector()\ .setInputCols(['document'])\ .setOutputCol('sentence') use = UniversalSentenceEncoder.load('/root/cache_pretrained/tfhub_use_en_2.4.4_2.4_1583158595769')\ .setInputCols(["sentence"])\ .setOutputCol("sentence_embeddings") classsifierdlmodel = ClassifierDLModel.load('classifierDL_model_20200317_5e') pipeline = Pipeline( stages = [ document, sentence, use, classsifierdlmodel ]) pipeline.fit(testData.limit(1)).transform(testData.limit(10)).select('category','description',"class.result").show(10, truncate=50) lm = LightPipeline(pipeline.fit(testDataset.limit(1))) lm.annotate('In its first two years, the UK dedicated card companies have surge') text=''' Fearing the fate of Italy, the centre-right government has threatened to be merciless with those who flout tough restrictions. As of Wednesday it will also include all shops being closed across Greece, with the exception of supermarkets. Banks, pharmacies, pet-stores, mobile phone stores, opticians, bakers, mini-markets, couriers and food delivery outlets are among the few that will also be allowed to remain open. ''' lm = LightPipeline(pipeline.fit(testDataset.limit(1))) lm.annotate(text) ``` # Classifier DL + Glove + Basic text processing ``` tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") lemma = LemmatizerModel.pretrained('lemma_antbnc') \ .setInputCols(["token"]) \ .setOutputCol("lemma") lemma_pipeline = Pipeline( stages=[document_assembler, tokenizer, lemma, glove_embeddings]) lemma_pipeline.fit(trainingData.limit(1000)).transform(trainingData.limit(1000)).show(truncate=30) document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) lemma = LemmatizerModel.pretrained('lemma_antbnc') \ .setInputCols(["cleanTokens"]) \ .setOutputCol("lemma") glove_embeddings = WordEmbeddingsModel().pretrained() \ .setInputCols(["document",'lemma'])\ .setOutputCol("embeddings")\ .setCaseSensitive(False) embeddingsSentence = SentenceEmbeddings() \ .setInputCols(["document", "embeddings"]) \ .setOutputCol("sentence_embeddings") \ .setPoolingStrategy("AVERAGE") classsifierdl = ClassifierDLApproach()\ .setInputCols(["sentence_embeddings"])\ .setOutputCol("class")\ .setLabelColumn("category")\ .setMaxEpochs(10)\ .setEnableOutputLogs(True) clf_pipeline = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, lemma, glove_embeddings, embeddingsSentence, classsifierdl]) !rm -rf classifier_dl_pipeline_glove clf_pipelineModel.save('classifier_dl_pipeline_glove') clf_pipelineModel = clf_pipeline.fit(trainingData) df = clf_pipelineModel.transform(testDataset).select('category','description',"class.result").toPandas() df['result'] = df['result'].apply(lambda x: x[0]) print(classification_report(df.category, df.result)) print(accuracy_score(df.category, df.result)) !cd data && ls -l import pandas as pd import news_df = newsDF.toPandas() news_df.head() news_df.to_csv('data/news_dataset.csv', index=False) document_assembler = DocumentAssembler() \ .setInputCol("description") \ .setOutputCol("document") tokenizer = Tokenizer() \ .setInputCols(["document"]) \ .setOutputCol("token") normalizer = Normalizer() \ .setInputCols(["token"]) \ .setOutputCol("normalized") stopwords_cleaner = StopWordsCleaner()\ .setInputCols("normalized")\ .setOutputCol("cleanTokens")\ .setCaseSensitive(False) lemma = LemmatizerModel.pretrained('lemma_antbnc') \ .setInputCols(["cleanTokens"]) \ .setOutputCol("lemma") glove_embeddings = WordEmbeddingsModel().pretrained() \ .setInputCols(["document",'lemma'])\ .setOutputCol("embeddings")\ .setCaseSensitive(False) txt_pipeline = Pipeline( stages=[document_assembler, tokenizer, normalizer, stopwords_cleaner, lemma, glove_embeddings, embeddingsSentence]) txt_pipelineModel = txt_pipeline.fit(testData.limit(1)) txt_pipelineModel.save('text_prep_pipeline_glove') df.head() ```
github_jupyter
``` import keras import keras.backend as K from keras.datasets import mnist from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, BatchNormalization, LocallyConnected2D, Permute, TimeDistributed, Bidirectional from keras.layers import Concatenate, Reshape, Conv2DTranspose, Embedding, Multiply, Activation from functools import partial from collections import defaultdict import os import pickle import numpy as np import scipy.sparse as sp import scipy.io as spio import matplotlib.pyplot as plt class MySequence : def __init__(self) : self.dummy = 1 keras.utils.Sequence = MySequence import isolearn.io as isoio import isolearn.keras as isol import matplotlib.pyplot as plt from sequence_logo_helper import dna_letter_at, plot_dna_logo import tensorflow as tf from keras.backend.tensorflow_backend import set_session def contain_tf_gpu_mem_usage() : config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) set_session(sess) contain_tf_gpu_mem_usage() #Define dataset/experiment name dataset_name = "apa_doubledope" #Load cached dataframe cached_dict = pickle.load(open('apa_doubledope_cached_set.pickle', 'rb')) data_df = cached_dict['data_df'] print("len(data_df) = " + str(len(data_df)) + " (loaded)") #Make generators valid_set_size = 0.05 test_set_size = 0.05 batch_size = 32 #Generate training and test set indexes data_index = np.arange(len(data_df), dtype=np.int) train_index = data_index[:-int(len(data_df) * (valid_set_size + test_set_size))] valid_index = data_index[train_index.shape[0]:-int(len(data_df) * test_set_size)] test_index = data_index[train_index.shape[0] + valid_index.shape[0]:] print('Training set size = ' + str(train_index.shape[0])) print('Validation set size = ' + str(valid_index.shape[0])) print('Test set size = ' + str(test_index.shape[0])) data_gens = { gen_id : isol.DataGenerator( idx, {'df' : data_df}, batch_size=batch_size, inputs = [ { 'id' : 'seq', 'source_type' : 'dataframe', 'source' : 'df', 'extractor' : isol.SequenceExtractor('padded_seq', start_pos=180, end_pos=180 + 205), 'encoder' : isol.OneHotEncoder(seq_length=205), 'dim' : (1, 205, 4), 'sparsify' : False } ], outputs = [ { 'id' : 'hairpin', 'source_type' : 'dataframe', 'source' : 'df', 'extractor' : lambda row, index: row['proximal_usage'], 'transformer' : lambda t: t, 'dim' : (1,), 'sparsify' : False } ], randomizers = [], shuffle = True if gen_id == 'train' else False ) for gen_id, idx in [('all', data_index), ('train', train_index), ('valid', valid_index), ('test', test_index)] } #Load data matrices x_train = np.concatenate([data_gens['train'][i][0][0] for i in range(len(data_gens['train']))], axis=0) x_test = np.concatenate([data_gens['test'][i][0][0] for i in range(len(data_gens['test']))], axis=0) y_train = np.concatenate([data_gens['train'][i][1][0] for i in range(len(data_gens['train']))], axis=0) y_test = np.concatenate([data_gens['test'][i][1][0] for i in range(len(data_gens['test']))], axis=0) print("x_train.shape = " + str(x_train.shape)) print("x_test.shape = " + str(x_test.shape)) print("y_train.shape = " + str(y_train.shape)) print("y_test.shape = " + str(y_test.shape)) #Define sequence template (APA Doubledope sublibrary) sequence_template = 'CTTCCGATCTNNNNNNNNNNNNNNNNNNNNCATTACTCGCATCCANNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCAGCCAATTAAGCCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCTAC' sequence_mask = np.array([1 if sequence_template[j] == 'N' else 0 for j in range(len(sequence_template))]) #Visualize background sequence distribution pseudo_count = 1.0 x_mean = (np.sum(x_train, axis=(0, 1)) + pseudo_count) / (x_train.shape[0] + 4. * pseudo_count) x_mean_logits = np.log(x_mean / (1. - x_mean)) #APARENT parameters seq_input_shape = (1, 205, 4) lib_input_shape = (13,) distal_pas_shape = (1,) num_outputs_iso = 1 num_outputs_cut = 206 #Shared model definition layer_1 = Conv2D(96, (8, 4), padding='valid', activation='relu') layer_1_pool = MaxPooling2D(pool_size=(2, 1)) layer_2 = Conv2D(128, (6, 1), padding='valid', activation='relu') layer_dense = Dense(256, activation='relu') layer_drop = Dropout(0.2) def shared_model(seq_input, distal_pas_input) : return layer_drop( layer_dense( Concatenate()([ Flatten()( layer_2( layer_1_pool( layer_1( seq_input ) ) ) ), distal_pas_input ]) ) ) #Inputs seq_input = Input(name="seq_input", shape=seq_input_shape) permute_layer = Lambda(lambda x: K.permute_dimensions(x, (0, 2, 3, 1))) lib_input = Lambda(lambda x: K.tile(K.expand_dims(K.constant(np.array([0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.])), axis=0), (K.shape(x)[0], 1)))(seq_input) distal_pas_input = Lambda(lambda x: K.tile(K.expand_dims(K.constant(np.array([1.])), axis=0), (K.shape(x)[0], 1)))(seq_input) plasmid_out_shared = Concatenate()([shared_model(permute_layer(seq_input), distal_pas_input), lib_input]) plasmid_out_cut = Dense(num_outputs_cut, activation='softmax', kernel_initializer='zeros')(plasmid_out_shared) plasmid_out_iso = Dense(num_outputs_iso, activation='sigmoid', kernel_initializer='zeros', name="apa_logodds")(plasmid_out_shared) predictor_temp = Model( inputs=[ seq_input ], outputs=[ plasmid_out_iso, plasmid_out_cut ] ) predictor_temp.load_weights('../../../aparent/saved_models/aparent_plasmid_iso_cut_distalpas_all_libs_no_sampleweights_sgd.h5') predictor = Model( inputs=predictor_temp.inputs, outputs=[ predictor_temp.outputs[0] ] ) predictor.trainable = False predictor.compile( optimizer=keras.optimizers.SGD(lr=0.1), loss='mean_squared_error' ) #Plot distribution of (Proximal Isoform) y_pred_test = predictor.predict(x=[x_test], batch_size=32)[:, 0] perc_50 = round(np.quantile(y_pred_test, q=0.5), 2) perc_80 = round(np.quantile(y_pred_test, q=0.8), 2) perc_90 = round(np.quantile(y_pred_test, q=0.9), 2) f = plt.figure(figsize=(6, 4)) plt.hist(y_pred_test, bins=50, edgecolor='black', color='blue', linewidth=2) plt.axvline(x=perc_50, color='green', linewidth=2, linestyle="--") plt.axvline(x=perc_80, color='orange', linewidth=2, linestyle="--") plt.axvline(x=perc_90, color='red', linewidth=2, linestyle="--") plt.xlabel("Predicted Proximal Isoform.", fontsize=12) plt.ylabel("Sequence Count", fontsize=12) t = np.sort(np.concatenate([ np.array([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]), np.array([perc_50, perc_80, perc_90]) ], axis=0)) plt.xticks(t, t, fontsize=12, rotation=45) plt.yticks(fontsize=12) plt.xlim(0, 1) plt.ylim(0) plt.tight_layout() plt.show() #Plot distribution of (Distal Isoform) y_pred_test_inv = 1. - predictor.predict(x=[x_test], batch_size=32)[:, 0] perc_50 = round(np.quantile(y_pred_test_inv, q=0.5), 2) perc_80 = round(np.quantile(y_pred_test_inv, q=0.8), 2) perc_90 = round(np.quantile(y_pred_test_inv, q=0.9), 2) f = plt.figure(figsize=(6, 4)) plt.hist(y_pred_test_inv, bins=50, edgecolor='black', color='blue', linewidth=2) plt.axvline(x=perc_50, color='green', linewidth=2, linestyle="--") plt.axvline(x=perc_80, color='orange', linewidth=2, linestyle="--") plt.axvline(x=perc_90, color='red', linewidth=2, linestyle="--") plt.xlabel("Predicted Distal Isoform.", fontsize=12) plt.ylabel("Sequence Count", fontsize=12) t = np.sort(np.concatenate([ np.array([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]), np.array([perc_50, perc_80, perc_90]) ], axis=0)) plt.xticks(t, t, fontsize=12, rotation=45) plt.yticks(fontsize=12) plt.xlim(0, 1) plt.ylim(0) plt.tight_layout() plt.show() import sis #Run SIS on test set fixed_threshold_proximal = 0.7 fixed_threshold_distal = 0.9 dynamic_threshold_scale = 0.8 n_seqs_to_test = x_test.shape[0] importance_scores_test = [] predictor_calls_test = [] for data_ix in range(n_seqs_to_test) : if data_ix % 100 == 0 : print("Processing example " + str(data_ix) + "...") is_prox = True if y_pred_test[data_ix] > 0.5 else False threshold = 0. if is_prox : threshold = fixed_threshold_proximal if y_pred_test[data_ix] >= fixed_threshold_proximal * (1. / dynamic_threshold_scale) else dynamic_threshold_scale * y_pred_test[data_ix] else : threshold = fixed_threshold_distal if (1. - y_pred_test[data_ix]) >= fixed_threshold_distal * (1. / dynamic_threshold_scale) else dynamic_threshold_scale * (1. - y_pred_test[data_ix]) x_curr = x_test[data_ix, 0, ...] bg = x_mean seq_mask = np.max(x_test[data_ix, 0, ...], axis=-1, keepdims=True) predictor_counter = { 'acc' : 0 } def _temp_pred_func(batch, is_prox=is_prox, mask=seq_mask, predictor_counter=predictor_counter) : temp_data = np.concatenate([np.expand_dims(np.expand_dims(arr * mask, axis=0), axis=0) for arr in batch], axis=0) predictor_counter['acc'] += temp_data.shape[0] temp_out = None if is_prox : temp_out = predictor.predict(x=[temp_data], batch_size=64)[:, 0] else : temp_out = 1. - predictor.predict(x=[temp_data], batch_size=64)[:, 0] return temp_out F_PRED = lambda batch: _temp_pred_func(batch) x_fully_masked = np.copy(bg) initial_mask = sis.make_empty_boolean_mask_broadcast_over_axis(x_curr.shape, 1) collection = sis.sis_collection(F_PRED, threshold, x_curr, x_fully_masked, initial_mask=initial_mask) importance_scores_test_curr = np.expand_dims(np.expand_dims(np.zeros(x_curr.shape), axis=0), axis=0) if collection[0].sis.shape[0] > 0 : imp_index = collection[0].sis[:, 0].tolist() importance_scores_test_curr[0, 0, imp_index, :] = 1. importance_scores_test_curr[0, 0, ...] = importance_scores_test_curr[0, 0, ...] * x_curr importance_scores_test.append(importance_scores_test_curr) predictor_calls_test.append(predictor_counter['acc']) importance_scores_test = np.concatenate(importance_scores_test, axis=0) predictor_calls_test = np.array(predictor_calls_test) #Print predictor call statistics print("Total number of predictor calls = " + str(np.sum(predictor_calls_test))) print("Average number of predictor calls = " + str(np.mean(predictor_calls_test))) #Gradient saliency/backprop visualization import matplotlib.collections as collections import operator import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors import matplotlib as mpl from matplotlib.text import TextPath from matplotlib.patches import PathPatch, Rectangle from matplotlib.font_manager import FontProperties from matplotlib import gridspec from matplotlib.ticker import FormatStrFormatter def plot_importance_scores(importance_scores, ref_seq, figsize=(12, 2), score_clip=None, sequence_template='', plot_start=0, plot_end=96) : end_pos = ref_seq.find("#") fig = plt.figure(figsize=figsize) ax = plt.gca() if score_clip is not None : importance_scores = np.clip(np.copy(importance_scores), -score_clip, score_clip) max_score = np.max(np.sum(importance_scores[:, :], axis=0)) + 0.01 for i in range(0, len(ref_seq)) : mutability_score = np.sum(importance_scores[:, i]) dna_letter_at(ref_seq[i], i + 0.5, 0, mutability_score, ax) plt.sca(ax) plt.xlim((0, len(ref_seq))) plt.ylim((0, max_score)) plt.axis('off') plt.yticks([0.0, max_score], [0.0, max_score], fontsize=16) for axis in fig.axes : axis.get_xaxis().set_visible(False) axis.get_yaxis().set_visible(False) plt.tight_layout() plt.show() #Visualize a few perturbations encoder = isol.OneHotEncoder(205) score_clip = None for plot_i in range(0, 10) : print("Test sequence " + str(plot_i) + ":") plot_dna_logo(x_test[plot_i, 0, :, :], sequence_template=sequence_template, plot_sequence_template=True, figsize=(14, 0.65), plot_start=0, plot_end=205) plot_importance_scores(importance_scores_test[plot_i, 0, :, :].T, encoder.decode(x_test[plot_i, 0, :, :]), figsize=(14, 0.65), score_clip=score_clip, sequence_template=sequence_template, plot_start=0, plot_end=205) #Save predicted importance scores model_name = "sufficient_input_subsets_" + dataset_name + "_thresh_07_mean" np.save(model_name + "_importance_scores_test", importance_scores_test) ```
github_jupyter
#Case Study 1 : Collecting Data from Twitter ** Due Date: February 10, before the class** *------------ **TEAM Members:** Haley Huang Helen Hong Tom Meagher Tyler Reese **Required Readings:** * Chapter 1 and Chapter 9 of the book [Mining the Social Web](http://www.learndatasci.com/wp-content/uploads/2015/08/Mining-the-Social-Web-2nd-Edition.pdf) * The codes for [Chapter 1](http://bit.ly/1qCtMrr) and [Chapter 9](http://bit.ly/1u7eP33) ** NOTE ** * Please don't forget to save the notebook frequently when working in IPython Notebook, otherwise the changes you made can be lost. *---------------------- #Problem 1: Sampling Twitter Data with Streaming API about a certain topic * Select a topic that you are interested in, for example, "WPI" or "Lady Gaga" * Use Twitter Streaming API to sample a collection of tweets about this topic in real time. (It would be recommended that the number of tweets should be larger than 200, but smaller than 1 million. * Store the tweets you downloaded into a local file (txt file or json file) Our topic of interest is the New England Patriots. All Patriots fans ourselves, we were disappointed upon their elimination from the post-season, and unsure how to approach the upcoming Super Bowl. In order to sample how others may be feeling about the Patriots, we use search term "Patriots" for the Twitter streaming API. ``` # HELPER FUNCTIONS import io import json import twitter def oauth_login(token, token_secret, consumer_key, consumer_secret): """ Snag an auth from Twitter """ auth = twitter.oauth.OAuth(token, token_secret, consumer_key, consumer_secret) return auth def save_json(filename, data): """ Save json data to a filename """ print 'Saving data into {0}.json...'.format(filename) with io.open('{0}.json'.format(filename), 'w', encoding='utf-8') as f: f.write(unicode(json.dumps(data, ensure_ascii=False))) def load_json(filename): """ Load json data from a filename """ print 'Loading data from {0}.json...'.format(filename) with open('{0}.json'.format(filename)) as f: return json.load(f) # API CONSTANTS CONSUMER_KEY = '92TpJf8O0c9AWN3ZJjcN8cYxs' CONSUMER_SECRET ='dyeCqzI2w7apETbTUvPai1oCDL5oponvZhHSmYm5XZTQbeiygq' OAUTH_TOKEN = '106590533-SEB5EGGoyJ8EsjOKN05YuOQYu2rg5muZgMDoNrqN' OAUTH_TOKEN_SECRET = 'BficAky6uGyGfRzDGJqZYVKo0HS6G6Ex3ijYW3zy3kjNJ' # CREATE AND CHECK API AND STREAM auth = oauth_login(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) twitter_api = twitter.Twitter(auth=auth) twitter_stream = twitter.TwitterStream(auth=auth) if twitter_api and twitter_stream: print 'Bingo! API and stream set up!' else: print 'Hmmmm, something is wrong here.' # COLLECT TWEETS FROM STREAM WITH TRACK, 'PATRIOTS' # track = "Patriots" # Tweets for Patriots # TOTAL_TWEETS = 2500 # patriots = [] # patriots_counter = 0 # while patriots_counter < TOTAL_TWEETS: # collect tweets while current time is less than endTime # # Create a stream instance # auth = oauth_login(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, # token=OAUTH_TOKEN, token_secret=OAUTH_TOKEN_SECRET) # twitter_stream = TwitterStream(auth=auth) # stream = twitter_stream.statuses.filter(track=track) # counter = 0 # for tweet in stream: # if patriots_counter == TOTAL_TWEETS: # print 'break' # break # elif counter % 500 == 0 and counter != 0: # print 'get new stream' # break # else: # patriots.append(tweet) # patriots_counter += 1 # counter += 1 # print patriots_counter, counter # save_json('json/patriots', patriots) # Use this code to load tweets that have already been collected filename = "stream/json/patriots" results = load_json(filename) print 'Number of tweets loaded:', len(results) # Compute additional statistics about the tweets collected # Determine the average number of words in the text of each tweet def average_words(tweet_texts): total_words = sum([len(s.split()) for s in tweet_texts]) return 1.0*total_words/len(tweet_texts) tweet_texts = [ tweet['text'] for tweet in results ] print 'Average number of words:', average_words(tweet_texts) # Calculate the lexical diversity of all words contained in the tweets def lexical_diversity(tokens): return 1.0*len(set(tokens))/len(tokens) words = [ word for tweet in tweet_texts for word in tweet.split() ] print 'Lexical Diversity:', lexical_diversity(words) ``` ###Report some statistics about the tweets you collected * The topic of interest: Patriots * The total number of tweets collected: 2,500 * Average number of words per tweet: 14.5536 * Lexical Diversity of all words contained in the collection of tweets: 0.1906 *----------------------- #Problem 2: Analyzing Tweets and Tweet Entities with Frequency Analysis **1. Word Count:** * Use the tweets you collected in Problem 1, and compute the frequencies of the words being used in these tweets. * Plot a table of the top 30 words with their counts ``` from collections import Counter from prettytable import PrettyTable import nltk tweet_texts = [ tweet['text'] for tweet in results ] words = [ word for tweet in tweet_texts for word in tweet.split() if word not in ['RT', '&amp;'] # filter out RT and ampersand ] # Use the natural language toolkit to eliminate stop words # nltk.download('stopwords') # download stop words if you do not have it stop_words = nltk.corpus.stopwords.words('english') non_stop_words = [w for w in words if w.lower() not in stop_words] # frequency of words count = Counter(non_stop_words).most_common() # table of the top 30 words with their counts pretty_table = PrettyTable(field_names=['Word', 'Count']) [ pretty_table.add_row(w) for w in count[:30] ] pretty_table.align['Word'] = 'l' pretty_table.align['Count'] = 'r' print pretty_table ``` **2. Find the most popular tweets in your collection of tweets** Please plot a table of the top 10 tweets that are the most popular among your collection, i.e., the tweets with the largest number of retweet counts. ``` from collections import Counter from prettytable import PrettyTable # Create a list of all tweets with a retweeted_status key, and index the originator of that tweet and the text. retweets = [ (tweet['retweet_count'], tweet['retweeted_status']['user']['screen_name'], tweet['text']) #Ensure that a retweet exists for tweet in results if tweet.has_key('retweeted_status') ] pretty_table = PrettyTable(field_names = ['Count','Screen Name','Text']) # Sort tweets by descending number of retweets and display the top 10 results in a table. [pretty_table.add_row(row) for row in sorted(retweets, reverse = True)[:10]] pretty_table.max_width['Text'] = 50 pretty_table.align = 'l' print pretty_table ``` Another measure of tweet "popularity" could be the number of times it is favorited. The following calculates the top-10 tweets with the most "favorites" ``` from prettytable import PrettyTable # Determine the number of "favorites" for each tweet collected. favorites = [ (tweet['favorite_count'], tweet['text']) for tweet in results ] pretty_table = PrettyTable(field_names = ['Count','Text']) # Sort tweets by descending number of favorites and display the top 10 results in a table. [pretty_table.add_row(row) for row in sorted(favorites, reverse = True)[:10]] pretty_table.max_width['Text'] = 75 pretty_table.align = 'l' print pretty_table ``` **3. Find the most popular Tweet Entities in your collection of tweets** Please plot a table of the top 10 hashtags, top 10 user mentions that are the most popular in your collection of tweets. ``` from collections import Counter from prettytable import PrettyTable # Extract the screen names which appear among the collection of tweets screen_names = [user_mention['screen_name'] for tweet in results for user_mention in tweet['entities']['user_mentions']] # Extract the hashtags which appear among the collection of tweets hashtags = [ hashtag['text'] for tweet in results for hashtag in tweet['entities']['hashtags']] # Simultaneously determine the frequency of screen names/hashtags, and display the top 10 most common in a table. for label, data in (('Screen Name',screen_names), ('Hashtag',hashtags)): pretty_table = PrettyTable(field_names =[label,'Count']) counter = Counter(data) [ pretty_table.add_row(entity) for entity in counter.most_common()[:10]] pretty_table.align[label] ='l' pretty_table.align['Count'] = 'r' print pretty_table ``` *------------------------ #Problem 3: Getting "All" friends and "All" followers of a popular user in twitter * choose a popular twitter user who has many followers, such as "ladygaga". * Get the list of all friends and all followers of the twitter user. * Plot 20 out of the followers, plot their ID numbers and screen names in a table. * Plot 20 out of the friends (if the user has more than 20 friends), plot their ID numbers and screen names in a table. Our chosen twitter user is RobGronkowski, one of the Patriots players ``` #---------------------------------------------- import sys import time from urllib2 import URLError from httplib import BadStatusLine import json from functools import partial from sys import maxint # The following is the "general-purpose API wrapper" presented in "Mining the Social Web" for making robust twitter requests. # This function can be used to accompany any twitter API function. It force-breaks after receiving more than max_errors # error messages from the Twitter API. It also sleeps and later retries when rate limits are enforced. def make_twitter_request(twitter_api_func, max_errors = 10, *args, **kw): def handle_twitter_http_error(e, wait_period = 2, sleep_when_rate_limited = True): if wait_period > 3600: print >> sys.stderr, 'Too many retries. Quitting.' raise e if e.e.code == 401: print >> sys.stderr, 'Encountered 401 Error (Not Authorized)' return None elif e.e.code == 404: print >> sys.stderr, 'Encountered 404 Error (Not Found)' return None elif e.e.code == 429: print >> sys.stderr, 'Encountered 429 Error (Rate Limit Exceeded)' if sleep_when_rate_limited: print >> sys.stderr, "Retrying again in 15 Minutes...ZzZ..." sys.stderr.flush() time.sleep(60*15 + 5) print >> sys.stderr, '...ZzZ...Awake now and trying again.' return 2 else: raise e elif e.e.code in (500,502,503,504): print >> sys.stderr, 'Encountered %i Error. Retrying in %i seconds' % \ (e.e.code, wait_period) time.sleel(wait.period) wait.period *= 1.5 return wait_period else: raise e wait_period = 2 error_count = 0 while True: try: return twitter_api_func(*args,**kw) except twitter.api.TwitterHTTPError, e: error_count = 0 wait_period = handle_twitter_http_error (e, wait_period) if wait_period is None: return except URLError, e: error_count += 1 print >> sys.stderr, "URLError encountered. Continuing" if error_count > max_errors: print >> sys.stderr, "Too many consecutive errors...bailing out." raise except BadStatusLine, e: error_count += 1 print >> sys.stderr, "BadStatusLineEncountered. Continuing" if error_count > max_errors: print >> sys.stderr, "Too many consecutive errors...bailing out." raise # This function uses the above Robust Request wrapper to retreive all friends and followers of a given user. This code # can be found in Chapter 9, the `Twitter Cookbook' in "Mining the social web" from functools import partial from sys import maxint def get_friends_followers_ids(twitter_api, screen_name = None, user_id = None, friends_limit = maxint, followers_limit = maxint): assert(screen_name != None) != (user_id != None), \ "Must have screen_name or user_id, but not both" # See https://dev.twitter.com/docs/api/1.1/get/friends/ids and # https://dev.twitter.com/docs/api/1.1/get/followers/ids for details # on API parameters get_friends_ids = partial(make_twitter_request, twitter_api.friends.ids, count=5000) get_followers_ids = partial(make_twitter_request, twitter_api.followers.ids, count=5000) friends_ids, followers_ids = [], [] for twitter_api_func, limit, ids, label in [ [get_friends_ids, friends_limit, friends_ids, "friends"], [get_followers_ids, followers_limit, followers_ids, "followers"] ]: if limit == 0: continue cursor = -1 while cursor != 0: # Use make_twitter_request via the partially bound callable... if screen_name: response = twitter_api_func(screen_name=screen_name, cursor=cursor) else: # user_id response = twitter_api_func(user_id=user_id, cursor=cursor) if response is not None: ids += response['ids'] cursor = response['next_cursor'] print 'Fetched {0} total {1} ids for {2}'.format(len(ids), label, (user_id or screen_name)) if len(ids) >= limit or response is None: break return friends_ids[:friends_limit], followers_ids[:followers_limit] ``` Use the following code to retreive all friends and followers of @RobGronkowski, one of the Patriots players. ``` # Retrieve the friends and followers of a user, and save to a json file. # screen_name = 'RobGronkowski' # gronk_friends_ids, gronk_followers_ids = get_friends_followers_ids(twitter_api, screen_name = screen_name) # filename = "json/gronk_friends" # save_json(filename, gronk_friends_ids) # filename = "json/gronk_followers" # save_json(filename, gronk_followers_ids) # Use this code to load the already-retrieved friends and followers from a json file. gronk_followers_ids = load_json('json/gronk_followers') gronk_friends_ids = load_json('json/gronk_friends') # The following function retrieves the screen names of Twitter users, given their user IDs. If a certain number of screen # names is desired (for example, 20) max_ids limits the number retreived. def get_screen_names(twitter_api, user_ids = None, max_ids = None): response = [] items = user_ids # Due to individual user security settings, not all user profiles can be obtained. Iterate over all user IDs # to ensure at least (max_ids) screen names are obtained. while len(response) < max_ids: items_str = ','.join([str(item) for item in items[:100]]) items = items[100:] responses = make_twitter_request(twitter_api.users.lookup, user_id = items_str) response += responses items_to_info = {} # The above loop has retrieved all user information. for user_info in response: items_to_info[user_info['id']] = user_info # Extract only the screen names obtained. The keys of items_to_info are the user ID numbers. names = [items_to_info[number]['screen_name'] for number in items_to_info.keys() ] numbers =[number for number in items_to_info.keys()] return names , numbers from prettytable import PrettyTable # Given a set of user ids, this function calls get_screen_names and plots a table of the first (max_ids) ID's and screen names. def table_ids_screen_names(twitter_api, user_ids = None, max_ids = None): names, numbers = get_screen_names(twitter_api, user_ids = user_ids, max_ids = max_ids) ids_screen_names = zip(numbers, names) pretty_table = PrettyTable(field_names = ['User ID','Screen Name']) [ pretty_table.add_row (row) for row in ids_screen_names[:max_ids]] pretty_table.align = 'l' print pretty_table # Given a list of friends_ids and followers_ids, this function counts and prints the size of each collection. # It then plots a tables of the first (max_ids) listed friends and followers. def display_friends_followers(screen_name, friends_ids, followers_ids ,max_ids = None): friends_ids_set, followers_ids_set = set(friends_ids),set(followers_ids) print print '{0} has {1} friends. Here are {2}:'.format(screen_name, len(friends_ids_set),max_ids) print table_ids_screen_names(twitter_api, user_ids = friends_ids, max_ids = max_ids) print print '{0} has {1} followers. Here are {2}:'.format(screen_name,len(followers_ids_set),max_ids) print table_ids_screen_names(twitter_api, user_ids = followers_ids, max_ids = max_ids) print display_friends_followers(screen_name = screen_name, friends_ids = gronk_friends_ids, followers_ids = gronk_followers_ids, max_ids = 20) ``` * Compute the mutual friends within the two groups, i.e., the users who are in both friend list and follower list, plot their ID numbers and screen names in a table ``` # Given a list of friends_ids and followers_ids, this function use set intersection to find the number of mutual friends. # It then plots a table of the first (max_ids) listed mutual friends. def display_mutual_friends(screen_name, friends_ids, followers_ids ,max_ids = None): friends_ids_set, followers_ids_set = set(friends_ids),set(followers_ids) print print '{0} has {1} mutual friends. Here are {2}:'.format(screen_name, len(friends_ids_set.intersection(followers_ids_set)),max_ids) print mutual_friends_ids = list(friends_ids_set.intersection(followers_ids_set)) table_ids_screen_names(twitter_api, user_ids = mutual_friends_ids, max_ids = max_ids) display_mutual_friends(screen_name = screen_name, friends_ids = gronk_friends_ids, followers_ids = gronk_followers_ids, max_ids = 20) ``` *------------------------ #Problem 4: Explore the data Run some additional experiments with your data to gain familiarity with the twitter data ant twitter API The following code was used to collect all Twitter followers of the Patriots, Broncos, and Panthers. Once collected, the followers were saved to files. ``` # ## PATRIOTS # patriots_friends_ids, patriots_followers_ids = get_friends_followers_ids(twitter_api, screen_name = 'Patriots') # save_json('json/Patriots_Followers',patriots_followers_ids) # save_json('json/Patriots_Friends', patriots_friends_ids) # ## BRONCOS # broncos_friends_ids, broncos_followers_ids = get_friends_followers_ids(twitter_api, screen_name = 'Broncos') # save_json('json/Broncos_Followers',broncos_followers_ids) # save_json('json/Broncos_Friends', broncos_friends_ids) # ## PANTHERS # panthers_friends_ids, panthers_followers_ids = get_friends_followers_ids(twitter_api, screen_name = 'Panthers') # save_json('json/Panthers_Followers',panthers_followers_ids) # save_json('json/Panthers_Friends', panthers_friends_ids) ``` This code is used to load the above followers, having already been collected. It then makes a venn-diagram comparing the mutual followers between the three teams. ``` patriots_followers_ids = load_json('json/Patriots_Followers') broncos_followers_ids = load_json('json/Broncos_Followers') panthers_followers_ids = load_json('json/Panthers_Followers') %matplotlib inline from matplotlib_venn import venn3 patriots_followers_set = set(patriots_followers_ids) broncos_followers_set = set(broncos_followers_ids) panthers_followers_set = set(panthers_followers_ids) venn3([patriots_followers_set, broncos_followers_set, panthers_followers_set], ('Patriots Followers', 'Broncos Followers', 'Panthers Followers')) ``` Next we wanted to estimate popularity of the Broncos and Panthers (the two remaining Super Bowl teams) in the Boston area. Our chosen metric of "popularity" is the speed at which tweets are generated. The following periodically collects tweets (constrained to the Boston geo zone) filtered for "Broncos" and "Panthers." It tracks the number of such tweets collected in each time window, allowing us to estimate a Tweets per Minute ratio. ``` # COLLECT TWEETS FROM STREAM WITH BRONCOS AND PANTHERS IN TWEET TEXT FROM BOSTON GEO ZONE # from datetime import timedelta, datetime # from time import sleep # from twitter import TwitterStream # track = "Broncos, Panthers" # Tweets for Broncos OR Panthers # locations = '-73.313057,41.236511,-68.826305,44.933163' # New England / Boston geo zone # NUMBER_OF_COLLECTIONS = 5 # number of times to collect tweets from stream # COLLECTION_TIME = 2.5 # length of each collection in minutes # WAIT_TIME = 10 # sleep time in between collections in minutes # date_format = '%m/%d/%Y %H:%M:%S' # i.e. 1/1/2016 13:00:00 # broncos, panthers, counts = [], [], [] # for counter in range(1, NUMBER_OF_COLLECTIONS + 1): # print '------------------------------------------' # print 'COLLECTION NUMBER %s out of %s' % (counter, NUMBER_OF_COLLECTIONS) # broncos_counter, panthers_counter = 0, 0 # set the internal counter for Broncos and Panthers to 0 # count_dict = {'start_time': datetime.now().strftime(format=date_format)} # add collection start time # # Create a new stream instance every collection to avoid rate limits # auth = oauth_login(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token=OAUTH_TOKEN, token_secret=OAUTH_TOKEN_SECRET) # twitter_stream = TwitterStream(auth=auth) # stream = twitter_stream.statuses.filter(track=track, locations=locations) # endTime = datetime.now() + timedelta(minutes=COLLECTION_TIME) # while datetime.now() <= endTime: # collect tweets while current time is less than endTime # for tweet in stream: # if 'text' in tweet.keys(): # check to see if tweet contains text # if datetime.now() > endTime: # break # if the collection time is up, break out of the loop # elif 'Broncos' in tweet['text'] and 'Panthers' in tweet['text']: # broncos.append(tweet), panthers.append(tweet) # if a tweet contains both Broncos and Panthers, add the tweet to both arrays # broncos_counter += 1 # panthers_counter += 1 # print 'Panthers: %s, Broncos: %s' % (panthers_counter, broncos_counter) # elif 'Broncos' in tweet['text']: # broncos.append(tweet) # broncos_counter += 1 # print 'Broncos: %s' % broncos_counter # elif 'Panthers' in tweet['text']: # panthers.append(tweet) # panthers_counter += 1 # print 'Panthers: %s' % panthers_counter # else: # print 'continue' # if the tweet text does not match 'Panthers' or 'Broncos', keep going # continue # count_dict['broncos'] = broncos_counter # count_dict['panthers'] = panthers_counter # count_dict['end_time'] = datetime.now().strftime(format=date_format) # add collection end time # counts.append(count_dict) # print counts # if counter != NUMBER_OF_COLLECTIONS: # print 'Sleeping until %s' % (datetime.now() + timedelta(minutes=WAIT_TIME)) # sleep(WAIT_TIME * 60) # sleep for WAIT_TIME # else: # print '------------------------------------------' # # Save arrays to files # save_json('stream/json/counts', counts) # save_json('stream/json/broncos', broncos) # save_json('stream/json/panthers', panthers) # LOAD JSON FOR BRONCOS AND PANTHERS broncos = load_json('stream/json/broncos') panthers = load_json('stream/json/panthers') counts = load_json('stream/json/counts') pretty_table = PrettyTable(field_names =['Broncos Tweets', 'Collection Start Time', 'Panthers Tweets','Collection End Time']) [ pretty_table.add_row(row.values()) for row in counts] pretty_table.align[label] ='l' pretty_table.align['Count'] = 'r' print pretty_table print 'TOTALS – Broncos: %s, Panthers: %s' % (len(broncos), len(panthers)) %matplotlib inline # CUMULATIVE TWEET DISTRIBUTION FOR BRONCOS AND PANTHERS import numpy as np import matplotlib.pyplot as plt from matplotlib import mlab # create numpy arrays for Broncos and Panthers tweets broncos_tweets = np.array([row['broncos'] for row in counts]) panthers_tweets = np.array([row['panthers'] for row in counts]) bins = len(counts) * 10 # evaluate histogram broncos_values, broncos_base = np.histogram(broncos_tweets, bins=bins) panthers_values, panthers_base = np.histogram(panthers_tweets, bins=bins) # evaluate cumulative function broncos_cumulative = np.cumsum(broncos_values) panthers_cumulative = np.cumsum(panthers_values) # plot cumulative function plt.plot(broncos_base[:-1], broncos_cumulative, c='darkorange') plt.plot(panthers_base[:-1], panthers_cumulative, c='blue') plt.grid(True) plt.title('Cumulative Distribution of Broncos & Panthers Tweets') plt.xlabel('Tweets') plt.ylabel('Collection') plt.show() ``` *----------------- # Done All set! ** What do you need to submit?** * **Notebook File**: Save this IPython notebook, and find the notebook file in your folder (for example, "filename.ipynb"). This is the file you need to submit. Please make sure all the plotted tables and figures are in the notebook. If you used "ipython notebook --pylab=inline" to open the notebook, all the figures and tables should have shown up in the notebook. * **PPT Slides**: please prepare PPT slides (for 10 minutes' talk) to present about the case study . We will ask two teams which are randomly selected to present their case studies in class for this case study. * ** Report**: please prepare a report (less than 10 pages) to report what you found in the data. * What data you collected? * Why this topic is interesting or important to you? (Motivations) * How did you analyse the data? * What did you find in the data? (please include figures or tables in the report, but no source code) Please compress all the files in a zipped file. ** How to submit: ** Please submit through myWPI, in the Assignment "Case Study 1". ** Note: Each team just need to submit one submission in myWPI ** # Grading Criteria: ** Totoal Points: 120 ** --------------------------------------------------------------------------- ** Notebook: ** Points: 80 ----------------------------------- Qestion 1: Points: 20 ----------------------------------- (1) Select a topic that you are interested in. Points: 6 (2) Use Twitter Streaming API to sample a collection of tweets about this topic in real time. (It would be recommended that the number of tweets should be larger than 200, but smaller than 1 million. Please check whether the total number of tweets collected is larger than 200? Points: 10 (3) Store the tweets you downloaded into a local file (txt file or json file) Points: 4 ----------------------------------- Qestion 2: Points: 20 ----------------------------------- 1. Word Count (1) Use the tweets you collected in Problem 1, and compute the frequencies of the words being used in these tweets. Points: 4 (2) Plot a table of the top 30 words with their counts Points: 4 2. Find the most popular tweets in your collection of tweets plot a table of the top 10 tweets that are the most popular among your collection, i.e., the tweets with the largest number of retweet counts. Points: 4 3. Find the most popular Tweet Entities in your collection of tweets (1) plot a table of the top 10 hashtags, Points: 4 (2) top 10 user mentions that are the most popular in your collection of tweets. Points: 4 ----------------------------------- Qestion 3: Points: 20 ----------------------------------- (1) choose a popular twitter user who has many followers, such as "ladygaga". Points: 4 (2) Get the list of all friends and all followers of the twitter user. Points: 4 (3) Plot 20 out of the followers, plot their ID numbers and screen names in a table. Points: 4 (4) Plot 20 out of the friends (if the user has more than 20 friends), plot their ID numbers and screen names in a table. Points: 4 (5) Compute the mutual friends within the two groups, i.e., the users who are in both friend list and follower list, plot their ID numbers and screen names in a table Points: 4 ----------------------------------- Qestion 4: Explore the data Points: 20 ----------------------------------- Novelty: 10 Interestingness: 10 ----------------------------------- Run some additional experiments with your data to gain familiarity with the twitter data and twitter API --------------------------------------------------------------------------- ** Report: communicate the results** Points: 20 (1) What data you collected? Points: 5 (2) Why this topic is interesting or important to you? (Motivations) Points: 5 (3) How did you analyse the data? Points: 5 (4) What did you find in the data? (please include figures or tables in the report, but no source code) Points: 5 --------------------------------------------------------------------------- ** Slides (for 10 minutes of presentation): Story-telling ** Points: 20 1. Motivation about the data collection, why the topic is interesting to you. Points: 5 2. Communicating Results (figure/table) Points: 10 3. Story telling (How all the parts (data, analysis, result) fit together as a story?) Points: 5
github_jupyter
# MNIST handwritten digits classification with MLPs In this notebook, we'll train a multi-layer perceptron model to classify MNIST digits using [TensorFlow](https://www.tensorflow.org/) (version $\ge$ 2.0 required) with the [Keras API](https://www.tensorflow.org/guide/keras/overview). First, the needed imports. ``` %matplotlib inline from pml_utils import show_failures import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten from tensorflow.keras.utils import plot_model, to_categorical from IPython.display import SVG, display import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() print('Using Tensorflow version: {}, and Keras version: {}.'.format(tf.__version__, tf.keras.__version__)) ``` Let's check if we have GPU available. ``` if tf.test.is_gpu_available(): from tensorflow.python.client import device_lib for d in device_lib.list_local_devices(): if d.device_type == 'GPU': print('GPU', d.physical_device_desc) else: print('No GPU, using CPU instead.') ``` ## MNIST data set Next we'll load the MNIST handwritten digits data set using TensorFlow's own tools. First time we may have to download the data, which can take a while. #### Altenative: Fashion-MNIST Alternatively, MNIST can be replaced with Fashion-MNIST, which can be used as drop-in replacement for MNIST. Fashion-MNIST contains images of 10 fashion categories: Label|Description|Label|Description --- | --- |--- | --- 0|T-shirt/top|5|Sandal 1|Trouser|6|Shirt 2|Pullover|7|Sneaker 3|Dress|8|Bag 4|Coat|9|Ankle boot ``` from tensorflow.keras.datasets import mnist, fashion_mnist ## MNIST: (X_train, y_train), (X_test, y_test) = mnist.load_data() ## Fashion-MNIST: #(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data() nb_classes = 10 X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255.0 X_test /= 255.0 # one-hot encoding: Y_train = to_categorical(y_train, nb_classes) Y_test = to_categorical(y_test, nb_classes) print() print('MNIST data loaded: train:',len(X_train),'test:',len(X_test)) print('X_train:', X_train.shape) print('y_train:', y_train.shape) print('Y_train:', Y_train.shape) ``` The training data (`X_train`) is a 3rd-order tensor of size (60000, 28, 28), i.e. it consists of 60000 images of size 28x28 pixels. `y_train` is a 60000-dimensional vector containing the correct classes ("0", "1", ..., "9") for each training sample, and `Y_train` is a [one-hot](https://en.wikipedia.org/wiki/One-hot) encoding of `y_train`. Let's take a closer look. Here are the first 10 training digits (or fashion items for Fashion-MNIST): ``` pltsize=1 plt.figure(figsize=(10*pltsize, pltsize)) for i in range(10): plt.subplot(1,10,i+1) plt.axis('off') plt.imshow(X_train[i,:,:], cmap="gray") plt.title('Class: '+str(y_train[i])) print('Training sample',i,': class:',y_train[i], ', one-hot encoded:', Y_train[i]) ``` ## Multi-layer perceptron (MLP) network ### Activation functions Let's start by plotting some common activation functions for neural networks. `'relu'` stands for rectified linear unit, $y=\max(0,x)$, a very simple non-linearity we will be using in our MLP network below. ``` x = np.arange(-4,4,.01) plt.figure() plt.plot(x, np.maximum(x,0), label='relu') plt.plot(x, 1/(1+np.exp(-x)), label='sigmoid') plt.plot(x, np.tanh(x), label='tanh') plt.axis([-4, 4, -1.1, 1.5]) plt.title('Activation functions') plt.legend(loc='best'); ``` ### Initialization Let's now create an MLP model that has multiple layers, non-linear activation functions, and optionally dropout layers for regularization. We first initialize the model with `Sequential()`. Then we add a `Dense` layer that has 28*28=784 input nodes (one for each pixel in the input image) and 20 output nodes. The `Dense` layer connects each input to each output with some weight parameter. Next, the output of the dense layer is passed through a ReLU non-linear activation function. Commented out is an alternative, more complex, model that you can also try out. It uses more layers and dropout. `Dropout()` randomly sets a fraction of inputs to zero during training, which is one approach to regularization and can sometimes help to prevent overfitting. The output of the last layer needs to be a softmaxed 10-dimensional vector to match the groundtruth (`Y_train`). This means that it will output 10 values between 0 and 1 which sum to 1, hence, together they can be interpreted as a probability distribution over our 10 classes. Finally, we select *categorical crossentropy* as the loss function, select [*Adam*](https://keras.io/optimizers/#adam) as the optimizer, add *accuracy* to the list of metrics to be evaluated, and `compile()` the model. Adam is simply a an advanced version of stochastic gradient descent, note there are [several different options](https://keras.io/optimizers/) for the optimizer in Keras that we could use instead of *adam*. ``` # Model initialization: model = Sequential() # A simple model: model.add(Dense(units=20, input_dim=28*28)) model.add(Activation('relu')) # A bit more complex model: #model.add(Dense(units=50, input_dim=28*28)) #model.add(Activation('relu')) #model.add(Dropout(0.2)) #model.add(Dense(units=50)) #model.add(Activation('relu')) #model.add(Dropout(0.2)) # The last layer needs to be like this: model.add(Dense(units=10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) ``` The summary shows that there are 15,910 parameters in total in our model. For example for the first dense layer we have 785x20 = 15,700 parameters as the weight matrix is of size 785x20 (not 784, as there's an additional bias term). We can also draw a fancier graph of our model. ``` plot_model(model, show_shapes=True) ``` ### Learning Next, we'll train our model. Notice how the interface is similar to scikit-learn: we still call the `fit()` method on our model object. An *epoch* means one pass through the whole training data, we'll begin by running training for 10 epochs. The `reshape()` function flattens our 28x28 images into vectors of length 784. (This means we are not using any information about the spatial neighborhood relations of pixels. This setup is known as the *permutation invariant MNIST*.) You can run code below multiple times and it will continue the training process from where it left off. If you want to start from scratch, re-initialize the model using the code a few cells ago. We use a batch size of 32, so the actual input will be 32x784 for each batch of 32 images. ``` %%time epochs = 10 history = model.fit(X_train.reshape((-1,28*28)), Y_train, epochs=epochs, batch_size=32, verbose=2) ``` Let's now see how the training progressed. * *Loss* is a function of the difference of the network output and the target values. We are minimizing the loss function during training so it should decrease over time. * *Accuracy* is the classification accuracy for the training data. It gives some indication of the real accuracy of the model but cannot be fully trusted, as it may have overfitted and just memorizes the training data. ``` plt.figure(figsize=(5,3)) plt.plot(history.epoch,history.history['loss']) plt.title('loss') plt.figure(figsize=(5,3)) plt.plot(history.epoch,history.history['accuracy']) plt.title('accuracy'); ``` ### Inference For a better measure of the quality of the model, let's see the model accuracy for the test data. ``` %%time scores = model.evaluate(X_test.reshape((-1,28*28)), Y_test, verbose=2) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) ``` We can now take a closer look at the results using the `show_failures()` helper function. Here are the first 10 test digits the MLP classified to a wrong class: ``` predictions = model.predict(X_test.reshape((-1,28*28))) show_failures(predictions, y_test, X_test) ``` We can use `show_failures()` to inspect failures in more detail. For example, here are failures in which the true class was "6": ``` show_failures(predictions, y_test, X_test, trueclass=6) ``` We can also compute the confusion matrix to see which digits get mixed the most, and look at classification accuracies separately for each class: ``` from sklearn.metrics import confusion_matrix print('Confusion matrix (rows: true classes; columns: predicted classes):'); print() cm=confusion_matrix(y_test, np.argmax(predictions, axis=1), labels=list(range(10))) print(cm); print() print('Classification accuracy for each class:'); print() for i,j in enumerate(cm.diagonal()/cm.sum(axis=1)): print("%d: %.4f" % (i,j)) ``` ## Model tuning Modify the MLP model. Try to improve the classification accuracy, or experiment with the effects of different parameters. If you are interested in the state-of-the-art performance on permutation invariant MNIST, see e.g. this [recent paper](https://arxiv.org/abs/1507.02672) by Aalto University / The Curious AI Company researchers. You can also consult the Keras documentation at https://keras.io/. For example, the Dense, Activation, and Dropout layers are described at https://keras.io/layers/core/.
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@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. ``` # TensorFlow 1 のコードを TensorFlow 2 に移行する <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/guide/migrate"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/guide/migrate.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png"> Google Colab で実行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/guide/migrate.ipynb"> <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/guide/migrate.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a></td> </table> 本ドキュメントは、低レベル TensorFlow API のユーザーを対象としています。高レベル API(`tf.keras`)をご使用の場合は、コードを TensorFlow 2.x と完全互換にするためのアクションはほとんどまたはまったくありません。 - [オプティマイザのデフォルトの学習率](#keras_optimizer_lr)を確認してください。 - メトリクスが記録される「名前」が[変更されている可能性がある](#keras_metric_names)ことに注意してください。 TensorFlow 2.x で 1.X のコードを未修正で実行することは、([contrib を除き](https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md))依然として可能です。 ```python import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ``` しかし、これでは TensorFlow 2.0 で追加された改善の多くを活用できません。このガイドでは、コードのアップグレード、さらなる単純化、パフォーマンス向上、そしてより容易なメンテナンスについて説明します。 ## 自動変換スクリプト このドキュメントで説明される変更を実装する前に行うべき最初のステップは、[アップグレードスクリプト](./upgrade.md)を実行してみることです。 これはコードを TensorFlow 2.x にアップグレードする際の初期パスとしては十分ですが、v2 特有のコードに変換するわけではありません。コードは依然として `tf.compat.v1` エンドポイントを使用して、プレースホルダー、セッション、コレクション、その他 1.x スタイルの機能へのアクセスが可能です。 ## トップレベルの動作の変更 `tf.compat.v1.disable_v2_behavior()` を使用することで TensorFlow 2.x でコードが機能する場合でも、対処すべきグローバルな動作の変更があります。主な変更点は次のとおりです。 - *Eager execution、`v1.enable_eager_execution()`*: 暗黙的に `tf.Graph` を使用するコードは失敗します。このコードは必ず `with tf.Graph().as_default()` コンテキストでラップしてください。 - *リソース変数、`v1.enable_resource_variables()`*: 一部のコードは、TensorFlow 参照変数によって有効化される非決定的な動作に依存する場合があります。 リソース変数は書き込み中にロックされるため、より直感的な一貫性を保証します。 - これによりエッジケースでの動作が変わる場合があります。 - これにより余分なコピーが作成されるため、メモリ使用量が増える可能性があります。 - これを無効にするには、`use_resource=False` を `tf.Variable` コンストラクタに渡します。 - *テンソルの形状、`v1.enable_v2_tensorshape()`*: TensorFlow 2.x は、テンソルの形状の動作を簡略化されており、`t.shape[0].value` の代わりに `t.shape[0]` とすることができます。簡単な変更なので、すぐに修正しておくことをお勧めします。例については [TensorShape](#tensorshape) をご覧ください。 - *制御フロー、`v1.enable_control_flow_v2()`*: TensorFlow 2.x 制御フローの実装が簡略化されたため、さまざまなグラフ表現を生成します。問題が生じた場合には、[バグを報告](https://github.com/tensorflow/tensorflow/issues)してください。 ## TensorFlow 2.x のコードを作成する このガイドでは、TensorFlow 1.x のコードを TensorFlow 2.x に変換するいくつかの例を確認します。これらの変更によって、コードがパフォーマンスの最適化および簡略化された API 呼び出しを活用できるようになります。 それぞれのケースのパターンは次のとおりです。 ### 1. `v1.Session.run` 呼び出しを置き換える すべての `v1.Session.run` 呼び出しは、Python 関数で置き換える必要があります。 - `feed_dict`および`v1.placeholder`は関数の引数になります。 - `fetch` は関数の戻り値になります。 - Eager execution では、`pdb` などの標準的な Python ツールを使用して、変換中に簡単にデバッグできます。 次に、`tf.function` デコレータを追加して、グラフで効率的に実行できるようにします。 この機能についての詳細は、[AutoGraph ガイド](function.ipynb)をご覧ください。 注意点: - `v1.Session.run` とは異なり、`tf.function` は固定のリターンシグネチャを持ち、常にすべての出力を返します。これによってパフォーマンスの問題が生じる場合は、2 つの個別の関数を作成します。 - `tf.control_dependencies` または同様の演算は必要ありません。`tf.function` は、記述された順序で実行されたかのように動作します。たとえば、`tf.Variable` 割り当てと `tf.assert` は自動的に実行されます。 [「モデルを変換する」セクション](#converting_models)には、この変換プロセスの実際の例が含まれています。 ### 2. Python オブジェクトを変数と損失の追跡に使用する TensorFlow 2.x では、いかなる名前ベースの変数追跡もまったく推奨されていません。 変数の追跡には Python オブジェクトを使用します。 `v1.get_variable` の代わりに `tf.Variable` を使用してください。 すべての`v1.variable_scope`は Python オブジェクトに変換が可能です。通常は次のうちの 1 つになります。 - `tf.keras.layers.Layer` - `tf.keras.Model` - `tf.Module` `tf.Graph.get_collection(tf.GraphKeys.VARIABLES)` などの変数のリストを集める必要がある場合には、`Layer` および `Model` オブジェクトの `.variables` と `.trainable_variables` 属性を使用します。 これら `Layer` クラスと `Model` クラスは、グローバルコレクションの必要性を除去した別のプロパティを幾つか実装します。`.losses` プロパティは、`tf.GraphKeys.LOSSES` コレクション使用の置き換えとなります。 詳細は [Keras ガイド](keras.ipynb)をご覧ください。 警告 : 多くの `tf.compat.v1` シンボルはグローバルコレクションを暗黙的に使用しています。 ### 3. トレーニングループをアップグレードする ご利用のユースケースで動作する最高レベルの API を使用してください。独自のトレーニングループを構築するよりも `tf.keras.Model.fit` の選択を推奨します。 これらの高レベル関数は、独自のトレーニングループを書く場合に見落とされやすい多くの低レベル詳細を管理します。例えば、それらは自動的に正則化損失を集めて、モデルを呼び出す時に`training=True`引数を設定します。 ### 4. データ入力パイプラインをアップグレードする データ入力には `tf.data` データセットを使用してください。それらのオブジェクトは効率的で、表現力があり、TensorFlow とうまく統合します。 次のように、`tf.keras.Model.fit` メソッドに直接渡すことができます。 ```python model.fit(dataset, epochs=5) ``` また、標準的な Python で直接にイテレートすることもできます。 ```python for example_batch, label_batch in dataset: break ``` ### 5. `compat.v1`シンボルを移行する `tf.compat.v1`モジュールには、元のセマンティクスを持つ完全な TensorFlow 1.x API が含まれています。 [TensorFlow 2 アップグレードスクリプト](upgrade.ipynb)は、変換が安全な場合、つまり v2 バージョンの動作が完全に同等であると判断できる場合は、シンボルを 2.0 と同等のものに変換します。(たとえば、これらは同じ関数なので、`v1.arg_max` の名前を `tf.argmax` に変更します。) コードの一部を使用してアップグレードスクリプトを実行した後に、`compat.v1` が頻出する可能性があります。 コードを調べ、それらを手動で同等の v2 のコードに変換する価値はあります。(該当するものがある場合には、ログに表示されているはずです。) ## モデルを変換する ### 低レベル変数 & 演算子実行 低レベル API の使用例を以下に示します。 - 変数スコープを使用して再利用を制御する。 - `v1.get_variable`で変数を作成する。 - コレクションに明示的にアクセスする。 - 次のようなメソッドでコレクションに暗黙的にアクセスする。 - `v1.global_variables` - `v1.losses.get_regularization_loss` - `v1.placeholder` を使用してグラフ入力のセットアップをする。 - `Session.run`でグラフを実行する。 - 変数を手動で初期化する。 #### 変換前 TensorFlow 1.x を使用したコードでは、これらのパターンは以下のように表示されます。 ``` import tensorflow as tf import tensorflow.compat.v1 as v1 import tensorflow_datasets as tfds g = v1.Graph() with g.as_default(): in_a = v1.placeholder(dtype=v1.float32, shape=(2)) in_b = v1.placeholder(dtype=v1.float32, shape=(2)) def forward(x): with v1.variable_scope("matmul", reuse=v1.AUTO_REUSE): W = v1.get_variable("W", initializer=v1.ones(shape=(2,2)), regularizer=lambda x:tf.reduce_mean(x**2)) b = v1.get_variable("b", initializer=v1.zeros(shape=(2))) return W * x + b out_a = forward(in_a) out_b = forward(in_b) reg_loss=v1.losses.get_regularization_loss(scope="matmul") with v1.Session(graph=g) as sess: sess.run(v1.global_variables_initializer()) outs = sess.run([out_a, out_b, reg_loss], feed_dict={in_a: [1, 0], in_b: [0, 1]}) print(outs[0]) print() print(outs[1]) print() print(outs[2]) ``` #### 変換後 変換されたコードでは : - 変数はローカル Python オブジェクトです。 - `forward`関数は依然として計算を定義します。 - `Session.run`呼び出しは`forward`への呼び出しに置き換えられます。 - パフォーマンス向上のためにオプションで`tf.function`デコレータを追加可能です。 - どのグローバルコレクションも参照せず、正則化は手動で計算されます。 - セッションやプレースホルダーはありません。 ``` W = tf.Variable(tf.ones(shape=(2,2)), name="W") b = tf.Variable(tf.zeros(shape=(2)), name="b") @tf.function def forward(x): return W * x + b out_a = forward([1,0]) print(out_a) out_b = forward([0,1]) regularizer = tf.keras.regularizers.l2(0.04) reg_loss=regularizer(W) ``` ### `tf.layers`ベースのモデル `v1.layers`モジュールは、変数を定義および再利用する`v1.variable_scope`に依存するレイヤー関数を含めるために使用されます。 #### 変換前 ``` def model(x, training, scope='model'): with v1.variable_scope(scope, reuse=v1.AUTO_REUSE): x = v1.layers.conv2d(x, 32, 3, activation=v1.nn.relu, kernel_regularizer=lambda x:0.004*tf.reduce_mean(x**2)) x = v1.layers.max_pooling2d(x, (2, 2), 1) x = v1.layers.flatten(x) x = v1.layers.dropout(x, 0.1, training=training) x = v1.layers.dense(x, 64, activation=v1.nn.relu) x = v1.layers.batch_normalization(x, training=training) x = v1.layers.dense(x, 10) return x train_data = tf.ones(shape=(1, 28, 28, 1)) test_data = tf.ones(shape=(1, 28, 28, 1)) train_out = model(train_data, training=True) test_out = model(test_data, training=False) print(train_out) print() print(test_out) ``` #### 変換後 - レイヤーの単純なスタックが `tf.keras.Sequential`にぴったり収まります。(より複雑なモデルについては[カスタムレイヤーとモデル](keras/custom_layers_and_models.ipynb)および[ Functional API ](keras/functional.ipynb)をご覧ください。) - モデルが変数と正則化損失を追跡します。 - `v1.layers`から`tf.keras.layers`への直接的なマッピングがあるため、変換は一対一対応でした。 ほとんどの引数はそのままです。しかし、以下の点は異なります。 - `training`引数は、それが実行される時点でモデルによって各レイヤーに渡されます。 - 元の`model`関数への最初の引数(入力 `x`)はなくなりました。これはオブジェクトレイヤーがモデルの呼び出しからモデルの構築を分離するためです。 また以下にも注意してください。 - `tf.contrib`からの初期化子の正則化子を使用している場合は、他よりも多くの引数変更があります。 - コードはコレクションに書き込みを行わないため、`v1.losses.get_regularization_loss`などの関数はそれらの値を返さなくなり、トレーニングループが壊れる可能性があります。 ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.04), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(10) ]) train_data = tf.ones(shape=(1, 28, 28, 1)) test_data = tf.ones(shape=(1, 28, 28, 1)) train_out = model(train_data, training=True) print(train_out) test_out = model(test_data, training=False) print(test_out) # Here are all the trainable variables. len(model.trainable_variables) # Here is the regularization loss. model.losses ``` ### 変数と`v1.layers`の混在 既存のコードは低レベルの TensorFlow 1.x 変数と演算子に高レベルの`v1.layers`が混ざっていることがよくあります。 #### 変換前 ``` def model(x, training, scope='model'): with v1.variable_scope(scope, reuse=v1.AUTO_REUSE): W = v1.get_variable( "W", dtype=v1.float32, initializer=v1.ones(shape=x.shape), regularizer=lambda x:0.004*tf.reduce_mean(x**2), trainable=True) if training: x = x + W else: x = x + W * 0.5 x = v1.layers.conv2d(x, 32, 3, activation=tf.nn.relu) x = v1.layers.max_pooling2d(x, (2, 2), 1) x = v1.layers.flatten(x) return x train_out = model(train_data, training=True) test_out = model(test_data, training=False) ``` #### 変換後 このコードを変換するには、前の例で示したレイヤーからレイヤーへのマッピングのパターンに従います。 一般的なパターンは次の通りです。 - `__init__`でレイヤーパラメータを収集する。 - `build`で変数を構築する。 - `call`で計算を実行し、結果を返す。 `v1.variable_scope`は事実上それ自身のレイヤーです。従って`tf.keras.layers.Layer`として書き直します。詳細は[ガイド](keras/custom_layers_and_models.ipynb)をご覧ください。 ``` # Create a custom layer for part of the model class CustomLayer(tf.keras.layers.Layer): def __init__(self, *args, **kwargs): super(CustomLayer, self).__init__(*args, **kwargs) def build(self, input_shape): self.w = self.add_weight( shape=input_shape[1:], dtype=tf.float32, initializer=tf.keras.initializers.ones(), regularizer=tf.keras.regularizers.l2(0.02), trainable=True) # Call method will sometimes get used in graph mode, # training will get turned into a tensor @tf.function def call(self, inputs, training=None): if training: return inputs + self.w else: return inputs + self.w * 0.5 custom_layer = CustomLayer() print(custom_layer([1]).numpy()) print(custom_layer([1], training=True).numpy()) train_data = tf.ones(shape=(1, 28, 28, 1)) test_data = tf.ones(shape=(1, 28, 28, 1)) # Build the model including the custom layer model = tf.keras.Sequential([ CustomLayer(input_shape=(28, 28, 1)), tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), ]) train_out = model(train_data, training=True) test_out = model(test_data, training=False) ``` 注意点: - サブクラス化された Keras モデルとレイヤーは v1 グラフ(自動制御依存性なし)と eager モードの両方で実行される必要があります。 - `call()`を`tf.function()`にラップして、AutoGraph と自動制御依存性を得るようにします。 - `training`引数を受け取って`call`することを忘れないようにしてください。 - それは`tf.Tensor`である場合があります。 - それは Python ブール型である場合があります。 - `self.add_weight()`を使用して、コンストラクタまたは`Model.build`でモデル変数を作成します。 - `Model.build`では、入力形状にアクセスできるため、適合する形状で重みを作成できます。 - `tf.keras.layers.Layer.add_weight`を使用すると、Keras が変数と正則化損失を追跡できるようになります。 - オブジェクトに`tf.Tensors`を保持してはいけません。 - それらは`tf.function`または eager コンテキスト内のいずれかで作成される可能性がありますが、それらのテンソルは異なる振る舞いをします。 - 状態には`tf.Variable`を使用してください。これは常に両方のコンテキストから使用可能です。 - `tf.Tensors`は中間値専用です。 ### Slim &amp; contrib.layers に関する注意 古い TensorFlow 1.x コードの大部分は [Slim](https://ai.googleblog.com/2016/08/tf-slim-high-level-library-to-define.html) ライブラリを使用しており、これは`tf.contrib.layers`として TensorFlow 1.x でパッケージ化されていました。 `contrib`モジュールに関しては、TensorFlow 2.x では`tf.compat.v1`内でも、あっても利用できなくなりました。Slim を使用したコードの TensorFlow 2.x への変換は、`v1.layers`を使用したレポジトリの変換よりも複雑です。現実的には、まず最初に Slim コードを`v1.layers`に変換してから Keras に変換するほうが賢明かもしれません。 - `arg_scopes`を除去します。すべての引数は明示的である必要があります。 - それらを使用する場合、 `normalizer_fn`と`activation_fn`をそれら自身のレイヤーに分割します。 - 分離可能な畳み込みレイヤーは 1 つまたはそれ以上の異なる Keras レイヤー(深さ的な、ポイント的な、分離可能な Keras レイヤー)にマップします。 - Slim と`v1.layers`には異なる引数名とデフォルト値があります。 - 一部の引数には異なるスケールがあります。 - Slim 事前トレーニング済みモデルを使用する場合は、`tf.keras.applications`から Keras 事前トレーニング済みモデル、または元の Slim コードからエクスポートされた [TensorFlow ハブ](https://tfhub.dev/s?q=slim%20tf2)の TensorFlow 2 SavedModel をお試しください。 一部の`tf.contrib`レイヤーはコアの TensorFlow に移動されていない可能性がありますが、代わりに [TensorFlow アドオンパッケージ](https://github.com/tensorflow/addons)に移動されています。 ## トレーニング `tf.keras`モデルにデータを供給する方法は沢山あります。それらは Python ジェネレータと Numpy 配列を入力として受け取ります。 モデルへのデータ供給方法として推奨するのは、データ操作用の高パフォーマンスクラスのコレクションを含む`tf.data`パッケージの使用です。 依然として`tf.queue`を使用している場合、これらは入力パイプラインとしてではなく、データ構造としてのみサポートされます。 ### データセットを使用する [TensorFlow Dataset](https://tensorflow.org/datasets) パッケージ(`tfds`)には、事前定義されたデータセットを`tf.data.Dataset`オブジェクトとして読み込むためのユーティリティが含まれています。 この例として、`tfds`を使用して MNISTdataset を読み込んでみましょう。 ``` datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) mnist_train, mnist_test = datasets['train'], datasets['test'] ``` 次に、トレーニング用のデータを準備します。 - 各画像をリスケールする。 - 例の順序をシャッフルする。 - 画像とラベルのバッチを集める。 ``` BUFFER_SIZE = 10 # Use a much larger value for real code. BATCH_SIZE = 64 NUM_EPOCHS = 5 def scale(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label ``` 例を短く保つために、データセットをトリミングして 5 バッチのみを返すようにします。 ``` train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) test_data = mnist_test.map(scale).batch(BATCH_SIZE) STEPS_PER_EPOCH = 5 train_data = train_data.take(STEPS_PER_EPOCH) test_data = test_data.take(STEPS_PER_EPOCH) image_batch, label_batch = next(iter(train_data)) ``` ### Keras トレーニングループを使用する トレーニングプロセスの低レベル制御が不要な場合は、Keras 組み込みの`fit`、`evaluate`、`predict`メソッドの使用が推奨されます。これらのメソッドは(シーケンシャル、関数型、またはサブクラス化)実装を問わず、モデルをトレーニングするための統一インターフェースを提供します。 これらのメソッドには次のような優位点があります。 - Numpy 配列、Python ジェネレータ、`tf.data.Datasets`を受け取ります。 - 正則化と活性化損失を自動的に適用します。 - [マルチデバイストレーニングのために](distributed_training.ipynb)`tf.distribute`をサポートします。 - 任意の callable は損失とメトリクスとしてサポートします。 - `tf.keras.callbacks.TensorBoard`のようなコールバックとカスタムコールバックをサポートします。 - 自動的に TensorFlow グラフを使用し、高性能です。 ここに`Dataset`を使用したモデルのトレーニング例を示します。(この機能ついての詳細は[チュートリアル](../tutorials)をご覧ください。) ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.02), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(10) ]) # Model is the full model w/o custom layers model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) model.fit(train_data, epochs=NUM_EPOCHS) loss, acc = model.evaluate(test_data) print("Loss {}, Accuracy {}".format(loss, acc)) ``` ### ループを自分で書く Keras モデルのトレーニングステップは動作していても、そのステップの外でより制御が必要な場合は、データ イテレーション ループで`tf.keras.Model.train_on_batch`メソッドの使用を検討してみてください。 `tf.keras.callbacks.Callback`として、多くのものが実装可能であることに留意してください。 このメソッドには前のセクションで言及したメソッドの優位点の多くがありますが、外側のループのユーザー制御も与えます。 `tf.keras.Model.test_on_batch`または`tf.keras.Model.evaluate`を使用して、トレーニング中のパフォーマンスをチェックすることも可能です。 注意: `train_on_batch`と`test_on_batch`は、デフォルトで単一バッチの損失とメトリクスを返します。`reset_metrics=False`を渡すと累積メトリックを返しますが、必ずメトリックアキュムレータを適切にリセットすることを忘れないようにしてくだい。また、`AUC`のような一部のメトリクスは正しく計算するために`reset_metrics=False`が必要なことも覚えておいてください。 上のモデルのトレーニングを続けます。 ``` # Model is the full model w/o custom layers model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) for epoch in range(NUM_EPOCHS): #Reset the metric accumulators model.reset_metrics() for image_batch, label_batch in train_data: result = model.train_on_batch(image_batch, label_batch) metrics_names = model.metrics_names print("train: ", "{}: {:.3f}".format(metrics_names[0], result[0]), "{}: {:.3f}".format(metrics_names[1], result[1])) for image_batch, label_batch in test_data: result = model.test_on_batch(image_batch, label_batch, # return accumulated metrics reset_metrics=False) metrics_names = model.metrics_names print("\neval: ", "{}: {:.3f}".format(metrics_names[0], result[0]), "{}: {:.3f}".format(metrics_names[1], result[1])) ``` <a name="custom_loop"></a> ### トレーニングステップをカスタマイズする より多くの柔軟性と制御を必要とする場合、独自のトレーニングループを実装することでそれが可能になります。以下の 3 つのステップを踏みます。 1. Python ジェネレータか`tf.data.Dataset`をイテレートして例のバッチを作成します。 2. `tf.GradientTape`を使用して勾配を集めます。 3. `tf.keras.optimizers`の 1 つを使用して、モデルの変数に重み更新を適用します。 留意点: - サブクラス化されたレイヤーとモデルの`call`メソッドには、常に`training`引数を含めます。 - `training`引数を確実に正しくセットしてモデルを呼び出します。 - 使用方法によっては、モデルがデータのバッチ上で実行されるまでモデル変数は存在しないかもしれません。 - モデルの正則化損失などを手動で処理する必要があります。 v1 と比べて簡略化されている点に注意してください : - 変数初期化子を実行する必要はありません。作成時に変数は初期化されます。 - たとえ`tf.function`演算が eager モードで振る舞う場合でも、手動の制御依存性を追加する必要はありません。 ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.02), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(10) ]) optimizer = tf.keras.optimizers.Adam(0.001) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) @tf.function def train_step(inputs, labels): with tf.GradientTape() as tape: predictions = model(inputs, training=True) regularization_loss=tf.math.add_n(model.losses) pred_loss=loss_fn(labels, predictions) total_loss=pred_loss + regularization_loss gradients = tape.gradient(total_loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) for epoch in range(NUM_EPOCHS): for inputs, labels in train_data: train_step(inputs, labels) print("Finished epoch", epoch) ``` ### 新しいスタイルのメトリクスと損失 TensorFlow 2.x では、メトリクスと損失はオブジェクトです。Eager で実行的に`tf.function`内で動作します。 損失オブジェクトは呼び出し可能で、(y_true, y_pred) を引数として期待します。 ``` cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True) cce([[1, 0]], [[-1.0,3.0]]).numpy() ``` メトリックオブジェクトには次のメソッドがあります 。 - `Metric.update_state()` — 新しい観測を追加する - `Metric.result()` — 観測値が与えられたとき、メトリックの現在の結果を得る - `Metric.reset_states()` — すべての観測をクリアする オブジェクト自体は呼び出し可能です。呼び出しは`update_state`と同様に新しい観測の状態を更新し、メトリクスの新しい結果を返します。 メトリックの変数を手動で初期化する必要はありません。また、TensorFlow 2.x は自動制御依存性を持つため、それらについても気にする必要はありません。 次のコードは、メトリックを使用してカスタムトレーニングループ内で観測される平均損失を追跡します。 ``` # Create the metrics loss_metric = tf.keras.metrics.Mean(name='train_loss') accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') @tf.function def train_step(inputs, labels): with tf.GradientTape() as tape: predictions = model(inputs, training=True) regularization_loss=tf.math.add_n(model.losses) pred_loss=loss_fn(labels, predictions) total_loss=pred_loss + regularization_loss gradients = tape.gradient(total_loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) # Update the metrics loss_metric.update_state(total_loss) accuracy_metric.update_state(labels, predictions) for epoch in range(NUM_EPOCHS): # Reset the metrics loss_metric.reset_states() accuracy_metric.reset_states() for inputs, labels in train_data: train_step(inputs, labels) # Get the metric results mean_loss=loss_metric.result() mean_accuracy = accuracy_metric.result() print('Epoch: ', epoch) print(' loss: {:.3f}'.format(mean_loss)) print(' accuracy: {:.3f}'.format(mean_accuracy)) ``` <a id="keras_metric_names"></a> ### Keras メトリック名 TensorFlow 2.x では、Keras モデルはメトリクス名の処理に関してより一貫性があります。 メトリクスリストで文字列を渡すと、*まさにその*文字列がメトリクスの`name`として使用されます。これらの名前は<br>`model.fit`によって返される履歴オブジェクトと、`keras.callbacks`に渡されるログに表示されます。これはメトリクスリストで渡した文字列に設定されています。 ``` model.compile( optimizer = tf.keras.optimizers.Adam(0.001), loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")]) history = model.fit(train_data) history.history.keys() ``` これは`metrics=["accuracy"]`を渡すと`dict_keys(['loss', 'acc'])`になっていた、以前のバージョンとは異なります。 ### Keras オプティマイザ `v1.train.AdamOptimizer`や`v1.train.GradientDescentOptimizer`などの`v1.train`内のオプティマイザは、`tf.keras.optimizers`内に同等のものを持ちます。 #### `v1.train`を`keras.optimizers`に変換する オプティマイザを変換する際の注意事項を次に示します。 - オプティマイザをアップグレードすると、[古いチェックポイントとの互換性がなくなる可能性があります](#checkpoints)。 - epsilon のデフォルトはすべて`1e-8`ではなく`1e-7`になりました。(これはほとんどのユースケースで無視できます。) - `v1.train.GradientDescentOptimizer`は`tf.keras.optimizers.SGD`で直接置き換えが可能です。 - `v1.train.MomentumOptimizer`はモメンタム引数(`tf.keras.optimizers.SGD(..., momentum=...)`)を使用して`SGD`オプティマイザで直接置き換えが可能です。 - `v1.train.AdamOptimizer`を変換して`tf.keras.optimizers.Adam`を使用することが可能です。<code>beta1</code>引数と`beta2`引数の名前は、`beta_1`と`beta_2`に変更されています。 - `v1.train.RMSPropOptimizer`は`tf.keras.optimizers.RMSprop`に変換可能です。 `decay`引数の名前は`rho`に変更されています。 - `v1.train.AdadeltaOptimizer`は`tf.keras.optimizers.Adadelta`に直接変換が可能です。 - `tf.train.AdagradOptimizer`は `tf.keras.optimizers.Adagrad`に直接変換が可能です。 - `tf.train.FtrlOptimizer`は`tf.keras.optimizers.Ftrl`に直接変換が可能です。`accum_name`および`linear_name`引数は削除されています。 - `tf.contrib.AdamaxOptimizer`と`tf.contrib.NadamOptimizer`は `tf.keras.optimizers.Adamax`と`tf.keras.optimizers.Nadam`に直接変換が可能です。`beta1`引数と`beta2`引数の名前は、`beta_1`と`beta_2`に変更されています。 #### 一部の`tf.keras.optimizers`の新しいデフォルト <a id="keras_optimizer_lr"></a> 警告: モデルの収束挙動に変化が見られる場合には、デフォルトの学習率を確認してください。 `optimizers.SGD`、`optimizers.Adam`、または`optimizers.RMSprop`に変更はありません。 次のデフォルトの学習率が変更されました。 - `optimizers.Adagrad` 0.01 から 0.001 へ - `optimizers.Adadelta` 1.0 から 0.001 へ - `optimizers.Adamax` 0.002 から 0.001 へ - `optimizers.Nadam` 0.002 から 0.001 へ ### TensorBoard TensorFlow 2 には、TensorBoard で視覚化するための要約データを記述するために使用される`tf.summary` API の大幅な変更が含まれています。新しい`tf.summary`の概要については、TensorFlow 2 API を使用した[複数のチュートリアル](https://www.tensorflow.org/tensorboard/get_started)があります。これには、[TensorBoard TensorFlow 2 移行ガイド](https://www.tensorflow.org/tensorboard/migrate)も含まれています。 ## 保存と読み込み <a id="checkpoints"></a> ### チェックポイントの互換性 TensorFlow 2.x は[オブジェクトベースのチェックポイント](checkpoint.ipynb)を使用します。 古いスタイルの名前ベースのチェックポイントは、注意を払えば依然として読み込むことができます。コード変換プロセスは変数名変更という結果になるかもしれませんが、回避方法はあります。 最も単純なアプローチは、チェックポイント内の名前と新しいモデルの名前を揃えて並べることです。 - 変数にはすべて依然として設定が可能な`name`引数があります。 - Keras モデルはまた `name`引数を取り、それらの変数のためのプレフィックスとして設定されます。 - `v1.name_scope`関数は、変数名のプレフィックスの設定に使用できます。これは`tf.variable_scope`とは大きく異なります。これは名前だけに影響するもので、変数と再利用の追跡はしません。 ご利用のユースケースで動作しない場合は、`v1.train.init_from_checkpoint`を試してみてください。これは`assignment_map`引数を取り、古い名前から新しい名前へのマッピングを指定します。 注意 : [読み込みを遅延](checkpoint.ipynb#loading_mechanics)できるオブジェクトベースのチェックポイントとは異なり、名前ベースのチェックポイントは関数が呼び出される時に全ての変数が構築されていることを要求します。一部のモデルは、`build`を呼び出すかデータのバッチでモデルを実行するまで変数の構築を遅延します。 [TensorFlow Estimatorリポジトリ](https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py)には事前作成された Estimator のチェックポイントを TensorFlow 1.X から 2.0 にアップグレードするための[変換ツール](#checkpoint_converter)が含まれています。これは、同様のユースケースのツールを構築する方法の例として有用な場合があります。 ### 保存されたモデルの互換性 保存されたモデルには、互換性に関する重要な考慮事項はありません。 - TensorFlow 1.x saved_models は TensorFlow 2.x で動作します。 - TensorFlow 2.x saved_models は全ての演算がサポートされていれば TensorFlow 1.x で動作します。 ### Graph.pb または Graph.pbtxt 未加工の`Graph.pb`ファイルを TensorFlow 2.x にアップグレードする簡単な方法はありません。確実な方法は、ファイルを生成したコードをアップグレードすることです。 ただし、「凍結グラフ」(変数が定数に変換された`tf.Graph`)がある場合、`v1.wrap_function`を使用して[`concrete_function`](https://tensorflow.org/guide/concrete_function)への変換が可能です。 ``` def wrap_frozen_graph(graph_def, inputs, outputs): def _imports_graph_def(): tf.compat.v1.import_graph_def(graph_def, name="") wrapped_import = tf.compat.v1.wrap_function(_imports_graph_def, []) import_graph = wrapped_import.graph return wrapped_import.prune( tf.nest.map_structure(import_graph.as_graph_element, inputs), tf.nest.map_structure(import_graph.as_graph_element, outputs)) ``` たとえば、次のような凍結された Inception v1 グラフ(2016 年)があります。 ``` path = tf.keras.utils.get_file( 'inception_v1_2016_08_28_frozen.pb', 'http://storage.googleapis.com/download.tensorflow.org/models/inception_v1_2016_08_28_frozen.pb.tar.gz', untar=True) ``` `tf.GraphDef`を読み込みます。 ``` graph_def = tf.compat.v1.GraphDef() loaded = graph_def.ParseFromString(open(path,'rb').read()) ``` これを`concrete_function`にラップします。 ``` inception_func = wrap_frozen_graph( graph_def, inputs='input:0', outputs='InceptionV1/InceptionV1/Mixed_3b/Branch_1/Conv2d_0a_1x1/Relu:0') ``` 入力としてテンソルを渡します。 ``` input_img = tf.ones([1,224,224,3], dtype=tf.float32) inception_func(input_img).shape ``` ## Estimator ### Estimator でトレーニングする Estimator は TensorFlow 2.0 でサポートされています。 Estimator を使用する際には、TensorFlow 1.x. からの`input_fn()`、`tf.estimator.TrainSpec`、`tf.estimator.EvalSpec`を使用できます。 ここに train と evaluate specs を伴う `input_fn` を使用する例があります。 #### input_fn と train/eval specs を作成する ``` # Define the estimator's input_fn def input_fn(): datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) mnist_train, mnist_test = datasets['train'], datasets['test'] BUFFER_SIZE = 10000 BATCH_SIZE = 64 def scale(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label[..., tf.newaxis] train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) return train_data.repeat() # Define train &amp; eval specs train_spec = tf.estimator.TrainSpec(input_fn=input_fn, max_steps=STEPS_PER_EPOCH * NUM_EPOCHS) eval_spec = tf.estimator.EvalSpec(input_fn=input_fn, steps=STEPS_PER_EPOCH) ``` ### Keras モデル定義を使用する TensorFlow 2.x で Estimator を構築する方法には、いくつかの違いがあります。 モデルは Keras を使用して定義することを推奨します。次に`tf.keras.estimator.model_to_estimator`ユーティリティを使用して、モデルを Estimator に変更します。次のコードは Estimator を作成してトレーニングする際に、このユーティリティをどのように使用するかを示します。 ``` def make_model(): return tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.02), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(10) ]) model = make_model() model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) estimator = tf.keras.estimator.model_to_estimator( keras_model = model ) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ``` 注意 : Keras で重み付きメトリクスを作成し、`model_to_estimator`を使用してそれらを Estimator API で重み付きメトリクスを変換することはサポートされません。それらのメトリクスは、`add_metrics`関数を使用して Estimator 仕様で直接作成する必要があります。 ### カスタム `model_fn` を使用する 保守する必要がある既存のカスタム Estimator `model_fn` を持つ場合には、`model_fn`を変換して Keras モデルを使用できるようにすることが可能です。 しかしながら、互換性の理由から、カスタム`model_fn`は依然として1.x スタイルのグラフモードで動作します。これは eager execution はなく自動制御依存性もないことも意味します。 注意: 長期的には、特にカスタムの `model_fn` を使って、`tf.estimator` から移行することを計画する必要があります。代替の API は `tf.keras` と `tf.distribute` です。トレーニングの一部に `Estimator` を使用する必要がある場合は、`tf.keras.estimator.model_to_estimator` コンバータを使用して `keras.Model` から <code>Estimator</code> を作成する必要があります。 <a name="minimal_changes"></a> #### 最小限の変更で model_fn をカスタマイズする TensorFlow 2.0 でカスタム`model_fn`を動作させるには、既存のコードの変更を最小限に留めたい場合、`optimizers`や`metrics`などの`tf.compat.v1`シンボルを使用することができます。 カスタム`model_fn`で Keras モデルを使用することは、それをカスタムトレーニングループで使用することに類似しています。 - `mode`引数を基に、`training`段階を適切に設定します。 - モデルの`trainable_variables`をオプティマイザに明示的に渡します。 しかし、[カスタムループ](#custom_loop)と比較して、重要な違いがあります。 - `Model.losses`を使用する代わりに`Model.get_losses_for`を使用して損失を抽出します。 - `Model.get_updates_for`を使用してモデルの更新を抽出します。 注意 : 「更新」は各バッチの後にモデルに適用される必要がある変更です。例えば、`layers.BatchNormalization`レイヤーの平均と分散の移動平均などです。 次のコードはカスタム`model_fn`から Estimator を作成し、これらの懸念事項をすべて示しています。 ``` def my_model_fn(features, labels, mode): model = make_model() optimizer = tf.compat.v1.train.AdamOptimizer() loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) training = (mode == tf.estimator.ModeKeys.TRAIN) predictions = model(features, training=training) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) reg_losses = model.get_losses_for(None) + model.get_losses_for(features) total_loss=loss_fn(labels, predictions) + tf.math.add_n(reg_losses) accuracy = tf.compat.v1.metrics.accuracy(labels=labels, predictions=tf.math.argmax(predictions, axis=1), name='acc_op') update_ops = model.get_updates_for(None) + model.get_updates_for(features) minimize_op = optimizer.minimize( total_loss, var_list=model.trainable_variables, global_step=tf.compat.v1.train.get_or_create_global_step()) train_op = tf.group(minimize_op, update_ops) return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=total_loss, train_op=train_op, eval_metric_ops={'accuracy': accuracy}) # Create the Estimator &amp; Train estimator = tf.estimator.Estimator(model_fn=my_model_fn) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ``` #### TensorFlow 2.x シンボルで`model_fn`をカスタマイズする TensorFlow 1.x シンボルをすべて削除し、カスタム`model_fn` をネイティブの TensorFlow 2.x にアップグレードする場合は、オプティマイザとメトリクスを`tf.keras.optimizers`と`tf.keras.metrics`にアップグレードする必要があります。 カスタム`model_fn`では、上記の[変更](#minimal_changes)に加えて、さらにアップグレードを行う必要があります。 - `v1.train.Optimizer` の代わりに `tf.keras.optimizers` を使用します。 - 損失が呼び出し可能(関数など)な場合は、`Optimizer.minimize()`を使用して`train_op/minimize_op`を取得します。 - `train_op/minimize_op`を計算するには、 - 損失がスカラー損失`Tensor`(呼び出し不可)の場合は、`Optimizer.get_updates()`を使用します。返されるリストの最初の要素は目的とする`train_op/minimize_op`です。 - 損失が呼び出し可能(関数など)な場合は、`Optimizer.minimize()`を使用して`train_op/minimize_op`を取得します。 - 評価には`tf.compat.v1.metrics`の代わりに[`tf.keras.metrics`](https://www.tensorflow.org/api_docs/python/tf/keras/metrics)を使用します。 上記の`my_model_fn`の例では、2.0 シンボルの移行されたコードは次のように表示されます。 ``` def my_model_fn(features, labels, mode): model = make_model() training = (mode == tf.estimator.ModeKeys.TRAIN) loss_obj = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) predictions = model(features, training=training) # Get both the unconditional losses (the None part) # and the input-conditional losses (the features part). reg_losses = model.get_losses_for(None) + model.get_losses_for(features) total_loss=loss_obj(labels, predictions) + tf.math.add_n(reg_losses) # Upgrade to tf.keras.metrics. accuracy_obj = tf.keras.metrics.Accuracy(name='acc_obj') accuracy = accuracy_obj.update_state( y_true=labels, y_pred=tf.math.argmax(predictions, axis=1)) train_op = None if training: # Upgrade to tf.keras.optimizers. optimizer = tf.keras.optimizers.Adam() # Manually assign tf.compat.v1.global_step variable to optimizer.iterations # to make tf.compat.v1.train.global_step increased correctly. # This assignment is a must for any `tf.train.SessionRunHook` specified in # estimator, as SessionRunHooks rely on global step. optimizer.iterations = tf.compat.v1.train.get_or_create_global_step() # Get both the unconditional updates (the None part) # and the input-conditional updates (the features part). update_ops = model.get_updates_for(None) + model.get_updates_for(features) # Compute the minimize_op. minimize_op = optimizer.get_updates( total_loss, model.trainable_variables)[0] train_op = tf.group(minimize_op, *update_ops) return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=total_loss, train_op=train_op, eval_metric_ops={'Accuracy': accuracy_obj}) # Create the Estimator &amp; Train. estimator = tf.estimator.Estimator(model_fn=my_model_fn) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) ``` ### 事前作成された Estimator `tf.estimator.DNN*`、`tf.estimator.Linear*`、 `tf.estimator.DNNLinearCombined*`のファミリーに含まれる[事前作成された Estimator](https://www.tensorflow.org/guide/premade_estimators) は、依然として TensorFlow 2.0 API でもサポートされていますが、一部の引数が変更されています。 1. `input_layer_partitioner`: v2 で削除されました。 2. `loss_reduction`: `tf.compat.v1.losses.Reduction`の代わりに`tf.keras.losses.Reduction`に更新されました。デフォルト値も`tf.compat.v1.losses.Reduction.SUM`から`tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE`に変更されています。 3. `optimizer`、`dnn_optimizer`、`linear_optimizer`: これらの引数は`tf.compat.v1.train.Optimizer`の代わりに`tf.keras.optimizers`に更新されています。 上記の変更を移行するには : 1. TensorFlow 2.x では[`配布戦略`](https://www.tensorflow.org/guide/distributed_training)が自動的に処理するため、`input_layer_partitioner`の移行は必要ありません。 2. `loss_reduction`については[`tf.keras.losses.Reduction`](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/losses/Reduction)でサポートされるオプションを確認してください。 3. `optimizer` 引数の場合: - 1) `optimizer`、`dnn_optimizer`、または `linear_optimizer` 引数を渡さない場合、または 2) `optimizer` 引数を `string` としてコードに指定しない場合、デフォルトで `tf.keras.optimizers` が使用されるため、何も変更する必要はありません。 - `optimizer`引数については、`optimizer`、`dnn_optimizer`、`linear_optimizer`引数を渡さない場合、または`optimizer`引数をコード内の内の`string`として指定する場合は、何も変更する必要はありません。デフォルトで`tf.keras.optimizers`を使用します。それ以外の場合は、`tf.compat.v1.train.Optimizer`から対応する[`tf.keras.optimizers`](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/optimizers)に更新する必要があります。 #### チェックポイントコンバータ <a id="checkpoint_converter"></a> `tf.keras.optimizers`は異なる変数セットを生成してチェックポイントに保存するするため、`keras.optimizers`への移行は TensorFlow 1.x を使用して保存されたチェックポイントを壊してしまいます。TensorFlow 2.x への移行後に古いチェックポイントを再利用できるようにするには、[チェックポイントコンバータツール](https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py)をお試しください。 ``` ! curl -O https://raw.githubusercontent.com/tensorflow/estimator/master/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py ``` ツールにはヘルプが組み込まれています。 ``` ! python checkpoint_converter.py -h ``` <a id="tensorshape"></a> ## TensorShape このクラスは`tf.compat.v1.Dimension`オブジェクトの代わりに`int`を保持することにより単純化されました。従って、`.value()`を呼び出して`int`を取得する必要はありません。 個々の`tf.compat.v1.Dimension`オブジェクトは依然として`tf.TensorShape.dims`からアクセス可能です。 以下に TensorFlow 1.x と TensorFlow 2.x 間の違いを示します。 ``` # Create a shape and choose an index i = 0 shape = tf.TensorShape([16, None, 256]) shape ``` TensorFlow 1.x で次を使っていた場合: ```python value = shape[i].value ``` Then do this in TensorFlow 2.x: ``` value = shape[i] value ``` TensorFlow 1.x で次を使っていた場合: ```python for dim in shape: value = dim.value print(value) ``` TensorFlow 2.0 では次のようにします: ``` for value in shape: print(value) ``` TensorFlow 1.x で次を使っていた場合(またはその他の次元のメソッドを使用していた場合): ```python dim = shape[i] dim.assert_is_compatible_with(other_dim) ``` TensorFlow 2.0 では次のようにします: ``` other_dim = 16 Dimension = tf.compat.v1.Dimension if shape.rank is None: dim = Dimension(None) else: dim = shape.dims[i] dim.is_compatible_with(other_dim) # or any other dimension method shape = tf.TensorShape(None) if shape: dim = shape.dims[i] dim.is_compatible_with(other_dim) # or any other dimension method ``` `tf.TensorShape` のブール型の値は、階数がわかっている場合は `True`で、そうでない場合は`False`です。 ``` print(bool(tf.TensorShape([]))) # Scalar print(bool(tf.TensorShape([0]))) # 0-length vector print(bool(tf.TensorShape([1]))) # 1-length vector print(bool(tf.TensorShape([None]))) # Unknown-length vector print(bool(tf.TensorShape([1, 10, 100]))) # 3D tensor print(bool(tf.TensorShape([None, None, None]))) # 3D tensor with no known dimensions print() print(bool(tf.TensorShape(None))) # A tensor with unknown rank. ``` ## その他の変更点 - `tf.colocate_with`を削除する : TensorFlow のデバイス配置アルゴリズムが大幅に改善されたため、これはもう必要ありません。削除したことによってパフォーマンスが低下する場合には、[バグを報告してください](https://github.com/tensorflow/tensorflow/issues)。 - `v1.ConfigProto`の使用を`tf.config`の同等の関数に置き換える。 ## まとめ 全体のプロセスは次のとおりです。 1. アップグレードスクリプトを実行する。 2. contrib シンボルを除去する。 3. モデルをオブジェクト指向スタイル (Keras) に切り替える。 4. 可能なところでは `tf.keras`または`tf.estimator`トレーニングと評価ループを使用する。 5. そうでない場合はカスタムループを使用してよいが、セッションとコレクションを回避すること。 コードを慣用的な TensorFlow 2.0 に変換するには少し作業を要しますが、変更するごとに次のような結果が得られます。 - コード行が減少する。 - 明瞭さと簡略性が向上する。 - デバッグが容易になる。
github_jupyter
# First Machine Learning Project ## Automate the Data Fetching ``` import os from zipfile import ZipFile def extract_data(name_of_zip="cars", ROOT='C:/Users/VTSB/Desktop/CS Resources/AI Hands-On ML/datasets', extension=".csv.zip", reset_path="C:/Users/VTSB/Desktop/CS Resources/AI Hands-On ML"): os.chdir("C:/Users/VTSB/Downloads") print(os.getcwd()) with ZipFile(name_of_zip + extension, 'r') as zipObj: zipObj.extractall(os.path.join(ROOT, name_of_zip)) os.chdir(reset_path) print(os.getcwd()) extract_data() import pandas as pd def load_data(ROOT='C:/Users/VTSB/Desktop/CS Resources/AI Hands-On ML/datasets', extension=".csv", name_of_zip="cars"): csv_path = ROOT + "/" + name_of_zip + "/" + name_of_zip + extension print(csv_path) return pd.read_csv(csv_path) original_df = load_data() original_df original_df = original_df.drop(columns="model_name") original_df["engine_fuel"].value_counts() original_df["engine_fuel"] = original_df["engine_fuel"].replace(["hybrid-diesel", "electric"], "gasoline") original_df["engine_fuel"].value_counts() ``` ## Preview the Data ``` original_df.head() original_df.info() # engine_capacity has a few nulls (10) # bool(13) # float64(2) # int64(5) # object(10) original_df.columns original_df.describe() original_df.shape for x in original_df.columns: if original_df[x].dtype == "O": print(x + ": ", original_df[x].value_counts().count()) # counter = 0 # for x in original_df["model_name"].value_counts(): # if x < 100: # counter += 1 # print(str(counter) + "\n") # number of model_names that have a frequency of less than 100 # print(original_df["model_name"].value_counts().sort_values(ascending=True)) import matplotlib.pyplot as plt %matplotlib inline def listing_numerical_columns(): list_of_numerical_columns = [] for x in original_df.columns: if original_df[x].dtype == "int64" or original_df[x].dtype == "float64": list_of_numerical_columns.append(x) print(list_of_numerical_columns) listing_numerical_columns() def preview_graphs(numerical_column_name): if original_df[numerical_column_name].dtype == "int64" or original_df[numerical_column_name].dtype == "float64": original_df[numerical_column_name].hist(bins=50) plt.title(numerical_column_name) preview_graphs("odometer_value") ``` ## Create Test Data ``` from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(test_size=0.2, n_splits=1, random_state=42) for train_index, test_index in split.split(original_df, original_df["manufacturer_name"]): strat_train_set = original_df.loc[train_index] strat_test_set = original_df.loc[test_index] strat_train_set # check how evenly distributed the stratification was strat_ratio = strat_train_set["manufacturer_name"].value_counts() / len(strat_train_set) print(strat_ratio) strat_test_set.info() strat_train_set.info() strat_train_set_features = strat_train_set.drop("price_usd", axis=1) strat_train_set_labels = strat_train_set["price_usd"].copy() strat_train_set_features strat_train_set_labels ``` ## EDA ``` strat_train_set_EDA = strat_train_set.copy() corr_matrix = strat_train_set_EDA.corr() corr_matrix["price_usd"].sort_values(ascending=False) ``` ## Data Cleaning And Combinations ``` from sklearn.pipeline import Pipeline from sklearn.base import TransformerMixin, BaseEstimator from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.impute import SimpleImputer from sklearn.compose import ColumnTransformer strat_train_set_features empty_list = [] for x in strat_train_set_features.columns: if strat_train_set_features[x].dtype == "float64" or strat_train_set_features[x].dtype == "int64": empty_list.append(x) print(empty_list) a = strat_train_set_features[empty_list] a 2019 - a.iloc[:,1] imputer = SimpleImputer(strategy="median") b = imputer.fit_transform(a) # print(imputer.statistics_) print(len(b), len(b[0])) print(b) print(b[:, 1]) ``` ### Custom Transformer ``` class CombinedAttributesAdder(BaseEstimator, TransformerMixin): def __init__(self): pass def fit(self, X, y=None): return self def transform(self, X): return X s = CombinedAttributesAdder() c = s.fit_transform(b) print(c) scaler = StandardScaler() scaler.fit_transform(a) ``` ### Numeric Pipeline ``` num_pipeline = Pipeline([ ("imputer", SimpleImputer(strategy="median")), ("attribs_adder", CombinedAttributesAdder()), ("standard_scaler", StandardScaler()) ]) num_pipeline.fit_transform(a) ``` ### Full Pipeline ``` num_attribs, cat_attribs = [], [] for x in strat_train_set_features.columns: if strat_train_set_features[x].dtype == "float64" or strat_train_set_features[x].dtype == "int64": num_attribs.append(x) if strat_train_set_features[x].dtype == "object" or strat_train_set_features[x].dtype == "bool": cat_attribs.append(x) print(num_attribs) print(cat_attribs) full_pipeline = ColumnTransformer([ ("num", num_pipeline, num_attribs), ("cat", OneHotEncoder(), cat_attribs) ]) strat_train_set_features_prepared = full_pipeline.fit_transform(strat_train_set_features) for x in strat_train_set_features.columns: print(x, strat_train_set_features[x].value_counts().count()) 55 + 2 + 12 + 6 + 2 + 3 + 12 + 2 + 3 + 3 + 2 + 6 + 20 + 6 strat_train_set_features["engine_fuel"].value_counts() len(strat_train_set_features_prepared.toarray()[0]) strat_train_set_features_prepared.toarray() ``` ## Create and Train the Models ``` from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(strat_train_set_features_prepared, strat_train_set_labels) some_data = strat_train_set_features[:5] print(some_data) some_data_prepared = full_pipeline.transform(some_data) some_labels = strat_train_set_labels[:5] print(some_labels) lin_reg.predict(some_data_prepared) from sklearn.tree import DecisionTreeRegressor decision_tree_reg = DecisionTreeRegressor() decision_tree_reg.fit(strat_train_set_features_prepared, strat_train_set_labels) print(some_labels) decision_tree_reg.predict(some_data_prepared) from sklearn.ensemble import RandomForestRegressor random_forest_reg = RandomForestRegressor(verbose=2, n_jobs=-1) random_forest_reg.fit(strat_train_set_features_prepared, strat_train_set_labels) len(strat_train_set_features_prepared.toarray()[0]) print(some_labels) random_forest_reg.predict(some_data_prepared) ``` ## Evaluate the Model ``` from sklearn.metrics import mean_squared_error import numpy as np lin_reg_all_predictions = lin_reg.predict(strat_train_set_features_prepared) lin_reg_mse = mean_squared_error(strat_train_set_labels, lin_reg_all_predictions) lin_reg_rmse = np.sqrt(lin_reg_mse) print("lin_reg_rmse: ", lin_reg_rmse) print(lin_reg_rmse/original_df["price_usd"].mean()) decision_tree_reg_all_predictions = decision_tree_reg.predict(strat_train_set_features_prepared) decision_tree_reg_mse = mean_squared_error(strat_train_set_labels, decision_tree_reg_all_predictions) decision_tree_reg_rmse = np.sqrt(decision_tree_reg_mse) print("decision_tree_reg_rmse: ", decision_tree_reg_rmse) print(decision_tree_reg_rmse/original_df["price_usd"].mean()) random_forest_reg_all_predictions = random_forest_reg.predict(strat_train_set_features_prepared) random_forest_reg_mse = mean_squared_error(strat_train_set_labels, random_forest_reg_all_predictions) random_forest_reg_rmse = np.sqrt(random_forest_reg_mse) print("random_forest_reg_rmse: ", random_forest_reg_rmse) print(random_forest_reg_rmse/original_df["price_usd"].mean()) ``` ### Cross Validation for Better Evaluations ``` from sklearn.model_selection import cross_val_score def display_scores(scores): print("Scores: ", scores) print("Mean: ", scores.mean()) print("Standard Deviation: ", scores.std()) lin_reg_scores = cross_val_score(lin_reg, strat_train_set_features_prepared, strat_train_set_labels, scoring="neg_mean_squared_error", cv=10) lin_reg_rmse_scores = np.sqrt(-lin_reg_scores) display_scores(lin_reg_rmse_scores) decision_tree_reg_scores = cross_val_score(decision_tree_reg, strat_train_set_features_prepared, strat_train_set_labels, scoring="neg_mean_squared_error", cv=10, verbose=2) decision_tree_reg_rmse_scores = np.sqrt(-decision_tree_reg_scores) display_scores(decision_tree_reg_rmse_scores) random_forest_reg_scores = cross_val_score(random_forest_reg, strat_train_set_features_prepared, strat_train_set_labels, scoring="neg_mean_squared_error", cv=10, verbose=2) random_forest_reg_rmse_scores = np.sqrt(-random_forest_reg_scores) display_scores(random_forest_reg_rmse_scores) ``` ## Fine Tuning ``` from sklearn.model_selection import RandomizedSearchCV param_grid = [ {"n_estimators": [3, 10, 30, 60], "max_features": [2, 4, 6, 8]}, {"bootstrap": [False], "n_estimators": [3, 10], "max_features": [2, 3, 4]} ] rnd_search_cv = RandomizedSearchCV(random_forest_reg, param_grid, cv=5, n_jobs=-1, scoring="neg_mean_squared_error", return_train_score=True, verbose=2) rnd_search_cv.fit(strat_train_set_features_prepared, strat_train_set_labels) rnd_search_cv.best_params_ rnd_search_cv.best_estimator_ cvres = rnd_search_cv.cv_results_ cvres for mean_test_scores, params in zip(cvres["mean_test_score"], cvres["params"]): print(np.sqrt(-mean_test_scores), params) feature_importances = rnd_search_cv.best_estimator_.feature_importances_ print(len(feature_importances)) cat_encoder = full_pipeline.named_transformers_["cat"] counter = 0 for x in cat_encoder.categories_: for y in x: counter += 1 print(counter) cat_encoder.categories_ feature_importances cat_encoder = full_pipeline.named_transformers_["cat"] cat_encoder_categories = cat_encoder.categories_ cat_attribs = [] for x in cat_encoder_categories: for y in x: cat_attribs.append(y) attributes = num_attribs + cat_attribs sorted(zip(feature_importances, attributes), reverse=True) cat_encoder_categories ``` ## Evaluate on Test Set ``` final_model = rnd_search_cv.best_estimator_ strat_test_set_features = strat_test_set.drop(columns="price_usd") strat_test_set_labels = strat_test_set["price_usd"].copy() strat_test_set_features_prepared = full_pipeline.transform(strat_test_set_features) final_predictions = final_model.predict(strat_test_set_features_prepared) final_mse = mean_squared_error(strat_test_set_labels, final_predictions) final_rmse = np.sqrt(final_mse) print(final_rmse) len(strat_test_set_features_prepared.toarray()[0]) for x in strat_test_set_features.columns: print(x, strat_test_set_features[x].value_counts().count()) 55 + 2 + 12 + 5 + 2 + 3 + 12 + 2 + 3 + 3 + 2 + 6 + 20 + 6 55 + 2 + 12 + 6 + 2 + 3 + 12 + 2 + 3 + 3 + 2 + 6 + 20 + 6 strat_test_set_features strat_train_set_features["engine_fuel"].value_counts() strat_test_set_features["engine_fuel"].value_counts() ``` ## Additional Fine Tuning #### Loading and Stratifying Data ``` original_df_copy = load_data() from sklearn.model_selection import StratifiedShuffleSplit split_copy = StratifiedShuffleSplit(test_size=0.2, n_splits=1, random_state=42) for train_index, test_index in split_copy.split(original_df_copy, original_df_copy["manufacturer_name"]): strat_train_set_copy = original_df_copy.loc[train_index] strat_test_set_copy = original_df_copy.loc[test_index] strat_train_set_copy strat_train_set_copy_features = strat_train_set_copy.drop(columns="price_usd") strat_train_set_copy_labels = strat_train_set_copy["price_usd"].copy() ``` #### Custom Boolean Transformer ``` bool_attribs_list = [] for x in strat_train_set_copy_features.columns: if strat_train_set_copy_features[x].dtype == "bool": bool_attribs_list.append(x) print(len(bool_attribs_list)) print(bool_attribs_list) # X["engine_fuel"] = X["engine_fuel"].replace(["hybrid-diesel", "electric"], "gasoline") class BooleanTransformer(BaseEstimator, TransformerMixin): def __init__(self): pass def fit(self, X, y=None): return self def transform(self, X): X_copy = X.copy() for attribute in X_copy.columns: if X_copy[attribute].dtype == "bool": X_copy[attribute] = X_copy[attribute].replace([True, False], [1, 0]) return X_copy bool_transformer = BooleanTransformer() stscf_bool_transformed = bool_transformer.fit_transform(strat_train_set_copy_features) stscf_bool_transformed stscf_bool_transformed.dtypes.value_counts() ``` #### Custom Categorical Transformer ``` # original_df["engine_fuel"] = original_df["engine_fuel"].replace(["hybrid-diesel", "electric"], "gasoline") # original_df = original_df.drop(columns="model_name") class CategoricalTransformer(BaseEstimator, TransformerMixin): def __init__(self, drop_model_name=True): self.drop_model_name = drop_model_name def fit(self, X, y=None): return self def transform(self, X): X_copy = X.copy() if self.drop_model_name: X_copy = X_copy.drop(columns="model_name") X_copy["engine_fuel"] = X_copy["engine_fuel"].replace(["hybrid-diesel", "electric"], "gasoline") return X_copy categorical_transformer = CategoricalTransformer() stscf_bool_transformed_cat_transformed = categorical_transformer.fit_transform(stscf_bool_transformed) stscf_bool_transformed_cat_transformed ``` #### Numerical Pipeline ``` num_pipeline_copy = Pipeline([ ("imputer", SimpleImputer(strategy="median")), ("attribs_adder", CombinedAttributesAdder()), ("standard_scaler", StandardScaler()) ]) ``` #### Full Pipeline ``` num_attribs_copy, cat_attribs_copy = [], [] for x in stscf_bool_transformed_cat_transformed.columns: if stscf_bool_transformed_cat_transformed[x].dtype == "float64" or stscf_bool_transformed_cat_transformed[x].dtype == "int64": num_attribs_copy.append(x) if stscf_bool_transformed_cat_transformed[x].dtype == "object": cat_attribs_copy.append(x) print(num_attribs_copy) print(len(num_attribs_copy)) print(cat_attribs_copy) print(len(cat_attribs_copy)) full_pipeline_1 = ColumnTransformer([ ("num_pipeline", num_pipeline_copy, num_attribs_copy), ("1hot_encoded", OneHotEncoder(), cat_attribs_copy) ]) fp1_stscf_bool_cat_transformed = full_pipeline_1.fit_transform(stscf_bool_transformed_cat_transformed) type(fp1_stscf_bool_cat_transformed) ``` #### Full and Modified Pipeline ``` strat_train_set_copy_features_COPY = strat_train_set_copy_features.copy() full_and_modified_pipeline = Pipeline([ ("bool_tfm", BooleanTransformer()), ("cat_transformer", CategoricalTransformer()), ("full_pipeline", full_pipeline_1), # ("feature_selection", TopFeatureSelector(feature_importances, k)) ]) fmp_prepared = full_and_modified_pipeline.fit_transform(strat_train_set_copy_features_COPY) fmp_prepared ``` #### Getting Feature Importances ``` from sklearn.model_selection import RandomizedSearchCV from sklearn.ensemble import RandomForestRegressor param_grid1 = [ {"n_estimators": [3, 10, 30, 60, 90, 120, 140, 160, 180, 200], "max_features": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]}, {"bootstrap": [False], "n_estimators": [3, 10, 30, 60, 90, 120, 140, 160, 180, 200], "max_features": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]} ] rand_forest_reg = RandomForestRegressor() rnd_search_cv1 = RandomizedSearchCV(rand_forest_reg, param_grid1, cv=5, n_jobs=-1, scoring="neg_mean_squared_error", return_train_score=True, verbose=2) rnd_search_cv1.fit(fmp_prepared, strat_train_set_copy_labels) print("The best parameters:", rnd_search_cv1.best_params_) print("The best estimator:", rnd_search_cv1.best_estimator_) print("The most important features on the best estimator:", \ rnd_search_cv1.best_estimator_.feature_importances_) cvres1 = rnd_search_cv1.cv_results_ for mean_test_scores, params in zip(cvres1["mean_test_score"], cvres1["params"]): print(np.sqrt(-mean_test_scores), params) fmp_prepared.toarray()[0] i = full_and_modified_pipeline.named_steps["full_pipeline"] # named_steps for Pipeline h = i.named_transformers_["1hot_encoded"] # named_transformers_ for ColumnTransformer h.categories_ be_feature_importances = rnd_search_cv1.best_estimator_.feature_importances_ print(len(be_feature_importances)) categorical_array_values_list = [] for array_of_categorical_values in h.categories_: for categorical_array_value in array_of_categorical_values: categorical_array_values_list.append(categorical_array_value) attributes = num_attribs_copy + categorical_array_values_list sorted_feature_importances = sorted(zip(be_feature_importances, attributes), reverse=True) sorted_feature_importances ``` #### Feature Selection ``` # k = 5 top_features_list = [] for x in sorted_feature_importances[:5]: top_features_list.append(x[1]) print(top_features_list) index_of_top_features = [] print(attributes) for x in top_features_list: index_of_top_features.append(attributes.index(x)) print(sorted(index_of_top_features)) def indices_of_top_k(sorted_feature_importances, k): top_features_list, index_of_top_features = [], [] for x in sorted_feature_importances[:k]: top_features_list.append(x[1]) for x in top_features_list: index_of_top_features.append(attributes.index(x)) return sorted(index_of_top_features) # return np.sort(np.argpartition(np.array(arr), -k)[-k:]) class FeatureSelection(BaseEstimator, TransformerMixin): def __init__(self, sorted_feature_importances, k): self.sorted_feature_importances = sorted_feature_importances self.k = k def fit(self, X, y=None): self.feature_indices_ = indices_of_top_k(self.sorted_feature_importances, self.k) # don't compute feature_importances_ here because it will drastically slow down # all calls to this fit() instance method return self def transform(self, X): X_copy = X.copy() if self.k > len(attributes): return X_copy elif self.k < len(attributes): return X_copy else: return X_copy[:, self.feature_indices_] y = FeatureSelection(sorted_feature_importances, 5) u = y.fit_transform(fp1_stscf_bool_cat_transformed) u # 143778; 30824x5 fp1_stscf_bool_cat_transformed # 863072; 30824x119 ``` #### Full Modified Pipeline With Feature Selection and Model Training ``` k = 30 fmp_selection_and_model_pipeline = Pipeline([ ("fmp", full_and_modified_pipeline), ("feature_selection", FeatureSelection(sorted_feature_importances, k)), ("random_forest_reg_final", RandomForestRegressor(**rnd_search_cv1.best_params_)) ]) fmp_selection_and_model_pipeline.fit(strat_train_set_copy_features, strat_train_set_copy_labels) strat_test_set_copy_features = strat_test_set_copy.drop(columns="price_usd") strat_test_set_copy_labels = strat_test_set_copy["price_usd"].copy() fmp_final_predictions = fmp_selection_and_model_pipeline.predict(strat_test_set_copy_features) fmp_mse = mean_squared_error(strat_test_set_copy_labels, fmp_final_predictions) fmp_rmse = np.sqrt(fmp_mse) fmp_rmse ``` #### Fine Tuning Preparation Methods ``` from sklearn.model_selection import GridSearchCV param_grid_pspp = [{ 'fmp__full_pipeline__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'], 'feature_selection__k': list(range(28, 32 + 1)) }] grid_search_pspp = GridSearchCV(fmp_selection_and_model_pipeline, param_grid_pspp, cv=5, scoring='neg_mean_squared_error', verbose=2, n_jobs=-1) grid_search_pspp.fit(strat_train_set_copy_features, strat_train_set_copy_labels) grid_search_pspp.best_params_ ```
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.neighbors import kneighbors_graph, radius_neighbors_graph from sklearn.metrics import pairwise_distances as all_dist import networkx as nx def GeoDist(data, method='K', param=4): n = data.shape[0] if method == 'K': edges = kneighbors_graph(data, param, mode='distance').toarray() elif method == 'e': edges = radius_neighbors_graph(data, param, mode='distance').toarray() edges[edges==0] = np.inf np.fill_diagonal(edges,0) G = nx.Graph() for i in range(n): for j in range(i+1, n): G.add_edge(i,j,weight=edges[i,j]) return nx.algorithms.shortest_paths.dense.floyd_warshall_numpy(G) triu = np.triu_indices class GeoNLM: def __init__(self, p, alfa, method='K', param=15): self.p = p # Nova dimensão self.alfa = alfa # Taxa de aprendizagem, entre 0.3 e 0.4 self.method = method self.param = param def transform(self, data): pca = PCA(n_components = self.p) return pca.fit_transform(data) def stress(self, dist_y, data_x): c = self.c n = dist_y.shape[0] dy = dist_y[self.triu] dist_x = all_dist(data_x)[self.triu] dx = dist_x.reshape((1,-1)) sub = np.ravel(dy-dx) soma_m = sub**2 /dy soma = np.sum(soma_m) return soma/c def derivate_1(self, i, dist_y, data_x, dist_x): c = self.c n = dist_y.shape[0] dx = (np.delete(dist_x[i,:],i)).reshape((1,-1)) dy = np.delete(dist_y[i,:],i) dy = dy.reshape((1,-1)) soma = np.dot( (dy - dx)/np.multiply(dx,dy) , np.delete(data_x[i,:] - data_x, i, 0) ) return -2*soma/c def derivate_2(self, i, dist_y, data_x, dist_x): c = self.c n = dist_y.shape[0] dx = np.ravel(np.delete(dist_x[i,:],i)) dy = np.ravel(np.delete(dist_y[i,:],i)) soma = np.zeros(data_x.shape[1]) for j in range(soma.size): soma[j] = np.sum( (dy - dx)/(dx*dy) - np.delete(data_x[i,j] - data_x[:,j], i, 0)**2 /dx**3 ) return np.abs((-2)*soma/c) def run(self, data_y, i_max = 10, show=False): stress = np.zeros(i_max) n = data_y.shape[0] data_x = self.transform(data_y) dist_y = GeoDist(data_y, self.method, self.param) self.triu = triu(dist_y.shape[0],1) self.c = np.sum(dist_y[self.triu]) score = np.zeros(i_max) for repeat in range(i_max): score[repeat] = self.stress(dist_y, data_x) dist_x = all_dist(data_x) delta_x = np.zeros(data_x.shape) for i in range(data_y.shape[0]): delta_x[i,:] = self.derivate_1(i,dist_y, data_x, dist_x)/self.derivate_2(i, dist_y, data_x, dist_x) data_x -= self.alfa*delta_x print(score[-1]) if show: plt.plot(np.arange(i_max), score) plt.show() return data_x x = np.random.random((3000,64)) import time s1 = time.time() g = GeoNLM(8, 0.3, param=40) a = g.run(x, i_max=20, show=True) print(time.time()-s1) ```
github_jupyter
### Minimizing KL Divergence Let’s see how we could go about minimizing the KL divergence between two probability distributions using gradient descent. To begin, we create a probability distribution with a known mean (0) and variance (2). Then, we create another distribution with random parameters. ``` import os import warnings warnings.filterwarnings('ignore') import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (4,4) # Make the figures a bit bigger plt.style.use('fivethirtyeight') import numpy as np from scipy.stats import norm import tensorflow as tf import seaborn as sns sns.set() import math from tqdm import tqdm np.random.seed(7) ``` To begin, we create a probability distribution, $p$, with a known mean (0) and variance (2). ``` x = np.arange(-10, 10, 0.1) x.shape[0] tf_pdf_shape=(1, x.shape[0]) p = tf.placeholder(tf.float64, shape=tf_pdf_shape)#p_pdf.shape #mu = tf.Variable(np.zeros(1)) #mu = tf.Variable(tf.truncated_normal((1,), stddev=3.0)) mu = tf.Variable(np.ones(1)*5) print(mu.dtype) varq = tf.Variable(np.eye(1)) print(varq.dtype) normal = tf.exp(-tf.square(x - mu) / (2 * varq)) q = normal / tf.reduce_sum(normal) learning_rate = 0.01 nb_epochs = 500*2 ``` We define a function to compute the KL divergence that excludes probabilities equal to zero. ``` kl_divergence = tf.reduce_sum( p * tf.log(p / q)) kl_divergence = tf.reduce_sum( tf.where(p == 0, tf.zeros(tf_pdf_shape, tf.float64), p * tf.log(p / q)) ) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(kl_divergence) init = tf.global_variables_initializer() sess = tf.compat.v1.InteractiveSession() sess.run(init) history = [] means = [] variances = [] ``` ### Just for test ``` m1 = 0 var1 = 2 p_pdf0 = norm.pdf(x, m1, np.sqrt(var1)) p_pdf1 = 1.0 / np.sqrt(var1) / np.sqrt(2 * math.pi) * np.exp(-np.square(x - m1) / (2 * var1)) import matplotlib plt.plot(p_pdf0) plt.plot(p_pdf1, marker=",") ``` ### KL(P||Q) !! * $p$ : given (target) * $q$ : variables to learn Generating values for $p$ ``` m_truth = 0 var_truth = 7 p_pdf0 = norm.pdf(x, m_truth, np.sqrt(var_truth)) p_pdf0 = 1.0 / np.sqrt(var_truth) / np.sqrt(2 * math.pi) * np.exp(-np.square(x - m_truth) / (2 * var_truth)) p_pdf = p_pdf0.reshape(1, -1) for i in tqdm(range(nb_epochs)): sess.run(optimizer, { p: p_pdf }) history.append(sess.run(kl_divergence, { p: p_pdf })) means.append(sess.run(mu)[0]) variances.append(sess.run(varq)[0][0]) if i % 100 == 10: print(sess.run(mu)[0], sess.run(varq)[0][0]) ``` ### Plot the results ``` len1 = np.shape(means)[0] alphas = np.linspace(0.1, 1, len1) rgba_colors = np.zeros((len1,4)) # for red the first column needs to be one rgba_colors[:,0] = 1.0 # the fourth column needs to be your alphas rgba_colors[:, 3] = alphas print(rgba_colors.shape) grange = range(len1) print(np.shape(grange)) for mean, variance, g in zip(means, variances, grange): if g%5 ==0: q_pdf = norm.pdf(x, mean, np.sqrt(variance)) plt.plot(x, q_pdf.reshape(-1, 1), color=rgba_colors[g]) plt.title('KL(P||Q) = %1.3f' % history[-1]) plt.plot(x, p_pdf.reshape(-1, 1), linewidth=3) plt.show() #target plt.plot(x, p_pdf.reshape(-1, 1), linewidth=5) #initial q_pdf = norm.pdf(x, means[0] , np.sqrt(variances[0])) plt.plot(x, q_pdf.reshape(-1, 1)) #final q_pdf = norm.pdf(x, means[-1] , np.sqrt(variances[-1])) plt.plot(x, q_pdf.reshape(-1, 1), color='r') plt.plot(means) plt.xlabel('epoch') plt.ylabel('mean') plt.plot(variances) plt.xlabel('epoch') plt.ylabel('variances') plt.plot(history) plt.title('history') plt.show() #sess.close() ``` ### Reference * https://towardsdatascience.com/kl-divergence-python-example-b87069e4b810
github_jupyter
### 20 Newsgroups Dataset http://qwone.com/~jason/20Newsgroups/ The 20 Newsgroups data set is a collection of approximately 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different news group 20news-19997.tar.gz - Original 20 Newsgroups data set 20news-bydate.tar.gz - 20 Newsgroups sorted by date; duplicates and some headers removed (18846 documents) 20news-18828.tar.gz - 20 Newsgroups; duplicates removed, only "From" and "Subject" headers (18828 documents) ``` import os import re import numpy as np import pandas as pd import tensorflow as tf def preprocess_text(text): # Applies preprocessing on text #remove leading & end white spaces and convert text to lowercase text = text.strip().lower() # remove HTML tags text = re.sub(r'<.*?>', '', text) # remove punctuation marks punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' for i in text: if i in punctuations: text = text.replace(i, "") # remove the characters [\], ['] and ["] text = re.sub(r"\\", "", text) text = re.sub(r"\'", "", text) text = re.sub(r"\"", "", text) #remove number text = re.sub(r"\d+", "", text) return text #Get Data data_root_path = 'D:\\Users\\chiawei\\konduit\\Github\\newsgroup_data\\20news-bydate\\' train_folder = '20news-bydate-train' test_folder = '20news-bydate-test' file_path = '' class_label = [f for f in os.listdir(os.path.join(data_root_path, train_folder))] class_index = [i for i in range(len(class_label))] total_class = len(class_index) label_index_pair = {} for label, index in zip(class_label, class_index): label_index_pair[label] = index print(label_index_pair) index_label_pair = {} for index, label in zip(class_index, class_label): index_label_pair[index] = label print('Save index label') label_path = "labelclass.pickle" with open(label_path, 'wb') as labelhandler: pickle.dump(index_label_pair, labelhandler) def get_dfs(data_path, class_dict): data = pd.DataFrame(columns = ["text", "classindex", "classlabel"]) text = [] class_index = [] class_label = [] for label in label_index_pair.keys(): class_path = os.path.join(data_path, label) files_list = [f for f in os.listdir(class_path) ] for f in os.listdir(class_path): with open(os.path.join(class_path, f), "r") as reader: text.append(reader.read())#spreprocess_text(reader.read())) class_label.append(label) class_index.append(class_dict[label]) data["text"] = text data["classindex"] = class_index data["classlabel"] = class_label return data train_data = get_dfs(os.path.join(data_root_path, train_folder), label_index_pair) test_data = get_dfs(os.path.join(data_root_path, test_folder), label_index_pair) #Shuffle data train_data = train_data.reindex(np.random.permutation(train_data.index)) test_data = test_data.reindex(np.random.permutation(test_data.index)) print("Number of training data: {}".format(train_data.shape[0])) print("Number of testing data: {}".format(test_data.shape[0])) train_data.head(20) #train_data.to_csv(os.path.join(data_root_path, "train_data.csv")) #test_data.to_csv(os.path.join(data_root_path, "test_data.csv")) # Create tokenizer for the data MAX_WORDS_PER_SEQUENCE = 8000 MAX_LEN = 256 EMBEDDINGS_SIZE = 200 BATCH_SIZE = 512 tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words = MAX_WORDS_PER_SEQUENCE, oov_token = "<unk>") tokenizer.fit_on_texts(train_data["text"]) train_sequences = tokenizer.texts_to_sequences(train_data["text"]) test_sequences = tokenizer.texts_to_sequences(test_data["text"]) train_sequences = tf.keras.preprocessing.sequence.pad_sequences(train_sequences, maxlen = MAX_LEN, padding = "post") test_sequences = tf.keras.preprocessing.sequence.pad_sequences(test_sequences, maxlen = MAX_LEN, padding = "post") # Build model model = tf.keras.Sequential() model.add(tf.keras.layers.Embedding(input_dim = MAX_WORDS_PER_SEQUENCE, output_dim = EMBEDDINGS_SIZE)) model.add(tf.keras.layers.Dense(150, input_shape = (EMBEDDINGS_SIZE, ), activation = "relu")) model.add(tf.keras.layers.Dropout(0.25)) model.add(tf.keras.layers.GlobalAveragePooling1D()) model.add(tf.keras.layers.Dense(total_class, activation = "softmax")) model.compile(loss = "sparse_categorical_crossentropy", optimizer = "Adam", metrics = ['accuracy']) callbacks = tf.keras.callbacks.EarlyStopping(monitor = "val_accuracy", mode = 'max') history = model.fit(train_sequences, train_data["classindex"].values, batch_size = BATCH_SIZE, epochs = 50, validation_split = 0.4, verbose = 1) import matplotlib.pyplot as plt history_dict = history.history loss_values = history_dict['loss'] val_loss_values = history_dict['val_loss'] epochs = range(1, len(history_dict['acc']) + 1) plt.plot(epochs, loss_values, 'bo', label='Training loss') plt.plot(epochs, val_loss_values, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() import pickle model_name = file_path + 'tf2-newsgroup-model.h5' print("save model") model.save(model_name) print("save tokenizer") tokenizer_path = file_path + 'tokenizer.pickle' with open(tokenizer_path, 'wb') as handle: pickle.dump(tokenizer, handle) results = model.evaluate(test_sequences, test_data["classindex"].values, verbose=2) for name, value in zip(model.metrics_names, results): print("%s: %.3f" % (name, value)) ```
github_jupyter
``` %matplotlib notebook import os import datetime as dt import pickle, joblib # Standard data science libraries import pandas as pd import numpy as np import scipy.stats as ss import scipy.optimize as so import scipy.interpolate as si # Visualization import matplotlib.pyplot as plt import seaborn as sns plt.style.use('seaborn-notebook') # Options for pandas pd.options.display.max_columns = 20 pd.options.display.max_rows = 200 # Display all cell outputs from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = 'all' from IPython.display import Image from IPython.display import Math from ipywidgets import interact, Dropdown from IPython.display import display import flopy as fp import geopandas as gpd from shapely.geometry import LineString, MultiLineString, Point import RTD_util6 as rtd_ut import Genmod_Utilities as gmu import matplotlib.dates as mdates import matplotlib.ticker as mticks import json ``` The next cell sets up some color and font choices that work for AGU journals. ``` KS1 = '#06366E' KS2 = '#00A3EB' KS3 = '#25C0A6' KS4 = '#FDDA58' KS5 = '#5D171A' font = {'family' : 'sans-serif', 'weight' : 'normal', 'size' : 12, 'sans-serif' : 'Arial'} plt.rc('font', **font) ``` The user can set the number of particles, porosity, and location of the MODPATH7 executable file. The number of particles that can be used is proportional to the amount of RAM availble. $4*10^6$ works with 64 GB of RAM, although more may be possible. The constant value for porosity can be replaced with a numpy array. ``` total_number_of_particles = 4.E+06 por = 0.20 mp_exe_name7 = '../Executables/modpath_7_2_001/bin/mpath7.exe' ``` Read in some files created by previous notebooks. ``` with open('GenMod_metadata.txt') as json_file: metadata = json.load(json_file) src = os.path.join('model_ws', 'gsm_metadata.json') with open(src, 'r') as f: gsm_metadata = json.load(f) from argparse import Namespace meta = Namespace(**gsm_metadata) ``` ## Use General Simulation Model to calculate TTD Read MODFLOW model and create RTD object ``` print('Reading model information') ml = fp.mf6.MFSimulation.load(sim_name='mfsim.nam', version='mf6', exe_name=metadata['modflow_path'], sim_ws='optimal_model', strict=True, verbosity_level=0, load_only=None, verify_data=False) model = ml.get_model() rtd = rtd_ut.RTD_util(ml, 'flow', 'rt') print(' ... done') ``` ## Read model output and compute net inflow to drain cells ``` # read shapefile created in step 1--NHD flowlines intersected with model grid src = os.path.join('gis', 'drain_segments.shp') shp = gpd.read_file(src) # read enhanced model_grid file in model_ws src = os.path.join('gis', 'model_grid.csv') data = pd.read_csv(src) # extract the drain budget terms from modflow output rtd.get_budget('DRN') drains = rtd.budget # create a dataframe of drain flows drn_df = pd.DataFrame(drains[0]) drn_df['node'] = drn_df['node'] - 1 # merge drain segments (by model cells) with drain flows shp_drn_df = shp.merge(drn_df, left_on='node', right_on='node', how='outer') shp_drn_df = shp_drn_df[shp_drn_df.q < 0] # save shapefile to model_ws dst = os.path.join('optimal_model', 'drain_flows.shp') shp_drn_df.to_file(dst) flow = drn_df.q.sum() particles_per_flow = total_number_of_particles / flow # make particle locations x_partloc, y_partloc, node_list, label_list = rtd.make_stream_particle_array( shp_drn_df, data, particles_per_flow, seg_ref='NHDPlusID') label_list = [np.int32(str(item)[-9:]) for item in label_list] ``` Test case for local coordinates for stream particles ``` # rtd.run_test(100) ``` * Write starting particle location file. * Particles start on top face of drain cells * Number of particles is proportional to new flux through top face * Label particles with the NHD reachcode ``` particle_data = fp.modpath.ParticleData(partlocs=node_list, structured=False, particleids=label_list, localx=x_partloc, localy=y_partloc, localz=1, timeoffset=None, drape=0) particle_group = fp.modpath.ParticleGroup(particlegroupname='drains', filename='particles.loc', releasedata=0, particledata=particle_data) ``` Run MODPATH ``` mpname = '{}_{}_{}'.format(model.name, 'volume', 'rt') mpnf = '{}_{}_{}.mpnam'.format(model.name, 'volume', 'rt') mplf = '{}_{}_{}.mplst'.format(model.name, 'volume', 'rt') headfile = model.oc.head_filerecord.array.getfield('O')[0] budfile = model.oc.budget_filerecord.array.getfield('O')[0] endpointfile = '{}.mpend'.format(model.name) mp = fp.modpath.Modpath7(modelname=mpname, simfile_ext='mpsim', namefile_ext='mpnam', version='modpath7', exe_name=mp_exe_name7, flowmodel=model, headfilename=headfile, budgetfilename=budfile, model_ws='optimal_model', verbose=True) mpsim = fp.modpath.Modpath7Sim(mp, mpnamefilename=mpnf, listingfilename=mplf, endpointfilename=endpointfile, simulationtype='endpoint', trackingdirection='backward', weaksinkoption='stop_at', weaksourceoption='stop_at', budgetoutputoption='summary', referencetime=rtd.ref_time, stoptimeoption='extend', zonedataoption='off', stopzone=-1, particlegroups=particle_group, extension='mpsim') mpbas = fp.modpath.Modpath7Bas(mp, porosity=0.20, defaultiface={'DRN': 6, 'RCH': 6}) mp.write_input() success, msg = mp.run_model(silent=True, report=False) ``` Read endpoint information ``` ep_data = rtd.read_endpoints(os.path.join('optimal_model', endpointfile)) ``` Write modified endpoint file ``` rtd.modify_endpoint_file(ep_data, write=True) try: os.remove(os.path.join('optimal_model', endpointfile)) except FileNotFoundError: pass try: os.remove(os.path.join('optimal_model', 'particles.loc')) except FileNotFoundError: pass ```
github_jupyter
# Measuring crop health <img align="right" src="../Supplementary_data/dea_logo.jpg"> * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser * **Compatibility:** Notebook currently compatible with both the `NCI` and `DEA Sandbox` environments * **Products used:** [s2a_ard_granule](https://explorer.sandbox.dea.ga.gov.au/s2a_ard_granule), [s2b_ard_granule](https://explorer.sandbox.dea.ga.gov.au/s2b_ard_granule) ## Background During a normal year, sugar cane in Queensland typically flowers early May through June; July to November is typically cane harvesting season. While sugar is growing, fields may look visually similar. However, health or growth rates from these fields can be quite different, leading to variability and unpredictability in revenue. Identifying underperforming crops can have two benefits: * Ability to scout for frost or disease damage. * Ability to investigate poor performing paddocks and undertake management action such as soil testing or targeted fertilising to improve yield. ### Sentinel-2 use case Satellite imagery can be used to measure pasture health over time and identify any changes in growth patterns between otherwise similar paddocks. Sentinel-2's 10 metre resolution makes it ideal for understanding the health of paddocks. The Normalised Difference Vegetation Index (NDVI) describes the difference between visible and near-infrared reflectance of vegetation cover. This index estimates the density of green on an area of land and can be used to track the health and growth of sugar as it matures. Comparing the NDVI of two similar paddocks will help to identify any anomalies in growth patterns. ## Description In this example, data from the European Sentinel-2 satellites is used to assess crop growing patterns for the last year. This data is made available through the Copernicus Regional Data Hub and Digital Earth Australia within 1-2 days of capture. The worked example below takes users through the code required to: 1. Create a time series data cube over a farming property. 2. Select multiple paddocks for comparison. 3. Create graphs to identify crop performance trends over the last year. 4. Interpret the results. *** ## Getting started **To run this analysis**, run all the cells in the notebook, starting with the "Load packages and apps" cell. ### Load packages and apps This notebook works via two functions, which are referred to as apps: `load_crophealth_data` and `run_crophealth_app`. The apps allow the majority of the analysis code to be stored in another file, making the notebook easy to use and run. To view the code behind the apps, open the [notebookapp_crophealth.py](../Supplementary_data/notebookapp_crophealth.py) file. ``` %matplotlib inline import datacube import sys sys.path.insert(1, "../Supplementary_data/") from notebookapp_crophealth import load_crophealth_data from notebookapp_crophealth import run_crophealth_app ``` ## Load the data The `load_crophealth_data()` command performs several key steps: * identify all available Sentinel-2 near real time data in the case-study area over the last year * remove any bad quality pixels * keep images where more than half of the image contains good quality pixels * collate images from Sentinel-2A and Sentinel-2B into a single data-set * calculate the NDVI from the red and near infrared bands * return the collated data for analysis The cleaned and collated data is stored in the `dataset_sentinel2` object. As the command runs, feedback will be provided below the cell, including information on the number of cleaned images loaded from each satellite. **Please be patient**. The load is complete when the cell status goes from `[*]` to `[number]`. ``` dataset_sentinel2 = load_crophealth_data() ``` ## Run the crop health app The `run_crophealth_app()` command launches an interactive map. Drawing polygons within the boundary (which represents the area covered by the loaded data) will result in plots of the average NDVI in that area. Draw polygons by clicking the &#11039; symbol in the app. The app works by taking the loaded data `dataset_sentinel2` as an argument. > **Note:** data points will only appear for images where more than 50% of the pixels were classified as good quality. This may cause trend lines on the average NDVI plot to appear disconnected. Available data points will be marked with the `*` symbol. ``` run_crophealth_app(dataset_sentinel2) ``` ## Drawing conclusions Here are some questions to think about: * What are some factors that might explain differences between fields? * From the NDVI value, can you tell when fields were harvested? *** ## Additional information **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks). **Last modified:** September 2021 **Compatible datacube version:** ``` print(datacube.__version__) ``` ## Tags Browse all available tags on the DEA User Guide's [Tags Index](https://docs.dea.ga.gov.au/genindex.html)
github_jupyter
<a href="https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_08_4_bayesian_hyperparameter_opt.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # T81-558: Applications of Deep Neural Networks **Module 8: Kaggle Data Sets** * 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 8 Material * Part 8.1: Introduction to Kaggle [[Video]](https://www.youtube.com/watch?v=v4lJBhdCuCU&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_08_1_kaggle_intro.ipynb) * Part 8.2: Building Ensembles with Scikit-Learn and Keras [[Video]](https://www.youtube.com/watch?v=LQ-9ZRBLasw&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_08_2_keras_ensembles.ipynb) * Part 8.3: How Should you Architect Your Keras Neural Network: Hyperparameters [[Video]](https://www.youtube.com/watch?v=1q9klwSoUQw&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_08_3_keras_hyperparameters.ipynb) * **Part 8.4: Bayesian Hyperparameter Optimization for Keras** [[Video]](https://www.youtube.com/watch?v=sXdxyUCCm8s&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_08_4_bayesian_hyperparameter_opt.ipynb) * Part 8.5: Current Semester's Kaggle [[Video]](https://www.youtube.com/watch?v=48OrNYYey5E) [[Notebook]](t81_558_class_08_5_kaggle_project.ipynb) # Google CoLab Instructions The following code ensures that Google CoLab is running the correct version of TensorFlow. ``` # Startup Google CoLab try: %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False # Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 * 60)) / 60) s = sec_elapsed % 60 return "{}:{:>02}:{:>05.2f}".format(h, m, s) ``` # Part 8.4: Bayesian Hyperparameter Optimization for Keras Bayesian Hyperparameter Optimization is a method of finding hyperparameters in a more efficient way than a grid search. Because each candidate set of hyperparameters requires a retraining of the neural network, it is best to keep the number of candidate sets to a minimum. Bayesian Hyperparameter Optimization achieves this by training a model to predict good candidate sets of hyperparameters. Snoek, J., Larochelle, H., & Adams, R. P. (2012). [Practical bayesian optimization of machine learning algorithms](https://arxiv.org/pdf/1206.2944.pdf). In *Advances in neural information processing systems* (pp. 2951-2959). * [bayesian-optimization](https://github.com/fmfn/BayesianOptimization) * [hyperopt](https://github.com/hyperopt/hyperopt) * [spearmint](https://github.com/JasperSnoek/spearmint) ``` # Ignore useless W0819 warnings generated by TensorFlow 2.0. Hopefully can remove this ignore in the future. # See https://github.com/tensorflow/tensorflow/issues/31308 import logging, os logging.disable(logging.WARNING) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import pandas as pd from scipy.stats import zscore # Read the data set df = pd.read_csv( "https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv", na_values=['NA','?']) # Generate dummies for job df = pd.concat([df,pd.get_dummies(df['job'],prefix="job")],axis=1) df.drop('job', axis=1, inplace=True) # Generate dummies for area df = pd.concat([df,pd.get_dummies(df['area'],prefix="area")],axis=1) df.drop('area', axis=1, inplace=True) # Missing values for income med = df['income'].median() df['income'] = df['income'].fillna(med) # Standardize ranges df['income'] = zscore(df['income']) df['aspect'] = zscore(df['aspect']) df['save_rate'] = zscore(df['save_rate']) df['age'] = zscore(df['age']) df['subscriptions'] = zscore(df['subscriptions']) # Convert to numpy - Classification x_columns = df.columns.drop('product').drop('id') x = df[x_columns].values dummies = pd.get_dummies(df['product']) # Classification products = dummies.columns y = dummies.values import pandas as pd import os import numpy as np import time import tensorflow.keras.initializers import statistics import tensorflow.keras from sklearn import metrics from sklearn.model_selection import StratifiedKFold from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Dropout, InputLayer from tensorflow.keras import regularizers from tensorflow.keras.callbacks import EarlyStopping from sklearn.model_selection import StratifiedShuffleSplit from tensorflow.keras.layers import LeakyReLU,PReLU from tensorflow.keras.optimizers import Adam def generate_model(dropout, neuronPct, neuronShrink): # We start with some percent of 5000 starting neurons on the first hidden layer. neuronCount = int(neuronPct * 5000) # Construct neural network # kernel_initializer = tensorflow.keras.initializers.he_uniform(seed=None) model = Sequential() # So long as there would have been at least 25 neurons and fewer than 10 # layers, create a new layer. layer = 0 while neuronCount>25 and layer<10: # The first (0th) layer needs an input input_dim(neuronCount) if layer==0: model.add(Dense(neuronCount, input_dim=x.shape[1], activation=PReLU())) else: model.add(Dense(neuronCount, activation=PReLU())) layer += 1 # Add dropout after each hidden layer model.add(Dropout(dropout)) # Shrink neuron count for each layer neuronCount = neuronCount * neuronShrink model.add(Dense(y.shape[1],activation='softmax')) # Output return model # Generate a model and see what the resulting structure looks like. model = generate_model(dropout=0.2, neuronPct=0.1, neuronShrink=0.25) model.summary() def evaluate_network(dropout,lr,neuronPct,neuronShrink): SPLITS = 2 # Bootstrap boot = StratifiedShuffleSplit(n_splits=SPLITS, test_size=0.1) # Track progress mean_benchmark = [] epochs_needed = [] num = 0 # Loop through samples for train, test in boot.split(x,df['product']): start_time = time.time() num+=1 # Split train and test x_train = x[train] y_train = y[train] x_test = x[test] y_test = y[test] model = generate_model(dropout, neuronPct, neuronShrink) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=lr)) monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=100, verbose=0, mode='auto', restore_best_weights=True) # Train on the bootstrap sample model.fit(x_train,y_train,validation_data=(x_test,y_test),callbacks=[monitor],verbose=0,epochs=1000) epochs = monitor.stopped_epoch epochs_needed.append(epochs) # Predict on the out of boot (validation) pred = model.predict(x_test) # Measure this bootstrap's log loss y_compare = np.argmax(y_test,axis=1) # For log loss calculation score = metrics.log_loss(y_compare, pred) mean_benchmark.append(score) m1 = statistics.mean(mean_benchmark) m2 = statistics.mean(epochs_needed) mdev = statistics.pstdev(mean_benchmark) # Record this iteration time_took = time.time() - start_time #print(f"#{num}: score={score:.6f}, mean score={m1:.6f}, stdev={mdev:.6f}, epochs={epochs}, mean epochs={int(m2)}, time={hms_string(time_took)}") tensorflow.keras.backend.clear_session() return (-m1) print(evaluate_network( dropout=0.2, lr=1e-3, neuronPct=0.2, neuronShrink=0.2)) from bayes_opt import BayesianOptimization import time # Supress NaN warnings, see: https://stackoverflow.com/questions/34955158/what-might-be-the-cause-of-invalid-value-encountered-in-less-equal-in-numpy import warnings warnings.filterwarnings("ignore",category =RuntimeWarning) # Bounded region of parameter space pbounds = {'dropout': (0.0, 0.499), 'lr': (0.0, 0.1), 'neuronPct': (0.01, 1), 'neuronShrink': (0.01, 1) } optimizer = BayesianOptimization( f=evaluate_network, pbounds=pbounds, verbose=2, # verbose = 1 prints only when a maximum is observed, verbose = 0 is silent random_state=1, ) start_time = time.time() optimizer.maximize(init_points=10, n_iter=100,) time_took = time.time() - start_time print(f"Total runtime: {hms_string(time_took)}") print(optimizer.max) ``` {'target': -0.6500334282952827, 'params': {'dropout': 0.12771198428037775, 'lr': 0.0074010841641111965, 'neuronPct': 0.10774655638231533, 'neuronShrink': 0.2784788676498257}}
github_jupyter
``` %matplotlib inline ``` =============================================== Creating a timeline with lines, dates, and text =============================================== How to create a simple timeline using Matplotlib release dates. Timelines can be created with a collection of dates and text. In this example, we show how to create a simple timeline using the dates for recent releases of Matplotlib. First, we'll pull the data from GitHub. ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates from datetime import datetime try: # Try to fetch a list of Matplotlib releases and their dates # from https://api.github.com/repos/matplotlib/matplotlib/releases import urllib.request import json url = 'https://api.github.com/repos/matplotlib/matplotlib/releases' url += '?per_page=100' data = json.loads(urllib.request.urlopen(url, timeout=.4).read().decode()) dates = [] names = [] for item in data: if 'rc' not in item['tag_name'] and 'b' not in item['tag_name']: dates.append(item['published_at'].split("T")[0]) names.append(item['tag_name']) # Convert date strings (e.g. 2014-10-18) to datetime dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates] except Exception: # In case the above fails, e.g. because of missing internet connection # use the following lists as fallback. names = ['v2.2.4', 'v3.0.3', 'v3.0.2', 'v3.0.1', 'v3.0.0', 'v2.2.3', 'v2.2.2', 'v2.2.1', 'v2.2.0', 'v2.1.2', 'v2.1.1', 'v2.1.0', 'v2.0.2', 'v2.0.1', 'v2.0.0', 'v1.5.3', 'v1.5.2', 'v1.5.1', 'v1.5.0', 'v1.4.3', 'v1.4.2', 'v1.4.1', 'v1.4.0'] dates = ['2019-02-26', '2019-02-26', '2018-11-10', '2018-11-10', '2018-09-18', '2018-08-10', '2018-03-17', '2018-03-16', '2018-03-06', '2018-01-18', '2017-12-10', '2017-10-07', '2017-05-10', '2017-05-02', '2017-01-17', '2016-09-09', '2016-07-03', '2016-01-10', '2015-10-29', '2015-02-16', '2014-10-26', '2014-10-18', '2014-08-26'] # Convert date strings (e.g. 2014-10-18) to datetime dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates] ``` Next, we'll create a `~.Axes.stem` plot with some variation in levels as to distinguish even close-by events. In contrast to a usual stem plot, we will shift the markers to the baseline for visual emphasis on the one-dimensional nature of the time line. For each event, we add a text label via `~.Axes.annotate`, which is offset in units of points from the tip of the event line. Note that Matplotlib will automatically plot datetime inputs. ``` # Choose some nice levels levels = np.tile([-5, 5, -3, 3, -1, 1], int(np.ceil(len(dates)/6)))[:len(dates)] # Create figure and plot a stem plot with the date fig, ax = plt.subplots(figsize=(8.8, 4), constrained_layout=True) ax.set(title="Matplotlib release dates") markerline, stemline, baseline = ax.stem(dates, levels, linefmt="C3-", basefmt="k-", use_line_collection=True) plt.setp(markerline, mec="k", mfc="w", zorder=3) # Shift the markers to the baseline by replacing the y-data by zeros. markerline.set_ydata(np.zeros(len(dates))) # annotate lines vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)] for d, l, r, va in zip(dates, levels, names, vert): ax.annotate(r, xy=(d, l), xytext=(-3, np.sign(l)*3), textcoords="offset points", va=va, ha="right") # format xaxis with 4 month intervals ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=4)) ax.get_xaxis().set_major_formatter(mdates.DateFormatter("%b %Y")) plt.setp(ax.get_xticklabels(), rotation=30, ha="right") # remove y axis and spines ax.get_yaxis().set_visible(False) for spine in ["left", "top", "right"]: ax.spines[spine].set_visible(False) ax.margins(y=0.1) plt.show() ``` ------------ References """""""""" The use of the following functions, methods and classes is shown in this example: ``` import matplotlib matplotlib.axes.Axes.stem matplotlib.axes.Axes.annotate matplotlib.axis.Axis.set_major_locator matplotlib.axis.Axis.set_major_formatter matplotlib.dates.MonthLocator matplotlib.dates.DateFormatter ```
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W3D1_RealNeurons/student/W3D1_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Neuromatch Academy: Week 3, Day 1, Tutorial 2 # Real Neurons: Effects of Input Correlation __Content creators:__ Qinglong Gu, Songtin Li, John Murray, Richard Naud, Arvind Kumar __Content reviewers:__ Maryam Vaziri-Pashkam, Ella Batty, Lorenzo Fontolan, Richard Gao, Matthew Krause, Spiros Chavlis, Michael Waskom --- # Tutorial Objectives In this tutorial, we will use the leaky integrate-and-fire (LIF) neuron model (see Tutorial 1) to study how they transform input correlations to output properties (transfer of correlations). In particular, we are going to write a few lines of code to: - inject correlated GWN in a pair of neurons - measure correlations between the spiking activity of the two neurons - study how the transfer of correlation depends on the statistics of the input, i.e. mean and standard deviation. --- # Setup ``` # Import libraries import matplotlib.pyplot as plt import numpy as np import time # @title Figure Settings import ipywidgets as widgets # interactive display %config InlineBackend.figure_format = 'retina' # use NMA plot style plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") my_layout = widgets.Layout() # @title Helper functions def default_pars(**kwargs): pars = {} ### typical neuron parameters### pars['V_th'] = -55. # spike threshold [mV] pars['V_reset'] = -75. # reset potential [mV] pars['tau_m'] = 10. # membrane time constant [ms] pars['g_L'] = 10. # leak conductance [nS] pars['V_init'] = -75. # initial potential [mV] pars['V_L'] = -75. # leak reversal potential [mV] pars['tref'] = 2. # refractory time (ms) ### simulation parameters ### pars['T'] = 400. # Total duration of simulation [ms] pars['dt'] = .1 # Simulation time step [ms] ### external parameters if any ### for k in kwargs: pars[k] = kwargs[k] pars['range_t'] = np.arange(0, pars['T'], pars['dt']) # Vector of discretized # time points [ms] return pars def run_LIF(pars, Iinj): """ Simulate the LIF dynamics with external input current Args: pars : parameter dictionary Iinj : input current [pA]. The injected current here can be a value or an array Returns: rec_spikes : spike times rec_v : mebrane potential """ # Set parameters V_th, V_reset = pars['V_th'], pars['V_reset'] tau_m, g_L = pars['tau_m'], pars['g_L'] V_init, V_L = pars['V_init'], pars['V_L'] dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size tref = pars['tref'] # Initialize voltage and current v = np.zeros(Lt) v[0] = V_init Iinj = Iinj * np.ones(Lt) tr = 0. # simulate the LIF dynamics rec_spikes = [] # record spike times for it in range(Lt - 1): if tr > 0: v[it] = V_reset tr = tr - 1 elif v[it] >= V_th: # reset voltage and record spike event rec_spikes.append(it) v[it] = V_reset tr = tref / dt # calculate the increment of the membrane potential dv = (-(v[it] - V_L) + Iinj[it] / g_L) * (dt / tau_m) # update the membrane potential v[it + 1] = v[it] + dv rec_spikes = np.array(rec_spikes) * dt return v, rec_spikes def my_GWN(pars, sig, myseed=False): """ Function that calculates Gaussian white noise inputs Args: pars : parameter dictionary mu : noise baseline (mean) sig : noise amplitute (standard deviation) myseed : random seed. int or boolean the same seed will give the same random number sequence Returns: I : Gaussian white noise input """ # Retrieve simulation parameters dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size # Set random seed. You can fix the seed of the random number generator so # that the results are reliable however, when you want to generate multiple # realization make sure that you change the seed for each new realization if myseed: np.random.seed(seed=myseed) else: np.random.seed() # generate GWN # we divide here by 1000 to convert units to sec. I_GWN = sig * np.random.randn(Lt) * np.sqrt(pars['tau_m'] / dt) return I_GWN def Poisson_generator(pars, rate, n, myseed=False): """ Generates poisson trains Args: pars : parameter dictionary rate : noise amplitute [Hz] n : number of Poisson trains myseed : random seed. int or boolean Returns: pre_spike_train : spike train matrix, ith row represents whether there is a spike in ith spike train over time (1 if spike, 0 otherwise) """ # Retrieve simulation parameters dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size # set random seed if myseed: np.random.seed(seed=myseed) else: np.random.seed() # generate uniformly distributed random variables u_rand = np.random.rand(n, Lt) # generate Poisson train poisson_train = 1. * (u_rand < rate * (dt / 1000.)) return poisson_train def example_plot_myCC(): pars = default_pars(T=50000, dt=.1) c = np.arange(10) * 0.1 r12 = np.zeros(10) for i in range(10): I1gL, I2gL = correlate_input(pars, mu=20.0, sig=7.5, c=c[i]) r12[i] = my_CC(I1gL, I2gL) plt.figure() plt.plot(c, r12, 'bo', alpha=0.7, label='Simulation', zorder=2) plt.plot([-0.05, 0.95], [-0.05, 0.95], 'k--', label='y=x', dashes=(2, 2), zorder=1) plt.xlabel('True CC') plt.ylabel('Sample CC') plt.legend(loc='best') def LIF_output_cc(pars, mu, sig, c, bin_size, n_trials=20): """ Simulates two LIF neurons with correlated input and computes output correlation Args: pars : parameter dictionary mu : noise baseline (mean) sig : noise amplitute (standard deviation) c : correlation coefficient ~[0, 1] bin_size : bin size used for time series n_trials : total simulation trials Returns: r : output corr. coe. sp_rate : spike rate sp1 : spike times of neuron 1 in the last trial sp2 : spike times of neuron 2 in the last trial """ r12 = np.zeros(n_trials) sp_rate = np.zeros(n_trials) for i_trial in range(n_trials): I1gL, I2gL = correlate_input(pars, mu, sig, c) _, sp1 = run_LIF(pars, pars['g_L'] * I1gL) _, sp2 = run_LIF(pars, pars['g_L'] * I2gL) my_bin = np.arange(0, pars['T'], bin_size) sp1_count, _ = np.histogram(sp1, bins=my_bin) sp2_count, _ = np.histogram(sp2, bins=my_bin) r12[i_trial] = my_CC(sp1_count[::20], sp2_count[::20]) sp_rate[i_trial] = len(sp1) / pars['T'] * 1000. return r12.mean(), sp_rate.mean(), sp1, sp2 def plot_c_r_LIF(c, r, mycolor, mylabel): z = np.polyfit(c, r, deg=1) c_range = np.array([c.min() - 0.05, c.max() + 0.05]) plt.plot(c, r, 'o', color=mycolor, alpha=0.7, label=mylabel, zorder=2) plt.plot(c_range, z[0] * c_range + z[1], color=mycolor, zorder=1) ``` The helper function contains the: - Parameter dictionary: `default_pars( **kwargs)` - LIF simulator: `run_LIF` - Gaussian white noise generator: `my_GWN(pars, sig, myseed=False)` - Poisson type spike train generator: `Poisson_generator(pars, rate, n, myseed=False)` - Two LIF neurons with correlated inputs simulator: `LIF_output_cc(pars, mu, sig, c, bin_size, n_trials=20)` - Some additional plotting utilities --- # Section 1: Correlations (Synchrony) Correlation or synchrony in neuronal activity can be described for any readout of brain activity. Here, we are concerned with the spiking activity of neurons. In the simplest way, correlation/synchrony refers to coincident spiking of neurons, i.e., when two neurons spike together, they are firing in **synchrony** or are **correlated**. Neurons can be synchronous in their instantaneous activity, i.e., they spike together with some probability. However, it is also possible that spiking of a neuron at time $t$ is correlated with the spikes of another neuron with a delay (time-delayed synchrony). ## Origin of synchronous neuronal activity: - Common inputs, i.e., two neurons are receiving input from the same sources. The degree of correlation of the shared inputs is proportional to their output correlation. - Pooling from the same sources. Neurons do not share the same input neurons but are receiving inputs from neurons which themselves are correlated. - Neurons are connected to each other (uni- or bi-directionally): This will only give rise to time-delayed synchrony. Neurons could also be connected via gap-junctions. - Neurons have similar parameters and initial conditions. ## Implications of synchrony When neurons spike together, they can have a stronger impact on downstream neurons. Synapses in the brain are sensitive to the temporal correlations (i.e., delay) between pre- and postsynaptic activity, and this, in turn, can lead to the formation of functional neuronal networks - the basis of unsupervised learning (we will study some of these concepts in a forthcoming tutorial). Synchrony implies a reduction in the dimensionality of the system. In addition, correlations, in many cases, can impair the decoding of neuronal activity. ``` # @title Video 1: Input & output correlations from IPython.display import YouTubeVideo video = YouTubeVideo(id="nsAYFBcAkes", width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video ``` ## How to study the emergence of correlations A simple model to study the emergence of correlations is to inject common inputs to a pair of neurons and measure the output correlation as a function of the fraction of common inputs. Here, we are going to investigate the transfer of correlations by computing the correlation coefficient of spike trains recorded from two unconnected LIF neurons, which received correlated inputs. The input current to LIF neuron $i$ $(i=1,2)$ is: \begin{equation} \frac{I_i}{g_L} =\mu_i + \sigma_i (\sqrt{1-c}\xi_i + \sqrt{c}\xi_c) \quad (1) \end{equation} where $\mu_i$ is the temporal average of the current. The Gaussian white noise $\xi_i$ is independent for each neuron, while $\xi_c$ is common to all neurons. The variable $c$ ($0\le c\le1$) controls the fraction of common and independent inputs. $\sigma_i$ shows the variance of the total input. So, first, we will generate correlated inputs. ``` # @title #@markdown Execute this cell to get a function for generating correlated GWN inputs def correlate_input(pars, mu=20., sig=7.5, c=0.3): """ Args: pars : parameter dictionary mu : noise baseline (mean) sig : noise amplitute (standard deviation) c. : correlation coefficient ~[0, 1] Returns: I1gL, I2gL : two correlated inputs with corr. coe. c """ # generate Gaussian whute noise xi_1, xi_2, xi_c xi_1 = my_GWN(pars, sig) xi_2 = my_GWN(pars, sig) xi_c = my_GWN(pars, sig) # Generate two correlated inputs by Equation. (1) I1gL = mu + np.sqrt(1. - c) * xi_1 + np.sqrt(c) * xi_c I2gL = mu + np.sqrt(1. - c) * xi_2 + np.sqrt(c) * xi_c return I1gL, I2gL print(help(correlate_input)) ``` ### Exercise 1: Compute the correlation The _sample correlation coefficient_ between two input currents $I_i$ and $I_j$ is defined as the sample covariance of $I_i$ and $I_j$ divided by the square root of the sample variance of $I_i$ multiplied with the square root of the sample variance of $I_j$. In equation form: \begin{align} r_{ij} &= \frac{cov(I_i, I_j)}{\sqrt{var(I_i)} \sqrt{var(I_j)}}\\ cov(I_i, I_j) &= \sum_{k=1}^L (I_i^k -\bar{I}_i)(I_j^k -\bar{I}_j) \\ var(I_i) &= \sum_{k=1}^L (I_i^k -\bar{I}_i)^2 \end{align} where $\bar{I}_i$ is the sample mean, k is the time bin, and L is the length of $I$. This means that $I_i^k$ is current i at time $k\cdot dt$. Note that the equations above are not accurate for sample covariances and variances as they should be additionally divided by L-1 - we have dropped this term because it cancels out in the sample correlation coefficient formula. The _sample correlation coefficient_ may also be referred to as the _sample Pearson correlation coefficient_. Here, is a beautiful paper that explains multiple ways to calculate and understand correlations [Rodgers and Nicewander 1988](https://www.stat.berkeley.edu/~rabbee/correlation.pdf). In this exercise, we will create a function, `my_CC` to compute the sample correlation coefficient between two time series. Note that while we introduced this computation here in the context of input currents, the sample correlation coefficient is used to compute the correlation between any two time series - we will use it later on binned spike trains. ``` def my_CC(i, j): """ Args: i, j : two time series with the same length Returns: rij : correlation coefficient """ ######################################################################## ## TODO for students: compute rxy, then remove the NotImplementedError # # Tip1: array([a1, a2, a3])*array([b1, b2, b3]) = array([a1*b1, a2*b2, a3*b3]) # Tip2: np.sum(array([a1, a2, a3])) = a1+a2+a3 # Tip3: square root, np.sqrt() # Fill out function and remove raise NotImplementedError("Student exercise: compute the sample correlation coefficient") ######################################################################## # Calculate the covariance of i and j cov = ... # Calculate the variance of i var_i = ... # Calculate the variance of j var_j = ... # Calculate the correlation coefficient rij = ... return rij # Uncomment the line after completing the my_CC function # example_plot_myCC() ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial2_Solution_03e44bdc.py) *Example output:* <img alt='Solution hint' align='left' width=558 height=413 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W3D1_RealNeurons/static/W3D1_Tutorial2_Solution_03e44bdc_0.png> ### Exercise 2: Measure the correlation between spike trains After recording the spike times of the two neurons, how can we estimate their correlation coefficient? In order to find this, we need to bin the spike times and obtain two time series. Each data point in the time series is the number of spikes in the corresponding time bin. You can use `np.histogram()` to bin the spike times. Complete the code below to bin the spike times and calculate the correlation coefficient for two Poisson spike trains. Note that `c` here is the ground-truth correlation coefficient that we define. ``` # @title # @markdown Execute this cell to get a function for generating correlated Poisson inputs (generate_corr_Poisson) def generate_corr_Poisson(pars, poi_rate, c, myseed=False): """ function to generate correlated Poisson type spike trains Args: pars : parameter dictionary poi_rate : rate of the Poisson train c. : correlation coefficient ~[0, 1] Returns: sp1, sp2 : two correlated spike time trains with corr. coe. c """ range_t = pars['range_t'] mother_rate = poi_rate / c mother_spike_train = Poisson_generator(pars, rate=mother_rate, n=1, myseed=myseed)[0] sp_mother = range_t[mother_spike_train > 0] L_sp_mother = len(sp_mother) sp_mother_id = np.arange(L_sp_mother) L_sp_corr = int(L_sp_mother * c) np.random.shuffle(sp_mother_id) sp1 = np.sort(sp_mother[sp_mother_id[:L_sp_corr]]) np.random.shuffle(sp_mother_id) sp2 = np.sort(sp_mother[sp_mother_id[:L_sp_corr]]) return sp1, sp2 print(help(generate_corr_Poisson)) def corr_coeff_pairs(pars, rate, c, trials, bins): """ Calculate the correlation coefficient of two spike trains, for different realizations Args: pars : parameter dictionary rate : rate of poisson inputs c : correlation coefficient ~ [0, 1] trials : number of realizations bins : vector with bins for time discretization Returns: r12 : correlation coefficient of a pair of inputs """ r12 = np.zeros(n_trials) for i in range(n_trials): ############################################################## ## TODO for students: Use np.histogram to bin the spike time # ## e.g., sp1_count, _= np.histogram(...) # Use my_CC() compute corr coe, compare with c # Note that you can run multiple realizations and compute their r_12(diff_trials) # with the defined function above. The average r_12 over trials can get close to c. # Note: change seed to generate different input per trial # Fill out function and remove raise NotImplementedError("Student exercise: compute the correlation coefficient") ############################################################## # Generate correlated Poisson inputs sp1, sp2 = generate_corr_Poisson(pars, ..., ..., myseed=2020+i) # Bin the spike times of the first input sp1_count, _ = np.histogram(..., bins=...) # Bin the spike times of the second input sp2_count, _ = np.histogram(..., bins=...) # Calculate the correlation coefficient r12[i] = my_CC(..., ...) return r12 poi_rate = 20. c = 0.2 # set true correlation pars = default_pars(T=10000) # bin the spike time bin_size = 20 # [ms] my_bin = np.arange(0, pars['T'], bin_size) n_trials = 100 # 100 realizations # Uncomment to test your function # r12 = corr_coeff_pairs(pars, rate=poi_rate, c=c, trials=n_trials, bins=my_bin) # print(f'True corr coe = {c:.3f}') # print(f'Simu corr coe = {r12.mean():.3f}') ``` Sample output ``` True corr coe = 0.200 Simu corr coe = 0.197 ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial2_Solution_e5eaac3e.py) --- # Section 2: Investigate the effect of input correlation on the output correlation Now let's combine the aforementioned two procedures. We first generate the correlated inputs by Equation (1). Then we inject the correlated inputs $I_1, I_2$ into a pair of neurons and record their output spike times. We continue measuring the correlation between the output and investigate the relationship between the input correlation and the output correlation. ## Drive a neuron with correlated inputs and visualize its output In the following, you will inject correlated GWN in two neurons. You need to define the mean (`gwn_mean`), standard deviation (`gwn_std`), and input correlations (`c_in`). We will simulate $10$ trials to get a better estimate of the output correlation. Change the values in the following cell for the above variables (and then run the next cell) to explore how they impact the output correlation. ``` # Play around with these parameters pars = default_pars(T=80000, dt=1.) # get the parameters c_in = 0.3 # set input correlation value gwn_mean = 10. gwn_std = 10. # @title # @markdown Do not forget to execute this cell to simulate the LIF bin_size = 10. # ms starttime = time.perf_counter() # time clock r12_ss, sp_ss, sp1, sp2 = LIF_output_cc(pars, mu=gwn_mean, sig=gwn_std, c=c_in, bin_size=bin_size, n_trials=10) # just the time counter endtime = time.perf_counter() timecost = (endtime - starttime) / 60. print(f"Simulation time = {timecost:.2f} min") print(f"Input correlation = {c_in}") print(f"Output correlation = {r12_ss}") plt.figure(figsize=(12, 6)) plt.plot(sp1, np.ones(len(sp1)) * 1, '|', ms=20, label='neuron 1') plt.plot(sp2, np.ones(len(sp2)) * 1.1, '|', ms=20, label='neuron 2') plt.xlabel('time (ms)') plt.ylabel('neuron id.') plt.xlim(1000, 8000) plt.ylim(0.9, 1.2) plt.legend() plt.show() ``` ## Think! - Is the output correlation always smaller than the input correlation? If yes, why? - Should there be a systematic relationship between input and output correlations? You will explore these questions in the next figure but try to develop your own intuitions first! Lets vary `c_in` and plot the relationship between the `c_in` and output correlation. This might take some time depending on the number of trials. ``` #@title #@markdown Don't forget to execute this cell! pars = default_pars(T=80000, dt=1.) # get the parameters bin_size = 10. c_in = np.arange(0, 1.0, 0.1) # set the range for input CC r12_ss = np.zeros(len(c_in)) # small mu, small sigma starttime = time.perf_counter() # time clock for ic in range(len(c_in)): r12_ss[ic], sp_ss, sp1, sp2 = LIF_output_cc(pars, mu=10.0, sig=10., c=c_in[ic], bin_size=bin_size, n_trials=10) endtime = time.perf_counter() timecost = (endtime - starttime) / 60. print(f"Simulation time = {timecost:.2f} min") plt.figure(figsize=(7, 6)) plot_c_r_LIF(c_in, r12_ss, mycolor='b', mylabel='Output CC') plt.plot([c_in.min() - 0.05, c_in.max() + 0.05], [c_in.min() - 0.05, c_in.max() + 0.05], 'k--', dashes=(2, 2), label='y=x') plt.xlabel('Input CC') plt.ylabel('Output CC') plt.legend(loc='best', fontsize=16) plt.show() ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial2_Solution_71e76f4d.py) --- # Section 3: Correlation transfer function The above plot of input correlation vs. output correlation is called the __correlation transfer function__ of the neurons. ## Section 3.1: How do the mean and standard deviation of the GWN affect the correlation transfer function? The correlations transfer function appears to be linear. The above can be taken as the input/output transfer function of LIF neurons for correlations, instead of the transfer function for input/output firing rates as we had discussed in the previous tutorial (i.e., F-I curve). What would you expect to happen to the slope of the correlation transfer function if you vary the mean and/or the standard deviation of the GWN? ``` #@markdown Execute this cell to visualize correlation transfer functions pars = default_pars(T=80000, dt=1.) # get the parameters no_trial = 10 bin_size = 10. c_in = np.arange(0., 1., 0.2) # set the range for input CC r12_ss = np.zeros(len(c_in)) # small mu, small sigma r12_ls = np.zeros(len(c_in)) # large mu, small sigma r12_sl = np.zeros(len(c_in)) # small mu, large sigma starttime = time.perf_counter() # time clock for ic in range(len(c_in)): r12_ss[ic], sp_ss, sp1, sp2 = LIF_output_cc(pars, mu=10.0, sig=10., c=c_in[ic], bin_size=bin_size, n_trials=no_trial) r12_ls[ic], sp_ls, sp1, sp2 = LIF_output_cc(pars, mu=18.0, sig=10., c=c_in[ic], bin_size=bin_size, n_trials=no_trial) r12_sl[ic], sp_sl, sp1, sp2 = LIF_output_cc(pars, mu=10.0, sig=20., c=c_in[ic], bin_size=bin_size, n_trials=no_trial) endtime = time.perf_counter() timecost = (endtime - starttime) / 60. print(f"Simulation time = {timecost:.2f} min") plt.figure(figsize=(7, 6)) plot_c_r_LIF(c_in, r12_ss, mycolor='b', mylabel=r'Small $\mu$, small $\sigma$') plot_c_r_LIF(c_in, r12_ls, mycolor='y', mylabel=r'Large $\mu$, small $\sigma$') plot_c_r_LIF(c_in, r12_sl, mycolor='r', mylabel=r'Small $\mu$, large $\sigma$') plt.plot([c_in.min() - 0.05, c_in.max() + 0.05], [c_in.min() - 0.05, c_in.max() + 0.05], 'k--', dashes=(2, 2), label='y=x') plt.xlabel('Input CC') plt.ylabel('Output CC') plt.legend(loc='best', fontsize=14) plt.show() ``` ### Think! Why do both the mean and the standard deviation of the GWN affect the slope of the correlation transfer function? [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial2_Solution_2deb4ccb.py) ## Section 3.2: What is the rationale behind varying $\mu$ and $\sigma$? The mean and the variance of the synaptic current depends on the spike rate of a Poisson process. We can use [Campbell's theorem](https://en.wikipedia.org/wiki/Campbell%27s_theorem_(probability)) to estimate the mean and the variance of the synaptic current: \begin{align} \mu_{\rm syn} = \lambda J \int P(t) \\ \sigma_{\rm syn} = \lambda J \int P(t)^2 dt\\ \end{align} where $\lambda$ is the firing rate of the Poisson input, $J$ the amplitude of the postsynaptic current and $P(t)$ is the shape of the postsynaptic current as a function of time. Therefore, when we varied $\mu$ and/or $\sigma$ of the GWN, we mimicked a change in the input firing rate. Note that, if we change the firing rate, both $\mu$ and $\sigma$ will change simultaneously, not independently. Here, since we observe an effect of $\mu$ and $\sigma$ on correlation transfer, this implies that the input rate has an impact on the correlation transfer function. ### Think! - What are the factors that would make output correlations smaller than input correlations? (Notice that the colored lines are below the black dashed line) - What does it mean for the correlation in the network? - Here we have studied the transfer of correlations by injecting GWN. But in the previous tutorial, we mentioned that GWN is unphysiological. Indeed, neurons receive colored noise (i.e., Shot noise or OU process). How do these results obtained from injection of GWN apply to the case where correlated spiking inputs are injected in the two LIFs? Will the results be the same or different? Reference - De La Rocha, Jaime, et al. "Correlation between neural spike trains increases with firing rate." Nature (2007) (https://www.nature.com/articles/nature06028/) - Bujan AF, Aertsen A, Kumar A. Role of input correlations in shaping the variability and noise correlations of evoked activity in the neocortex. Journal of Neuroscience. 2015 Jun 3;35(22):8611-25. (https://www.jneurosci.org/content/35/22/8611) [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D1_RealNeurons/solutions/W3D1_Tutorial2_Solution_39d29f52.py) --- # Summary In this tutorial, we studied how the input correlation of two LIF neurons is mapped to their output correlation. Specifically, we: - injected correlated GWN in a pair of neurons, - measured correlations between the spiking activity of the two neurons, and - studied how the transfer of correlation depends on the statistics of the input, i.e., mean and standard deviation. Here, we were concerned with zero time lag correlation. For this reason, we restricted estimation of correlation to instantaneous correlations. If you are interested in time-lagged correlation, then we should estimate the cross-correlogram of the spike trains and find out the dominant peak and area under the peak to get an estimate of output correlations. We leave this as a future to-do for you if you are interested. --- # Bonus 1: Example of a conductance-based LIF model Above, we have written code to generate correlated Poisson spike trains. You can write code to stimulate the LIF neuron with such correlated spike trains and study the correlation transfer function for spiking input and compare it to the correlation transfer function obtained by injecting correlated GWNs. ``` # @title Function to simulate conductance-based LIF def run_LIF_cond(pars, I_inj, pre_spike_train_ex, pre_spike_train_in): """ conductance-based LIF dynamics Args: pars : parameter dictionary I_inj : injected current [pA]. The injected current here can be a value or an array pre_spike_train_ex : spike train input from presynaptic excitatory neuron pre_spike_train_in : spike train input from presynaptic inhibitory neuron Returns: rec_spikes : spike times rec_v : mebrane potential gE : postsynaptic excitatory conductance gI : postsynaptic inhibitory conductance """ # Retrieve parameters V_th, V_reset = pars['V_th'], pars['V_reset'] tau_m, g_L = pars['tau_m'], pars['g_L'] V_init, E_L = pars['V_init'], pars['E_L'] gE_bar, gI_bar = pars['gE_bar'], pars['gI_bar'] VE, VI = pars['VE'], pars['VI'] tau_syn_E, tau_syn_I = pars['tau_syn_E'], pars['tau_syn_I'] tref = pars['tref'] dt, range_t = pars['dt'], pars['range_t'] Lt = range_t.size # Initialize tr = 0. v = np.zeros(Lt) v[0] = V_init gE = np.zeros(Lt) gI = np.zeros(Lt) Iinj = I_inj * np.ones(Lt) # ensure I has length Lt if pre_spike_train_ex.max() == 0: pre_spike_train_ex_total = np.zeros(Lt) else: pre_spike_train_ex_total = pre_spike_train_ex * np.ones(Lt) if pre_spike_train_in.max() == 0: pre_spike_train_in_total = np.zeros(Lt) else: pre_spike_train_in_total = pre_spike_train_in * np.ones(Lt) # simulation rec_spikes = [] # recording spike times for it in range(Lt - 1): if tr > 0: v[it] = V_reset tr = tr - 1 elif v[it] >= V_th: # reset voltage and record spike event rec_spikes.append(it) v[it] = V_reset tr = tref / dt # update the synaptic conductance gE[it+1] = gE[it] - (dt / tau_syn_E) * gE[it] + gE_bar * pre_spike_train_ex_total[it + 1] gI[it+1] = gI[it] - (dt / tau_syn_I) * gI[it] + gI_bar * pre_spike_train_in_total[it + 1] # calculate the increment of the membrane potential dv = (-(v[it] - E_L) - (gE[it + 1] / g_L) * (v[it] - VE) - \ (gI[it + 1] / g_L) * (v[it] - VI) + Iinj[it] / g_L) * (dt / tau_m) # update membrane potential v[it + 1] = v[it] + dv rec_spikes = np.array(rec_spikes) * dt return v, rec_spikes, gE, gI print(help(run_LIF_cond)) ``` ## Interactive Demo: Correlated spike input to an LIF neuron In the following you can explore what happens when the neurons receive correlated spiking input. You can vary the correlation between excitatory input spike trains. For simplicity, the correlation between inhibitory spike trains is set to 0.01. Vary both excitatory rate and correlation and see how the output correlation changes. Check if the results are qualitatively similar to what you observed previously when you varied the $\mu$ and $\sigma$. ``` # @title # @markdown Make sure you execute this cell to enable the widget! my_layout.width = '450px' @widgets.interact( pwc_ee=widgets.FloatSlider(0.3, min=0.05, max=0.99, step=0.01, layout=my_layout), exc_rate=widgets.FloatSlider(1e3, min=500., max=5e3, step=50., layout=my_layout), inh_rate=widgets.FloatSlider(500., min=300., max=5e3, step=5., layout=my_layout), ) def EI_isi_regularity(pwc_ee, exc_rate, inh_rate): pars = default_pars(T=1000.) # Add parameters pars['V_th'] = -55. # spike threshold [mV] pars['V_reset'] = -75. # reset potential [mV] pars['tau_m'] = 10. # membrane time constant [ms] pars['g_L'] = 10. # leak conductance [nS] pars['V_init'] = -65. # initial potential [mV] pars['E_L'] = -75. # leak reversal potential [mV] pars['tref'] = 2. # refractory time (ms) pars['gE_bar'] = 4.0 # [nS] pars['VE'] = 0. # [mV] excitatory reversal potential pars['tau_syn_E'] = 2. # [ms] pars['gI_bar'] = 2.4 # [nS] pars['VI'] = -80. # [mV] inhibitory reversal potential pars['tau_syn_I'] = 5. # [ms] my_bin = np.arange(0, pars['T']+pars['dt'], .1) # 20 [ms] bin-size # exc_rate = 1e3 # inh_rate = 0.4e3 # pwc_ee = 0.3 pwc_ii = 0.01 # generate two correlated spike trains for excitatory input sp1e, sp2e = generate_corr_Poisson(pars, exc_rate, pwc_ee) sp1_spike_train_ex, _ = np.histogram(sp1e, bins=my_bin) sp2_spike_train_ex, _ = np.histogram(sp2e, bins=my_bin) # generate two uncorrelated spike trains for inhibitory input sp1i, sp2i = generate_corr_Poisson(pars, inh_rate, pwc_ii) sp1_spike_train_in, _ = np.histogram(sp1i, bins=my_bin) sp2_spike_train_in, _ = np.histogram(sp2i, bins=my_bin) v1, rec_spikes1, gE, gI = run_LIF_cond(pars, 0, sp1_spike_train_ex, sp1_spike_train_in) v2, rec_spikes2, gE, gI = run_LIF_cond(pars, 0, sp2_spike_train_ex, sp2_spike_train_in) # bin the spike time bin_size = 20 # [ms] my_bin = np.arange(0, pars['T'], bin_size) spk_1, _ = np.histogram(rec_spikes1, bins=my_bin) spk_2, _ = np.histogram(rec_spikes2, bins=my_bin) r12 = my_CC(spk_1, spk_2) print(f"Input correlation = {pwc_ee}") print(f"Output correlation = {r12}") plt.figure(figsize=(14, 7)) plt.subplot(211) plt.plot(sp1e, np.ones(len(sp1e)) * 1, '|', ms=20, label='Exc. input 1') plt.plot(sp2e, np.ones(len(sp2e)) * 1.1, '|', ms=20, label='Exc. input 2') plt.plot(sp1i, np.ones(len(sp1i)) * 1.3, '|k', ms=20, label='Inh. input 1') plt.plot(sp2i, np.ones(len(sp2i)) * 1.4, '|k', ms=20, label='Inh. input 2') plt.ylim(0.9, 1.5) plt.legend() plt.ylabel('neuron id.') plt.subplot(212) plt.plot(pars['range_t'], v1, label='neuron 1') plt.plot(pars['range_t'], v2, label='neuron 2') plt.xlabel('time (ms)') plt.ylabel('membrane voltage $V_{m}$') plt.tight_layout() plt.show() ``` Above, we are estimating the output correlation for one trial. You can modify the code to get a trial average of output correlations. --- # Bonus 2: Ensemble Response Finally, there is a short BONUS lecture video on the firing response of an ensemble of neurons to time-varying input. There are no associated coding exercises - just enjoy. ``` #@title Video 2 (Bonus): Response of ensemble of neurons to time-varying input from IPython.display import YouTubeVideo video = YouTubeVideo(id="78_dWa4VOIo", width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video ```
github_jupyter
# Number of Simulations by Team This notebook explores the number of simulations that were done by team and grouped by their experimental condition. ``` import sys import os.path sys.path.append("../CommonModules") # go to parent dir/CommonModules import Learning2019GTL.Globals as Globals import Learning2019GTL.DataConnector as DataConnector data_map = Globals.FileNameMaps() TEAM_MAP = dict([[v,k] for k,v in data_map.CSV_MAP.items()]) DATA_FILE = os.path.expanduser("~/Learning2019Data/PostProcessingResults/TeamNumSimulationsByFile.csv") import csv import numpy as np conditions = ['A - control (discuss conference) at beginning', 'B - strategy at beginning', 'D - strategy at mid'] uniqueSimsA = [] uniqueSimsB =[] uniqueSimsD =[] totSimsA = [] totSimsB =[] totSimsD =[] with open(DATA_FILE, 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: team_file = row['File'] team_str = TEAM_MAP[team_file] t = DataConnector.Team() condition = t.getCondition(team_str)[0] #print(row) #print(condition) if condition == 'A': uniqueSimsA.append(int(row[' UniqueSims'])) totSimsA.append(int(row[' TotalSims'])) elif condition == 'B': uniqueSimsB.append(int(row[' UniqueSims'])) totSimsB.append(int(row[' TotalSims'])) elif condition == 'D': uniqueSimsD.append(int(row[' UniqueSims'])) totSimsD.append(int(row[' TotalSims'])) %matplotlib inline import matplotlib import matplotlib.pyplot as plt font = {'family' : 'DejaVu Sans', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) golden_ratio = np.array([1.61803398875, 1]) plt.figure(figsize=golden_ratio*8) uniqueSimsA = np.array(uniqueSimsA) uniqueSimsB = np.array(uniqueSimsB) uniqueSimsD = np.array(uniqueSimsD) plt.hist(uniqueSimsA-1/6, bins=np.arange(0, 18, 1/6), density=False) plt.hist(uniqueSimsB+0/6, bins=np.arange(0, 18, 1/6), density=False) plt.hist(uniqueSimsD+1/6, bins=np.arange(0, 18, 1/6), density=False) plt.xlim([0, 18]) plt.legend(conditions, fontsize=12, loc=2) plt.ylabel('Number of Teams') plt.xlabel('Number of Unique Simulations') plt.show() print(max(uniqueSimsA)) print(max(uniqueSimsB)) print(max(uniqueSimsD)) print(len(uniqueSimsA)) print(len(uniqueSimsB)) print(len(uniqueSimsD)) DATA_FILE = os.path.expanduser("~/Learning2019Data/PostProcessingResults/ParetoRankingByFile.csv") paretoRanksA = [] paretoRanksB = [] paretoRanksD = [] def getPRank(row): rank = -1 for p in range(17): key = f'P{p}' if int(row[key]) > 0: rank = p break return rank with open(DATA_FILE, 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: team_file = row['File'] team_str = TEAM_MAP[team_file] t = DataConnector.Team() condition = t.getCondition(team_str)[0] rank = getPRank(row) print(f'{row["File"]}: {rank}, {condition}') #print(condition) if condition == 'A': paretoRanksA.append(rank) elif condition == 'B': paretoRanksB.append(rank) elif condition == 'D': paretoRanksD.append(rank) paretoRanksA = np.array(paretoRanksA) + 1 paretoRanksB = np.array(paretoRanksB) + 1 paretoRanksD = np.array(paretoRanksD) + 1 %matplotlib inline import matplotlib import matplotlib.pyplot as plt font = {'family' : 'DejaVu Sans', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) golden_ratio = np.array([1.61803398875, 1]) plt.figure(figsize=golden_ratio*8) plt.hist(paretoRanksA-1/6, bins=np.arange(0, 6, 1/6), align='left') plt.hist(paretoRanksB+0/6, bins=np.arange(0, 6, 1/6), align='left') plt.hist(paretoRanksD+1/6, bins=np.arange(0, 6, 1/6), align='left') plt.xticks(np.arange(1, 6)) plt.xlabel('Rank') plt.ylabel('Number of Teams') plt.legend(conditions, loc=1, fontsize=15) plt.title('Pareto Ranks (using one or more solutions to be the same rank)', fontsize=20) plt.show() print(conditions[0], paretoRanksA) print(conditions[1], paretoRanksB) print(conditions[2], paretoRanksD) DATA_FILE = os.path.expanduser("~/Learning2019Data/PostProcessingResults/ParetoRankingByFile.csv") paretoRanksA = [] paretoRanksB = [] paretoRanksD = [] def getPRankWithNum(row): rank = -1 for p in range(17): key = f'P{p}' val = int(row[key]) if val > 0: rank = p + 1/(val + 1) break return rank with open(DATA_FILE, 'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: team_file = row['File'] team_str = TEAM_MAP[team_file] t = DataConnector.Team() condition = t.getCondition(team_str)[0] rank = getPRankWithNum(row) print(f'{row["File"]}: {rank}, {condition}') #print(condition) if condition == 'A': paretoRanksA.append(rank) elif condition == 'B': paretoRanksB.append(rank) elif condition == 'D': paretoRanksD.append(rank) print("Before ordinal rank") allData = paretoRanksA + paretoRanksB + paretoRanksD print(allData) print(conditions[0], len(paretoRanksA), paretoRanksA) print(conditions[1], len(paretoRanksB), paretoRanksB) print(conditions[2], len(paretoRanksD), paretoRanksD) import scipy.stats rankedData = scipy.stats.rankdata(allData, method='dense') paretoRanksA = rankedData[0:len(paretoRanksA)] paretoRanksB = rankedData[len(paretoRanksA):len(paretoRanksA)+len(paretoRanksB)] paretoRanksD = rankedData[len(paretoRanksA)+len(paretoRanksB):] print("After ordinal rank") print(rankedData) print(conditions[0], len(paretoRanksA), paretoRanksA) print(conditions[1], len(paretoRanksB), paretoRanksB) print(conditions[2], len(paretoRanksD), paretoRanksD) %matplotlib inline import matplotlib.pyplot as plt font = {'family' : 'DejaVu Sans', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) golden_ratio = np.array([1.61803398875, 1]) plt.figure(figsize=golden_ratio*8) plt.hist(paretoRanksA-1/6, bins=np.arange(0, 12, 1/6), align='left') plt.hist(paretoRanksB+0/6, bins=np.arange(0, 12, 1/6), align='left') plt.hist(paretoRanksD+1/6, bins=np.arange(0, 12, 1/6), align='left') plt.xticks(np.arange(1, 12)) plt.xlabel('Rank (lower is better)') plt.ylabel('Number of Teams') plt.legend(conditions, loc=1, fontsize=15) plt.title('Pareto Ranks (using multiple solutions for ranking)', fontsize=15) plt.show() %matplotlib inline import matplotlib.pyplot as plt font = {'family' : 'DejaVu Sans', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) golden_ratio = np.array([1.61803398875, 1]) plt.figure(figsize=golden_ratio*8) plt.hist(paretoRanksA-1/6, bins=np.arange(0, 12, 1/6), align='left', density=True) plt.hist(paretoRanksB+0/6, bins=np.arange(0, 12, 1/6), align='left', density=True) plt.hist(paretoRanksD+1/6, bins=np.arange(0, 12, 1/6), align='left', density=True) plt.xticks(np.arange(1, 12)) plt.xlabel('Rank (lower is better)') plt.ylabel('Probability Density') plt.legend(conditions, loc=1, fontsize=15) plt.title('Pareto Ranks (multiple solutions at Pareto front ranked better)', fontsize=22) plt.show() print(f'{conditions[0]}\n(mean, std) = ({np.mean(paretoRanksA)}, {np.std(paretoRanksA)})\n') print(f'{conditions[1]}\n(mean, std) = ({np.mean(paretoRanksB)}, {np.std(paretoRanksB)})\n') print(f'{conditions[2]}\n(mean, std) = ({np.mean(paretoRanksD)}, {np.std(paretoRanksD)})\n') paretoRanksBD = np.append(paretoRanksB, paretoRanksD) print(f'{conditions[1]}, {conditions[2]}\n(mean, std) = ({np.mean(paretoRanksBD)}, {np.std(paretoRanksBD)})\n') t2, p2 = scipy.stats.ttest_ind(paretoRanksA,paretoRanksB) print("t = " + str(t2)) print("p = " + str(p2)) t2, p2 = scipy.stats.ttest_ind(paretoRanksA,paretoRanksD) print("t = " + str(t2)) print("p = " + str(p2)) t2, p2 = scipy.stats.ttest_ind(paretoRanksB,paretoRanksD) print("t = " + str(t2)) print("p = " + str(p2)) t2, p2 = scipy.stats.ttest_ind(paretoRanksA,paretoRanksBD) print("t = " + str(t2)) print("p = " + str(p2)) ```
github_jupyter
``` #@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. ``` # CNN (Convolutional) EncoderDecoder ## Installations ``` # requirements = """ # tensorflow # drawSvg # matplotlib # numpy # scipy # pillow # #urllib # #skimage # scikit-image # #gzip # #pickle # """ # %store requirements > requirements.txt # !pip install -r requirements.txt ``` ## Import TensorFlow and other libraries ``` from __future__ import absolute_import, division, print_function, unicode_literals # !pip install tensorflow-gpu==2.0.0-alpha0 import tensorflow as tf import os import time import matplotlib.pyplot as plt from IPython.display import clear_output import os from tensorflow.keras.preprocessing.image import img_to_array, load_img from random import shuffle import PIL import json import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) import matplotlib.pyplot as plt import matplotlib # matplotlib.use('TKAgg') %matplotlib inline ``` ## Load the dataset Steps to generate URL used below: - Say, your data files are in the directory called 'input' - Manually create a zip file, 'input.zip' - Sync it to gDrive - In gDrive, Share it with Public model, copy its share-able link - Use https://sites.google.com/site/gdocs2direct/ to generate corresponding Direct link - Paste it below ``` # _URL = 'https://drive.google.com/uc?export=download&id=16rqDFLO__WySSQGlAht0FEj2uJZg4M9M' # path_to_zip = tf.keras.utils.get_file('input.zip', # origin=_URL, # extract=True) # input_data_folder = os.path.join(os.path.dirname(path_to_zip), 'input') input_data_folder = "D:/Yogesh/ToDos/Research/MidcurveNN/code/data/input" def read_input_image_pairs(datafolder=input_data_folder): profile_pngs = [] midcurve_pngs = [] for file in os.listdir(datafolder): fullpath = os.path.join(datafolder, file) if os.path.isdir(fullpath): continue if file.endswith(".png"): if file.find("Profile") != -1: profile_pngs.append(fullpath) if file.find("Midcurve") != -1: midcurve_pngs.append(fullpath) profile_pngs = sorted(profile_pngs) midcurve_pngs = sorted(midcurve_pngs) return profile_pngs,midcurve_pngs def get_training_data(datafolder = input_data_folder): profile_pngs,midcurve_pngs = read_input_image_pairs(datafolder) profile_pngs_objs = [img_to_array(load_img(f, color_mode='rgba', target_size=(100, 100))) for f in profile_pngs ] midcurve_pngs_objs = [img_to_array(load_img(f, color_mode='rgba', target_size=(100, 100))) for f in midcurve_pngs] # profile_pngs_objs = np.array([x.reshape((1,) + x.shape) for x in profile_pngs_objs]) # midcurve_pngs_objs = np.array([x.reshape((1,) + x.shape) for x in midcurve_pngs_objs]) profile_pngs_gray_objs = [x[:,:,3] for x in profile_pngs_objs] midcurve_pngs_gray_objs =[x[:,:,3] for x in midcurve_pngs_objs] # profile_pngs_gray_objs = [np.where(x>128, 0, 1) for x in profile_pngs_gray_objs] # midcurve_pngs_gray_objs =[np.where(x>128, 0, 1) for x in midcurve_pngs_gray_objs] # shufle them zipped_profiles_midcurves = [(p,m) for p,m in zip(profile_pngs_gray_objs,midcurve_pngs_gray_objs)] shuffle(zipped_profiles_midcurves) profile_pngs_gray_objs, midcurve_pngs_gray_objs = zip(*zipped_profiles_midcurves) return profile_pngs_gray_objs, midcurve_pngs_gray_objs profile_pngs_objs, midcurve_pngs_objs = get_training_data() def plot_results(original_imgs,computed_imgs): n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(original_imgs[i].reshape(100, 100),cmap='gray_r') # plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) plt.imshow(computed_imgs[i].reshape(100, 100),cmap='gray_r') # plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() plot_results(profile_pngs_objs,midcurve_pngs_objs) from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model from tensorflow.keras import regularizers import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) def build_cnn_autoencoder_model(profile_pngs_gray_objs, midcurve_pngs_gray_objs,encoding_dim = 100, input_dim = 100): input_img = Input(shape=(input_dim, input_dim, 1)) # adapt this if using `channels_first` image data format 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 1: Full AutoEncoder, includes both encoder single dense layer and decoder single dense layer. # This model maps an input to its reconstruction autoencoder = Model(input_img, decoded) # Compilation of Autoencoder (only) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') # Training profile_pngs_flat_objs = [x.reshape(input_dim,input_dim,1) for x in profile_pngs_gray_objs] midcurve_pngs_flat_objs = [x.reshape(input_dim,input_dim,1) for x in midcurve_pngs_gray_objs] profile_pngs_objs = np.array(profile_pngs_flat_objs) midcurve_pngs_objs= np.array(midcurve_pngs_flat_objs) train_size = int(len(profile_pngs_objs)*0.7) x_train = profile_pngs_objs[:train_size] y_train = midcurve_pngs_objs[:train_size] x_test = profile_pngs_objs[train_size:] y_test = midcurve_pngs_objs[train_size:] autoencoder.fit(x_train, y_train, epochs=50, batch_size=5, shuffle=True, validation_data=(x_test, y_test)) encoded_imgs = autoencoder.predict(x_test) decoded_imgs = autoencoder.predict(encoded_imgs) return x_test,decoded_imgs original_imgs,decoded_imgs = build_cnn_autoencoder_model(profile_pngs_objs, midcurve_pngs_objs) plot_results(original_imgs,decoded_imgs) ```
github_jupyter
# LSTM Stock Predictor Using Closing Prices In this notebook, you will build and train a custom LSTM RNN that uses a 10 day window of Bitcoin closing prices to predict the 11th day closing price. You will need to: 1. Prepare the data for training and testing 2. Build and train a custom LSTM RNN 3. Evaluate the performance of the model ## Data Preparation In this section, you will need to prepare the training and testing data for the model. The model will use a rolling 10 day window to predict the 11th day closing price. You will need to: 1. Use the `window_data` function to generate the X and y values for the model. 2. Split the data into 70% training and 30% testing 3. Apply the MinMaxScaler to the X and y values 4. Reshape the X_train and X_test data for the model. Note: The required input format for the LSTM is: ```python reshape((X_train.shape[0], X_train.shape[1], 1)) ``` ``` import numpy as np import pandas as pd import hvplot.pandas # Set the random seed for reproducibility # Note: This is for the homework solution, but it is good practice to comment this out and run multiple experiments to evaluate your model from numpy.random import seed seed(1) from tensorflow import random random.set_seed(2) # Load the fear and greed sentiment data for Bitcoin df = pd.read_csv('btc_sentiment.csv', index_col="date", infer_datetime_format=True, parse_dates=True) df = df.drop(columns="fng_classification") df.head() # Load the historical closing prices for Bitcoin df2 = pd.read_csv('btc_historic.csv', index_col="Date", infer_datetime_format=True, parse_dates=True)['Close'] df2 = df2.sort_index() df2.tail() # Join the data into a single DataFrame df = df.join(df2, how="inner") df.tail() df.head() # This function accepts the column number for the features (X) and the target (y) # It chunks the data up with a rolling window of Xt-n to predict Xt # It returns a numpy array of X any y def window_data(df, window, feature_col_number, target_col_number): X = [] y = [] for i in range(len(df) - window - 1): features = df.iloc[i:(i + window), feature_col_number] target = df.iloc[(i + window), target_col_number] X.append(features) y.append(target) return np.array(X), np.array(y).reshape(-1, 1) # Predict Closing Prices using a 10 day window of previous closing prices # Then, experiment with window sizes anywhere from 1 to 10 and see how the model performance changes window_size = 10 # Column index 0 is the 'fng_value' column # Column index 1 is the `Close` column feature_column = 1 target_column = 1 X, y = window_data(df, window_size, feature_column, target_column) # Use 70% of the data for training and the remaineder for testing split = int(0.7 * len(X)) X_train = X[: split -1] X_test = X[split:] y_train = y[: split -1] y_test = y[split:] from sklearn.preprocessing import MinMaxScaler # Use the MinMaxScaler to scale data between 0 and 1. scaler = MinMaxScaler() scaler.fit(X) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) scaler.fit(y) y_train = scaler.transform(y_train) y_test = scaler.transform(y_test) # Reshape the features for the model X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1)) print(f"X_train sample values:\n{X_train[:5]} \n") print(f"X_test sample values:\n{X_test[:5]}") ``` --- ## Build and Train the LSTM RNN In this section, you will design a custom LSTM RNN and fit (train) it using the training data. You will need to: 1. Define the model architecture 2. Compile the model 3. Fit the model to the training data ### Hints: You will want to use the same model architecture and random seed for both notebooks. This is necessary to accurately compare the performance of the FNG model vs the closing price model. ``` from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout # Build the LSTM model. # The return sequences need to be set to True if you are adding additional LSTM layers, but # You don't have to do this for the final layer. # Note: The dropouts help prevent overfitting # Note: The input shape is the number of time steps and the number of indicators # Note: Batching inputs has a different input shape of Samples/TimeSteps/Features model = Sequential() number_units = 30 dropout_fraction = 0.2 #1 model.add(LSTM( units=number_units, return_sequences=True, input_shape=(X_train.shape[1], 1)) ) model.add(Dropout(dropout_fraction)) #2 model.add(LSTM(units=number_units, return_sequences=True)) model.add(Dropout(dropout_fraction)) #3 model.add(LSTM(units=number_units)) model.add(Dropout(dropout_fraction)) # Output model.add(Dense(1)) # Compile the model model.compile(optimizer="adam", loss="mean_squared_error") # Summarize the model model.summary() # Train the model # Use at least 10 epochs # Do not shuffle the data # Experiement with the batch size, but a smaller batch size is recommended model.fit(X_train, y_train, epochs=10, shuffle=False, batch_size=1000, verbose=1) ``` --- ## Model Performance In this section, you will evaluate the model using the test data. You will need to: 1. Evaluate the model using the `X_test` and `y_test` data. 2. Use the X_test data to make predictions 3. Create a DataFrame of Real (y_test) vs predicted values. 4. Plot the Real vs predicted values as a line chart ### Hints Remember to apply the `inverse_transform` function to the predicted and y_test values to recover the actual closing prices. ``` # Evaluate the model model.evaluate(X_test, y_test) # Make some predictions predicted = model.predict(X_test) # Recover the original prices instead of the scaled version predicted_prices = scaler.inverse_transform(predicted) real_prices = scaler.inverse_transform(y_test.reshape(-1, 1)) # Create a DataFrame of Real and Predicted values stocks = pd.DataFrame({ "Real": real_prices.ravel(), "Predicted": predicted_prices.ravel() }, index = df.index[-len(real_prices): ]) stocks.head() # Plot the real vs predicted values as a line chart stocks.plot() ``` Which model has a lower loss? - Closing Prices Which model tracks the actual values better over time? - Closing Prices Which window size works best for the model? - As the window size increased, the predicted values more closely matched the real values. Since we only tested 1-10, the window size of 10 was the best fit for the model.
github_jupyter
# 1. Loading and organizing data ``` # loading datasets import pandas as pd # Vertebral Column # dataset for classification between Normal (NO) and Abnormal (AB) vc2c = pd.read_csv('vertebral_column_data/column_2C.dat', delim_whitespace=True, header=None) # dataset for classification between DH (Disk Hernia), Spondylolisthesis (SL) and Normal (NO) vc3c = pd.read_csv('vertebral_column_data/column_3C.dat', delim_whitespace=True, header=None) # Wall-Following # dataset with all 24 ultrassound sensors readings wf24f = pd.read_csv('wall_following_data/sensor_readings_24.data', header=None) # dataset with simplified 4 readings (front, left, right and back) wf4f = pd.read_csv('wall_following_data/sensor_readings_4.data', header=None) # dataset with simplified 2 readings (front and left) wf2f = pd.read_csv('wall_following_data/sensor_readings_2.data', header=None) # Parkinson (31 people, 23 with Parkinson's disease (PD)) temp = pd.read_csv('parkinson_data/parkinsons.data') labels = temp.columns.values.tolist() new_labels = [label for label in labels if label not in ('name')] # taking off column 'name' pk = temp[new_labels] pk_features = pk.columns.tolist() pk_features.remove('status') # datasets with separation between 'features' and 'labels' datasets = { "vc2c": {"features": vc2c.iloc[:,0:6], "labels": pd.get_dummies(vc2c.iloc[:,6], drop_first=True)}, "vc3c": {"features": vc3c.iloc[:,0:6], "labels": pd.get_dummies(vc3c.iloc[:,6], drop_first=True)}, "wf24f": {"features": wf24f.iloc[:,0:24],"labels": pd.get_dummies(wf24f.iloc[:,24],drop_first=True)}, "wf4f": {"features": wf4f.iloc[:,0:4], "labels": pd.get_dummies(wf4f.iloc[:,4], drop_first=True)}, "wf2f": {"features": wf2f.iloc[:,0:2], "labels": pd.get_dummies(wf2f.iloc[:,2], drop_first=True)}, "pk": {"features": pk.loc[:,pk_features], "labels": pk.loc[:,["status"]]} } for dataset in datasets: print("Dataset name: {}\nNumber of features: {}\nNumber of samples: {}\n".format( dataset, datasets[dataset]["features"].shape[1], datasets[dataset]["features"].shape[0] )) # Auxiliary function to tell when processing is over def is_over(): # linux os import os os.system('spd-say "your program has finished"') ``` # 2. SOM studies ``` # importing old som %run -i 'som.py' import cupy as cp # New SOM import numpy as np import plotly.offline as plt import plotly.graph_objs as go from random import randint import ipywidgets as widgets from IPython.display import clear_output from plotly import tools from multiprocessing import Pool plt.init_notebook_mode(connected=True) # enabling plotly inside jupyter notebook class SOM: 'Class of Self Organizing Maps conected in a two-dimensional grid.' def __init__(self, nRows, nColumns): self.nRows = nRows self.nColumns = nColumns self.__epochs = 0 # number of epochs of trained SOM self.neurons = None self.indexes = None # list of index2D <=> index1D self.neuronsHist = None self.ssdHist = None def init(self, X): # giving the data, so we can define maximum and minimum in each dimension # reset neuronsHist and ssdHist self.neuronsHist = None self.ssdHist = None dim = X.shape[1] # number of features rand = np.random.rand(self.nRows*self.nColumns, dim) # Auxiliary random element # find min-max for each dimension minimum = np.amin(X, axis=0) maximum = np.amax(X, axis=0) # Initializing neurons in random positions between minimum and maximum of the dataset self.neurons = (maximum - minimum)*rand + minimum # list of index2D == index1D self.indexes = self.index1Dto2D(np.arange(len(self.neurons))) def fit(self, X, alpha0, sigma0, nEpochs=100, saveNeuronsHist=False, saveSSDHist=True, tol=1e-6, verboses=0, batchSize=np.inf): if self.neurons is None: self.init(X) # if self.init() wasn't run tau1 = nEpochs/sigma0 tau2 = nEpochs SSD_new = self.SSD(X) # initial SSD, from random parameters if saveNeuronsHist: self.neuronsHist = [np.zeros(self.neurons.shape)]*(nEpochs+1) self.neuronsHist[0] = np.copy(self.neurons) # random neurons if saveSSDHist: self.ssdHist = np.zeros((nEpochs+1)) self.ssdHist[0] = SSD_new # initial SSD, from random parameters sigma = sigma0 alpha = alpha0 inertia = np.inf # initial value of inertia batchSize = min(len(X), batchSize) # adjusting ill defined batchSize for epoch in range(nEpochs): # Updating alpha and sigma sigma = sigma0*np.exp(-epoch/tau1); alpha = alpha0*np.exp(-epoch/tau2); order = np.random.permutation(len(X)) # shuffling order for i in order[:batchSize]: # for each datapoint in the shuflled order until batchSize # search for winner neuron winner_idx = self.get_winner(X[i]) # neighbor function h_ik = self.h_neighbor(winner_idx, self.indexes, sigma) # updating neurons self.neurons += (h_ik[:, np.newaxis]*(X[i] - self.neurons))*alpha self.__epochs+=1 # updating number of epochs trained if verboses==1: print("End of epoch {}".format(epoch+1)) SSD_old = SSD_new SSD_new = self.SSD(X) inertia = abs((SSD_old - SSD_new)/SSD_old) # Saving if necessary if saveNeuronsHist: self.neuronsHist[epoch+1] = np.copy(self.neurons) if saveSSDHist: self.ssdHist[epoch+1] = SSD_new # breaking if tolerance reached before nEpochs if inertia < tol: # history cutting if saveNeuronsHist: self.neuronsHist = self.neuronsHist[0:epoch+2] if saveSSDHist: self.ssdHist = self.ssdHist[0:epoch+2] break def SSD(self, X): SSD = 0 for x in X: # can it be vectorized? dist_2 = np.sum((self.neurons - x)**2, axis=1) # norm**2 SSD += np.amin(dist_2) return SSD def index1Dto2D(self, index): # convert index of neurons parameter matrix to the 2D grid index return np.asarray([np.ceil((index+1)/self.nRows)-1, index%self.nRows], dtype='int').T def get_winner(self, x, dim=2): dist_2 = np.sum((self.neurons - x)**2, axis=1) # norm**2 temp = np.argmin(dist_2) winner = self.index1Dto2D(temp) if dim==2 else temp return winner def h_neighbor(self, idx_1, idx_2, sigma): dist_2 = np.sum((idx_2 - idx_1)**2, axis=1) # norm**2 return np.exp( -dist_2/(2*sigma**2) ) def getLabels(self, X, dim=1): # get labels in 1 dimension or 2 dimension (neuron grid) N = len(X) labels = np.zeros((N,dim), dtype='int') for i in range(N): labels[i,:] = self.get_winner(X[i,:],dim) return labels def plotSSD(self): traceData = go.Scatter( x = [i+1 for i in range(self.__epochs)], # epochs y = self.ssdHist, mode='lines', name='SSD') data = [traceData] layoutData = go.Layout( title = "SSD history", xaxis=dict(title='Epoch'), yaxis=dict(title='SSD') ) fig = go.Figure(data=data, layout=layoutData) plt.iplot(fig) def plotSOM(self, X=None): if self.neuronsHist is not None: # Int box to change the iteration number n_txt = widgets.BoundedIntText( value=0, min=0, max=len(self.neuronsHist)-1, step=10, description='epoch:' ) ############################################################### # Function to draw the graph def upgradeChart(change): clear_output() if self.neuronsHist is not None: display(n_txt) n_ = change['new'] # new iteration number if self.neuronsHist is not None: x = self.neuronsHist[n_][:,0].tolist() y = self.neuronsHist[n_][:,1].tolist() name = 'neurons [epoch ='+str(n_)+']' else: x = self.neurons[:,0].tolist() y = self.neurons[:,1].tolist() name = 'neurons' neurons = go.Scatter(x=x, y=y, mode='markers', name=name, marker = dict(size=10,color = '#673AB7')) # cada linha que conecta os neurônios linhas = [{}]*(2*self.nRows*self.nColumns - self.nRows - self.nColumns) count=0 #contador para saber qual linha estamos for linha in range(self.nRows): # conecta da esquerda para direita for coluna in range(self.nColumns): # e de cima para baixo try: if self.neuronsHist is not None: x0 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna)).all(axis=1))[0][0], 0] y0 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna)).all(axis=1))[0][0], 1] x1 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna+1)).all(axis=1))[0][0], 0] y1 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna+1)).all(axis=1))[0][0], 1] else: x0 = self.neurons[np.where((self.indexes==(linha,coluna)).all(axis=1))[0][0], 0] y0 = self.neurons[np.where((self.indexes==(linha,coluna)).all(axis=1))[0][0], 1] x1 = self.neurons[np.where((self.indexes==(linha,coluna+1)).all(axis=1))[0][0], 0] y1 = self.neurons[np.where((self.indexes==(linha,coluna+1)).all(axis=1))[0][0], 1] linhas[count]= {'type':'line','x0':x0,'y0': y0,'x1':x1,'y1':y1, 'line': {'color': '#673AB7','width': 1,}} count+=1 except: # edge of the grid pass try: if self.neuronsHist is not None: x0 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna)).all(axis=1))[0][0], 0] y0 = self.neuronsHist[n_][np.where( (self.indexes==(linha, coluna)).all(axis=1))[0][0], 1] x1 = self.neuronsHist[n_][np.where( (self.indexes==(linha+1, coluna)).all(axis=1))[0][0], 0] y1 = self.neuronsHist[n_][np.where( (self.indexes==(linha+1, coluna)).all(axis=1))[0][0], 1] else: x0 = self.neurons[np.where((self.indexes==(linha,coluna)).all(axis=1))[0][0], 0] y0 = self.neurons[np.where((self.indexes==(linha,coluna)).all(axis=1))[0][0], 1] x1 = self.neurons[np.where((self.indexes==(linha+1,coluna)).all(axis=1))[0][0], 0] y1 = self.neurons[np.where((self.indexes==(linha+1,coluna)).all(axis=1))[0][0], 1] linhas[count] = {'type': 'line','x0': x0,'y0': y0,'x1': x1,'y1': y1, 'line': {'color': '#673AB7','width': 1}} count+=1 except: # edge of the grid pass data = [] title = "" if X is not None: datapoints = go.Scatter(x = X[:,0], y = X[:,1], mode='markers', name='data', marker = dict(size = 5,color = '#03A9F4')) data = [datapoints, neurons] title = "Data + SOM" else: data = [neurons] title = "SOM" layout = go.Layout(title=title, xaxis=dict(title="$x_1$"), yaxis=dict(title="$x_2$"), shapes=linhas) fig = go.Figure(data=data, layout=layout) plt.iplot(fig) ########################################################################### if self.neuronsHist is not None: n_txt.observe(upgradeChart, names='value') upgradeChart({'new': 0}) ``` # Testing consistency ``` import cupy as cp x = cp.arange(6).reshape(2, 3).astype('f') print(x) print(x.sum(axis=1)) ``` ### SSD curves for parkinson dataset: ``` %%time from math import ceil # choosing and preparing dataset dataset_name='pk' data = datasets[dataset_name] N = len(data['features'].index) # number of datapoints l = ceil((5*N**.5)**.5) # tamanho do lado da grid quadrada de neurônios X = data['features'].values.copy() X1, X2 = scale_feat(X,X,scaleType='min-max') X=X1 params = { "X": X ,"alpha0": 0.1 ,"sigma0": 3 ,"nEpochs": 50 ,"verboses": 0 #,"saveNeuronsHist": True } som_old = SOM_2D(l, l, X.shape[1]); som_old.init(X) som_new = SOM(l, l) som_new.fit(**params) som_old.train(**params, batchSize=len(X)) print("SOM_new:"); som_new.plotSSD() print("SOM_old:"); som_old.plotSSD() print("SOM_old last SSD: {}\nSOM_new last SSD: {}".format(som_old.ssdHist[-1], som_new.ssdHist[-1])) ``` ### SSD curves and neurons evolution for Wall-Following data set: ``` %%time from math import ceil import datetime # choosing and preparing dataset dataset_name='wf2f' data = datasets[dataset_name] N = len(data['features'].index) # number of datapoints l = ceil((5*N**.5)**.5) # tamanho do lado da grid quadrada de neurônios X = data['features'].values.copy() X1, X2 = scale_feat(X,X,scaleType='min-max') X=X1 params = { "X": X ,"alpha0": 0.1 ,"sigma0": 3 ,"nEpochs": 100 ,"verboses": 1 #,"saveNeuronsHist": True } som_old = SOM_2D(l, l, X.shape[1]); som_old.init(X) som_new = SOM(l, l) print("SOM_old training started at {}".format(datetime.datetime.now())) som_old.train(**params, batchSize=len(X), saveParam=True) print("SOM_new training started at {}".format(datetime.datetime.now())) som_new.fit(**params,saveNeuronsHist=True) # nEpochs = 10 # Wall time: 1min 17s print( som_new.ssdHist[-1]/som_old.ssdHist[-1] ) print("SOM_old:") som_old.plotSSD() print("SOM_new:") som_new.plotSSD() ``` ## Performance comparison with old SOM: ``` %%time import time import datetime from math import ceil # choosing and preparing dataset dataset_name='pk' data = datasets[dataset_name] N = len(data['features'].index) # number of datapoints l = ceil((5*N**.5)**.5) # tamanho do lado da grid quadrada de neurônios X = data['features'].values.copy() X1, X2 = scale_feat(X,X,scaleType='min-max') X=X1 n = 100 params = { "X": X ,"alpha0": 0.1 ,"sigma0": 3 ,"nEpochs": 5 ,"verboses": 0 #,"saveNeuronsHist": False } som_old = SOM_2D(l, l, X.shape[1]); som_old.init(X) som_new = SOM(l, l) print("n={}".format(n)) t0 = time.time() for i in range(n): som_old.train(**params, batchSize=len(X)); t1 = time.time() total_old = (t1-t0)/n print("som_old finished at {}".format(datetime.datetime.now())) t0 = time.time() for i in range(n): som_new.fit(**params) t1 = time.time() total_new = (t1-t0)/n print("som_new finished at {}".format(datetime.datetime.now())) print("\nOld SOM time: {}\nNew SOM time: {}\n".format(total_old,total_new)) print("New SOM {}x faster.\n".format(total_old/total_new)) is_over() ```
github_jupyter
``` import numpy as np from scipy import fft from scipy.io import loadmat import matplotlib.pyplot as plt whale = loadmat('whale.mat',squeeze_me=True,struct_as_record=True) ``` ## 绘制信号时域和频域波形 ``` whale_data = whale['w'] whale_fs = whale['fs'] t = np.arange(0,len(whale_data)/whale_fs,1/whale_fs) whale_num = len(whale_data) whale_fftnum = np.power(2,(np.ceil(np.log2(whale_num)))) whale_spec = np.abs(fft.fft(whale_data,int(whale_fftnum))) whale_power = 20*np.log10(whale_spec/np.max(whale_spec)) whale_freq = (np.arange(whale_fftnum)/whale_fftnum*whale_fs) import seaborn as sns sns.set(style = 'darkgrid') fig,axs = plt.subplots(2,1,constrained_layout=True) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False #用来显示负号 axs[0].plot(t,whale_data);axs[0].autoscale(tight=True) axs[0].set_xlabel('时间t/s') axs[1].plot(whale_freq[:int(np.floor(whale_fftnum/2)+1)],whale_power[:int(np.floor(whale_fftnum/2)+1)]) axs[1].set_xlabel('频率f/Hz');axs[1].set_ylabel('功率谱/dB') axs[1].autoscale(tight=True) ``` ## 对信号图形坐标缩放操作 ``` import ipywidgets as widgets from ipywidgets import interact,interact_manual from IPython.display import display def scalefunc(Time_Domain_xaxis,Time_Domain_yaxis,Spec_Domain_xaxis,Spec_Domain_yaxis,Time_Domain_Color,Spec_Domain_Color): fig,axs = plt.subplots(2,1,constrained_layout=True) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False #用来显示负号 axs[0].plot(t,whale_data,c=Time_Domain_Color);axs[0].autoscale(tight=True) axs[0].set_xlabel('时间t/s');axs[0].set_ylabel('幅度') t_xaxis = Time_Domain_xaxis;t_yaxis = Time_Domain_yaxis axs[0].set_xlim(t_xaxis[0],t_xaxis[1]);axs[0].set_ylim(t_yaxis[0],t_yaxis[1]) axs[1].plot(whale_freq[:int(np.floor(whale_fftnum/2)+1)],whale_power[:int(np.floor(whale_fftnum/2)+1)],c=Spec_Domain_Color) axs[1].autoscale(tight=True) axs[1].set_xlabel('频率f/Hz');axs[1].set_ylabel('功率谱/dB') s_xaxis = Spec_Domain_xaxis;s_yaxis = Spec_Domain_yaxis axs[1].set_xlim(s_xaxis[0],s_xaxis[1]);axs[1].set_ylim(s_yaxis[0],s_yaxis[1]) myplot = interact_manual(scalefunc, Time_Domain_xaxis=widgets.FloatRangeSlider(value=(np.min(t),np.max(t)),min=np.min(t),max=np.max(t),step=0.0001,description='Time Domain xaxis:'), Time_Domain_yaxis=widgets.FloatRangeSlider(value=(np.min(whale_data),np.max(whale_data)),min=np.min(whale_data),max=np.max(whale_data),step=0.0001,description='Time Domain yaxis:'), Spec_Domain_xaxis=widgets.FloatRangeSlider(value=(np.min(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),np.max(whale_freq[:int(np.floor(whale_fftnum/2)+1)])),min=np.min(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),max=np.max(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),step=1,description='Spec Domain xaxis:'), Spec_Domain_yaxis=widgets.FloatRangeSlider(value=(np.min(whale_power[:int(np.floor(whale_fftnum/2)+1)]),np.max(whale_power[:int(np.floor(whale_fftnum/2)+1)])),min=np.min(whale_power[:int(np.floor(whale_fftnum/2)+1)]),max=np.max(whale_power[:int(np.floor(whale_fftnum/2)+1)]),step=1,description='Spec Domain yaxis:'), Time_Domain_Color=widgets.Dropdown(options=['black','blue','coral','cyan','gold','pink','red','yellow','magenta'],value='black',description='Time Domain Color:'), Spec_Domain_Color=widgets.Dropdown(options=['black','blue','coral','cyan','gold','pink','red','yellow','magenta'],value='black',description='Spec Domain Color:')) ``` ## 对信号图形上某点的数值进行读取 ``` def datafunc(Time_Domain_xdata,Spec_Domain_xdata): fig,axs = plt.subplots(2,1,constrained_layout=True) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False #用来显示负号 axs[0].plot(t,whale_data,alpha=0.7);axs[0].autoscale(tight=True) axs[0].set_xlabel('时间t/s');axs[0].set_ylabel('幅度') require_x_time = np.around(Time_Domain_xdata*whale_fs)/whale_fs x_tloc = np.where(t==require_x_time);y_tval = whale_data[x_tloc] axs[0].text(x=require_x_time+0.05,y=y_tval[0]+0.05,s='%f,%f'%(require_x_time,y_tval[0]),fontdict=dict(fontsize=10, color='b',family='Times New Roman',weight='normal') ,bbox={'facecolor': 'w', #填充色 'edgecolor':'gray',#外框色 'alpha': 0.5, #框透明度 'pad': 1,#本文与框周围距离 }) axs[0].scatter(require_x_time,y_tval[0],marker='o',c='r',s=20) axs[1].plot(whale_freq[:int(np.floor(whale_fftnum/2)+1)],whale_power[:int(np.floor(whale_fftnum/2)+1)],alpha=0.7) axs[1].autoscale(tight=True) axs[1].set_xlabel('频率f/Hz');axs[1].set_ylabel('功率谱/dB') require_x_spec = np.around(Spec_Domain_xdata*whale_fftnum/whale_fs)*(1/whale_fftnum*whale_fs) x_sloc = np.where(whale_freq==require_x_spec);y_sval = whale_power[x_sloc] axs[1].text(x=require_x_spec-12,y=y_sval[0]-15,s='%f,%f'%(require_x_spec,y_sval[0]),fontdict=dict(fontsize=10, color='b',family='Times New Roman',weight='normal') ,bbox={'facecolor': 'w', #填充色 'edgecolor':'gray',#外框色 'alpha': 0.5, #框透明度 'pad': 1,#本文与框周围距离 }) axs[1].scatter(require_x_spec,y_sval[0],marker='o',c='r',s=20) myplot = interact_manual(datafunc, Time_Domain_xdata=widgets.FloatSlider(value=np.min(t),min=np.min(t),max=np.max(t),step=1/whale_fs,description='Time Domain xdata:'), Spec_Domain_xdata=widgets.FloatSlider(value=np.min(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),min=np.min(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),max=np.max(whale_freq[:int(np.floor(whale_fftnum/2)+1)]),step=1/whale_fftnum*whale_fs,description='Spec Domain xdata:')) ```
github_jupyter
## Telluric correction with `muler` and `gollum` Telluric correction can be complicated, with the right approach depending on one's own science application. In this notebook we demonstrate one uncontroversial, albeit imperfect approach: dividing by an observed A0V standard, and multiplying back by an A0V template. #### August 24, 2021: This method is under active development ``` %config InlineBackend.figure_format='retina' from muler.hpf import HPFSpectrum example_file = '../../data/HPF/Goldilocks_20210517T054403_v1.0_0060.spectra.fits' spectrum = HPFSpectrum(file=example_file, order=19) spectrum = spectrum.normalize().sky_subtract(method='vector').deblaze().normalize() ``` ### Retrieve and doctor the model with `gollum` `gollum` is a sister project to muler. While not a dependency, it has lots of parallel use cases and we hope you will install it too. It makes it easy to retrieve and manipulate theoretical models. Follow the instructions in gollum for downloading the raw high-resolution PHOENIX models. ``` from gollum.phoenix import PHOENIXSpectrum wl_lo, wl_hi = spectrum.wavelength.min().value*0.998, spectrum.wavelength.max().value*1.002 native_resolution_template = PHOENIXSpectrum(teff=9600, logg=4.5, path='~/libraries/raw/PHOENIX/', wl_lo=wl_lo, wl_hi=wl_hi).normalize() ax = spectrum.plot(ylo=0.0, yhi=1.5, label='Observed A0V') native_resolution_template.plot(ax=ax, label='Native resolution A0V template') ax.set_xlim(10_820, 10_960) ax.legend(); ``` The deep Hydrogen lines appear to have a different shape, since the A0V template is shown with near-infinite resolution. Let's "doctor the template" with rotational broadening. ``` A0V_model = native_resolution_template.rotationally_broaden(130.0) A0V_model = A0V_model.instrumental_broaden() # "just works" for HPF A0V_model = A0V_model.rv_shift(25.0) A0V_model = A0V_model.resample(spectrum) ax = spectrum.plot(ylo=0.0, yhi=1.5, label='Observed A0V') A0V_model.plot(ax=ax, label='Fine-tuned A0V model') ax.legend(); ``` Awesome! That's a better fit! Let's compute the ratio. ``` telluric_response = spectrum / A0V_model ax = telluric_response.plot(ylo=0); ax.axhline(1.0, linestyle='dotted', color='k'); ``` We see that the telluric response exhibits sharp discrete lines from the atmosphere. The spectrum also exhibits a smooth continuum variation likely attributable to the imperfections in the A0V templates. The imperfect A0V templates are a known limitation of this telluric correction strategy.
github_jupyter
# Content __1. Exploratory Visualization__ __2. Data Cleaning__ __3. Feature Engineering__ __4. Modeling & Evaluation__ __5. Ensemble Methods__ ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') %matplotlib inline plt.style.use('ggplot') from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import RobustScaler, StandardScaler from sklearn.metrics import mean_squared_error from sklearn.pipeline import Pipeline, make_pipeline from scipy.stats import skew from sklearn.decomposition import PCA, KernelPCA from sklearn.preprocessing import Imputer from sklearn.model_selection import cross_val_score, GridSearchCV, KFold from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor from sklearn.svm import SVR, LinearSVR from sklearn.linear_model import ElasticNet, SGDRegressor, BayesianRidge from sklearn.kernel_ridge import KernelRidge from xgboost import XGBRegressor train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') ``` # Exploratory Visualization + __It seems that the price of recent-built houses are higher. So later I 'll use labelencoder for three "Year" feature.__ ``` plt.figure(figsize=(15,8)) sns.boxplot(train.YearBuilt, train.SalePrice) ``` + __As is discussed in other kernels, the bottom right two two points with extremely large GrLivArea are likely to be outliers. So we delete them.__ ``` plt.figure(figsize=(12,6)) plt.scatter(x=train.GrLivArea, y=train.SalePrice) plt.xlabel("GrLivArea", fontsize=13) plt.ylabel("SalePrice", fontsize=13) plt.ylim(0,800000) train.drop(train[(train["GrLivArea"]>4000)&(train["SalePrice"]<300000)].index,inplace=True) full=pd.concat([train,test], ignore_index=True) full.drop(['Id'],axis=1, inplace=True) full.shape ``` # Data Cleaning ### Missing Data ``` aa = full.isnull().sum() aa[aa>0].sort_values(ascending=False) ``` + __Let's first imput the missing values of LotFrontage based on the median of LotArea and Neighborhood. Since LotArea is a continuous feature, We use qcut to divide it into 10 parts.__ ``` full.groupby(['Neighborhood'])[['LotFrontage']].agg(['mean','median','count']) full["LotAreaCut"] = pd.qcut(full.LotArea,10) full.groupby(['LotAreaCut'])[['LotFrontage']].agg(['mean','median','count']) full['LotFrontage']=full.groupby(['LotAreaCut','Neighborhood'])['LotFrontage'].transform(lambda x: x.fillna(x.median())) # Since some combinations of LotArea and Neighborhood are not available, so we just LotAreaCut alone. full['LotFrontage']=full.groupby(['LotAreaCut'])['LotFrontage'].transform(lambda x: x.fillna(x.median())) ``` + __Then we filling in other missing values according to data_description.__ ``` cols=["MasVnrArea", "BsmtUnfSF", "TotalBsmtSF", "GarageCars", "BsmtFinSF2", "BsmtFinSF1", "GarageArea"] for col in cols: full[col].fillna(0, inplace=True) cols1 = ["PoolQC" , "MiscFeature", "Alley", "Fence", "FireplaceQu", "GarageQual", "GarageCond", "GarageFinish", "GarageYrBlt", "GarageType", "BsmtExposure", "BsmtCond", "BsmtQual", "BsmtFinType2", "BsmtFinType1", "MasVnrType"] for col in cols1: full[col].fillna("None", inplace=True) # fill in with mode cols2 = ["MSZoning", "BsmtFullBath", "BsmtHalfBath", "Utilities", "Functional", "Electrical", "KitchenQual", "SaleType","Exterior1st", "Exterior2nd"] for col in cols2: full[col].fillna(full[col].mode()[0], inplace=True) ``` + __And there is no missing data except for the value we want to predict !__ ``` full.isnull().sum()[full.isnull().sum()>0] ``` # Feature Engineering + __Convert some numerical features into categorical features. It's better to use LabelEncoder and get_dummies for these features.__ ``` NumStr = ["MSSubClass","BsmtFullBath","BsmtHalfBath","HalfBath","BedroomAbvGr","KitchenAbvGr","MoSold","YrSold","YearBuilt","YearRemodAdd","LowQualFinSF","GarageYrBlt"] for col in NumStr: full[col]=full[col].astype(str) ``` + __Now I want to do a long list of value-mapping. __ + __I was influenced by the insight that we should build as many features as possible and trust the model to choose the right features. So I decided to groupby SalePrice according to one feature and sort it based on mean and median. Here is an example:__ ``` full.groupby(['MSSubClass'])[['SalePrice']].agg(['mean','median','count']) ``` + __So basically I'll do__ '180' : 1 '30' : 2 '45' : 2 '190' : 3, '50' : 3, '90' : 3, '85' : 4, '40' : 4, '160' : 4 '70' : 5, '20' : 5, '75' : 5, '80' : 5, '150' : 5 '120': 6, '60' : 6 + __Different people may have different views on how to map these values, so just follow your instinct =^_^=__ __Below I also add a small "o" in front of the features so as to keep the original features to use get_dummies in a moment.__ ``` def map_values(): full["oMSSubClass"] = full.MSSubClass.map({'180':1, '30':2, '45':2, '190':3, '50':3, '90':3, '85':4, '40':4, '160':4, '70':5, '20':5, '75':5, '80':5, '150':5, '120': 6, '60':6}) full["oMSZoning"] = full.MSZoning.map({'C (all)':1, 'RH':2, 'RM':2, 'RL':3, 'FV':4}) full["oNeighborhood"] = full.Neighborhood.map({'MeadowV':1, 'IDOTRR':2, 'BrDale':2, 'OldTown':3, 'Edwards':3, 'BrkSide':3, 'Sawyer':4, 'Blueste':4, 'SWISU':4, 'NAmes':4, 'NPkVill':5, 'Mitchel':5, 'SawyerW':6, 'Gilbert':6, 'NWAmes':6, 'Blmngtn':7, 'CollgCr':7, 'ClearCr':7, 'Crawfor':7, 'Veenker':8, 'Somerst':8, 'Timber':8, 'StoneBr':9, 'NoRidge':10, 'NridgHt':10}) full["oCondition1"] = full.Condition1.map({'Artery':1, 'Feedr':2, 'RRAe':2, 'Norm':3, 'RRAn':3, 'PosN':4, 'RRNe':4, 'PosA':5 ,'RRNn':5}) full["oBldgType"] = full.BldgType.map({'2fmCon':1, 'Duplex':1, 'Twnhs':1, '1Fam':2, 'TwnhsE':2}) full["oHouseStyle"] = full.HouseStyle.map({'1.5Unf':1, '1.5Fin':2, '2.5Unf':2, 'SFoyer':2, '1Story':3, 'SLvl':3, '2Story':4, '2.5Fin':4}) full["oExterior1st"] = full.Exterior1st.map({'BrkComm':1, 'AsphShn':2, 'CBlock':2, 'AsbShng':2, 'WdShing':3, 'Wd Sdng':3, 'MetalSd':3, 'Stucco':3, 'HdBoard':3, 'BrkFace':4, 'Plywood':4, 'VinylSd':5, 'CemntBd':6, 'Stone':7, 'ImStucc':7}) full["oMasVnrType"] = full.MasVnrType.map({'BrkCmn':1, 'None':1, 'BrkFace':2, 'Stone':3}) full["oExterQual"] = full.ExterQual.map({'Fa':1, 'TA':2, 'Gd':3, 'Ex':4}) full["oFoundation"] = full.Foundation.map({'Slab':1, 'BrkTil':2, 'CBlock':2, 'Stone':2, 'Wood':3, 'PConc':4}) full["oBsmtQual"] = full.BsmtQual.map({'Fa':2, 'None':1, 'TA':3, 'Gd':4, 'Ex':5}) full["oBsmtExposure"] = full.BsmtExposure.map({'None':1, 'No':2, 'Av':3, 'Mn':3, 'Gd':4}) full["oHeating"] = full.Heating.map({'Floor':1, 'Grav':1, 'Wall':2, 'OthW':3, 'GasW':4, 'GasA':5}) full["oHeatingQC"] = full.HeatingQC.map({'Po':1, 'Fa':2, 'TA':3, 'Gd':4, 'Ex':5}) full["oKitchenQual"] = full.KitchenQual.map({'Fa':1, 'TA':2, 'Gd':3, 'Ex':4}) full["oFunctional"] = full.Functional.map({'Maj2':1, 'Maj1':2, 'Min1':2, 'Min2':2, 'Mod':2, 'Sev':2, 'Typ':3}) full["oFireplaceQu"] = full.FireplaceQu.map({'None':1, 'Po':1, 'Fa':2, 'TA':3, 'Gd':4, 'Ex':5}) full["oGarageType"] = full.GarageType.map({'CarPort':1, 'None':1, 'Detchd':2, '2Types':3, 'Basment':3, 'Attchd':4, 'BuiltIn':5}) full["oGarageFinish"] = full.GarageFinish.map({'None':1, 'Unf':2, 'RFn':3, 'Fin':4}) full["oPavedDrive"] = full.PavedDrive.map({'N':1, 'P':2, 'Y':3}) full["oSaleType"] = full.SaleType.map({'COD':1, 'ConLD':1, 'ConLI':1, 'ConLw':1, 'Oth':1, 'WD':1, 'CWD':2, 'Con':3, 'New':3}) full["oSaleCondition"] = full.SaleCondition.map({'AdjLand':1, 'Abnorml':2, 'Alloca':2, 'Family':2, 'Normal':3, 'Partial':4}) return "Done!" map_values() # drop two unwanted columns full.drop("LotAreaCut",axis=1,inplace=True) full.drop(['SalePrice'],axis=1,inplace=True) ``` ## Pipeline + __Next we can build a pipeline. It's convenient to experiment different feature combinations once you've got a pipeline.__ + __Label Encoding three "Year" features.__ ``` class labelenc(BaseEstimator, TransformerMixin): def __init__(self): pass def fit(self,X,y=None): return self def transform(self,X): lab=LabelEncoder() X["YearBuilt"] = lab.fit_transform(X["YearBuilt"]) X["YearRemodAdd"] = lab.fit_transform(X["YearRemodAdd"]) X["GarageYrBlt"] = lab.fit_transform(X["GarageYrBlt"]) return X ``` + __Apply log1p to the skewed features, then get_dummies.__ ``` class skew_dummies(BaseEstimator, TransformerMixin): def __init__(self,skew=0.5): self.skew = skew def fit(self,X,y=None): return self def transform(self,X): X_numeric=X.select_dtypes(exclude=["object"]) skewness = X_numeric.apply(lambda x: skew(x)) skewness_features = skewness[abs(skewness) >= self.skew].index X[skewness_features] = np.log1p(X[skewness_features]) X = pd.get_dummies(X) return X # build pipeline pipe = Pipeline([ ('labenc', labelenc()), ('skew_dummies', skew_dummies(skew=1)), ]) # save the original data for later use full2 = full.copy() data_pipe = pipe.fit_transform(full2) data_pipe.shape data_pipe.head() ``` + __use robustscaler since maybe there are other outliers.__ ``` scaler = RobustScaler() n_train=train.shape[0] X = data_pipe[:n_train] test_X = data_pipe[n_train:] y= train.SalePrice X_scaled = scaler.fit(X).transform(X) y_log = np.log(train.SalePrice) test_X_scaled = scaler.transform(test_X) ``` ## Feature Selection + __I have to confess, the feature engineering above is not enough, so we need more.__ + __Combining different features is usually a good way, but we have no idea what features should we choose. Luckily there are some models that can provide feature selection, here I use Lasso, but you are free to choose Ridge, RandomForest or GradientBoostingTree.__ ``` lasso=Lasso(alpha=0.001) lasso.fit(X_scaled,y_log) FI_lasso = pd.DataFrame({"Feature Importance":lasso.coef_}, index=data_pipe.columns) FI_lasso.sort_values("Feature Importance",ascending=False) FI_lasso[FI_lasso["Feature Importance"]!=0].sort_values("Feature Importance").plot(kind="barh",figsize=(15,25)) plt.xticks(rotation=90) plt.show() ``` + __Based on the "Feature Importance" plot and other try-and-error, I decided to add some features to the pipeline.__ ``` class add_feature(BaseEstimator, TransformerMixin): def __init__(self,additional=1): self.additional = additional def fit(self,X,y=None): return self def transform(self,X): if self.additional==1: X["TotalHouse"] = X["TotalBsmtSF"] + X["1stFlrSF"] + X["2ndFlrSF"] X["TotalArea"] = X["TotalBsmtSF"] + X["1stFlrSF"] + X["2ndFlrSF"] + X["GarageArea"] else: X["TotalHouse"] = X["TotalBsmtSF"] + X["1stFlrSF"] + X["2ndFlrSF"] X["TotalArea"] = X["TotalBsmtSF"] + X["1stFlrSF"] + X["2ndFlrSF"] + X["GarageArea"] X["+_TotalHouse_OverallQual"] = X["TotalHouse"] * X["OverallQual"] X["+_GrLivArea_OverallQual"] = X["GrLivArea"] * X["OverallQual"] X["+_oMSZoning_TotalHouse"] = X["oMSZoning"] * X["TotalHouse"] X["+_oMSZoning_OverallQual"] = X["oMSZoning"] + X["OverallQual"] X["+_oMSZoning_YearBuilt"] = X["oMSZoning"] + X["YearBuilt"] X["+_oNeighborhood_TotalHouse"] = X["oNeighborhood"] * X["TotalHouse"] X["+_oNeighborhood_OverallQual"] = X["oNeighborhood"] + X["OverallQual"] X["+_oNeighborhood_YearBuilt"] = X["oNeighborhood"] + X["YearBuilt"] X["+_BsmtFinSF1_OverallQual"] = X["BsmtFinSF1"] * X["OverallQual"] X["-_oFunctional_TotalHouse"] = X["oFunctional"] * X["TotalHouse"] X["-_oFunctional_OverallQual"] = X["oFunctional"] + X["OverallQual"] X["-_LotArea_OverallQual"] = X["LotArea"] * X["OverallQual"] X["-_TotalHouse_LotArea"] = X["TotalHouse"] + X["LotArea"] X["-_oCondition1_TotalHouse"] = X["oCondition1"] * X["TotalHouse"] X["-_oCondition1_OverallQual"] = X["oCondition1"] + X["OverallQual"] X["Bsmt"] = X["BsmtFinSF1"] + X["BsmtFinSF2"] + X["BsmtUnfSF"] X["Rooms"] = X["FullBath"]+X["TotRmsAbvGrd"] X["PorchArea"] = X["OpenPorchSF"]+X["EnclosedPorch"]+X["3SsnPorch"]+X["ScreenPorch"] X["TotalPlace"] = X["TotalBsmtSF"] + X["1stFlrSF"] + X["2ndFlrSF"] + X["GarageArea"] + X["OpenPorchSF"]+X["EnclosedPorch"]+X["3SsnPorch"]+X["ScreenPorch"] return X ``` + __By using a pipeline, you can quickily experiment different feature combinations.__ ``` pipe = Pipeline([ ('labenc', labelenc()), ('add_feature', add_feature(additional=2)), ('skew_dummies', skew_dummies(skew=1)), ]) ``` ## PCA + __Im my case, doing PCA is very important. It lets me gain a relatively big boost on leaderboard. At first I don't believe PCA can help me, but in retrospect, maybe the reason is that the features I built are highly correlated, and it leads to multicollinearity. PCA can decorrelate these features.__ + __So I'll use approximately the same dimension in PCA as in the original data. Since the aim here is not deminsion reduction.__ ``` full_pipe = pipe.fit_transform(full) full_pipe.shape n_train=train.shape[0] X = full_pipe[:n_train] test_X = full_pipe[n_train:] y= train.SalePrice X_scaled = scaler.fit(X).transform(X) y_log = np.log(train.SalePrice) test_X_scaled = scaler.transform(test_X) pca = PCA(n_components=410) X_scaled=pca.fit_transform(X_scaled) test_X_scaled = pca.transform(test_X_scaled) X_scaled.shape, test_X_scaled.shape ``` # Modeling & Evaluation ``` # define cross validation strategy def rmse_cv(model,X,y): rmse = np.sqrt(-cross_val_score(model, X, y, scoring="neg_mean_squared_error", cv=5)) return rmse ``` + __We choose 13 models and use 5-folds cross-calidation to evaluate these models.__ Models include: + LinearRegression + Ridge + Lasso + Random Forrest + Gradient Boosting Tree + Support Vector Regression + Linear Support Vector Regression + ElasticNet + Stochastic Gradient Descent + BayesianRidge + KernelRidge + ExtraTreesRegressor + XgBoost ``` models = [LinearRegression(),Ridge(),Lasso(alpha=0.01,max_iter=10000),RandomForestRegressor(),GradientBoostingRegressor(),SVR(),LinearSVR(), ElasticNet(alpha=0.001,max_iter=10000),SGDRegressor(max_iter=1000,tol=1e-3),BayesianRidge(),KernelRidge(alpha=0.6, kernel='polynomial', degree=2, coef0=2.5), ExtraTreesRegressor(),XGBRegressor()] names = ["LR", "Ridge", "Lasso", "RF", "GBR", "SVR", "LinSVR", "Ela","SGD","Bay","Ker","Extra","Xgb"] for name, model in zip(names, models): score = rmse_cv(model, X_scaled, y_log) print("{}: {:.6f}, {:.4f}".format(name,score.mean(),score.std())) ``` + __Next we do some hyperparameters tuning. First define a gridsearch method.__ ``` class grid(): def __init__(self,model): self.model = model def grid_get(self,X,y,param_grid): grid_search = GridSearchCV(self.model,param_grid,cv=5, scoring="neg_mean_squared_error") grid_search.fit(X,y) print(grid_search.best_params_, np.sqrt(-grid_search.best_score_)) grid_search.cv_results_['mean_test_score'] = np.sqrt(-grid_search.cv_results_['mean_test_score']) print(pd.DataFrame(grid_search.cv_results_)[['params','mean_test_score','std_test_score']]) ``` ### Lasso ``` grid(Lasso()).grid_get(X_scaled,y_log,{'alpha': [0.0004,0.0005,0.0007,0.0009],'max_iter':[10000]}) ``` ### Ridge ``` grid(Ridge()).grid_get(X_scaled,y_log,{'alpha':[35,40,45,50,55,60,65,70,80,90]}) ``` ### SVR ``` grid(SVR()).grid_get(X_scaled,y_log,{'C':[11,13,15],'kernel':["rbf"],"gamma":[0.0003,0.0004],"epsilon":[0.008,0.009]}) ``` ### Kernel Ridge ``` param_grid={'alpha':[0.2,0.3,0.4], 'kernel':["polynomial"], 'degree':[3],'coef0':[0.8,1]} grid(KernelRidge()).grid_get(X_scaled,y_log,param_grid) ``` ### ElasticNet ``` grid(ElasticNet()).grid_get(X_scaled,y_log,{'alpha':[0.0008,0.004,0.005],'l1_ratio':[0.08,0.1,0.3],'max_iter':[10000]}) ``` # Ensemble Methods ### Weight Average + __Average base models according to their weights.__ ``` class AverageWeight(BaseEstimator, RegressorMixin): def __init__(self,mod,weight): self.mod = mod self.weight = weight def fit(self,X,y): self.models_ = [clone(x) for x in self.mod] for model in self.models_: model.fit(X,y) return self def predict(self,X): w = list() pred = np.array([model.predict(X) for model in self.models_]) # for every data point, single model prediction times weight, then add them together for data in range(pred.shape[1]): single = [pred[model,data]*weight for model,weight in zip(range(pred.shape[0]),self.weight)] w.append(np.sum(single)) return w lasso = Lasso(alpha=0.0005,max_iter=10000) ridge = Ridge(alpha=60) svr = SVR(gamma= 0.0004,kernel='rbf',C=13,epsilon=0.009) ker = KernelRidge(alpha=0.2 ,kernel='polynomial',degree=3 , coef0=0.8) ela = ElasticNet(alpha=0.005,l1_ratio=0.08,max_iter=10000) bay = BayesianRidge() # assign weights based on their gridsearch score w1 = 0.02 w2 = 0.2 w3 = 0.25 w4 = 0.3 w5 = 0.03 w6 = 0.2 weight_avg = AverageWeight(mod = [lasso,ridge,svr,ker,ela,bay],weight=[w1,w2,w3,w4,w5,w6]) score = rmse_cv(weight_avg,X_scaled,y_log) print(score.mean()) ``` + __But if we average only two best models, we gain better cross-validation score.__ ``` weight_avg = AverageWeight(mod = [svr,ker],weight=[0.5,0.5]) score = rmse_cv(weight_avg,X_scaled,y_log) print(score.mean()) ``` ## Stacking + __Aside from normal stacking, I also add the "get_oof" method, because later I'll combine features generated from stacking and original features.__ ``` class stacking(BaseEstimator, RegressorMixin, TransformerMixin): def __init__(self,mod,meta_model): self.mod = mod self.meta_model = meta_model self.kf = KFold(n_splits=5, random_state=42, shuffle=True) def fit(self,X,y): self.saved_model = [list() for i in self.mod] oof_train = np.zeros((X.shape[0], len(self.mod))) for i,model in enumerate(self.mod): for train_index, val_index in self.kf.split(X,y): renew_model = clone(model) renew_model.fit(X[train_index], y[train_index]) self.saved_model[i].append(renew_model) oof_train[val_index,i] = renew_model.predict(X[val_index]) self.meta_model.fit(oof_train,y) return self def predict(self,X): whole_test = np.column_stack([np.column_stack(model.predict(X) for model in single_model).mean(axis=1) for single_model in self.saved_model]) return self.meta_model.predict(whole_test) def get_oof(self,X,y,test_X): oof = np.zeros((X.shape[0],len(self.mod))) test_single = np.zeros((test_X.shape[0],5)) test_mean = np.zeros((test_X.shape[0],len(self.mod))) for i,model in enumerate(self.mod): for j, (train_index,val_index) in enumerate(self.kf.split(X,y)): clone_model = clone(model) clone_model.fit(X[train_index],y[train_index]) oof[val_index,i] = clone_model.predict(X[val_index]) test_single[:,j] = clone_model.predict(test_X) test_mean[:,i] = test_single.mean(axis=1) return oof, test_mean ``` + __Let's first try it out ! It's a bit slow to run this method, since the process is quite compliated. __ ``` # must do imputer first, otherwise stacking won't work, and i don't know why. a = Imputer().fit_transform(X_scaled) b = Imputer().fit_transform(y_log.values.reshape(-1,1)).ravel() stack_model = stacking(mod=[lasso,ridge,svr,ker,ela,bay],meta_model=ker) score = rmse_cv(stack_model,a,b) print(score.mean()) ``` + __Next we extract the features generated from stacking, then combine them with original features.__ ``` X_train_stack, X_test_stack = stack_model.get_oof(a,b,test_X_scaled) X_train_stack.shape, a.shape X_train_add = np.hstack((a,X_train_stack)) X_test_add = np.hstack((test_X_scaled,X_test_stack)) X_train_add.shape, X_test_add.shape score = rmse_cv(stack_model,X_train_add,b) print(score.mean()) ``` + __You can even do parameter tuning for your meta model after you get "X_train_stack", or do it after combining with the original features. but that's a lot of work too !__ ### Submission ``` # This is the final model I use stack_model = stacking(mod=[lasso,ridge,svr,ker,ela,bay],meta_model=ker) stack_model.fit(a,b) pred = np.exp(stack_model.predict(test_X_scaled)) result=pd.DataFrame({'Id':test.Id, 'SalePrice':pred}) result.to_csv("submission.csv",index=False) ```
github_jupyter
# Analysis - exp64 - Control for opt calculations. ``` import os import csv import numpy as np import torch as th import pandas as pd from glob import glob from pprint import pprint import matplotlib import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' import seaborn as sns sns.set(font_scale=1.5) sns.set_style('ticks') matplotlib.rcParams.update({'font.size': 16}) matplotlib.rc('axes', titlesize=16) from notebook_helpers import load_params from notebook_helpers import load_monitored from notebook_helpers import join_monitored from notebook_helpers import score_summary def load_data(path, model, run_index=None): runs = range(run_index[0], run_index[1]+1) exps = [] for r in runs: file = os.path.join(path, f"run_{model}_{r}_monitor.csv".format(int(r))) try: mon = load_monitored(file) except FileNotFoundError: mon = None exps.append(mon) return exps def load_hp(name): return pd.read_csv(name, index_col=False) def find_best(hp, data, window, score="score"): scores = [] for r, mon in enumerate(exp_62): if mon is not None: full = mon[score] # print(len(full)) selected = full[window[0]:window[1]] # print(selected) x = np.mean(selected) # print(x) scores.append(x) else: scores.append(np.nan) # print(scores) best = np.nanargmax(scores) # print(best) return hp[best:best+1] ``` # Load data ``` path = "/Users/qualia/Code/azad/data/wythoff/exp64/" hp_64 = load_hp(os.path.join(path,"grid.csv")) models = ["DQN_xy4"] index = (0, 50) hp_64[0:1] ``` # Plots ## All parameter summary How's it look overall. ### Timecourse ``` for model in models: exp_64 = load_data(path, model, run_index=index) plt.figure(figsize=(6, 3)) for r, mon in enumerate(exp_64): if mon is not None: _ = plt.plot(mon['episode'], mon['score'], color='black', alpha=0.05) # _ = plt.ylim(0, 1) _ = plt.title(model) _ = plt.ylabel("Optimal score") _ = plt.xlabel("Episode") sns.despine() ``` ## Initial timecourse ``` stop = 100 # Plot episodes up until this value for model in models: exp_62 = load_data(path, model, run_index=index) plt.figure(figsize=(6, 3)) for r, mon in enumerate(exp_62): if mon is not None: t = np.asarray(mon['episode']) x = np.asarray(mon['score']) avg = np.mean(x) m = t <= stop _ = plt.plot(t[m], x[m], color='black', alpha=0.05) _ = plt.title(model) _ = plt.ylabel("Optimal score") _ = plt.xlabel("Episode") sns.despine() ``` - There is real progress this time. For the first time with DQN on wythoff's. But why does it stop at arounf 0.3 or so of optimal? - If it gets this far it should be able to get to the best? - Code problem? - Player interaction problem? # Find the best HP ``` for model in models: exp_64 = load_data(path, model, run_index=index) best_hp = find_best(hp_64, exp_64, (450,500)) print(f"{model}:\n{best_hp}\n---") ```
github_jupyter
## GeostatsPy: Basic Univariate Statistics and Distribution Plotting for Subsurface Data Analytics in Python ### Michael Pyrcz, Associate Professor, University of Texas at Austin #### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1) ### PGE 383 Exercise: Basic Univariate Summary Statistics and Data Distribution Plotting in Python with GeostatsPy Here's a simple workflow with some basic univariate statistics and distribution plotting of tabular (easily extended to gridded) data summary statistics and distributions. This should help you get started data visualization and interpretation. #### Objective In the PGE 383: Stochastic Subsurface Modeling class I want to provide hands-on experience with building subsurface modeling workflows. Python provides an excellent vehicle to accomplish this. I have coded a package called GeostatsPy with GSLIB: Geostatistical Library (Deutsch and Journel, 1998) functionality that provides basic building blocks for building subsurface modeling workflows. The objective is to remove the hurdles of subsurface modeling workflow construction by providing building blocks and sufficient examples. This is not a coding class per se, but we need the ability to 'script' workflows working with numerical methods. #### Getting Started Here's the steps to get setup in Python with the GeostatsPy package: 1. Install Anaconda 3 on your machine (https://www.anaconda.com/download/). 2. From Anaconda Navigator (within Anaconda3 group), go to the environment tab, click on base (root) green arrow and open a terminal. 3. In the terminal type: pip install geostatspy. 4. Open Jupyter and in the top block get started by copy and pasting the code block below from this Jupyter Notebook to start using the geostatspy functionality. You will need to copy the data files to your working directory. They are avaiable here: 1. Tabular data - sample_data.csv at https://git.io/fh4gm 2. Gridded data - AI_grid.csv at https://git.io/fh4gU There are exampled below with these functions. You can go here to see a list of the available functions, https://git.io/fh4eX, other example workflows and source code. ``` import geostatspy.GSLIB as GSLIB # GSLIB utilies, visualization and wrapper import geostatspy.geostats as geostats # GSLIB methods convert to Python ``` We will also need some standard packages. These should have been installed with Anaconda 3. ``` import numpy as np # ndarrys for gridded data import pandas as pd # DataFrames for tabular data import os # set working directory, run executables import matplotlib.pyplot as plt # for plotting from scipy import stats # summary statistics ``` #### Set the working directory I always like to do this so I don't lose files and to simplify subsequent read and writes (avoid including the full address each time). ``` os.chdir("c:/PGE383/Examples") # set the working directory ``` #### Loading Tabular Data Here's the command to load our comma delimited data file in to a Pandas' DataFrame object. For fun try misspelling the name. You will get an ugly, long error. ``` df = pd.read_csv('sample_data_cow.csv') # load our data table (wrong name!) ``` That's Python, but there's method to the madness. In general the error shows a trace from the initial command into all the nested programs involved until the actual error occured. If you are debugging code (I know, I'm getting ahead of myself now), this is valuable for the detective work of figuring out what went wrong. I've spent days in C++ debugging one issue, this helps. So since you're working in Jupyter Notebook, the program just assumes you code. Fine. If you scroll to the bottom of the error you often get a summary statement *FileNotFoundError: File b'sample_data_cow.csv' does not exist*. Ok, now you know that you don't have a file iwth that name in the working directory. Painful to leave that error in our workflow, eh? Everytime I passes it while making this documented I wanted to fix it. Its a coder thing... go ahead and erase it if you like. Just select the block and click on the scissors above in the top bar of this window. While we are at it, notice if you click the '+' you can add in a new block anywhere. Ok, let's spell the file name correctly and get back to work, already. ``` df = pd.read_csv('sample_data.csv') # load our data table (wrong name!) ``` No error now! It worked, we loaded our file into our DataFrame called 'df'. But how do you really know that it worked? Visualizing the DataFrame would be useful and we already leard about these methods in this demo (https://git.io/fNgRW). We can preview the DataFrame by printing a slice or by utilizing the 'head' DataFrame member function (with a nice and clean format, see below). With the slice we could look at any subset of the data table and with the head command, add parameter 'n=13' to see the first 13 rows of the dataset. ``` print(df.iloc[0:5,:]) # display first 4 samples in the table as a preview df.head(n=13) # we could also use this command for a table preview ``` #### Summary Statistics for Tabular Data The table includes X and Y coordinates (meters), Facies 1 and 2 (1 is sandstone and 0 interbedded sand and mudstone), Porosity (fraction), permeability as Perm (mDarcy) and acoustic impedance as AI (kg/m2s*10^6). There are a lot of efficient methods to calculate summary statistics from tabular data in DataFrames. The describe command provides count, mean, minimum, maximum, and quartiles all in a nice data table. We use transpose just to flip the table so that features are on the rows and the statistics are on the columns. ``` df.describe().transpose() ``` We can also use a wide variety of statistical summaries built into NumPy's ndarrays. When we use the command: ```p df['Porosity'] # returns an Pandas series df['Porosity'].values # returns an ndarray ``` Panda's DataFrame returns all the porosity data as a series and if we add 'values' it returns a NumPy ndarray and we have access to a lot of NumPy methods. I also like to use the round function to round the answer to a limited number of digits for accurate reporting of precision and ease of reading. For example, now we could use commands. like this one: ``` print('The minimum is ' + str(round((df['Porosity'].values).min(),2)) + '.') print('The maximum is ' + str(round((df['Porosity'].values).max(),2)) + '.') print('The standard deviation is ' + str(round((df['Porosity'].values).std(),2)) + '.') print('The standard deviation is ' + str(round((df['Porosity'].values).std(),2)) + '.') ``` Here's some of the NumPy statistical functions that take ndarrays as an inputs. With these methods if you had a multidimensional array you could calculate the average by row (axis = 1) or by column (axis = 0) or over the entire array (no axis specified). We just have a 1D ndarray so this is not applicable here. ``` print('The minimum is ' + str(round(np.amin(df['Porosity'].values),2))) print('The maximum is ' + str(round(np.amax(df['Porosity'].values),2))) print('The range (maximum - minimum) is ' + str(round(np.ptp(df['Porosity'].values),2))) print('The P10 is ' + str(round(np.percentile(df['Porosity'].values,10),3))) print('The P50 is ' + str(round(np.percentile(df['Porosity'].values,50),3))) print('The P90 is ' + str(round(np.percentile(df['Porosity'].values,90),3))) print('The P13 is ' + str(round(np.percentile(df['Porosity'].values,13),3))) print('The media (P50) is ' + str(round(np.median(df['Porosity'].values),3))) print('The mean is ' + str(round(np.mean(df['Porosity'].values),3))) ``` Later in the ocurse we will talke about weights statistics. The NumPy command average allows for weighted averages as in the case of statistical expectation and declutered statistics. For demonstration, lets make a weighting array and apply it. ``` nd = len(df) # get the number of data values wts = np.ones(nd) # make an array of nd length of 1's print('The equal weighted average is ' + str(round(np.average(df['Porosity'].values,weights = wts),3)) + ', the same as the mean above.') ``` Let's get fancy, we will modify the weights to be 0.5 if the porosity is greater than 13% and retain 1.0 if the porosity is less than or equal to 13%. The results should be a lower weighted average. ``` porosity = df['Porosity'].values wts[porosity > 0.13] *= 0.1 print('The equal weighted average is ' + str(round(np.average(df['Porosity'].values,weights = wts),3)) + ', lower than the equal weighted average above.') ``` I should note that SciPy stats functions provide a handy summary statistics function. The output is a 'list' of values (actually it is a SciPy.DescribeResult ojbect). One can extract any one of them to use in a workflow as follows. ``` print(stats.describe(df['Porosity'].values)) # summary statistics por_stats = stats.describe(df['Porosity'].values) # store as an array print('Porosity kurtosis is ' + str(round(por_stats[5],2))) # extract a statistic ``` #### Plotting Distributions Let's display some histograms. I reimplimented the hist function from GSLIB. See the parameters. ``` GSLIB.hist ``` Let's make a histogram for porosity. ``` pormin = 0.05; pormax = 0.25 GSLIB.hist(df['Porosity'].values,pormin,pormax,log=False,cumul = False,bins=10,weights = None, xlabel='Porosity (fraction)',title='Porosity Well Data',fig_name='hist_Porosity') ``` What's going on here? Looks quite bimodal. Let's explore with a couple bins sizes to check. ``` plt.subplot(131) GSLIB.hist_st(df['Porosity'].values,pormin,pormax,log=False,cumul = False,bins=5,weights = None,xlabel='Porosity (fraction)',title='Porosity Well Data') plt.subplot(132) GSLIB.hist_st(df['Porosity'].values,pormin,pormax,log=False,cumul = False,bins=10,weights = None,xlabel='Porosity (fraction)',title='Porosity Well Data') plt.subplot(133) GSLIB.hist_st(df['Porosity'].values,pormin,pormax,log=False,cumul = False,bins=20,weights = None,xlabel='Porosity (fraction)',title='Porosity Well Data') plt.subplots_adjust(left=0.0, bottom=0.0, right=3.0, top=1.5, wspace=0.1, hspace=0.2) plt.savefig('hist_Porosity_Multiple_bins.tif',dpi=600,bbox_inches="tight") plt.show() ``` What about cumulative plots? This method makes a cumulative histogram, but the axis remains in frequency. To be a true cumulative distribution function we would need to standardize the Y-axis to be from 0.0 to 1.0. ``` GSLIB.hist(df['Porosity'].values,pormin,pormax,log=False,cumul = True,bins=100,weights = None,xlabel='Porosity (fraction)',title='Porosity Well Data',fig_name='hist_Porosity_CDF') ``` I don't want to suggest that matplotlib is hard to use. The GSLIB visualizations provide convenience and once again use the same parameters as the GSLIB methods. Particularly, the 'hist' function is pretty easy to use. Here's how we can make a pretty nice looking CDF from our data. Note after the initial hist command we can add a variety of features such as labels to our plot as shown below. ``` plt.hist(df['Porosity'].values,density=True, cumulative=True, label='CDF', histtype='stepfilled', alpha=0.2, bins = 100, color='red', edgecolor = 'black', range=[0.0,0.25]) plt.xlabel('Porosity (fraction)') plt.title('Porosity CDF') plt.ylabel('Cumulation Probability') plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.1, hspace=0.2) plt.savefig('cdf_Porosity.tif',dpi=600,bbox_inches="tight") plt.show() ``` Let's finish with the histograms of all our properties of interest as a finale! ``` permmin = 0.01; permmax = 3000; # user specified min and max AImin = 1000.0; AImax = 8000 Fmin = 0; Fmax = 1 plt.subplot(221) GSLIB.hist_st(df['Facies'].values,Fmin,Fmax,log=False,cumul = False,bins=20,weights = None,xlabel='Facies (1-sand, 0-shale)',title='Facies Well Data') plt.subplot(222) GSLIB.hist_st(df['Porosity'].values,pormin,pormax,log=False,cumul = False,bins=20,weights = None,xlabel='Porosity (fraction)',title='Porosity Well Data') plt.subplot(223) GSLIB.hist_st(df['Perm'].values,permmin,permmax,log=False,cumul = False,bins=20,weights = None,xlabel='Permeaiblity (mD)',title='Permeability Well Data') plt.subplot(224) GSLIB.hist_st(df['AI'].values,AImin,AImax,log=False,cumul = False,bins=20,weights = None,xlabel='Acoustic Impedance (kg/m2s*10^6)',title='Acoustic Impedance Well Data') plt.subplots_adjust(left=0.0, bottom=0.0, right=3.0, top=3.5, wspace=0.1, hspace=0.2) plt.savefig('hist_Porosity_Multiple_bins.tif',dpi=600,bbox_inches="tight") plt.show() ``` #### Comments This was a basic demonstration of calculating univariate statistics and visualizing data distributions. Much more could be done, I have other demosntrations on basics of working with DataFrames, ndarrays and many other workflows availble at https://github.com/GeostatsGuy/PythonNumericalDemos and https://github.com/GeostatsGuy/GeostatsPy. I hope this was helpful, *Michael* Michael Pyrcz, Ph.D., P.Eng. Associate Professor The Hildebrand Department of Petroleum and Geosystems Engineering, Bureau of Economic Geology, The Jackson School of Geosciences, The University of Texas at Austin #### More Resources Available at: [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)
github_jupyter
# 使用卷积神经网络进行图像分类 **作者:** [PaddlePaddle](https://github.com/PaddlePaddle) <br> **日期:** 2021.12 <br> **摘要:** 本示例教程将会演示如何使用飞桨的卷积神经网络来完成图像分类任务。这是一个较为简单的示例,将会使用一个由三个卷积层组成的网络完成[cifar10](https://www.cs.toronto.edu/~kriz/cifar.html)数据集的图像分类任务。 ## 一、环境配置 本教程基于Paddle 2.2 编写,如果你的环境不是本版本,请先参考官网[安装](https://www.paddlepaddle.org.cn/install/quick) Paddle 2.2 。 ``` import paddle import paddle.nn.functional as F from paddle.vision.transforms import ToTensor import numpy as np import matplotlib.pyplot as plt print(paddle.__version__) ``` ## 二、加载数据集 本案例将会使用飞桨提供的API完成数据集的下载并为后续的训练任务准备好数据迭代器。cifar10数据集由60000张大小为32 * 32的彩色图片组成,其中有50000张图片组成了训练集,另外10000张图片组成了测试集。这些图片分为10个类别,将训练一个模型能够把图片进行正确的分类。 ``` transform = ToTensor() cifar10_train = paddle.vision.datasets.Cifar10(mode='train', transform=transform) cifar10_test = paddle.vision.datasets.Cifar10(mode='test', transform=transform) ``` ## 三、组建网络 接下来使用飞桨定义一个使用了三个二维卷积( ``Conv2D`` ) 且每次卷积之后使用 ``relu`` 激活函数,两个二维池化层( ``MaxPool2D`` ),和两个线性变换层组成的分类网络,来把一个(32, 32, 3)形状的图片通过卷积神经网络映射为10个输出,这对应着10个分类的类别。 ``` class MyNet(paddle.nn.Layer): def __init__(self, num_classes=1): super(MyNet, self).__init__() self.conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=32, kernel_size=(3, 3)) self.pool1 = paddle.nn.MaxPool2D(kernel_size=2, stride=2) self.conv2 = paddle.nn.Conv2D(in_channels=32, out_channels=64, kernel_size=(3,3)) self.pool2 = paddle.nn.MaxPool2D(kernel_size=2, stride=2) self.conv3 = paddle.nn.Conv2D(in_channels=64, out_channels=64, kernel_size=(3,3)) self.flatten = paddle.nn.Flatten() self.linear1 = paddle.nn.Linear(in_features=1024, out_features=64) self.linear2 = paddle.nn.Linear(in_features=64, out_features=num_classes) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.pool1(x) x = self.conv2(x) x = F.relu(x) x = self.pool2(x) x = self.conv3(x) x = F.relu(x) x = self.flatten(x) x = self.linear1(x) x = F.relu(x) x = self.linear2(x) return x ``` ## 四、模型训练&预测 接下来,用一个循环来进行模型的训练,将会: <br> - 使用 ``paddle.optimizer.Adam`` 优化器来进行优化。 - 使用 ``F.cross_entropy`` 来计算损失值。 - 使用 ``paddle.io.DataLoader`` 来加载数据并组建batch。 ``` epoch_num = 10 batch_size = 32 learning_rate = 0.001 val_acc_history = [] val_loss_history = [] def train(model): print('start training ... ') # turn into training mode model.train() opt = paddle.optimizer.Adam(learning_rate=learning_rate, parameters=model.parameters()) train_loader = paddle.io.DataLoader(cifar10_train, shuffle=True, batch_size=batch_size) valid_loader = paddle.io.DataLoader(cifar10_test, batch_size=batch_size) for epoch in range(epoch_num): for batch_id, data in enumerate(train_loader()): x_data = data[0] y_data = paddle.to_tensor(data[1]) y_data = paddle.unsqueeze(y_data, 1) logits = model(x_data) loss = F.cross_entropy(logits, y_data) if batch_id % 1000 == 0: print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, loss.numpy())) loss.backward() opt.step() opt.clear_grad() # evaluate model after one epoch model.eval() accuracies = [] losses = [] for batch_id, data in enumerate(valid_loader()): x_data = data[0] y_data = paddle.to_tensor(data[1]) y_data = paddle.unsqueeze(y_data, 1) logits = model(x_data) loss = F.cross_entropy(logits, y_data) acc = paddle.metric.accuracy(logits, y_data) accuracies.append(acc.numpy()) losses.append(loss.numpy()) avg_acc, avg_loss = np.mean(accuracies), np.mean(losses) print("[validation] accuracy/loss: {}/{}".format(avg_acc, avg_loss)) val_acc_history.append(avg_acc) val_loss_history.append(avg_loss) model.train() model = MyNet(num_classes=10) train(model) plt.plot(val_acc_history, label = 'validation accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.ylim([0.5, 0.8]) plt.legend(loc='lower right') ``` ## The End 从上面的示例可以看到,在cifar10数据集上,使用简单的卷积神经网络,用飞桨可以达到70%以上的准确率。你也可以通过调整网络结构和参数,达到更好的效果。
github_jupyter
# Artificial Intelligence Nanodegree ## Recurrent Neural Network Projects Welcome to the Recurrent Neural Network Project in the Artificial Intelligence Nanodegree! In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. 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. ### Implementation TODOs in this notebook This notebook contains two problems, cut into a variety of TODOs. Make sure to complete each section containing a TODO marker throughout the notebook. For convinence we provide links to each of these sections below. [TODO #1: Implement a function to window time series](#TODO_1) [TODO #2: Create a simple RNN model using keras to perform regression](#TODO_2) [TODO #3: Finish cleaning a large text corpus](#TODO_3) [TODO #4: Implement a function to window a large text corpus](#TODO_4) [TODO #5: Create a simple RNN model using keras to perform multiclass classification](#TODO_5) [TODO #6: Generate text using a fully trained RNN model and a variety of input sequences](#TODO_6) # Problem 1: Perform time series prediction In this project you will perform time series prediction using a Recurrent Neural Network regressor. In particular you will re-create the figure shown in the notes - where the stock price of Apple was forecasted (or predicted) 7 days in advance. In completing this exercise you will learn how to construct RNNs using Keras, which will also aid in completing the second project in this notebook. The particular network architecture we will employ for our RNN is known as [Long Term Short Memory (LTSM)](https://en.wikipedia.org/wiki/Long_short-term_memory), which helps significantly avoid technical problems with optimization of RNNs. ## 1.1 Getting started First we must load in our time series - a history of around 140 days of Apple's stock price. Then we need to perform a number of pre-processing steps to prepare it for use with an RNN model. First off, it is good practice to normalize time series - by normalizing its range. This helps us avoid serious numerical issues associated how common activation functions (like tanh) transform very large (positive or negative) numbers, as well as helping us to avoid related issues when computing derivatives. Here we normalize the series to lie in the range [0,1] [using this scikit function](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html), but it is also commonplace to normalize by a series standard deviation. ``` ### Load in necessary libraries for data input and normalization %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler ### load in and normalize the dataset dataset = np.loadtxt('datasets/normalized_apple_prices.csv') ``` Lets take a quick look at the (normalized) time series we'll be performing predictions on. ``` # lets take a look at our time series plt.plot(dataset) plt.xlabel('time period') plt.ylabel('normalized series value') ``` ## 1.2 Cutting our time series into sequences Remember, our time series is a sequence of numbers that we can represent in general mathematically as $$s_{0},s_{1},s_{2},...,s_{P}$$ where $s_{p}$ is the numerical value of the time series at time period $p$ and where $P$ is the total length of the series. In order to apply our RNN we treat the time series prediction problem as a regression problem, and so need to use a sliding window to construct a set of associated input/output pairs to regress on. This process is animated in the gif below. <img src="images/timeseries_windowing_training.gif" width=600 height=600/> For example - using a window of size T = 5 (as illustrated in the gif above) we produce a set of input/output pairs like the one shown in the table below $$\begin{array}{c|c} \text{Input} & \text{Output}\\ \hline \color{CornflowerBlue} {\langle s_{1},s_{2},s_{3},s_{4},s_{5}\rangle} & \color{Goldenrod}{ s_{6}} \\ \ \color{CornflowerBlue} {\langle s_{2},s_{3},s_{4},s_{5},s_{6} \rangle } & \color{Goldenrod} {s_{7} } \\ \color{CornflowerBlue} {\vdots} & \color{Goldenrod} {\vdots}\\ \color{CornflowerBlue} { \langle s_{P-5},s_{P-4},s_{P-3},s_{P-2},s_{P-1} \rangle } & \color{Goldenrod} {s_{P}} \end{array}$$ Notice here that each input is a sequence (or vector) of length 4 (and in general has length equal to the window size T) while each corresponding output is a scalar value. Notice also how given a time series of length P and window size T = 5 as shown above, we created P - 5 input/output pairs. More generally, for a window size T we create P - T such pairs. Now its time for you to window the input time series as described above! <a id='TODO_1'></a> **TODO:** Fill in the function below - called **window_transform_series** - that runs a sliding window along the input series and creates associated input/output pairs. Note that this function should input a) the series and b) the window length, and return the input/output subsequences. Make sure to format returned input/output as generally shown in table above (where window_size = 5), and make sure your returned input is a numpy array. ----- You can test your function on the list of odd numbers given below ``` odd_nums = np.array([1,3,5,7,9,11,13]) print(int(len(odd_nums)/2)) ``` To window this sequence with a window_size = 2 using the **window_transform_series** you should get the following input/output pairs ``` def window_transform_series(dataset, window_size): #Function to run a sliding window of window_size across the dataset dataX, dataY = [], [] for i in range(len(dataset)-window_size): a = dataset[i:(i+window_size)] dataX.append(a) dataY.append(dataset[i + window_size]) return np.array(dataX), (np.array(dataY)).reshape(-1,1) # run a window of size 2 over the odd number sequence and display the results window_size = 2 X,y = window_transform_series(odd_nums,window_size) # print out input/output pairs --> here input = X, corresponding output = y print ('--- the input X will look like ----') print (X) print ('--- the associated output y will look like ----') print (y) print ('the shape of X is ' + str(np.shape(X))) print ('the shape of y is ' + str(np.shape(y))) print('the type of X is ' + str(type(X))) print('the type of y is ' + str(type(y))) ``` Again - you can check that your completed **window_transform_series** function works correctly by trying it on the odd_nums sequence - you should get the above output. ----- ``` ### TODO: fill out the function below that transforms the input series and window-size into a set of input/output pairs for use with our RNN model def window_transform_series(series,window_size): # containers for input/output pairs #Function to run a sliding window of window_size across the dataset dataX, dataY = [], [] for i in range(len(series)-window_size): a = series[i:(i+window_size)] dataX.append(a) dataY.append(series[i + window_size]) # reshape each X = np.asarray(dataX) X.shape = (np.shape(X)[0:2]) y = np.asarray(dataY) y.shape = (len(y),1) return X,y ``` With this function in place apply it to the series in the Python cell below. We use a window_size = 7 for these experiments. ``` # window the data using your windowing function window_size = 7 X,y = window_transform_series(series = dataset,window_size = window_size) print(X.shape, y.shape) ``` ## 1.3 Splitting into training and testing sets In order to perform proper testing on our dataset we will lop off the last 1/3 of it for validation (or testing). This is that once we train our model we have something to test it on (like any regression problem!). This splitting into training/testing sets is done in the cell below. Note how here we are **not** splitting the dataset *randomly* as one typically would do when validating a regression model. This is because our input/output pairs *are related temporally*. We don't want to validate our model by training on a random subset of the series and then testing on another random subset, as this simulates the scenario that we receive new points *within the timeframe of our training set*. We want to train on one solid chunk of the series (in our case, the first full 2/3 of it), and validate on a later chunk (the last 1/3) as this simulates how we would predict *future* values of a time series. ``` # split our dataset into training / testing sets train_test_split = int(np.ceil(2*len(y)/float(3))) # set the split point # partition the training set X_train = X[:train_test_split,:] y_train = y[:train_test_split] # keep the last chunk for testing X_test = X[train_test_split:,:] y_test = y[train_test_split:] # NOTE: to use keras's RNN LSTM module our input must be reshaped to [samples, stepsize, window size] X_train = np.asarray(np.reshape(X_train, (X_train.shape[0], 1, window_size))) X_test = np.asarray(np.reshape(X_test, (X_test.shape[0], 1, window_size))) ``` <a id='TODO_2'></a> ## 1.4 Build and run an RNN regression model Having created input/output pairs out of our time series and cut this into training/testing sets, we can now begin setting up our RNN. We use Keras to quickly build a two hidden layer RNN of the following specifications - layer 1 uses an LSTM module with 5 hidden units (note here the input_shape = (1,window_size)) - layer 2 uses a fully connected module with one unit - the 'mean_squared_error' loss should be used (remember: we are performing regression here) This can be constructed using just a few lines - see e.g., the [general Keras documentation](https://keras.io/getting-started/sequential-model-guide/) and the [LTSM documentation in particular](https://keras.io/layers/recurrent/) for examples of how to quickly use Keras to build neural network models. Make sure you are initializing your optimizer given the [keras-recommended approach for RNNs](https://keras.io/optimizers/) (given in the cell below). ``` ### TODO: create required RNN model # import keras network libraries from keras.models import Sequential from keras.layers import Dense, Dropout from keras.layers import LSTM import keras # given - fix random seed - so we can all reproduce the same results on our default time series np.random.seed(0) # TODO: build an RNN to perform regression on our time series input/output data model = Sequential() #LSTM layer with 5 hidden units model.add(LSTM(5, input_shape=(1, window_size))) #Dropout added to avoid overfitting model.add(Dropout(0.2)) #Fully connected layer with one output cell model.add(Dense(1)) # build model using keras documentation recommended optimizer initialization optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # compile the model model.compile(loss='mean_squared_error', optimizer=optimizer) ``` With your model built you can now fit the model by activating the cell below! Note: the number of epochs (np_epochs) and batch_size are preset (so we can all produce the same results). You can choose to toggle the verbose parameter - which gives you regular updates on the progress of the algorithm - on and off by setting it to 1 or 0 respectively. ``` # run your model! model.fit(X_train, y_train, epochs=1000, batch_size=50, verbose=0) ``` ## 1.5 Checking model performance With your model fit we can now make predictions on both our training and testing sets. ``` # generate predictions for training train_predict = model.predict(X_train) test_predict = model.predict(X_test) ``` In the next cell we compute training and testing errors using our trained model - you should be able to achieve at least *training_accuracy* < 0.02 and *testing_accuracy* < 0.02 with your fully trained model. If either or both of your accuracies are larger than 0.02 re-train your model - increasing the number of epochs you take (a maximum of around 1,000 should do the job) and/or adjusting your batch_size. ``` # print out training and testing errors training_accuracy = model.evaluate(X_train, y_train, verbose=0) print('training accuracy = ' + str(training_accuracy)) testing_accuracy = model.evaluate(X_test, y_test, verbose=0) print('testing accuracy = ' + str(testing_accuracy)) ``` Activating the next cell plots the original data, as well as both predictions on the training and testing sets. ``` ### Plot everything - the original series as well as predictions on training and testing sets import matplotlib.pyplot as plt %matplotlib inline # plot original series plt.plot(dataset,color = 'k') # plot training set prediction split_pt = train_test_split + window_size plt.plot(np.arange(window_size,split_pt,1),train_predict,color = 'b') # plot testing set prediction plt.plot(np.arange(split_pt,split_pt + len(test_predict),1),test_predict,color = 'r') # pretty up graph plt.xlabel('day') plt.ylabel('(normalized) price of Apple stock') plt.legend(['original series','training fit','testing fit'],loc='center left', bbox_to_anchor=(1, 0.5)) plt.show() ``` **Note:** you can try out any time series for this exercise! If you would like to try another see e.g., [this site containing thousands of time series](https://datamarket.com/data/list/?q=provider%3Atsdl) and pick another one! # Problem 2: Create a sequence generator ## 2.1 Getting started In this project you will implement a popular Recurrent Neural Network (RNN) architecture to create an English language sequence generator capable of building semi-coherent English sentences from scratch by building them up character-by-character. This will require a substantial amount amount of parameter tuning on a large training corpus (at least 100,000 characters long). In particular for this project we will be using a complete version of Sir Arthur Conan Doyle's classic book The Adventures of Sherlock Holmes. How can we train a machine learning model to generate text automatically, character-by-character? *By showing the model many training examples so it can learn a pattern between input and output.* With this type of text generation each input is a string of valid characters like this one *dogs are grea* whlie the corresponding output is the next character in the sentence - which here is 't' (since the complete sentence is 'dogs are great'). We need to show a model many such examples in order for it to make reasonable predictions. **Fun note:** For those interested in how text generation is being used check out some of the following fun resources: - [Generate wacky sentences](http://www.cs.toronto.edu/~ilya/rnn.html) with this academic RNN text generator - Various twitter bots that tweet automatically generated text like[this one](http://tweet-generator-alex.herokuapp.com/). - the [NanoGenMo](https://github.com/NaNoGenMo/2016) annual contest to automatically produce a 50,000+ novel automatically - [Robot Shakespeare](https://github.com/genekogan/RobotShakespeare) a text generator that automatically produces Shakespear-esk sentences ## 2.2 Preprocessing a text dataset Our first task is to get a large text corpus for use in training, and on it we perform a several light pre-processing tasks. The default corpus we will use is the classic book Sherlock Holmes, but you can use a variety of others as well - so long as they are fairly large (around 100,000 characters or more). ``` # read in the text, transforming everything to lower case text = open('datasets/holmes.txt').read().lower() print('our original text has ' + str(len(text)) + ' characters') ``` Next, lets examine a bit of the raw text. Because we are interested in creating sentences of English words automatically by building up each word character-by-character, we only want to train on valid English words. In other words - we need to remove all of the other junk characters that aren't words! ``` ### print out the first 1000 characters of the raw text to get a sense of what we need to throw out text[:2000] ``` Wow - there's a lot of junk here (i.e., weird uncommon character combinations - as this first character chunk contains the title and author page, as well as table of contents)! e.g., all the carriage return and newline sequences '\n' and '\r' sequences. We want to train our RNN on a large chunk of real english sentences - we don't want it to start thinking non-english words or strange characters are valid! - so lets clean up the data a bit. First, since the dataset is so large and the first few hundred characters contain a lot of junk, lets cut it out. Lets also find-and-replace those newline tags with empty spaces. ``` ### find and replace '\n' and '\r' symbols - replacing them text = text[1302:] text = text.replace('\n',' ') # replacing '\n' with '' simply removes the sequence text = text.replace('\r',' ') ``` Lets see how the first 1000 characters of our text looks now! ``` ### print out the first 1000 characters of the raw text to get a sense of what we need to throw out text[:1000] ``` <a id='TODO_3'></a> #### TODO: finish cleaning the text Lets make sure we haven't left any other non-English/proper punctuation (commas, periods, etc., are ok) characters lurking around in the depths of the text. You can do this by ennumerating all the text's unique characters, examining them, and then replacing any unwanted (non-english) characters with empty spaces! Once we find all of the text's unique characters, we can remove all of the non-English/proper punctuation ones in the next cell. Note: don't remove necessary punctuation marks! ascii_dict = dict() ascii_in_number = range(0,256) for i in ascii_in_number: ascii_dict[str(i)] = chr(i) # print chars corresponding to ASCII numbers unique_dict = {} for num in vocab: val = ascii_dict.get(str(num)) unique_dict[num] = val print(unique_dict) ``` ### TODO: list all unique characters in the text and remove any non-english ones # find all unique characters in the text vocab = set(text) print(vocab) # remove as many non-english characters and character sequences as you can text = text.replace('!',' ') text = text.replace('"',' ') text = text.replace('$',' ') text = text.replace('%',' ') text = text.replace('&',' ') text = text.replace("`",' ') text = text.replace("(",' ') text = text.replace(")",' ') text = text.replace("*",' ') text = text.replace("-",' ') text = text.replace("/",' ') text = text.replace(";",' ') text = text.replace("@",' ') text = text.replace("?",' ') text = text.replace(":",' ') text = text.replace("'",' ') text = text.replace("©",' ') text = text.replace("¢",' ') text = text.replace("¨",' ') text = text.replace("ã",' ') text = text.replace("\xa0",' ') for ch in ['0','1', '2', '3', '4', '5', '6', '7', '8', '9']: if ch in text: text=text.replace(ch,' ') # shorten any extra dead space created above text = text.replace(' ',' ') ``` With your chosen characters removed print out the first few hundred lines again just to double check that everything looks good. ``` ### Test your algorithm vocab = set(text) print(vocab) ``` Now that we have thrown out a good number of non-English characters/character sequences lets print out some statistics about the dataset - including number of total characters and number of unique characters. ``` # count the number of unique characters in the text chars = sorted(list(set(text))) print(chars) # print some of the text, as well as statistics print ("this corpus has " + str(len(text)) + " total number of characters") print ("this corpus has " + str(len(chars)) + " unique characters") ``` ## 2.3 Cutting data into input/output pairs Now that we have our text all cleaned up, how can we use it to train a model to generate sentences automatically? First we need to train a machine learning model - and in order to do that we need a set of input/output pairs for a model to train on. How can we create a set of input/output pairs from our text to train on? Remember in part 1 of this notebook how we used a sliding window to extract input/output pairs from a time series? We do the same thing here! We slide a window of length $T$ along our giant text corpus - everything in the window becomes one input while the character following becomes its corresponding output. This process of extracting input/output pairs is illustrated in the gif below on a small example text using a window size of T = 4. <img src="images/text_windowing_training.gif" width=400 height=400/> Notice one aspect of the sliding window in this gif that does not mirror the analaogous gif for time series shown in part 1 of the notebook - we do not need to slide the window along one character at a time but can move by a fixed step size $M$ greater than 1 (in the gif indeed $M = 1$). This is done with large input texts (like ours which has over 500,000 characters!) when sliding the window along one character at a time we would create far too many input/output pairs to be able to reasonably compute with. More formally lets denote our text corpus - which is one long string of characters - as follows $$s_{0},s_{1},s_{2},...,s_{P}$$ where $P$ is the length of the text (again for our text $P \approx 500,000!$). Sliding a window of size T = 5 with a step length of M = 1 (these are the parameters shown in the gif above) over this sequence produces the following list of input/output pairs $$\begin{array}{c|c} \text{Input} & \text{Output}\\ \hline \color{CornflowerBlue} {\langle s_{1},s_{2},s_{3},s_{4}\rangle} & \color{Goldenrod}{ s_{5}} \\ \ \color{CornflowerBlue} {\langle s_{2},s_{3},s_{4},s_{5} \rangle } & \color{Goldenrod} {s_{6} } \\ \color{CornflowerBlue} {\vdots} & \color{Goldenrod} {\vdots}\\ \color{CornflowerBlue} { \langle s_{P-4},s_{P-3},s_{P-2},s_{P-1} \rangle } & \color{Goldenrod} {s_{P}} \end{array}$$ Notice here that each input is a sequence (or vector) of 4 characters (and in general has length equal to the window size T) while each corresponding output is a single character. We created around P total number of input/output pairs (for general step size M we create around ceil(P/M) pairs). <a id='TODO_4'></a> Now its time for you to window the input time series as described above! **TODO:** Create a function that runs a sliding window along the input text and creates associated input/output pairs. A skeleton function has been provided for you. Note that this function should input a) the text b) the window size and c) the step size, and return the input/output sequences. Note: the return items should be *lists* - not numpy arrays. ``` ### TODO: fill out the function below that transforms the input text and window-size into a set of input/output pairs for use with our RNN model def window_transform_series(text,window_size,step_size): # containers for input/output pairs inputs = [] outputs = [] n_batches = int((len(text)-window_size) / step_size) print(n_batches) for i in range(n_batches-1): a = text[i*step_size:((i*step_size)+window_size)] inputs.append(a) b = text[(i*step_size)+window_size] outputs.append(b) return inputs,outputs ``` With our function complete we can now use it to produce input/output pairs! We employ the function in the next cell, where the window_size = 50 and step_size = 5. ``` # run your text window-ing function window_size = 100 step_size = 5 inputs, outputs = window_transform_series(text,window_size,step_size) ``` Lets print out a few input/output pairs to verify that we have made the right sort of stuff! ``` # print out a few of the input/output pairs to verify that we've made the right kind of stuff to learn from print('input = ' + inputs[3]) print('output = ' + outputs[3]) print('--------------') print('input = ' + inputs[100]) print('output = ' + outputs[100]) ``` Looks good! ## 2.4 Wait, what kind of problem is text generation again? In part 1 of this notebook we used the same pre-processing technique - the sliding window - to produce a set of training input/output pairs to tackle the problem of time series prediction *by treating the problem as one of regression*. So what sort of problem do we have here now, with text generation? Well, the time series prediction was a regression problem because the output (one value of the time series) was a continuous value. Here - for character-by-character text generation - each output is a *single character*. This isn't a continuous value - but a distinct class - therefore **character-by-character text generation is a classification problem**. How many classes are there in the data? Well, the number of classes is equal to the number of unique characters we have to predict! How many of those were there in our dataset again? Lets print out the value again. ``` # print out the number of unique characters in the dataset chars = sorted(list(set(text))) print ("this corpus has " + str(len(chars)) + " unique characters") print ('and these characters are ') print (chars) ``` Rockin' - so we have a multi-class classification problem on our hands! ## 2.5 One-hot encoding characters There's just one last issue we have to deal with before tackle: machine learning algorithm deal with numerical data and all of our input/output pairs are characters. So we just need to transform our characters into equivalent numerical values. The most common way of doing this is via a 'one-hot encoding' scheme. Here's how it works. We transform each character in our inputs/outputs into a vector with length equal to the number of unique characters in our text. This vector is all zeros except one location where we place a 1 - and this location is unique to each character type. e.g., we transform 'a', 'b', and 'c' as follows $$a\longleftarrow\left[\begin{array}{c} 1\\ 0\\ 0\\ \vdots\\ 0\\ 0 \end{array}\right]\,\,\,\,\,\,\,b\longleftarrow\left[\begin{array}{c} 0\\ 1\\ 0\\ \vdots\\ 0\\ 0 \end{array}\right]\,\,\,\,\,c\longleftarrow\left[\begin{array}{c} 0\\ 0\\ 1\\ \vdots\\ 0\\ 0 \end{array}\right]\cdots$$ where each vector has 32 entries (or in general: number of entries = number of unique characters in text). The first practical step towards doing this one-hot encoding is to form a dictionary mapping each unique character to a unique integer, and one dictionary to do the reverse mapping. We can then use these dictionaries to quickly make our one-hot encodings, as well as re-translate (from integers to characters) the results of our trained RNN classification model. ``` # this dictionary is a function mapping each unique character to a unique integer chars_to_indices = dict((c, i) for i, c in enumerate(chars)) # map each unique character to unique integer # this dictionary is a function mapping each unique integer back to a unique character indices_to_chars = dict((i, c) for i, c in enumerate(chars)) # map each unique integer back to unique character ``` Now we can transform our input/output pairs - consisting of characters - to equivalent input/output pairs made up of one-hot encoded vectors. In the next cell we provide a function for doing just this: it takes in the raw character input/outputs and returns their numerical versions. In particular the numerical input is given as $\bf{X}$, and numerical output is given as the $\bf{y}$ ``` # transform character-based input/output into equivalent numerical versions def encode_io_pairs(text,window_size,step_size): # number of unique chars chars = sorted(list(set(text))) num_chars = len(chars) # cut up text into character input/output pairs inputs, outputs = window_transform_series(text,window_size,step_size) # create empty vessels for one-hot encoded input/output X = np.zeros((len(inputs), window_size, num_chars), dtype=np.bool) y = np.zeros((len(inputs), num_chars), dtype=np.bool) # loop over inputs/outputs and tranform and store in X/y for i, sentence in enumerate(inputs): for t, char in enumerate(sentence): X[i, t, chars_to_indices[char]] = 1 y[i, chars_to_indices[outputs[i]]] = 1 return X,y ``` Now run the one-hot encoding function by activating the cell below and transform our input/output pairs! ``` # use your function window_size = 100 step_size = 5 X,y = encode_io_pairs(text,window_size,step_size) ``` <a id='TODO_5'></a> ## 2.6 Setting up our RNN With our dataset loaded and the input/output pairs extracted / transformed we can now begin setting up our RNN for training. Again we will use Keras to quickly build a single hidden layer RNN - where our hidden layer consists of LTSM modules. Time to get to work: build a 3 layer RNN model of the following specification - layer 1 should be an LSTM module with 200 hidden units --> note this should have input_shape = (window_size,len(chars)) where len(chars) = number of unique characters in your cleaned text - layer 2 should be a linear module, fully connected, with len(chars) hidden units --> where len(chars) = number of unique characters in your cleaned text - layer 3 should be a softmax activation ( since we are solving a *multiclass classification*) - Use the **categorical_crossentropy** loss This network can be constructed using just a few lines - as with the RNN network you made in part 1 of this notebook. See e.g., the [general Keras documentation](https://keras.io/getting-started/sequential-model-guide/) and the [LTSM documentation in particular](https://keras.io/layers/recurrent/) for examples of how to quickly use Keras to build neural network models. ``` ### necessary functions from the keras library from keras.models import Sequential from keras.layers import Dense, Activation, LSTM from keras.optimizers import RMSprop from keras.utils.data_utils import get_file import keras import random # TODO build the required RNN model: a single LSTM hidden layer with softmax activation, categorical_crossentropy loss hidden_units = len(chars) model = Sequential() # First layer is LSTM layer with 200 units model.add(LSTM(200, input_shape=(window_size, len(chars)))) # Dropout layer to avoid overfitting model.add(Dropout(0.2)) # Fully connected, with len(chars) hidden units and linear activation model.add(Dense(hidden_units, activation='linear')) # Fully connected output layer with softmax activation model.add(Dense(y.shape[1], activation='softmax')) # initialize optimizer optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) # compile model --> make sure initialized optimizer and callbacks - as defined above - are used model.compile(loss='categorical_crossentropy', optimizer=optimizer) ``` ## 2.7 Training our RNN model for text generation With our RNN setup we can now train it! Lets begin by trying it out on a small subset of the larger version. In the next cell we take the first 10,000 input/output pairs from our training database to learn on. ``` # a small subset of our input/output pairs Xsmall = X[:10000,:,:] ysmall = y[:10000,:] ``` Now lets fit our model! ``` # train the model model.fit(Xsmall, ysmall, batch_size=500, epochs=40,verbose = 2) # save weights model.save_weights('model_weights/best_RNN_small_textdata_weights.hdf5') ``` How do we make a given number of predictions (characters) based on this fitted model? First we predict the next character after following any chunk of characters in the text of length equal to our chosen window size. Then we remove the first character in our input sequence and tack our prediction onto the end. This gives us a slightly changed sequence of inputs that still has length equal to the size of our window. We then feed in this updated input sequence into the model to predict the another character. Together then we have two predicted characters following our original input sequence. Repeating this process N times gives us N predicted characters. In the next Python cell we provide you with a completed function that does just this - it makes predictions when given a) a trained RNN model, b) a subset of (window_size) characters from the text, and c) a number of characters to predict (to follow our input subset). ``` # function that uses trained model to predict a desired number of future characters def predict_next_chars(model,input_chars,num_to_predict): # create output predicted_chars = '' for i in range(num_to_predict): # convert this round's predicted characters to numerical input x_test = np.zeros((1, window_size, len(chars))) for t, char in enumerate(input_chars): x_test[0, t, chars_to_indices[char]] = 1. # make this round's prediction test_predict = model.predict(x_test,verbose = 0)[0] # translate numerical prediction back to characters r = np.argmax(test_predict) # predict class of each test input d = indices_to_chars[r] # update predicted_chars and input predicted_chars+=d input_chars+=d input_chars = input_chars[1:] return predicted_chars ``` <a id='TODO_6'></a> With your trained model try a few subsets of the complete text as input - note the length of each must be exactly equal to the window size. For each subset us the function above to predict the next 100 characters that follow each input. ``` # TODO: choose an input sequence and use the prediction function in the previous Python cell to predict 100 characters following it # get an appropriately sized chunk of characters from the text choice = int(np.random.rand(1)*len(chars)) start_inds = [2000, 5000, 7000] # load in weights model.load_weights('model_weights/best_RNN_small_textdata_weights.hdf5') for s in start_inds: start_index = s input_chars = text[start_index: start_index + window_size] # use the prediction function predict_input = predict_next_chars(model,input_chars,num_to_predict = 100) # print out input characters print('------------------') input_line = 'input chars = ' + '\n' + input_chars + '"' + '\n' print(input_line) # print out predicted characters line = 'predicted chars = ' + '\n' + predict_input + '"' + '\n' print(line) ``` This looks ok, but not great. Now lets try the same experiment with a larger chunk of the data - with the first 100,000 input/output pairs. Tuning RNNs for a typical character dataset like the one we will use here is a computationally intensive endeavour and thus timely on a typical CPU. Using a reasonably sized cloud-based GPU can speed up training by a factor of 10. Also because of the long training time it is highly recommended that you carefully write the output of each step of your process to file. This is so that all of your results are saved even if you close the web browser you're working out of, as the processes will continue processing in the background but variables/output in the notebook system will not update when you open it again. In the next cell we show you how to create a text file in Python and record data to it. This sort of setup can be used to record your final predictions. ``` ### A simple way to write output to file f = open('my_test_output.txt', 'w') # create an output file to write too f.write('this is only a test ' + '\n') # print some output text x = 2 f.write('the value of x is ' + str(x) + '\n') # record a variable value f.close() # print out the contents of my_test_output.txt f = open('my_test_output.txt', 'r') # create an output file to write too f.read() ``` With this recording devices we can now more safely perform experiments on larger portions of the text. In the next cell we will use the first 100,000 input/output pairs to train our RNN model. First we fit our model to the dataset, then generate text using the trained model in precisely the same generation method applied before on the small dataset. **Note:** your generated words should be - by and large - more realistic than with the small dataset, but you won't be able to generate perfect English sentences even with this amount of data. A rule of thumb: your model is working well if you generate sentences that largely contain real English words. ``` # a small subset of our input/output pairs Xlarge = X[:100000,:,:] ylarge = y[:100000,:] # TODO: fit to our larger dataset model.fit(Xlarge, ylarge, batch_size=50, epochs=30,verbose = 2) # save weights model.save_weights('model_weights/best_RNN_large_textdata_weights.hdf5') # TODO: choose an input sequence and use the prediction function in the previous Python cell to predict 100 characters following it # get an appropriately sized chunk of characters from the text start_inds = [2000,5000,7000] # save output f = open('text_gen_output/RNN_large_textdata_output.txt', 'w') # create an output file to write too # load weights model.load_weights('model_weights/best_RNN_large_textdata_weights.hdf5') for s in start_inds: start_index = s input_chars = text[start_index: start_index + window_size] # use the prediction function predict_input = predict_next_chars(model,input_chars,num_to_predict = 200) # print out input characters line = '-------------------' + '\n' print(line) f.write(line) input_line = 'input chars = ' + '\n' + input_chars + '"' + '\n' print(input_line) f.write(input_line) # print out predicted characters predict_line = 'predicted chars = ' + '\n' + predict_input + '"' + '\n' print(predict_line) f.write(predict_line) f.close() ```
github_jupyter
# Neural Networks as Dynamical Systems ![feedforward](Single_layer_ann.png) A neuronal model is made up of an input vector $\overrightarrow{X}=(x_1,x_2,\ldots, x_n)^T$, A vector of synaptic weights, $W_k=w_{kj}$, $j=1,2,\ldots,n$ a bias $b_k$ and an output $y_k$. The neuron itself is a nonlinear transfer function $\phi$. \begin{align} v_k &= W_k X + b_k\\ y_k &= \phi(v_k). \end{align} The function $\phi$, also known as the activation function, typically range from $-1$ to $+1$ and can take many forms such as the Heaviside function, piece-wise linear function, a sigmoid function, etc. # Training training a neural network corresponds to the act of adjusting the parameters described above to minimize the error of the network with respect to a target vector. ## Generalized Delta rule for a linear activation function, the weights are adjusted according to: $$w_{kj}(n+1)=w_{kj}(n)-\eta g_{kj},$$ where n is the number of iterations, $g_{kj}=-(t_k-y_k)$, and $\eta$ is a small positive constant called the learning rate. For a nonlinear activation function, the generalized delta rule is: $$w_{kj}(n+1)=w_{kj}(n)-\eta g_{kj},$$ where $$g_{kj}=(y_k-t_k)\frac{\partial \phi}{\partial v_k}x_j$$ ``` np.c_[np.ones(rows), X].shape import matplotlib.pyplot as plt import numpy as np data = np.loadtxt('housing.txt') rows, columns = data.shape columns = 4 # Using 4 columns from data in this case X = data[:, [5, 8, 12]] t = data[:, 13] ws1, ws2, ws3, ws4 = [], [], [], [] k = 0 # Scale the data to zero mean and unit variance xmean = X.mean(axis=0) xstd = X.std(axis=0) ones = np.ones((1,rows)) X = (X - xmean * ones.T) / (xstd * ones.T) X = np.c_[np.ones(rows), X] tmean = (max(t) + min(t)) / 2 tstd = (max(t) - min(t)) / 2 t = (t - tmean) / tstd w = 0.1 * np.random.random(columns) y1 = np.tanh(X.dot(w)) e1 = t - y1 mse = np.var(e1) num_epochs = 20 # number of iterations eta = 0.001 # Learning rate k = 1 erros = [e1.mean()] for m in range(num_epochs): for n in range(rows): yk = np.tanh(X[n, :].dot(w)) err = yk - t[n] g = X[n, :].T * ((1 - yk**2) * err) w = w - eta*g k += 1 ws1.append([k, np.array(w[0]).tolist()]) ws2.append([k, np.array(w[1]).tolist()]) ws3.append([k, np.array(w[2]).tolist()]) ws4.append([k, np.array(w[3]).tolist()]) # print(err.mean()) erros.append(err.mean()) # break # print(erros) ws1 = np.array(ws1) ws2 = np.array(ws2) ws3 = np.array(ws3) ws4 = np.array(ws4) plt.plot(ws1[:, 0], ws1[:, 1], 'k.', markersize=0.1, label='ws1') plt.plot(ws2[:, 0], ws2[:, 1], 'g.', markersize=0.1, label='ws2') plt.plot(ws3[:, 0], ws3[:, 1], 'b.', markersize=0.1, label='ws3') plt.plot(ws4[:, 0], ws4[:, 1], 'r.', markersize=0.1, label='ws4') # plt.plot(erros, label='erro') plt.xlabel('Number of iterations', fontsize=15) plt.ylabel('Weights', fontsize=15) plt.tick_params(labelsize=15) plt.grid() plt.legend() plt.show() ``` ## Backpropagation Backpropagation is the most common training algorithm in use. It's required to train neurons in a *hidden* layer. ``` %%html <div style='position:relative; padding-bottom:calc(56.25% + 44px)'><iframe src='https://gfycat.com/ifr/AdolescentIdioticGoldeneye' frameborder='0' scrolling='no' width='100%' height='100%' style='position:absolute;top:0;left:0;' allowfullscreen></iframe></div><p> <a href="https://gfycat.com/adolescentidioticgoldeneye">via Gfycat</a></p> ``` ### Algorithm **Definitions:** Partial derivatives: $$\frac{\partial E_d}{\partial w_{ij}^k} = \delta_j^k o_i^{k-1}.\label{eq:1}$$ Final layer's error: $$\delta_1^m = g_o^{\prime}(a_1^m)\left(\hat{y_d}-y_d\right).\label{eq:2}$$ Hidden layer's error: $$\delta_j^k = g^{\prime}\big(a_j^k\big)\sum_{l=1}^{r^{k+1}}w_{jl}^{k+1}\delta_l^{k+1}.\label{eq:3}$$ Combining the partial derivatives for each input-output pair, $$\frac{\partial E(X, \theta)}{\partial w_{ij}^k} = \frac{1}{N}\sum_{d=1}^N\frac{\partial}{\partial w_{ij}^k}\left(\frac{1}{2}\left(\hat{y_d} - y_d\right)^{2}\right) = \frac{1}{N}\sum_{d=1}^N\frac{\partial E_d}{\partial w_{ij}^k}.\label{eq:4}$$ Weight update: $$\Delta w_{ij}^k = - \alpha \frac{\partial E(X, \theta)}{\partial w_{ij}^k}.\label{eq:5}$$ 1. Calculate the forward phase for each input-output pair $(\vec{x_d}, y_d)$ and store the results $\hat{y_d}$, $a_j^k$, and $o_j^k$ for each node $j$ in layer $k$ by proceeding from layer $0$, the input layer, to layer $m$, the output layer. 1. Calculate the backward phase for each input-output pair $(\vec{x_d}, y_d)$ and store the results $\frac{\partial E_d}{\partial w_{ij}^k}$ for each weight $w_{ij}^k$ connecting node $i$ in layer $k-1$ to node $j$ in layer $k$ by proceeding from layer $m$, the output layer, to layer $1$, the input layer. - Evaluate the error term for the final layer $\delta_1^m$ by using equation (\ref{eq:2}). - Backpropagate the error terms for the hidden layers $\delta_j^k$, working backwards from the final hidden layer $k = m-1$, by repeatedly using equation (\ref{eq:3}). - Evaluate the partial derivatives of the individual error $E_d$ with respect to $w_{ij}^k$ by using equation (\ref{eq:1}). 1. Combine the individual gradients for each input-output pair $\frac{\partial E_d}{\partial w_{ij}^k}$ to get the total gradient $\frac{\partial E(X, \theta)}{\partial w_{ij}^k}$ for the entire set of input-output pairs $X = \big\{(\vec{x_1}, y_1), \dots, (\vec{x_N}, y_N) \big\}$ by using equation (\ref{eq:4}) (a simple average of the individual gradients). 1. Update the weights according to the learning rate α\alpha and total gradient $\frac{\partial E(X, \theta)}{\partial w_{ij}^k}$ by using equation (\ref{eq:5}) (moving in the direction of the negative gradient). In the example below, the matrix $X$ is the set of inputs $\vec{x}$ and the matrix y is the set of outputs $y$. The number of nodes in the hidden layer can be customized by setting the value of the variable `num_hidden`. The learning rate $\alpha$ is controlled by the variable `alpha`. The number of iterations of gradient descent is controlled by the variable `num_iterations`. By changing these variables and comparing the output of the program to the target values $y$, one can see how these variables control how well backpropagation can learn the dataset $X$ and y. For example, more nodes in the hidden layer and more iterations of gradient descent will generally improve the fit to the training dataset. However, using too large or too small a learning rate can cause the model to diverge or converge too slowly, respectively. Adapted from: `Backpropagation. Brilliant.org`. Retrieved 08:32, August 31, 2021, from https://brilliant.org/wiki/backpropagation/ ``` import numpy as np # define the sigmoid function def sigmoid(x, derivative=False): if (derivative == True): return sigmoid(x,derivative=False) * (1 - sigmoid(x,derivative=False)) else: return 1 / (1 + np.exp(-x)) # choose a random seed for reproducible results np.random.seed(1) # learning rate alpha = .1 # number of nodes in the hidden layer num_hidden = 3 # inputs X = np.array([ [0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0], [1, 0, 1], [1, 1, 1], ]) # outputs # x.T is the transpose of x, making this a column vector y = np.array([[0, 1, 0, 1, 1, 0]]).T # initialize weights randomly with mean 0 and range [-1, 1] # the +1 in the 1st dimension of the weight matrices is for the bias weight hidden_weights = 2*np.random.random((X.shape[1] + 1, num_hidden)) - 1 output_weights = 2*np.random.random((num_hidden + 1, y.shape[1])) - 1 # number of iterations of gradient descent num_iterations = 10000 outputs=[] # for each iteration of gradient descent for i in range(num_iterations): # forward phase # np.hstack((np.ones(...), X) adds a fixed input of 1 for the bias weight input_layer_outputs = np.hstack((np.ones((X.shape[0], 1)), X)) hidden_layer_outputs = np.hstack((np.ones((X.shape[0], 1)), sigmoid(np.dot(input_layer_outputs, hidden_weights)))) output_layer_outputs = np.dot(hidden_layer_outputs, output_weights) # backward phase # output layer error term output_error = output_layer_outputs - y # hidden layer error term # [:, 1:] removes the bias term from the backpropagation hidden_error = hidden_layer_outputs[:, 1:] * (1 - hidden_layer_outputs[:, 1:]) * np.dot(output_error, output_weights.T[:, 1:]) # partial derivatives hidden_pd = input_layer_outputs[:, :, np.newaxis] * hidden_error[: , np.newaxis, :] output_pd = hidden_layer_outputs[:, :, np.newaxis] * output_error[:, np.newaxis, :] # average for total gradients total_hidden_gradient = np.average(hidden_pd, axis=0) total_output_gradient = np.average(output_pd, axis=0) # update weights hidden_weights += - alpha * total_hidden_gradient output_weights += - alpha * total_output_gradient outputs.append(output_layer_outputs) # print the final outputs of the neural network on the inputs X print("Output After Training: \n{}".format(output_layer_outputs)) plt.plot(np.hstack(outputs).T); plt.legend([str(i) for i in y]); from scipy.integrate import odeint ``` ## Continuous Hopfield Model Hopfield equation where derived from Kirchoff's laws for electrical circuits. $$\frac{d\overrightarrow{x}(t)}{dt}=-x(t) +Wa(t) +b$$ where x(t) is a vector of neuron activation levels, $W$ is the weigth matrix, b are the biases, and $a(t)=\phi(x(t))$. ### Two neuron example \begin{align} \dot{x}&=-x +\frac{2}{\pi}tan^{-1}\left(\frac{\gamma\pi y}{2}\right)\\ \dot{y}&=-y +\frac{2}{\pi}tan^{-1}\left(\frac{\gamma\pi x}{2}\right) \end{align} let \begin{equation} \nonumber W=\begin{bmatrix} 0 & 1 \\ 1 & 0 \\ \end{bmatrix}, b=\begin{bmatrix} 0\\ 0 \end{bmatrix}, a1=2/\pi tan^{-1} \end{equation} ``` def hop2(Y,t): x,y = Y gamma = 20.5 return -x+(2/np.pi)*np.arctan(gamma*np.pi*y/2), -y+(2/np.pi)*np.arctan(gamma*np.pi*x/2) res = odeint(hop2,[0.5,0.5], range(100)) plt.plot(res); ``` ## Discrete Hopfield Model ``` from sympy import Matrix, eye import random # The fundamental memories: x1 = [1, 1, 1, 1, 1] x2 = [1, -1, -1, 1, -1] x3 = [-1, 1, -1, 1, 1] X = Matrix([x1, x2, x3]) W = X.T * X / 5 - 3*eye(5) / 5 def hsgn(v, x): if v > 0: return 1 elif v == 0: return x else: return -1 L = [0, 1, 2, 3, 4] n = random.sample(L, len(L)) xinput = [1, -1, -1, 1, 1] xtest = xinput for j in range(4): M = W.row(n[j]) * Matrix(xtest) xtest[n[j]] = hsgn(M[0], xtest[n[j]]) if xtest == x1: print('Net has converged to X1') elif xtest == x2: print('Net has converged to X2') elif xtest == x3: print('Net has converged to X3') else: print('Iterate again: May have converged to spurious state') # Program 20c: Iteration of the minimal chaotic neuromodule. # See Figure 20.13. import matplotlib.pyplot as plt import numpy as np # Parameters b1, b2, w11, w21, w12, a = -2, 3, -20, -6, 6, 1 num_iterations = 10000 def neuromodule(X): x,y=X xn=b1+w11/(1+np.exp(-a*x))+w12/(1+np.exp(-a*y)) yn=b2+w21/(1+np.exp(-a*x)) return xn,yn X0 = [0, 2] X, Y = [], [] for i in range(num_iterations): xn, yn = neuromodule(X0) X, Y = X + [xn], Y + [yn] X0 = [xn, yn] fig, ax = plt.subplots(figsize=(8, 8)) ax.scatter(X, Y, color='blue', s=0.1) plt.xlabel('x', fontsize=15) plt.ylabel('y', fontsize=15) plt.tick_params(labelsize=15) plt.show() # Program 20d: Bifurcation diagram of the neuromodule. # See Figure 20.16. from matplotlib import pyplot as plt import numpy as np # Parameters b2, w11, w21, w12, a = 3, 7, 5, -4, 1 start, max = -5, 10 half_N = 1999 N = 2 * half_N + 1 N1 = 1 + half_N xs_up, xs_down = [], [] x, y = -10, -3 ns_up = np.arange(half_N) ns_down = np.arange(N1, N) # Ramp b1 up for n in ns_up: b1 = start + n*max / half_N x = b1 + w11 / (1 + np.exp(-a*x)) + w12 / (1 + np.exp(-a*y)) y = b2+w21 / (1 + np.exp(-a*x)) xn = x xs_up.append([n, xn]) xs_up = np.array(xs_up) # Ramp b1 down for n in ns_down: b1 = start + 2*max - n*max / half_N x = b1 + w11 / (1 + np.exp(-a*x)) + w12 / (1 + np.exp(-a*y)) y = b2 + w21 / (1 + np.exp(-a*x)) xn = x xs_down.append([N-n, xn]) xs_down = np.array(xs_down) fig, ax = plt.subplots() xtick_labels = np.linspace(start, max, 7) ax.set_xticks([(-start + x) / max * N1 for x in xtick_labels]) ax.set_xticklabels(['{:.1f}'.format(xtick) for xtick in xtick_labels]) plt.plot(xs_up[:, 0], xs_up[:, 1], 'r.', markersize=0.1) plt.plot(xs_down[:, 0], xs_down[:,1], 'b.', markersize=0.1) plt.xlabel(r'$b_1$', fontsize=15) plt.ylabel(r'$x_n$', fontsize=15) plt.tick_params(labelsize=15) plt.show() ```
github_jupyter
**Post-Processing Amazon Textract with Location-Aware Transformers** # Part 3: Implementing Human Review > *This notebook works well with the `Python 3 (Data Science)` kernel on SageMaker Studio* In this final notebook, we'll set up the human review component of the OCR pipeline using [Amazon Augmented AI (A2I)](https://aws.amazon.com/augmented-ai/): Completing the demo pipeline. The A2I service shares a lot in common with SageMaker Ground Truth, with the main difference that A2I is designed for **near-real-time, single-example** annotation/review to support a live business process, while SMGT is oriented towards **offline, batch** annotation for building datasets. The two services both use the Liquid HTML templating language, and you might reasonably wonder: "*Are we going to use the same custom boxes-plus-review template from earlier?*" In fact, no we won't - for reasons we'll get to in a moment. First though, let's load the required libraries and configuration for the notebook as before: ## Dependencies and configuration The custom task template demonstrated in this notebook is a little more complex than the SageMaker Ground Truth one we saw in notebook 1, so is built with a [NodeJS](https://nodejs.org/en/)-based **toolchain** rather than edited as a raw HTML file. - If you're running this notebook in SageMaker Studio, you can install NodeJS by running the below. - If you're on a SageMaker Notebook Instance, check as it may already be installed - in which case you can skip this step. - If you're running on some other environment (like a local laptop), you probably want to install NodeJS via standard tools instead. [nvm](https://github.com/nvm-sh/nvm) is a helpful utility for managing multiple different Node versions on your system. - If you're not able to install NodeJS on your environment, don't worry - there's an alternative pre-built option (missing some features) mentioned later when we use it. ``` # Check if NodeJS installed: !node --version # Install NodeJS: NODE_VER = "v16.14.2" NODE_DISTRO = "linux-x64" !mkdir -p /usr/local/lib/nodejs !wget -c https://nodejs.org/dist/{NODE_VER}/node-{NODE_VER}-{NODE_DISTRO}.tar.xz -O - | tar -xJ -C /usr/local/lib/nodejs # Can't easily override PATH here, so instead we'll just symlink relevant executable files into a # folder that's already on the PATH: NODE_BIN_DIR = f"/usr/local/lib/nodejs/node-{NODE_VER}-{NODE_DISTRO}/bin" ONPATH_BIN_DIR = "/usr/local/bin" !ln -fs {NODE_BIN_DIR}/node {ONPATH_BIN_DIR}/node && \ ln -fs {NODE_BIN_DIR}/npm {ONPATH_BIN_DIR}/npm && \ ln -fs {NODE_BIN_DIR}/npx {ONPATH_BIN_DIR}/npx && \ echo "NodeJS {NODE_VER} installed!" ``` As before, once required libraries are installed, we can proceed with other imports and configuration: ``` %load_ext autoreload %autoreload 2 # Python Built-Ins: import json from logging import getLogger import os # External Dependencies: import boto3 # AWS SDK for Python import sagemaker # High-level SDK for SageMaker # Local Dependencies: import util logger = getLogger() role = sagemaker.get_execution_role() s3 = boto3.resource("s3") smclient = boto3.client("sagemaker") # Manual configuration (check this matches notebook 1): bucket_name = sagemaker.Session().default_bucket() bucket_prefix = "textract-transformers/" print(f"Working in bucket s3://{bucket_name}/{bucket_prefix}") config = util.project.init("ocr-transformers-demo") print(config) # Field configuration saved from first notebook: with open("data/field-config.json", "r") as f: fields = [ util.postproc.config.FieldConfiguration.from_dict(cfg) for cfg in json.loads(f.read()) ] entity_classes = [f.name for f in fields] # S3 URIs per first notebook: raw_s3uri = f"s3://{bucket_name}/{bucket_prefix}data/raw" ``` ## The rationale for a separate review template For many ML-powered processes, intercepting low-confidence predictions for human review is important for delivering efficient, accurate service. To deliver high-performing ML models sustainably, continuous collection of feedback for re-training is also important. In this section we'll detail some reasons **why**; although joining the two processes together might be ideal; this example will demonstrate a **separate prediction review workflow** from the training data collection. ### Tension between process execution and model improvement As we saw when setting up the pipeline in the last notebook, there's a **post-processing step** after the ML model - whose purpose is: - To consolidate consecutive `WORD`s of the same class into a single "entity" detection via a simple heuristic - To apply (configurable) business rules to consolidate entity detections into "fields" on the document (e.g. selecting a single value from multiple possible matches, etc). Both of these processes are implemented in a simple Python Lambda function, and so would be technically straightforward to port into the ML model endpoint itself (in [src/inference.py](src/inference.py)). However, it's the **second one** that's important. For any use case where there's a non-trivial **gap** between what the model is trained to estimate and what the business process consumes, there's a **tension** in the review process: 1. Reviewing business process fields is efficient, but does not collect model training data (although it may help us understand overall accuracy) 2. Reviewing the model inputs & outputs directly collects training data, but: - Does not directly review the accuracy of the end-to-end business process, so requires complete trust in the post-processing rules - May be inefficient, as the reviewer needs to collect more information than the business process absolutely requires (e.g. having to highlight every instance of `Provider Name` in the doc, when the business process just needs to know what the name is) 3. Splitting the review into multiple stages collects training/accuracy data for both components (ML model and business rules), but requires even more time - especially if the hand-off between the review stages might be asynchronous In many cases the efficiency of the live process is most important for customer experience and cost management, and so approach 1 is taken (as we will in this example): With collection of additional model training data handled as an additional background task. In some cases it may be possible to fully close the gap to resolve the tension and make a single offline-annotation/online-review UI work for everybody... E.g. for the credit cards use case, we might be able to: - (Add effort) Move from word classification to a **sequence-to-sequence model**, to support more complex output processing (like OCR error correction, field format standardization, grouping words into matches, etc)... *OR* - (Reduce scope) **Focus only on use-cases** where: - Each entity class only appears once in the document, *OR* most/every detection of multiple entities is equally important to the business process (may often be the case! E.g. on forms or other well-structured use cases) *AND* - Errors in OCR transcription or the heuristic rules to group matched words together are rare enough *or unpredictable enough* that there's no value in a confidence-score-based review (E.g. if "The OCR/business rules aren't making mistakes very often, and even when they do the confidence is still high - so our online review isn't helping these issues") ### A small techical challenge So what if your use case for this model is: - Seeing **high enough OCR accuracy rates** from Textract, and - Enjoying good success with the heuristic for **joining classified words together** into multi-word entities based on the order Textract returned them, and - Either having only **one match per entity type** per document; or where it's important to **always return multiple matches** if they're present? Then maybe it would make sense roll your online review and training data collection into one process! By simply trusting the post-processing logic / OCR quality, and having reviewers use the bounding box tool. **However,** there's one final hurdle: At the time of writing, the Ground Truth/A2I bounding box annotator works only for individual images, not PDFs. This means you'd also need to either: - Restrict the pipeline to processing single-page documents/images, or - Implement a custom box task UI capable of working with PDFs also, or - Orchestrate around the problem by splitting and dispatching each document to multiple single-page A2I reviews. ### In summary For some use cases of technology like this, directly using the training data annotation UI for online review could be the most efficient option. But to avoid ignoring the (potentially large) set of viable use cases where it's not practical; and to avoid introducing complexity or workarounds for handling multi-page documents; this sample presents a separate tailored online review UI. ## Develop the review task template Just as with SageMaker Ground Truth, a custom task UI template has been provided and we can preview it via the SageMaker SDK. The interfaces for building SMGT and A2I templates are generally very similar but in this particular case there are some differences here from our notebook 1: 1. This template accepts the list of fields dynamically at run-time, so **no extra parameter substitutions** are required in the template itself 1. The input to this stage of the pipeline is a little more complex than a simple image + Amazon Textract result URI: So we'll use an **example JSON file** and substitute the Textract URI to match your bucket and prefix (so the displayed file will not match the extracted field content) 1. Since the custom template here is a little more complex, we use a **NodeJS-based toolchain** to build it rather than directly authoring a browser-ready HTML file. You can find more detailed information about the reasons and practicalities for this in the [review/README.md](review/README.md) file. First, you'll need to set up the custom UI project in the `review/` folder - installing the additional dependencies it requires: > ⚠️ **If you have problems** with the node/npm build process, you can instead fall back to the provided legacy straight-to-HTML template instead - by just setting: > > ```python > ui_template_file = "review/fields-validation-legacy.liquid.html" # (Already exists) > ``` ``` !cd review && npm install ``` Then, build the UI HTML template from source: ``` !cd review && npm run build ui_template_file = "review/dist/index.html" ``` Next, prepare the dummy task JSON object for usefully previewing the UI: ``` # Load the sample input from file: with open("review/task-input.example.json", "r") as f: sample_obj = json.loads(f.read()) # Find any `a_pdf_s3uri`, so long as it exists in your account: textract_s3key_root = f"{bucket_prefix}data/raw" try: a_pdf_s3obj = next(filter( lambda o: o.key.endswith(".pdf"), s3.Bucket(bucket_name).objects.filter(Prefix=textract_s3key_root) )) a_pdf_s3uri = f"s3://{a_pdf_s3obj.bucket_name}/{a_pdf_s3obj.key}" except StopIteration as e: raise ValueError( f"Couldn't find any .pdf files in s3://{bucket_name}/{textract_s3key_root}" ) from e # Substitute the PDF URI in the sample input object: sample_obj["TaskObject"] = a_pdf_s3uri ``` Finally, render the template: ``` ui_render_file = "review/render.tmp.html" with open(ui_template_file, "r") as fui: with open(ui_render_file, "w") as frender: ui_render_resp = smclient.render_ui_template( UiTemplate={ "Content": fui.read() }, Task={ "Input": json.dumps(sample_obj) }, RoleArn=role, ) frender.write(ui_render_resp["RenderedContent"]) if "Errors" in ui_render_resp: if (ui_render_resp["Errors"] and len(ui_render_resp["Errors"])): print(ui_render_resp["Errors"]) raise ValueError("Template render returned errors") print(f"▶️ Open {ui_render_file} and click 'Trust HTML' to see the UI in action!") ``` Opening [review/render.tmp.html](review/render.tmp.html) and clicking **Trust HTML** in the toolbar, you should see a view something similar to the below. In this UI, the model's detections are rendered as bounding boxes over the source document with the same class colours as the original annotation view. In the right panel, you can view and amend the detected values for each field or use the checkboxes to toggle whether the field is present in the document or not. Both single- and multi-value fields are supported, and the overall confidence of detection is shown as a bar graph for each field type. ![](img/a2i-custom-template-demo.png "Screenshot of custom review UI") ## Set up the human review workflow Similarly to a SageMaker Ground Truth labelling job, we have 3 main concerns for setting up an A2I review workflow: - **Who's** doing the labelling - **What** the task will look like - **Where** the output reviews will be stored to once the review completes (i.e. location on Amazon S3) Our **workteam** from notebook 1 should already be set up. ▶️ **Check** the workteam name below matches your setup, and run the cell to store the ARN: ``` workteam_name = "just-me" # TODO: Update this to match yours, if different workteam_arn = util.smgt.workteam_arn_from_name(workteam_name) ``` Our **template** has been tested as above, so just needs to be registered with A2I. You can use the below code to register your template and store its ARN, but can also refer to the [A2I Console worker task templates list](https://console.aws.amazon.com/a2i/home?#/worker-task-templates) ``` with open(ui_template_file, "r") as f: create_template_resp = smclient.create_human_task_ui( HumanTaskUiName="fields-validation-1", # (Can change this name as you like) UiTemplate={ "Content": f.read() }, ) task_template_arn = create_template_resp["HumanTaskUiArn"] print(f"Created A2I task template:\n{task_template_arn}") ``` To finish setting up the "workflow" itself, we need 2 more pieces of information: - The **location in S3** where review outputs should be stored - An appropriate **execution role** which will give the A2I workflow to read input documents and write review results. These are determined by the **OCR pipeline solution stack**, because the reviews bucket is created by the pipeline with event triggers to resume the next stage when reviews are uploaded. The code below should be able to look up these parameters for you automatically: ``` reviews_bucket_name = config.pipeline_reviews_bucket_name print(reviews_bucket_name) reviews_role_arn = config.a2i_execution_role_arn print(reviews_role_arn) ``` Alternatively, you may **find** your pipeline solution stack from the [AWS CloudFormation Console](https://console.aws.amazon.com/cloudformation/home?#/stacks) and click through to the stack detail page. From the **Outputs** tab, you should see the `A2IHumanReviewBucketName` and `A2IHumanReviewExecutionRoleArn` values as shown below. (You may also note the `A2IHumanReviewFlowParamName`, which we'll use in the next section) ![](img/cfn-stack-outputs-a2i.png "CloudFormation stack outputs for OCR pipeline") Once these values are populated, you're ready to create your review workflow by running the code below. Note that you can also manage flows via the [A2I Human Review Workflows Console](https://console.aws.amazon.com/a2i/home?#/human-review-workflows/). ``` create_flow_resp = smclient.create_flow_definition( FlowDefinitionName="ocr-fields-validation-1", # (Can change this name as you like) HumanLoopConfig={ "WorkteamArn": workteam_arn, "HumanTaskUiArn": task_template_arn, "TaskTitle": "Review OCR Field Extractions", "TaskDescription": "Review and correct credit card agreement field extractions", "TaskCount": 1, # One reviewer per item "TaskAvailabilityLifetimeInSeconds": 60 * 60, # Availability timeout "TaskTimeLimitInSeconds": 60 * 60, # Working timeout }, OutputConfig={ "S3OutputPath": f"s3://{reviews_bucket_name}/reviews", }, RoleArn=reviews_role_arn, ) print(f"Created review workflow:\n{create_flow_resp['FlowDefinitionArn']}") ``` ## Integrate with the OCR pipeline Once the human review workflow is created, the final integration step is to point the pipeline at it - just as we did for our SageMaker endpoint earlier. In code, this can be done as follows: ``` print(f"Configuring pipeline with review workflow: {create_flow_resp['FlowDefinitionArn']}") ssm = boto3.client("ssm") ssm.put_parameter( Name=config.a2i_review_flow_arn_param, Overwrite=True, Value=create_flow_resp["FlowDefinitionArn"], ) ``` Alternatively through the console, you would follow these steps: ▶️ **Check** the `A2IHumanReviewFlowParamName` output of your OCR pipeline stack in [CloudFormation](https://console.aws.amazon.com/cloudformation/home?#/stacks) (as we did above) ▶️ **Open** the [AWS Systems Manager Parameter Store console](https://console.aws.amazon.com/systems-manager/parameters/?tab=Table) and **find the review flow parameter in the list**. ▶️ **Click** on the name of the parameter to open its detail page, and then on the **Edit** button in the top right corner. Set the value to the **workflow ARN** (see previous code cell in this notebook) and save the changes. ![](img/ssm-a2i-param-detail.png "Screenshot of SSM parameter detail page for human workflow") ## Final testing Your OCR pipeline should now be fully functional! Let's try it out: ▶️ **Log in** to the labelling portal (URL available from the [SageMaker Ground Truth Workforces Console](https://console.aws.amazon.com/sagemaker/groundtruth?#/labeling-workforces) for your correct AWS Region) ![](img/smgt-find-workforce-url.png "Screenshot of SMGT console with workforce login URL") ▶️ **Upload** one of the sample documents to your pipeline's input bucket in Amazon S3, either using the code snippets below or drag and drop in the [Amazon S3 Console](https://console.aws.amazon.com/s3/) ``` pdfpaths = [] for currpath, dirs, files in os.walk("data/raw"): if "/." in currpath or "__" in currpath: continue pdfpaths += [ os.path.join(currpath, f) for f in files if f.lower().endswith(".pdf") ] pdfpaths = sorted(pdfpaths) test_filepath = pdfpaths[14] test_s3uri = f"s3://{config.pipeline_input_bucket_name}/{test_filepath}" !aws s3 cp '{test_filepath}' '{test_s3uri}' ``` ▶️ **Open up** your "Processing Pipeline" state machine in the [AWS Step Functions Console](https://console.aws.amazon.com/states/home?#/statemachines) After a few seconds you should find that a Step Function execution is automatically triggered and (since we enabled so many fields that at least one is always missing) the example is eventually forwarded for human review in A2I. As you'll see from the `ModelResult` field in your final *Step Output*, this pipeline produces a rich but usefully-structured output - with good opportunities for onward integration into further Step Functions steps or external systems. You can find more information and sample solutions for integrating AWS Step Functions in the [Step Functions Developer Guide](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html). ![](img/sfn-statemachine-success.png "Screenshot of successful Step Function execution with output JSON") ## Conclusion In this worked example we showed how advanced, open-source language processing models specifically tailored for document understanding can be integrated with [Amazon Textract](https://aws.amazon.com/textract/): providing a trainable, ML-driven framework for tackling more niche or complex requirements where Textract's [built-in structure extraction tools](https://aws.amazon.com/textract/features/) may not fully solve the challenges out-of-the-box. The underlying principle of the model - augmenting multi-task neural text processing architectures with positional data - is highly extensible, with potential to tackle a wide range of use cases where joint understanding of the content and presentation of text can deliver better results than considering text alone. We demonstrated how an end-to-end process automation pipeline applying this technology might look: Developing and deploying the model with [Amazon SageMaker](https://aws.amazon.com/sagemaker/), building a serverless workflow with [AWS Step Functions](https://aws.amazon.com/step-functions/) and [AWS Lambda](https://aws.amazon.com/lambda/), and driving quality with human review of low-confidence documents through [Amazon Augmented AI](https://aws.amazon.com/augmented-ai/). Thanks for following along, and for more information, don't forget to check out: - The other published [Amazon Textract Examples](https://docs.aws.amazon.com/textract/latest/dg/other-examples.html) listed in the [Textract Developer Guide](https://docs.aws.amazon.com/textract/latest/dg/what-is.html) - The extensive repository of [Amazon SageMaker Examples](https://github.com/aws/amazon-sagemaker-examples) and usage documentation in the [SageMaker Python SDK User Guide](https://sagemaker.readthedocs.io/en/stable/) - as well as the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/index.html) - The wide range of other open algorithms and models published by [HuggingFace Transformers](https://huggingface.co/transformers/), and their specific documentation on [using the library with SageMaker](https://huggingface.co/transformers/sagemaker.html) - The conversational AI and NLP area (and others) of Amazon's own [Amazon.Science](https://www.amazon.science/conversational-ai-natural-language-processing) blog Happy building!
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline from numpy import * from IPython.html.widgets import * import matplotlib.pyplot as plt from IPython.core.display import clear_output ``` # PCA and EigenFaces Demo In this demo, we will go through the basic concepts behind the principal component analysis (PCA). We will then apply PCA to a face dataset to find the characteristic faces ("eigenfaces"). ## What is PCA? PCA is a **linear** transformation. Suppose we have a $N \times P$ data matrix ${\bf X}$, where $N$ is the number of samples and $P$ is the dimension of each sample. Then PCA will find you a $K \times P$ matrix ${\bf V}$ such that $$ \underbrace{{\bf X}}_{N \times P} = \underbrace{{\bf S}}_{P \times K} \underbrace{{\bf V}}_{K \times P}. $$ Here, $K$ is the number of **principal components** with $K \le P$. ## But what does the V matrix do? We can think of ${\bf V}$ in many different ways. The first way is to think of it as a de-correlating transformation: originally, each variable (or dimension) in ${\bf X}$ - there are $P$ of them - may be *correlated*. That is, if we take any two column vectors of ${\bf X}$, say ${\bf x}_0$ and ${\bf x}_1$, their covariance is not going to be zero. Let's try this in a randomly generated data: ``` from numpy.random import standard_normal # Gaussian variables N = 1000; P = 5 X = standard_normal((N, P)) W = X - X.mean(axis=0,keepdims=True) print(dot(W[:,0], W[:,1])) ``` I'll skip ahead and use a pre-canned PCA routine from `scikit-learn` (but we'll dig into it a bit later!) Let's see what happens to the transformed variables, ${\bf S}$: ``` from sklearn.decomposition import PCA S=PCA(whiten=True).fit_transform(X) print(dot(S[:,0], S[:,1])) ``` Another way to look at ${\bf V}$ is to think of them as **projections**. Since the row vectors of ${\bf V}$ is *orthogonal* to each other, the projected data ${\bf S}$ lines in a new "coordinate system" specified by ${\bf V}$. Furthermore, the new coordinate system is sorted in the decreasing order of *variance* in the original data. So, PCA can be thought of as calculating a new coordinate system where the basis vectors point toward the direction of largest variances first. <img src="files/images/PCA/pca.png" style="margin:auto; width: 483px;"/> Exercise 1. Let's get a feel for this in the following interactive example. Try moving the sliders around to generate the data, and see how the principal component vectors change. In this demo, `mu_x` and `mu_y` specifies the center of the data, `sigma_x` and `sigma_y` the standard deviations, and everything is rotated by the angle `theta`. The two blue arrows are the rows of ${\bf V}$ that gets calculated. When you click on `center`, the data is first centered (mean is subtracted from the data) first. (Question: why is it necessary to "center" data when `mu_x` and `mu_y` are not zero?) ``` from numpy.random import standard_normal from matplotlib.patches import Ellipse from numpy.linalg import svd @interact def plot_2d_pca(mu_x=FloatSlider(min=-3.0, max=3.0, value=0), mu_y=FloatSlider(min=-3.0, max=3.0, value=0), sigma_x=FloatSlider(min=0.2, max=1.8, value=1.8), sigma_y=FloatSlider(min=0.2, max=1.8, value=0.3), theta=FloatSlider(min=0.0, max=pi, value=pi/6), center=False): mu=array([mu_x, mu_y]) sigma=array([sigma_x, sigma_y]) R=array([[cos(theta),-sin(theta)],[sin(theta),cos(theta)]]) X=dot(standard_normal((1000, 2)) * sigma[newaxis,:],R.T) + mu[newaxis,:] # Plot the points and the ellipse fig, ax = plt.subplots(figsize=(8,8)) ax.scatter(X[:200,0], X[:200,1], marker='.') ax.grid() M=8.0 ax.set_xlim([-M,M]) ax.set_ylim([-M,M]) e=Ellipse(xy=array([mu_x, mu_y]), width=sigma_x*3, height=sigma_y*3, angle=theta/pi*180, facecolor=[1.0,0,0], alpha=0.3) ax.add_artist(e) # Perform PCA and plot the vectors if center: X_mean=X.mean(axis=0,keepdims=True) else: X_mean=zeros((1,2)) # Doing PCA here... I'm using svd instead of scikit-learn PCA, we'll come back to this. U,s,V =svd(X-X_mean, full_matrices=False) for v in dot(diag(s/sqrt(X.shape[0])),V): # Each eigenvector ax.arrow(X_mean[0,0],X_mean[0,1],-v[0],-v[1], head_width=0.5, head_length=0.5, fc='b', ec='b') Ustd=U.std(axis=0) ax.set_title('std(U*s) [%f,%f]' % (Ustd[0]*s[0],Ustd[1]*s[1])) ``` Yet another use for ${\bf V}$ is to perform a **dimensionality reduction**. In many scenarios you encounter in image manipulation (as we'll see soon), we might want to have a more concise representation of the data ${\bf X}$. PCA with $K < P$ is one way to *reduce the dimesionality*: because PCA picks the directions with highest data variances, if a small number of top $K$ rows are sufficient to approximate (reconstruct) ${\bf X}$. ## How do we actually *perform* PCA? Well, we can use `from sklearn.decomposition import PCA`. But for learning, let's dig just one step into what it acutally does. One of the easiest way to perform PCA is to use the singular value decomposition (SVD). SVD decomposes a matrix ${\bf X}$ into a unitary matrix ${\bf U}$, rectangular diagonal matrix ${\bf \Sigma}$ (called "singular values"), and another unitary matrix ${\bf W}$ such that $$ {\bf X} = {\bf U} {\bf \Sigma} {\bf W}$$ So how can we use that to do PCA? Well, it turns out ${\bf \Sigma} {\bf W}$ of SVD, are exactly what we need to calculate the ${\bf V}$ matrix for the PCA, so we just have to run SVD and set ${\bf V} = {\bf \Sigma} {\bf W}$. (Note: `svd` of `numpy` returns only the diagonal elements of ${\bf \Sigma}$.) Exercise 2. Generate 1000 10-dimensional data and perform PCA this way. Plot the squares of the singular values. To reduce the the $P$-dimesional data ${\bf X}$ to a $K$-dimensional data, we just need to pick the top $K$ row vectors of ${\bf V}$ - let's call that ${\bf W}$ - then calcuate ${\bf T} = {\bf X} {\bf W}^\intercal$. ${\bf T}$ then has the dimension $N \times K$. If we want to reconstruct the data ${\bf T}$, we simply do ${\hat {\bf X}} = {\bf T} {\bf W}$ (and re-add the means for ${\bf X}$, if necessary). Exercise 3. Reduce the same data to 5 dimensions, then based on the projected data ${\bf T}$, reconstruct ${\bf X}$. What's the mean squared error of the reconstruction? # Performing PCA on a face dataset Now that we have a handle on the PCA method, let's try applying it to a dataset consisting of face data. We have two datasets in this demo, CAFE and POFA. The following code loads the dataset into the `dataset` variable: ``` import pickle dataset=pickle.load(open('data/cafe.pkl','r')) # or 'pofa.pkl' for POFA disp('dataset.images shape is %s' % str(dataset.images.shape)) disp('dataset.data shape is %s' % str(dataset.data.shape)) @interact def plot_face(image_id=(0, dataset.images.shape[0]-1)): plt.imshow(dataset.images[image_id],cmap='gray') plt.title('Image Id = %d, Gender = %d' % (dataset.target[image_id], dataset.gender[image_id])) plt.axis('off') ``` ## Preprocessing We'll center the data by subtracting the mean. The first axis (`axis=0`) is the `n_samples` dimension. ``` X=dataset.data.copy() # So that we won't mess up the data in the dataset\ X_mean=X.mean(axis=0,keepdims=True) # Mean for each dimension across sample (centering) X_std=X.std(axis=0,keepdims=True) X-=X_mean disp(all(abs(X.mean(axis=0))<1e-12)) # Are means for all dimensions very close to zero? ``` Then we perform SVD to calculate the projection matrix $V$. By default, `U,s,V=svd(...)` returns full matrices, which will return $n \times n$ matrix `U`, $n$-dimensional vector of singular values `s`, and $d \times d$ matrix `V`. But here, we don't really need $d \times d$ matrix `V`; with `full_matrices=False`, `svd` only returns $n \times d$ matrix for `V`. ``` from numpy.linalg import svd U,s,V=svd(X,compute_uv=True, full_matrices=False) disp(str(U.shape)) disp(str(s.shape)) disp(str(V.shape)) ``` We can also plot how much each eigenvector in `V` contributes to the overall variance by plotting `variance_ratio` = $\frac{s^2}{\sum s^2}$. (Notice that `s` is already in the decreasing order.) The `cumsum` (cumulative sum) of `variance_ratio` then shows how much of the variance is explained by components up to `n_components`. ``` variance_ratio=s**2/(s**2).sum() # Normalized so that they add to one. @interact def plot_variance_ratio(n_components=(1, len(variance_ratio))): n=n_components-1 fig, axs = plt.subplots(1, 2, figsize=(12, 5)) axs[0].plot(variance_ratio) axs[0].set_title('Explained Variance Ratio') axs[0].set_xlabel('n_components') axs[0].axvline(n, color='r', linestyle='--') axs[0].axhline(variance_ratio[n], color='r', linestyle='--') axs[1].plot(cumsum(variance_ratio)) axs[1].set_xlabel('n_components') axs[1].set_title('Cumulative Sum') captured=cumsum(variance_ratio)[n] axs[1].axvline(n, color='r', linestyle='--') axs[1].axhline(captured, color='r', linestyle='--') axs[1].annotate(s='%f%% with %d components' % (captured * 100, n_components), xy=(n, captured), xytext=(10, 0.5), arrowprops=dict(arrowstyle="->")) ``` Since we're dealing with face data, each row vector of ${\bf V}$ is called an "eigenface". The first "eigenface" is the one that explains a lot of variances in the data, whereas the last one explains the least. ``` image_shape=dataset.images.shape[1:] # (H x W) @interact def plot_eigenface(eigenface=(0, V.shape[0]-1)): v=V[eigenface]*X_std plt.imshow(v.reshape(image_shape), cmap='gray') plt.title('Eigenface %d (%f to %f)' % (eigenface, v.min(), v.max())) plt.axis('off') ``` Now let's try reconstructing faces with different number of principal components (PCs)! Now, the transformed `X` is reconstructed by multiplying by the sample standard deviations for each dimension and adding the sample mean. For this reason, even for zero components, you get a face-like image! The rightmost plot is the "relative" reconstruction error (image minus the reconstruction squared, divided by the data standard deviations). White is where the error is close to zero, and black is where the relative error is large (1 or more). As you increase the number of PCs, you should see the error mostly going to zero (white). ``` @interact def plot_reconstruction(image_id=(0,dataset.images.shape[0]-1), n_components=(0, V.shape[0]-1), pc1_multiplier=FloatSlider(min=-2,max=2, value=1)): # This is where we perform the projection and un-projection Vn=V[:n_components] M=ones(n_components) if n_components > 0: M[0]=pc1_multiplier X_hat=dot(multiply(dot(X[image_id], Vn.T), M), Vn) # Un-center I=X[image_id] + X_mean I_hat = X_hat + X_mean D=multiply(I-I_hat,I-I_hat) / multiply(X_std, X_std) # And plot fig, axs = plt.subplots(1, 3, figsize=(10, 10)) axs[0].imshow(I.reshape(image_shape), cmap='gray', vmin=0, vmax=1) axs[0].axis('off') axs[0].set_title('Original') axs[1].imshow(I_hat.reshape(image_shape), cmap='gray', vmin=0, vmax=1) axs[1].axis('off') axs[1].set_title('Reconstruction') axs[2].imshow(1-D.reshape(image_shape), cmap='gray', vmin=0, vmax=1) axs[2].axis('off') axs[2].set_title('Difference^2 (mean = %f)' % sqrt(D.mean())) plt.tight_layout() ``` ## Image morphing As a fun exercise, we'll morph two images by taking averages of the two images within the transformed data space. How is it different than simply morphing them in the pixel space? ``` def plot_morph(left=0, right=1, mix=0.5): # Projected images x_lft=dot(X[left], V.T) x_rgt=dot(X[right], V.T) # Mix x_avg = x_lft * (1.0-mix) + x_rgt * (mix) # Un-project X_hat = dot(x_avg[newaxis,:], V) I_hat = X_hat + X_mean # And plot fig, axs = plt.subplots(1, 3, figsize=(10, 10)) axs[0].imshow(dataset.images[left], cmap='gray', vmin=0, vmax=1) axs[0].axis('off') axs[0].set_title('Left') axs[1].imshow(I_hat.reshape(image_shape), cmap='gray', vmin=0, vmax=1) axs[1].axis('off') axs[1].set_title('Morphed (%.2f %% right)' % (mix * 100)) axs[2].imshow(dataset.images[right], cmap='gray', vmin=0, vmax=1) axs[2].axis('off') axs[2].set_title('Right') plt.tight_layout() interact(plot_morph, left=IntSlider(max=dataset.images.shape[0]-1), right=IntSlider(max=dataset.images.shape[0]-1,value=1), mix=FloatSlider(value=0.5, min=0, max=1.0)) ```
github_jupyter
# Notebook Basics ## The Notebook dashboard When you first start the notebook server, your browser will open to the notebook dashboard. The dashboard serves as a home page for the notebook. Its main purpose is to display the notebooks and files in the current directory. For example, here is a screenshot of the dashboard page for the `examples` directory in the Jupyter repository: <img src="images/dashboard_files_tab.png" width="791px"/> The top of the notebook list displays clickable breadcrumbs of the current directory. By clicking on these breadcrumbs or on sub-directories in the notebook list, you can navigate your file system. To create a new notebook, click on the "New" button at the top of the list and select a kernel from the dropdown (as seen below). Which kernels are listed depend on what's installed on the server. Some of the kernels in the screenshot below may not exist as an option to you. <img src="images/dashboard_files_tab_new.png" width="202px" /> Notebooks and files can be uploaded to the current directory by dragging a notebook file onto the notebook list or by the "click here" text above the list. The notebook list shows green "Running" text and a green notebook icon next to running notebooks (as seen below). Notebooks remain running until you explicitly shut them down; closing the notebook's page is not sufficient. <img src="images/dashboard_files_tab_run.png" width="777px"/> To shutdown, delete, duplicate, or rename a notebook check the checkbox next to it and an array of controls will appear at the top of the notebook list (as seen below). You can also use the same operations on directories and files when applicable. <img src="images/dashboard_files_tab_btns.png" width="301px" /> To see all of your running notebooks along with their directories, click on the "Running" tab: <img src="images/dashboard_running_tab.png" width="786px" /> This view provides a convenient way to track notebooks that you start as you navigate the file system in a long running notebook server. ## Overview of the Notebook UI If you create a new notebook or open an existing one, you will be taken to the notebook user interface (UI). This UI allows you to run code and author notebook documents interactively. The notebook UI has the following main areas: * Menu * Toolbar * Notebook area and cells The notebook has an interactive tour of these elements that can be started in the "Help:User Interface Tour" menu item. ## Modal editor Starting with IPython 2.0, the Jupyter Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode. ### Edit mode Edit mode is indicated by a green cell border and a prompt showing in the editor area: <img src="images/edit_mode.png"> When a cell is in edit mode, you can type into the cell, like a normal text editor. <div class="alert alert-success"> Enter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area. </div> ### Command mode Command mode is indicated by a grey cell border with a blue left margin: <img src="images/command_mode.png"> When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press `c`, you will copy the current cell - no modifier is needed. <div class="alert alert-error"> Don't try to type into a cell in command mode; unexpected things will happen! </div> <div class="alert alert-success"> Enter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area. </div> ## Mouse navigation All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area: <img src="images/menubar_toolbar.png" width="786px" /> The first idea of mouse based navigation is that **cells can be selected by clicking on them.** The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode. If you are running this notebook in a live session (not on http://nbviewer.jupyter.org) try selecting different cells and going between edit and command mode. Try typing into a cell. The second idea of mouse based navigation is that **cell actions usually apply to the currently selected cell**. Thus if you want to run the code in a cell, you would select it and click the <button class='btn btn-default btn-xs'><i class="fa fa-step-forward icon-step-forward"></i></button> button in the toolbar or the "Cell:Run" menu item. Similarly, to copy a cell you would select it and click the <button class='btn btn-default btn-xs'><i class="fa fa-copy icon-copy"></i></button> button in the toolbar or the "Edit:Copy" menu item. With this simple pattern, you should be able to do most everything you need with the mouse. Markdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the <button class='btn btn-default btn-xs'><i class="fa fa-step-forward icon-step-forward"></i></button> button in the toolbar or the "Cell:Run" menu item. To unrender the selected cell, double click on the cell. ## Keyboard Navigation The modal user interface of the Jupyter Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode. The most important keyboard shortcuts are `Enter`, which enters edit mode, and `Esc`, which enters command mode. In edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts. In command mode, the entire keyboard is available for shortcuts, so there are many more. The `Help`->`Keyboard Shortcuts` dialog lists the available shortcuts. We recommend learning the command mode shortcuts in the following rough order: 1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j` 2. Saving the notebook: `s` 2. Change Cell types: `y`, `m`, `1-6`, `t` 3. Cell creation: `a`, `b` 4. Cell editing: `x`, `c`, `v`, `d`, `z` 5. Kernel operations: `i`, `0` (press twice)
github_jupyter
# Layers > All the basic layers used keratorch. ``` # default_exp layers # export import numpy as np import torch.nn as nn from fastai.vision import * from fastai import layers from keraTorch.activations import * from functools import partial # export class __inputDimError__(Exception): pass class Layer: def __init__(self, input_shape=None): # breakpoint() self.input_shape = input_shape def __set_io_shape__(self, input_shape): if input_shape is None and self.input_shape is None: __inputDimError__("Need to specify input shape in first layer") elif input_shape: self.input_shape = input_shape ``` ## Dense Linear layer that takes in `input_dim` and converts it to `units` number of dimensions. ``` # export class Dense: def __init__(self, units, input_dim=None, activation=None, use_bias=True, kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ Linear layer that takes in `input_dim` and converts it to `units` number of dimensions. parameters: - units: output dimension. - input_dim: input dimension. - activation (optional): non-linear activation. - use_bias (optional): To include bias layer or not (default: True) """ super().__init__() self.input_dim = input_dim self.activation = get_activation(activation) if activation else None if input_dim: self.layer = nn.Linear(input_dim, units, bias=use_bias) else: self.layer = partial(nn.Linear, out_features=units, bias=use_bias) # TODO: implement regularizers def get_layer(self, input_dim=None): if input_dim is None and self.input_dim is None: __inputDimError__("Need to specify number of input dimensions in first layer") elif input_dim: self.input_dim = input_dim self.layer = self.layer(in_features=input_dim) # else self.layer is already is assigned self.output_dim = self.layer.out_features layers = [layer for layer in [self.layer, self.activation] if layer] return {'output_dim': self.output_dim, 'layers': layers} # hide Dense(3, 5, activation='mish').get_layer() Dense(3, activation='mish').get_layer(5) ``` ## Conv2D ``` # export class Conv2D: def __init__(self, filters:int, kernel_size:int=3, strides:int=1, padding:int=None, activation:str=None, use_bias:bool=True, input_shape:tuple=None): """ Apply convolution on image using kernel filters. parameters: - filters: number of kernel filters - kernel_size: the width of the (square) kernel - strides: number of pixels to skip when sliding kernel (default 1) - padding: number of pixels to pad incoming image ` defaults to `ks//2` - activation: non-linearity - use_bias: bias - input_shape: incoming image shape of (#Channels, width, height) """ self.input_shape = input_shape if input_shape: ni = input_shape[0] self.layer = conv2d(ni, filters, kernel_size, strides, padding, use_bias) else: self.layer = partial(conv2d, nf=filters, ks=kernel_size, stride=strides, padding=padding, bias=use_bias) self.activation = get_activation(activation) if activation else None def get_layer(self, input_shape=None): if input_shape is None and self.input_shape is None: __inputDimError__("Need to specify input shape in first layer") elif input_shape: self.input_shape = input_shape ni = self.input_shape[0] self.layer = self.layer(ni=ni) # else self.input_shape is already is assigned dummy_x = torch.zeros(self.input_shape).unsqueeze(0) self.output_shape = self.layer(dummy_x).shape[1:] layers = [layer for layer in [self.layer, self.activation] if layer] return {'output_dim': self.output_shape, 'layers': layers} out_layer = Conv2D(5, activation='Relu', input_shape=(1, 10, 10)).get_layer() print(out_layer) conv_layer = out_layer['layers'][0] conv_layer(torch.zeros((1, 1, 10, 10))).shape out_layer = Conv2D(5, activation='Relu').get_layer((1, 10, 10)) print(out_layer) conv_layer = out_layer['layers'][0] conv_layer(torch.zeros((1, 1, 10, 10))).shape ``` ## Max Pool ``` # export class MaxPool2D: def __init__(self, kernel_size:int=2, strides:int=None, padding:int=0, input_shape:tuple=None): """ Apply convolution on image using kernel filters. parameters: - filters: number of kernel filters - kernel_size: the width of the (square) kernel - strides: number of pixels to skip when sliding kernel (default 1) - padding: number of pixels to pad incoming image ` defaults to `ks//2` - activation: non-linearity - use_bias: bias - input_shape: incoming image shape of (#Channels, width, height) """ self.input_shape = input_shape self.layer = nn.MaxPool2d(kernel_size, strides, padding) def get_layer(self, input_shape=None): if input_shape is None and self.input_shape is None: __inputDimError__("Need to specify input shape in first layer") elif input_shape: self.input_shape = input_shape # else self.input_shape is already is assigned dummy_x = torch.zeros(self.input_shape).unsqueeze(0) self.output_shape = self.layer(dummy_x).shape[1:] layers = [self.layer] return {'output_dim': self.output_shape, 'layers': layers} out_layer = MaxPool2D(2, input_shape=(1, 10, 10)).get_layer() print(out_layer) maxpool_layer = out_layer['layers'][0] maxpool_layer(torch.zeros((1, 1, 10, 10))).shape out_layer = MaxPool2D(2).get_layer((1, 10, 10)) print(out_layer) maxpool_layer = out_layer['layers'][0] maxpool_layer(torch.zeros((1, 1, 10, 10))).shape ``` ## Flatten ``` # export class Flatten: def __init__(self, input_shape=None): self.layer = layers.Flatten() self.input_shape = input_shape def get_layer(self, input_shape=None): if input_shape is None and self.input_shape is None: __inputDimError__("Need to specify input shape in first layer") elif input_shape: self.input_shape = input_shape # else self.input_shape is already is assigned self.output_dim = np.prod(self.input_shape) layers = [self.layer] return {'output_dim': self.output_dim, 'layers': layers} flatten = Flatten((5, 3)) flatten.get_layer() ``` ## Activation class ``` # export class Activation: def __init__(self, activation, input_shape=None): self.layer = get_activation(activation) self.input_shape = input_shape self.output_dim = input_shape def get_layer(self, input_shape=None): if input_shape is None and self.input_shape is None: __inputDimError__("Need to specify input shape in first layer") elif input_shape: self.input_shape = input_shape self.output_dim = input_shape # else self.input_shape is already is assigned layers = [self.layer] return {'output_dim': self.output_dim, 'layers': layers} Activation('softmax').get_layer() # hide from nbdev.export import * notebook2script() ```
github_jupyter
This flocking example is based on the following colab notebook: https://github.com/google/jax-md/blob/main/notebooks/flocking.ipynb ``` import jax from IPython.display import Image as DisplayImage from evojax import Trainer from evojax.policy import MLPPolicy from evojax.algo import PGPE from evojax.task.flocking import FlockinSgTask from evojax.util import create_logger # Let's create a directory to save logs and models. log_dir = './log' logger = create_logger(name='EvoJAX', log_dir=log_dir) logger.info('Welcome to the tutorial on Task creation!') logger.info('Jax backend: {}'.format(jax.local_devices())) !nvidia-smi --query-gpu=name --format=csv,noheader seed = 42 neighbor_num = 5 rollout_key = jax.random.PRNGKey(seed=seed) reset_key, rollout_key = jax.random.split(rollout_key, 2) reset_key = reset_key[None, :] train_task = FlockingTask(150) test_task = FlockingTask(150) policy = MLPPolicy( input_dim=neighbor_num*3, hidden_dims=[60, 60], output_dim=1, logger=logger, ) solver = PGPE( pop_size=64, param_size=policy.num_params, optimizer='adam', center_learning_rate=0.05, seed=seed, ) trainer = Trainer( policy=policy, solver=solver, train_task=train_task, test_task=test_task, max_iter=150, log_interval=10, test_interval=30, n_repeats=5, n_evaluations=10, seed=seed, log_dir=log_dir, logger=logger, ) _ = trainer.run() # Let's visualize the learned policy. def render(task, algo, policy): """Render the learned policy.""" task_reset_fn = jax.jit(task.reset) policy_reset_fn = jax.jit(policy.reset) step_fn = jax.jit(task.step) act_fn = jax.jit(policy.get_actions) params = algo.best_params[None, :] task_s = task_reset_fn(jax.random.PRNGKey(seed=seed)[None, :]) policy_s = policy_reset_fn(task_s) images = [FlockingTask.render(task_s, 0)] done = False step = 0 reward = 0 while not done: act, policy_s = act_fn(task_s, params, policy_s) task_s, r, done = step_fn(task_s, act) step += 1 reward = reward + r images.append(FlockingTask.render(task_s, 0)) print('reward={}'.format(reward)) return images def save_images_as_gif(images, file_name): images[0].save(file_name, save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0) imgs = render(test_task, solver, policy) save_images_as_gif(imgs, 'flocking.gif') DisplayImage('flocking.gif', format='png') ```
github_jupyter
# 25 - Advanced Exercises * Decorators ### Function review exercises ## 🎎🎎🎎 1.assign **```myfuction```** to a new variable, then access the function from that variable and print it using inputs 2 and 3. ``` # Write your own code in this cell def myfunction(a, b): return a + b = myfunction print() ``` ## 🎎🎎🎎 2.Define a function named **```inner_function```** that is nested within another function named **```outer_function```**. try to execute the inner_function outside of the outer_function . What error do you encounter and why? ``` # Write your own code in this cell ``` ## 🎎🎎🎎 3.Add a line of code to the functions below to make **```factorial_10()```** callable. ``` # Write your own code in this cell import math def outer_function(n): description = f'Calculating the factorial of {n}.' def inner_function(): print(description) print(f"Result = {math.factorial(n)}") factorial_10 = outer_function(10) factorial_10() ``` ## 🎎🎎🎎 4.Complete the following functions to allow them to call **```myreminder```** function with **```do```** function as an argument. ``` # Write your own code in this cell def myreminder( ): print('Remember to bring your glasses!') def do(): print('I\'m going to read a book.') myreminder(do) ``` ### Decorator exercises ## 🎎🎎 5.Create a decorator called **```retry```** that repeats the functions a given number of times and at a particular interval(In seconds). Take a keyword argument for the number of iterations **"repeat"** and a keyword argument for the distance between iterations **"interval"**. (Using the **```time.sleep(n)```** method, you can delay n seconds until the next line is executed) ``` # Write your own code in this cell import math import time def retry(func): @retry def factorial_calculation(n): r = math.factorial(n) print(r) factorial_calculation(10, repeat=3, interval=1) ``` ## 🎎 6.Write a decorator named **```log```** that adds the function name , function execution time and date and execution result to a file in the **"./Files/decorators/log.txt"** path. **```the sample contents of a log file:```** ``` The factorial_calculation function was executed at 11/15/2021, 19:37:30 with input 6 and output 720. The factorial_calculation function was executed at 11/15/2021, 19:37:34 with input 7 and output 5040. The factorial_calculation function was executed at 11/15/2021, 19:37:37 with input 8 and output 40320. The factorial_calculation function was executed at 11/15/2021, 19:37:41 with input 13 and output 6227020800. The factorial_calculation function was executed at 11/15/2021, 19:37:46 with input 24 and output 620448401733239439360000 ``` ``` # Write your own code in this cell import math import time from pathlib import Path def log(func): def wraper(*args, **kwargs): mytuple = time.localtime() time_string = time.strftime("%m/%d/%Y, %H:%M:%S", mytuple) @log def factorial_calculation(n): r = math.factorial(n) print(r) return r ``` ## 🎎🎎🎎 7.Create a decorator that prints the execution time of a function in seconds. Use **time.time()** method to calculate how long it takes to execute a function. Record the time before and after the execution of the function, then subtract them to calculate execution time. Can you add the amount of ram used to this decorator? ``` # Write your own code in this cell import time def timeit(func): @timeit def factorial_calculation(n): r = math.factorial(n) print(f"{n}! = {r}") factorial_calculation(1) factorial_calculation(10) factorial_calculation(20) ``` ## 🎎🎎 8.Function **```get_coin_price```** takes as input the symbol of each cryptocurrency and displays the current price. Create a decorator that allows you to give function **```get_coin_price```** multiple inputs instead of just one. ``` # Write your own code in this cell import urllib import json def multiple_inputs(func): @multiple_inputs def get_coin_price(coin): url = f"https://data.messari.io/api/v1/assets/{coin}/metrics" response=urllib.request.urlopen(url) if response.getcode() == 200: myjson = response.read() mydict = json.loads(myjson) price = mydict["data"]["market_data"]["price_usd"] coin_name = mydict["data"]['name'] print(f"{coin_name} price = {price:0.5f}") else: print("An error has occurred!") get_coin_price('btc') print("---------------------------") get_coin_price('btc', 'ada', 'xrp', 'link') ```
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from collections import Counter import re import unicodedata as ud from nltk.corpus import wordnet as wn from nltk.corpus import words as w from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import sent_tokenize, word_tokenize from nltk.stem import WordNetLemmatizer import os pd.set_option('display.max_colwidth', None) if not os.path.isfile("data/github-labels-top3-803k-train.csv"): print('downloading data...') !cd data & curl "https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-train.tar.gz" | tar -xz if not os.path.isfile("data/github-labels-top3-803k-test.csv"): print('downloading data...') !cd data & curl "https://tickettagger.blob.core.windows.net/datasets/github-labels-top3-803k-test.tar.gz" | tar -xz print('loading data...') train = pd.read_csv('data/github-labels-top3-803k-train.csv') test = pd.read_csv('data/github-labels-top3-803k-test.csv') print(train.shape, test.shape) label= 'issue_label' time = 'issue_created_at' repo = 'repository_url' title = 'issue_title' body = 'issue_body' author = 'issue_author_association' url = 'issue_url' label_col = 'labels' text_col = 'text' max_title = 30 max_body = 170 punctuations = '!"$%&\()*,/:;<=>[\\]^`{|}~+#@-`' ascii_regex = re.compile(r'[^\x00-\x7f]') issue_regex = re.compile(r'#[0-9]+') function_regex = re.compile(r'[a-zA-Z][a-zA-Z0-9_.]*\([a-zA-Z0-9_, ]*\)') ``` # first deduplicate the TRAINING dataset based on issue URls ``` dedup_train = train.sort_values(url).drop_duplicates(subset=[url]).copy() print('Number of dropped issue duplications: ' , train.shape[0] - dedup_train.shape[0]) dedup_train[title] = dedup_train[title].astype(str) dedup_train[body] = dedup_train[body].astype(str) dedup_train[author] = dedup_train[author].astype(str) dedup_train[time] = dedup_train[time].astype(str) dedup_train[repo] = dedup_train[repo].astype(str) test[title] = test[title].astype(str) test[body] = test[body].astype(str) test[author] = test[author].astype(str) test[time] = test[time].astype(str) test[repo] = test[repo].astype(str) ``` # text normalization on text columns of issues ``` print('Replacing functions...') dedup_train[body] = dedup_train[body].apply(lambda x:function_regex.sub(" function ",x)) test[body] = test[body].apply(lambda x:function_regex.sub(" function ",x)) print('Replacing issue numbers...') dedup_train[title] = dedup_train[title].apply(lambda x:issue_regex.sub(" issue ",x)) dedup_train[body] = dedup_train[body].apply(lambda x:issue_regex.sub(" issue ",x)) test[title] = test[title].apply(lambda x:issue_regex.sub(" issue ",x)) test[body] = test[body].apply(lambda x:issue_regex.sub(" issue ",x)) print('Converting to lower case...') dedup_train[title] = dedup_train[title].str.lower() dedup_train[body] = dedup_train[body].str.lower() test[title] = test[title].str.lower() test[body] = test[body].str.lower() ``` # remove extra information from text ``` print('Removing punctuations...') replace_string = ' '*len(punctuations) dedup_train[title] = dedup_train[title].str.translate(str.maketrans(punctuations, replace_string)) dedup_train[body] = dedup_train[body].str.translate(str.maketrans(punctuations, replace_string)) test[title] = test[title].str.translate(str.maketrans(punctuations, replace_string)) test[body] = test[body].str.translate(str.maketrans(punctuations, replace_string)) print('Removing non-ascii charachters...') dedup_train[title] = dedup_train[title].apply(lambda x:re.sub(ascii_regex, '', x)) dedup_train[title] = dedup_train[title].apply(lambda x:ud.normalize('NFD', x)) dedup_train[body] = dedup_train[body].apply(lambda x:re.sub(ascii_regex, '', x)) dedup_train[body] = dedup_train[body].apply(lambda x:ud.normalize('NFD', x)) test[title] = test[title].apply(lambda x:re.sub(ascii_regex, '', x)) test[title] = test[title].apply(lambda x:ud.normalize('NFD', x)) test[body] = test[body].apply(lambda x:re.sub(ascii_regex, '', x)) test[body] = test[body].apply(lambda x:ud.normalize('NFD', x)) print('Replacing fixed part of repo URl column...') dedup_train[repo] = dedup_train[repo].apply(lambda x: x.replace('https://api.github.com/repos/', '')) test[repo] = test[repo].apply(lambda x: x.replace('https://api.github.com/repos/', '')) print('Replacing white spaces...') dedup_train[title] = dedup_train[title].apply(lambda x:" ".join(x.split())) dedup_train[body] = dedup_train[body].apply(lambda x:" ".join(x.split())) test[title] = test[title].apply(lambda x:" ".join(x.split())) test[body] = test[body].apply(lambda x:" ".join(x.split())) ``` # truncate columns ``` dedup_train[title] = dedup_train[title].apply(lambda x: ' '.join(x.split(maxsplit=max_title)[:max_title])) dedup_train[body] = dedup_train[body].apply(lambda x: ' '.join(x.split(maxsplit=max_body)[:max_body])) test[title] = test[title].apply(lambda x: ' '.join(x.split(maxsplit=max_title)[:max_title])) test[body] = test[body].apply(lambda x: ' '.join(x.split(maxsplit=max_body)[:max_body])) ``` # prepare labels column ``` # convert categorical data to codes dedup_train[label] = pd.Categorical(dedup_train[label]) test[label] = pd.Categorical(test[label]) dedup_train[label_col] = dedup_train[label].cat.codes test[label_col] = test[label].cat.codes ``` # concat issue columns in one "text" column to feed the model ``` # concat columns in a bag of sentences dedup_train[text_col] = 'time ' + dedup_train[time] + ' author ' + dedup_train[author] +' repo ' + dedup_train[repo] + ' title ' + dedup_train[title] + ' body ' + dedup_train[body] test[text_col] = 'time ' + test[time] + ' author ' + test[author] +' repo ' + test[repo] + ' title ' + test[title] + ' body ' + test[body] ``` # split and save datasets ``` # reset index dedup_train.reset_index(drop=True, inplace=True) test.reset_index(drop=True, inplace=True) dedup_train[[text_col, label_col]].to_csv(f'data/train_clean_concat_{max_title+max_body}.csv', index = False) test[[text_col, label_col]].to_csv(f'data/test_clean_concat_{max_title+max_body}.csv', index = False) ```
github_jupyter
# Modeling and Simulation in Python Project 1 example Copyright 2018 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim library from modsim import * from pandas import read_html filename = '../data/World_population_estimates.html' tables = read_html(filename, header=0, index_col=0, decimal='M') table2 = tables[2] table2.columns = ['census', 'prb', 'un', 'maddison', 'hyde', 'tanton', 'biraben', 'mj', 'thomlinson', 'durand', 'clark'] def plot_results(census, un, timeseries, title): """Plot the estimates and the model. census: TimeSeries of population estimates un: TimeSeries of population estimates timeseries: TimeSeries of simulation results title: string """ plot(census, ':', label='US Census') plot(un, '--', label='UN DESA') if len(timeseries): plot(timeseries, color='gray', label='model') decorate(xlabel='Year', ylabel='World population (billion)', title=title) un = table2.un / 1e9 census = table2.census / 1e9 empty = TimeSeries() plot_results(census, un, empty, 'World population estimates') ``` ### Why is world population growing linearly? Since 1970, world population has been growing approximately linearly, as shown in the previous figure. During this time, death and birth rates have decreased in most regions, but it is hard to imagine a mechanism that would cause them to decrease in a way that yields constant net growth year after year. So why is world population growing linearly? To explore this question, we will look for a model that reproduces linear growth, and identify the essential features that yield this behavior. Specifically, we'll add two new features to the model: 1. Age: The current model does not account for age; we will extend the model by including two age groups, young and old, roughly corresponding to people younger or older than 40. 2. The demographic transition: Birth rates have decreased substantially since 1970. We model this transition with an abrupt change in 1970 from an initial high level to a lower level. We'll use the 1950 world population from the US Census as an initial condition, assuming that half the population is young and half old. ``` half = get_first_value(census) / 2 init = State(young=half, old=half) ``` We'll use a `System` object to store the parameters of the model. ``` system = System(birth_rate1 = 1/18, birth_rate2 = 1/25, transition_year = 1970, mature_rate = 1/40, death_rate = 1/40, t_0 = 1950, t_end = 2016, init=init) ``` Here's an update function that computes the state of the system during the next year, given the current state and time. ``` def update_func1(state, t, system): if t <= system.transition_year: births = system.birth_rate1 * state.young else: births = system.birth_rate2 * state.young maturings = system.mature_rate * state.young deaths = system.death_rate * state.old young = state.young + births - maturings old = state.old + maturings - deaths return State(young=young, old=old) ``` We'll test the update function with the initial condition. ``` state = update_func1(init, system.t_0, system) ``` And we can do one more update using the state we just computed: ``` state = update_func1(state, system.t_0, system) ``` The `run_simulation` function is similar to the one in the book; it returns a time series of total population. ``` def run_simulation(system, update_func): """Simulate the system using any update function. init: initial State object system: System object update_func: function that computes the population next year returns: TimeSeries """ results = TimeSeries() state = system.init results[system.t_0] = state.young + state.old for t in linrange(system.t_0, system.t_end): state = update_func(state, t, system) results[t+1] = state.young + state.old return results ``` Now we can run the simulation and plot the results: ``` results = run_simulation(system, update_func1); plot_results(census, un, results, 'World population estimates') ``` This figure shows the results from our model along with world population estimates from the United Nations Department of Economic and Social Affairs (UN DESA) and the US Census Bureau. We adjusted the parameters by hand to fit the data as well as possible. Overall, the model fits the data well. Nevertheless, between 1970 and 2016 there is clear curvature in the model that does not appear in the data, and in the most recent years it looks like the model is diverging from the data. In particular, the model would predict accelerating growth in the near future, which does not seem consistent with the trend in the data, and it contradicts predictions by experts. It seems that this model does not explain why world population is growing linear. We conclude that adding two age groups to the model is not sufficient to produce linear growth. Modeling the demographic transition with an abrupt change in birth rate is not sufficient either. In future work, we might explore whether a gradual change in birth rate would work better, possibly using a logistic function. We also might explore the behavior of the model with more than two age groups.
github_jupyter
``` w = 'w' b = 'b' advisor = 'a' cannon = 'c' elephant = 'e' general = 'g' horse = 'h' pawn = 'p' rock = 'r' start_coords = { w: { advisor: [104,106], cannon: [82, 88], elephant: [103,107], general: [105], horse: [102,108], pawn: [71, 73, 75, 77, 79], rock: [101,109] }, b: { advisor: [14, 16], cannon: [32,38], elephant: [13,17], general: [15], horse: [12, 18], pawn: [41,43,45,47,49], rock: [11,19] } } start_coords_2 = { 'A': [104,106], 'C': [82, 88], 'E': [103,107], 'G': [105], 'H': [102,108], 'P': [71, 73, 75, 77, 79], 'R': [101,109], 'a': [14, 16], 'c': [32,38], 'e': [13,17], 'g': [15], 'h': [12, 18], 'p': [41,43,45,47,49], 'r': [11,19] } board_matrix= [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 110], [ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 210], [ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 310], [ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 410], [ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 510], [ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 610], [ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 710], [ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 810], [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 910], [100,101,102,103,104,105,106,107,108,109,1010], [110,111,112,113,114,115,116,117,118,119,1110] ] from IPython.display import clear_output, HTML, display from copy import deepcopy class Game: def __init__(self): self.SYMBOLS = 'aceghprACEGHPR' self.ALLOWED_MOVE_ORDER = '.-/' self.EMPTY = ' ' self.BORDER = "|" self.nex_move = 'w' self.board_matrix = deepcopy(board_matrix) self.start_coords = deepcopy(start_coords_2) self.game_state = [] def new_game(self): self.game_state = deepcopy(self.start_coords) self.next_move = 'w' return self.game_state def _translate_move(self, move): #move is a string 'H2.4' means horse 2 move forth to 4 if move[0].islower() and self.next_move == 'w': translated_move = self._translate_move_red(move) elif move[0].isupper() and self.next_move == 'b': translated_move = self._translate_move_black(move) else: raise ValueError('Move cannot be proccessed!') def _translate_move_red(self, move): pass def _translate_move_black(self,move): pass def _update_move(self): pass def verify(self, move): return len(move) == 4 and move[0] in self.SYMBOLS and move[2] in self.ALLOWED_MOVE_ORDER and 1 <= int(move[1]) <= 9 and 1 <= int(move[3]) <= 9 def _make_border_show(self, board): for i in range(1,len(board[0])): if i < len(board[0])-1: board[0][i] = str(i) board[11][i] = str(len(board[0]) -1- i) board[i][0] = str(i) board[i][10] = str(i) return board def _make_empty_space_show(self, board): for i in range(12): for j in range(11): if isinstance(board[i][j], int): board[i][j] = self.EMPTY return board def _make_board(self): board = deepcopy(self.board_matrix) board = self._make_border_show(board) for piece in self.game_state: for val in self.game_state[piece]: board[val//10][val%10] = piece board = self._make_empty_space_show(board) return board def display_board(self): self.board= self._make_board() clear_output() display(HTML( '<div class="container" style="white-space: nowrap;"> <table style="width:40%;float:left"><tr>{0}</tr></table></div>'.format( '</tr><tr>'.join( '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in self.board) ) )) def play(self): order = 'null' self.new_game() while order[0] != 'pause': self.display_board() order = input('Next move: ').split(' ') if order[0]== 'pause': break print('Order recieved: {0} move to {2} from {1}'.format(order[0], order[1], order[2])) if len(order) == 3: self.game_state[order[0]] = [int(order[2]) if i== int(order[1]) else i for i in self.game_state[order[0]] ] else: print('Unknown order') game = Game() game.new_game() game.display_board() game.play() game.game_state a = input('move: ').split(' ') print(a[0]) ```
github_jupyter
#  测试目标检测性能 ``` !pip install gluoncv import gluoncv as gcv import mxnet as mx import os class DetectionDataset(gcv.data.VOCDetection): CLASSES = ['cocacola', 'noodles', 'hand', 'fake'] # Yolo3 need at least 4 classes (https://github.com/apache/incubator-mxnet/pull/17689/files) def __init__(self, root): self._im_shapes = {} self._root = os.path.expanduser(root) self._transform = None self._items = [(self._root, x.strip('.jpg')) for x in os.listdir(self._root) if x.endswith('.jpg')] self._anno_path = os.path.join('{}', '{}.xml') self._image_path = os.path.join('{}', '{}.jpg') self.index_map = dict(zip(self.classes, range(self.num_class))) self._label_cache = self._preload_labels() def __str__(self): detail = self._root return self.__class__.__name__ + '(' + detail + ')' @property def classes(self): return self.CLASSES @property def num_class(self): return len(self.classes) def get_image_list(self): return [os.path.join(x[0], x[1] + '.jpg') for x in self._items] test_dataset = DetectionDataset('../images/shenzhen_v1') print('class_names:', test_dataset.classes) print('num_images:', len(test_dataset)) ``` # 载入训练好的模型 ``` net = gcv.model_zoo.get_model('yolo3_darknet53_custom', classes=test_dataset.classes, pretrained_base=False) param_files = ([x for x in os.listdir('.') if x.endswith('.params')]) selected = param_files[0] print('磁盘上有训练好的模型:', param_files) net.load_parameters(selected) print('载入完毕:', selected) ``` # 观察检测性能 ``` images = test_dataset.get_image_list() print('测试图像集:', images) %%time from matplotlib import pyplot as plt # Use GPU ctx = mx.gpu(0) # ctx = mx.cpu(0) net.collect_params().reset_ctx(ctx) for image in images: x, img = gcv.data.transforms.presets.yolo.load_test(image, short=512) class_IDs, scores, bounding_boxes = net(x.as_in_context(ctx)) ax = gcv.utils.viz.plot_bbox(img, bounding_boxes[0], scores[0], class_IDs[0], class_names=net.classes) plt.show() ``` # 测试结果总结 ``` import time from tqdm import tqdm from gluoncv.data.batchify import Tuple, Stack, Pad from gluoncv.data.transforms.presets.yolo import YOLO3DefaultTrainTransform def validate(net, test_dataset, ctx): if isinstance(ctx, mx.Context): ctx = [ctx] size = len(test_dataset) metric = gcv.utils.metrics.voc_detection.VOC07MApMetric(iou_thresh=0.5, class_names=test_dataset.classes) net.collect_params().reset_ctx(ctx) metric.reset() width, height = 512, 512 batch_size = 4 batchify_fn = Tuple(Stack(), Pad(pad_val=-1)) val_loader = mx.gluon.data.DataLoader( test_dataset.transform(YOLO3DefaultTrainTransform(width, height)), batchify_fn=batchify_fn, batch_size=batch_size, shuffle=False, last_batch='rollover', num_workers=0) with tqdm(total=size) as pbar: start = time.time() for ib, batch in enumerate(val_loader): data = mx.gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0, even_split=False) label = mx.gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0, even_split=False) det_bboxes = [] det_ids = [] det_scores = [] gt_bboxes = [] gt_ids = [] gt_difficults = [] for x, y in zip(data, label): ids, scores, bboxes = net(x) det_ids.append(ids) det_scores.append(scores) # clip to image size det_bboxes.append(bboxes.clip(0, batch[0].shape[2])) # split ground truths gt_ids.append(y.slice_axis(axis=-1, begin=4, end=5)) gt_bboxes.append(y.slice_axis(axis=-1, begin=0, end=4)) gt_difficults.append(y.slice_axis(axis=-1, begin=5, end=6) if y.shape[-1] > 5 else None) metric.update(det_bboxes, det_ids, det_scores, gt_bboxes, gt_ids, gt_difficults) pbar.update(batch[0].shape[0]) end = time.time() speed = size / (end - start) print('Throughput is %f img/sec.'% speed) return metric.get() final_result = validate(net, test_dataset, mx.gpu(0)) for name, score in zip(*final_result): print(name, ':', score) ```
github_jupyter
``` # Copyright 2019 The TensorFlow Authors All Rights Reserved. # # 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 # # http://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. # ============================================================================== # Visualization of the YAMNet audio event classification model. # See https://github.com/tensorflow/models/tree/master/research/audioset/yamnet/ # # This notebook can be run in Google Colab at https://colab.research.google.com # by either downloading this ipynb and uploading it, or by looking up the # notebook directly on GitHub in Colab's "Open notebook" dialog. # Install required packages. !pip install soundfile !git clone https://github.com/tensorflow/models.git %cd models/research/audioset/yamnet # Download YAMNet data !curl -O https://storage.googleapis.com/audioset/yamnet.h5 # Download audio for testing !curl -O https://storage.googleapis.com/audioset/speech_whistling2.wav !ls -l # Imports. import numpy as np import soundfile as sf import matplotlib.pyplot as plt import params import yamnet as yamnet_model import tensorflow as tf # Read in the audio. wav_file_name = 'speech_whistling2.wav' wav_data, sr = sf.read(wav_file_name, dtype=np.int16) waveform = wav_data / 32768.0 # The graph is designed for a sampling rate of 16 kHz, but higher rates # should work too. params.SAMPLE_RATE = sr print("Sample rate =", params.SAMPLE_RATE) # Set up the YAMNet model. class_names = yamnet_model.class_names('yamnet_class_map.csv') params.PATCH_HOP_SECONDS = 0.1 # 10 Hz scores frame rate. yamnet = yamnet_model.yamnet_frames_model(params) yamnet.load_weights('yamnet.h5') # Run the model. scores, embeddings, spectrogram = yamnet(waveform) scores = scores.numpy() spectrogram = spectrogram.numpy() # Visualize the results. plt.figure(figsize=(10, 8)) # Plot the waveform. plt.subplot(3, 1, 1) plt.plot(waveform) plt.xlim([0, len(waveform)]) # Plot the log-mel spectrogram (returned by the model). plt.subplot(3, 1, 2) plt.imshow(spectrogram.T, aspect='auto', interpolation='nearest', origin='bottom') # Plot and label the model output scores for the top-scoring classes. mean_scores = np.mean(scores, axis=0) top_N = 10 top_class_indices = np.argsort(mean_scores)[::-1][:top_N] plt.subplot(3, 1, 3) plt.imshow(scores[:, top_class_indices].T, aspect='auto', interpolation='nearest', cmap='gray_r') # Compensate for the PATCH_WINDOW_SECONDS (0.96 s) context window to align with spectrogram. patch_padding = (params.PATCH_WINDOW_SECONDS / 2) / params.PATCH_HOP_SECONDS plt.xlim([-patch_padding, scores.shape[0] + patch_padding]) # Label the top_N classes. yticks = range(0, top_N, 1) plt.yticks(yticks, [class_names[top_class_indices[x]] for x in yticks]) _ = plt.ylim(-0.5 + np.array([top_N, 0])) ```
github_jupyter
*** # 数据抓取: > # 使用Python编写网络爬虫 *** 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com # 需要解决的问题 - 页面解析 - 获取Javascript隐藏源数据 - 自动翻页 - 自动登录 - 连接API接口 ``` import urllib2 from bs4 import BeautifulSoup ``` - 一般的数据抓取,使用urllib2和beautifulsoup配合就可以了。 - 尤其是对于翻页时url出现规则变化的网页,只需要处理规则化的url就可以了。 - 以简单的例子是抓取天涯论坛上关于某一个关键词的帖子。 - 在天涯论坛,关于雾霾的帖子的第一页是: http://bbs.tianya.cn/list.jsp?item=free&nextid=0&order=8&k=雾霾 - 第二页是: http://bbs.tianya.cn/list.jsp?item=free&nextid=1&order=8&k=雾霾 *** # 数据抓取: > # 抓取天涯回帖网络 *** 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com ``` from IPython.display import display_html, HTML HTML('<iframe src=http://bbs.tianya.cn/list.jsp?item=free&nextid=%d&order=8&k=PX width=1000 height=500></iframe>') # the webpage we would like to crawl page_num = 0 url = "http://bbs.tianya.cn/list.jsp?item=free&nextid=%d&order=8&k=PX"% page_num content = urllib2.urlopen(url).read() #获取网页的html文本 soup = BeautifulSoup(content, "lxml") articles = soup.find_all('tr') print articles[0] print articles[1] len(articles[1:]) ``` ![](./img/inspect.png) http://bbs.tianya.cn/list.jsp?item=free&nextid=0&order=8&k=PX # 通过分析帖子列表的源代码,使用inspect方法,会发现所有要解析的内容都在‘td’这个层级下 ``` for t in articles[1].find_all('td'): print t td = articles[1].find_all('td') print td[0] print td[0] print td[0].text print td[0].text.strip() print td[0].a['href'] print td[1] print td[2] print td[3] print td[4] records = [] for i in articles[1:]: td = i.find_all('td') title = td[0].text.strip() title_url = td[0].a['href'] author = td[1].text author_url = td[1].a['href'] views = td[2].text replies = td[3].text date = td[4]['title'] record = title + '\t' + title_url+ '\t' + author + '\t'+ author_url + '\t' + views+ '\t' + replies+ '\t'+ date records.append(record) print records[2] ``` # 抓取天涯论坛PX帖子列表 回帖网络(Thread network)的结构 - 列表 - 主帖 - 回帖 ``` def crawler(page_num, file_name): try: # open the browser url = "http://bbs.tianya.cn/list.jsp?item=free&nextid=%d&order=8&k=PX" % page_num content = urllib2.urlopen(url).read() #获取网页的html文本 soup = BeautifulSoup(content, "lxml") articles = soup.find_all('tr') # write down info for i in articles[1:]: td = i.find_all('td') title = td[0].text.strip() title_url = td[0].a['href'] author = td[1].text author_url = td[1].a['href'] views = td[2].text replies = td[3].text date = td[4]['title'] record = title + '\t' + title_url+ '\t' + author + '\t'+ \ author_url + '\t' + views+ '\t' + replies+ '\t'+ date with open(file_name,'a') as p: # '''Note''':Append mode, run only once! p.write(record.encode('utf-8')+"\n") ##!!encode here to utf-8 to avoid encoding except Exception, e: print e pass # crawl all pages for page_num in range(10): print (page_num) crawler(page_num, '/Users/chengjun/bigdata/tianya_bbs_threads_list2017.txt') import pandas as pd df = pd.read_csv('/Users/chengjun/bigdata/tianya_bbs_threads_list2017.txt',\ sep = "\t", names = ['title', 'link', 'author', \ 'author_page', 'click', 'reply', 'time']) df[:2] len(df) len(df.link) ``` # 抓取作者信息 ``` df.author_page[:5] ``` http://www.tianya.cn/62237033 http://www.tianya.cn/67896263 ``` # user_info url = df.author_page[2] content = urllib2.urlopen(url).read() #获取网页的html文本 soup = BeautifulSoup(content, "lxml") user_info = soup.find('div', {'class', 'userinfo'})('p') for i in user_info: print i.get_text()[4:] user_info = soup.find('div', {'class', 'userinfo'})('p') nid, freq_use, last_login_time, reg_time = \ [i.get_text()[4:] for i in user_info] print nid, freq_use, last_login_time, reg_time link_info = soup1.find_all('div', {'class', 'link-box'}) followed_num, fans_num = [i.a.text for i in link_info] print followed_num, fans_num activity = soup1.find_all('span', {'class', 'subtitle'}) post_num, reply_num = [j.text[2:] for i in activity[:1] for j in i('a')] print post_num, reply_num print activity[0] link_info = soup.find_all('div', {'class', 'link-box'}) followed_num, fans_num = [i.a.text for i in link_info] print followed_num, fans_num link_info[0].a.text # user_info = soup.find('div', {'class', 'userinfo'})('p') # user_infos = [i.get_text()[4:] for i in user_info] def author_crawler(url, file_name): try: content = urllib2.urlopen(url).read() #获取网页的html文本 soup = BeautifulSoup(content, "lxml") link_info = soup.find_all('div', {'class', 'link-box'}) followed_num, fans_num = [i.a.text for i in link_info] try: activity = soup.find_all('span', {'class', 'subtitle'}) post_num, reply_num = [j.text[2:] for i in activity[:1] for j in i('a')] except: post_num, reply_num = 1, 0 record = '\t'.join([url, followed_num, fans_num, post_num, reply_num]) with open(file_name,'a') as p: # '''Note''':Append mode, run only once! p.write(record.encode('utf-8')+"\n") ##!!encode here to utf-8 to avoid encoding except Exception, e: print e, url record = '\t'.join([url, 'na', 'na', 'na', 'na']) with open(file_name,'a') as p: # '''Note''':Append mode, run only once! p.write(record.encode('utf-8')+"\n") ##!!encode here to utf-8 to avoid encoding pass import sys def flushPrint(s): sys.stdout.write('\r') sys.stdout.write('%s' % s) sys.stdout.flush() import time, random for k, url in enumerate(df.author_page): time.sleep(random.random()) if k % 10==0: flushPrint(k) author_crawler(url, '/Users/chengjun/github/cjc/data/tianya_bbs_threads_author_info2017_1.txt') ``` http://www.tianya.cn/50499450/follow 还可抓取他们的关注列表和粉丝列表 *** *** # 数据抓取: > # 使用Python抓取回帖 *** *** 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com ``` df.link[0] url = 'http://bbs.tianya.cn' + df.link[2] print url from IPython.display import display_html, HTML HTML('<iframe src=http://bbs.tianya.cn/post-free-2848797-1.shtml width=1000 height=500></iframe>') # the webpage we would like to crawl post = urllib2.urlopen(url).read() #获取网页的html文本 post_soup = BeautifulSoup(post, "lxml") #articles = soup.find_all('tr') print (post_soup.prettify())[:5000] pa = post_soup.find_all('div', {'class', 'atl-item'}) len(pa) print pa[0] print pa[1] print pa[89] ``` 作者:柠檬在追逐 时间:2012-10-28 21:33:55   @lice5 2012-10-28 20:37:17   作为宁波人 还是说一句:革命尚未成功 同志仍需努力   -----------------------------   对 现在说成功还太乐观,就怕说一套做一套 作者:lice5 时间:2012-10-28 20:37:17   作为宁波人 还是说一句:革命尚未成功 同志仍需努力 4 /post-free-4242156-1.shtml 2014-04-09 15:55:35 61943225 野渡自渡人 @Y雷政府34楼2014-04-0422:30:34  野渡君雄文!支持是必须的。  -----------------------------  @清坪过客16楼2014-04-0804:09:48  绝对的权力导致绝对的腐败!  -----------------------------  @T大漠鱼T35楼2014-04-0810:17:27  @周丕东@普欣@拾月霜寒2012@小摸包@姚文嚼字@四號@凌宸@乔志峰@野渡自渡人@曾兵2010@缠绕夜色@曾颖@风青扬请关注 ``` print pa[0].find('div', {'class', 'bbs-content'}).text.strip() print pa[87].find('div', {'class', 'bbs-content'}).text.strip() pa[1].a print pa[0].find('a', class_ = 'reportme a-link') print pa[0].find('a', class_ = 'reportme a-link')['replytime'] print pa[0].find('a', class_ = 'reportme a-link')['author'] for i in pa[:10]: p_info = i.find('a', class_ = 'reportme a-link') p_time = p_info['replytime'] p_author_id = p_info['authorid'] p_author_name = p_info['author'] p_content = i.find('div', {'class', 'bbs-content'}).text.strip() p_content = p_content.replace('\t', '') print p_time, '--->', p_author_id, '--->', p_author_name,'--->', p_content, '\n' ``` # 如何翻页 http://bbs.tianya.cn/post-free-2848797-1.shtml http://bbs.tianya.cn/post-free-2848797-2.shtml http://bbs.tianya.cn/post-free-2848797-3.shtml ``` post_soup.find('div', {'class', 'atl-pages'})#.['onsubmit'] post_pages = post_soup.find('div', {'class', 'atl-pages'}) post_pages = post_pages.form['onsubmit'].split(',')[-1].split(')')[0] post_pages #post_soup.select('.atl-pages')[0].select('form')[0].select('onsubmit') url = 'http://bbs.tianya.cn' + df.link[2] url_base = ''.join(url.split('-')[:-1]) + '-%d.shtml' url_base def parsePage(pa): records = [] for i in pa: p_info = i.find('a', class_ = 'reportme a-link') p_time = p_info['replytime'] p_author_id = p_info['authorid'] p_author_name = p_info['author'] p_content = i.find('div', {'class', 'bbs-content'}).text.strip() p_content = p_content.replace('\t', '').replace('\n', '')#.replace(' ', '') record = p_time + '\t' + p_author_id+ '\t' + p_author_name + '\t'+ p_content records.append(record) return records import sys def flushPrint(s): sys.stdout.write('\r') sys.stdout.write('%s' % s) sys.stdout.flush() url_1 = 'http://bbs.tianya.cn' + df.link[10] content = urllib2.urlopen(url_1).read() #获取网页的html文本 post_soup = BeautifulSoup(content, "lxml") pa = post_soup.find_all('div', {'class', 'atl-item'}) b = post_soup.find('div', class_= 'atl-pages') b url_1 = 'http://bbs.tianya.cn' + df.link[0] content = urllib2.urlopen(url_1).read() #获取网页的html文本 post_soup = BeautifulSoup(content, "lxml") pa = post_soup.find_all('div', {'class', 'atl-item'}) a = post_soup.find('div', {'class', 'atl-pages'}) a a.form if b.form: print 'true' else: print 'false' import random import time def crawler(url, file_name): try: # open the browser url_1 = 'http://bbs.tianya.cn' + url content = urllib2.urlopen(url_1).read() #获取网页的html文本 post_soup = BeautifulSoup(content, "lxml") # how many pages in a post post_form = post_soup.find('div', {'class', 'atl-pages'}) if post_form.form: post_pages = post_form.form['onsubmit'].split(',')[-1].split(')')[0] post_pages = int(post_pages) url_base = '-'.join(url_1.split('-')[:-1]) + '-%d.shtml' else: post_pages = 1 # for the first page pa = post_soup.find_all('div', {'class', 'atl-item'}) records = parsePage(pa) with open(file_name,'a') as p: # '''Note''':Append mode, run only once! for record in records: p.write('1'+ '\t' + url + '\t' + record.encode('utf-8')+"\n") # for the 2nd+ pages if post_pages > 1: for page_num in range(2, post_pages+1): time.sleep(random.random()) flushPrint(page_num) url2 =url_base % page_num content = urllib2.urlopen(url2).read() #获取网页的html文本 post_soup = BeautifulSoup(content, "lxml") pa = post_soup.find_all('div', {'class', 'atl-item'}) records = parsePage(pa) with open(file_name,'a') as p: # '''Note''':Append mode, run only once! for record in records: p.write(str(page_num) + '\t' +url + '\t' + record.encode('utf-8')+"\n") else: pass except Exception, e: print e pass ``` # 测试 ``` url = df.link[2] file_name = '/Users/chengjun/github/cjc/data/tianya_bbs_threads_4test.txt' crawler(url, file_name) ``` # 正式抓取! ``` for k, link in enumerate(df.link): flushPrint(link) if k % 10== 0: print 'This it the post of : ' + str(k) file_name = '/Users/chengjun/github/cjc/data/tianya_bbs_threads_network_2017.txt' crawler(link, file_name) ``` # 读取数据 ``` dtt = [] with open('/Users/chengjun/github/cjc/data/tianya_bbs_threads_network_2017.txt', 'r') as f: for line in f: pnum, link, time, author_id, author, content = line.replace('\n', '').split('\t') dtt.append([pnum, link, time, author_id, author, content]) len(dtt) dt = pd.DataFrame(dtt) dt[:5] dt=dt.rename(columns = {0:'page_num', 1:'link', 2:'time', 3:'author',4:'author_name', 5:'reply'}) dt[:5] dt.reply[:100] ``` ## 总帖数是多少? http://search.tianya.cn/bbs?q=PX 共有18459 条内容 ``` 18459/50 ``` 实际上到第10页就没有了 http://bbs.tianya.cn/list.jsp?item=free&order=1&nextid=9&k=PX, 原来那只是天涯论坛,还有其它各种版块,如天涯聚焦: http://focus.tianya.cn/ 等等。 - 娱乐八卦 512 - 股市论坛 187 - 情感天地 242 - 天涯杂谈 1768 在天涯杂谈搜索雾霾,有41页 http://bbs.tianya.cn/list.jsp?item=free&order=20&nextid=40&k=%E9%9B%BE%E9%9C%BE # 天涯SDK http://open.tianya.cn/wiki/index.php?title=SDK%E4%B8%8B%E8%BD%BD
github_jupyter
# Задача 2: аппроксимация функции ``` from math import sin, exp def func(x): return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x / 2.) import numpy as np from scipy import linalg arrCoordinates = np.arange(1., 15.1, 0.1) arrFunction = np.array([func(coordinate) for coordinate in arrCoordinates]) ``` ## 1. Сформировать СЛАУ для многочлена первой степени, который должен совпадать с функцией в точках 1 и 15. ``` #многочлен первой степени arrCoord1 = np.array([1, 15]) N = 2 arrA1 = np.empty((0, N)) for i in xrange(N): arrA1Line = list() for j in xrange(N): arrA1Line.append(arrCoord1[i] ** j) arrA1 = np.append(arrA1, np.array([arrA1Line]), axis = 0) arrB1 = np.array([func(coordinate) for coordinate in arrCoord1]) print arrCoord1 print arrA1 print arrB1 arrX1 = linalg.solve(arrA1, arrB1) print arrX1 def func1(x): return arrX1[0] + arrX1[1] * x arrFunc1 = np.array([func1(coordinate) for coordinate in arrCoordinates]) %matplotlib inline import matplotlib.pylab as plt plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1) plt.show() ``` ## 2. Многочлен второй степени в точка 1, 8, 15. ``` #многочлен второй степени arrCoord2 = np.array([1, 8, 15]) N = 3 arrA2 = np.empty((0, N)) for i in xrange(N): arrA2Line = list() for j in xrange(N): arrA2Line.append(arrCoord2[i] ** j) arrA2 = np.append(arrA2, np.array([arrA2Line]), axis = 0) arrB2 = np.array([func(coordinate) for coordinate in arrCoord2]) print arrCoord2 print arrA2 print arrB2 arrX2 = linalg.solve(arrA2, arrB2) print arrX2 def func2(x): return arrX2[0] + arrX2[1] * x + arrX2[2] * (x ** 2) arrFunc2 = np.array([func2(coordinate) for coordinate in arrCoordinates]) plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1, arrCoordinates, arrFunc2) plt.show() ``` ## 3. Многочлен третьей степени в точка 1, 4, 10, 15. ``` #многочлен третьей степени arrCoord3 = np.array([1, 4, 10, 15]) N = 4 arrA3 = np.empty((0, N)) for i in xrange(N): arrA3Line = list() for j in xrange(N): arrA3Line.append(arrCoord3[i] ** j) arrA3 = np.append(arrA3, np.array([arrA3Line]), axis = 0) arrB3 = np.array([func(coordinate) for coordinate in arrCoord3]) print arrCoord3 print arrA3 print arrB3 arrX3 = linalg.solve(arrA3, arrB3) print arrX3 def func3(x): return arrX3[0] + arrX3[1] * x + arrX3[2] * (x ** 2) + arrX3[3] * (x ** 3) arrFunc3 = np.array([func3(coordinate) for coordinate in arrCoordinates]) plt.plot(arrCoordinates, arrFunction, arrCoordinates, arrFunc1, arrCoordinates, arrFunc2, arrCoordinates, arrFunc3) plt.show() with open('answer2.txt', 'w') as fileAnswer: for item in arrX3: fileAnswer.write(str(item) + ' ') ```
github_jupyter