code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns from sklearn.model_selection import train_test_split # - tr_data = pd.read_csv('../input/train.csv') te_data = pd.read_csv('../input/test.csv') print('train shape is: {} \r\ntest shape is: {} '.format(tr_data.shape,te_data.shape)) # + from sklearn.feature_extraction.text import TfidfTransformer y = tr_data.target tr_ids = tr_data.id te_ids = te_data.id tr_data.drop(['id','target'],axis=1,inplace=True) te_data.drop(['id'],axis=1,inplace=True) # + tr_data['count_zeros'] = (tr_data == 0).astype(int).sum(axis=1) te_data['count_zeros'] = (te_data == 0).astype(int).sum(axis=1) tr_data['num_greater_than_3'] = (tr_data > 3).astype(int).sum(axis=1) te_data['num_greater_than_3'] = (te_data > 3).astype(int).sum(axis=1) tr_data['num_greater_than_10'] = (tr_data > 10).astype(int).sum(axis=1) te_data['num_greater_than_10'] = (te_data > 10).astype(int).sum(axis=1) # + tfidf = TfidfTransformer() tr_data_tfidf = pd.DataFrame(tfidf.fit_transform(tr_data).toarray()) te_data_tfidf = pd.DataFrame(tfidf.transform(te_data).toarray()) tr_data_tfidf.columns = [str(x)+'tfidf' for x in tr_data_tfidf.columns] te_data_tfidf.columns = [str(x)+'tfidf' for x in te_data_tfidf.columns] tr_data_log1p = pd.DataFrame(tr_data.apply(lambda x: np.log1p(x))) te_data_log1p = pd.DataFrame(te_data.apply(lambda x: np.log1p(x))) tr_data_log1p.columns = [str(x)+'log1p' for x in tr_data_log1p.columns] te_data_log1p.columns = [str(x)+'log1p' for x in te_data_log1p.columns] tr_data_comb = pd.concat([tr_data,tr_data_tfidf,tr_data_log1p],axis=1) te_data_comb = pd.concat([te_data,te_data_tfidf,te_data_log1p],axis=1) # - # from sklearn.preprocessing import LabelEncoder # le = LabelEncoder() # y_encoded = le.fit_transform(y) y_encoded = [int(x.split('_')[1]) for x in y] y_encoded = [y-1 for y in y_encoded] # + from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix,log_loss from sklearn.model_selection import train_test_split,KFold X_train, X_val, y_train, y_val = train_test_split(tr_data_comb,y_encoded,test_size = 0.2,random_state =12345) # + import xgboost as xgb params = {'objective':'multi:softprob', 'learning_rate':0.1, 'subsample':0.8, 'colsample_bytree':0.9, 'colsample_bylevel':0.7, 'max_depth':7, 'nthread':4, 'eval_metric':'mlogloss', 'num_class':9, 'gamma':0.1, 'seed':1234} bst_cv = xgb.cv(params=params,dtrain=xgb.DMatrix(tr_data_comb,label=y_encoded),verbose_eval=2, nfold=5,early_stopping_rounds=20,num_boost_round=30) #try 400 boosting rounds # + #bst = xgb.train(params=params,dtrain=xgb.DMatrix(tr_data_comb,label=y_encoded),num_boost_round=400) # - pred = bst.predict(xgb.DMatrix(te_data_comb)) subm = pd.DataFrame(pred) subm.columns = ['class_'+ str(x) for x in range(1,10)] subm['id'] = pd.read_csv('../input/test.csv',usecols=['id']) #subm.index_label = 'id' subm.to_csv('../subm/tfidf_log1p_raw_xgb_sub1.csv',index=False) # #### let's ignore the tfidf transform for and see what you could also come up with based on the things we learned... # + from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix,log_loss from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val = train_test_split(tr_data,y_encoded,test_size = 0.2,random_state =12345) knn2 = KNeighborsClassifier(n_jobs=4,n_neighbors=2,) knn2.fit(X_train,y_train) knn2_pred = knn2.predict_proba(X_val) print('log loss for knn2: {}'.format(log_loss(y_pred = knn2_pred,y_true = y_val))) knn4 = KNeighborsClassifier(n_jobs=4,n_neighbors=4,) knn4.fit(X_train,y_train) knn4_pred = knn4.predict_proba(X_val) print('log loss for knn4: {}'.format(log_loss(y_pred = knn4_pred,y_true = y_val))) knn8 = KNeighborsClassifier(n_jobs=8,n_neighbors=8,) knn8.fit(X_train,y_train) knn8_pred = knn8.predict_proba(X_val) print('log loss for knn8: {}'.format(log_loss(y_pred = knn8_pred,y_true = y_val))) knn16 = KNeighborsClassifier(n_jobs=4,n_neighbors=16,) knn16.fit(X_train,y_train) knn16_pred = knn16.predict_proba(X_val) print('log loss for knn16: {}'.format(log_loss(y_pred = knn16_pred,y_true = y_val))) knn32 = KNeighborsClassifier(n_jobs=4,n_neighbors=32,) knn32.fit(X_train,y_train) knn32_pred = knn32.predict_proba(X_val) print('log loss for knn32: {}'.format(log_loss(y_pred = knn32_pred,y_true = y_val))) knn64 = KNeighborsClassifier(n_jobs=4,n_neighbors=64,) knn64.fit(X_train,y_train) knn64_pred = knn64.predict_proba(X_val) print('log loss for knn64: {}'.format(log_loss(y_pred = knn64_pred,y_true = y_val))) knn128 = KNeighborsClassifier(n_jobs=4,n_neighbors=128,) knn128.fit(X_train,y_train) knn128_pred = knn128.predict_proba(X_val) print('log loss for knn128: {}'.format(log_loss(y_pred = knn128_pred,y_true = y_val))) # - class_weights = {0:1,1:1,2:1,3:10,4:1,5:1,6:1,7:1,8:1} from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier(class_weight=class_weights,max_depth=4,max_features=92,min_samples_split=2,random_state=12345) dtc.fit(X_train,y_train) tree_pred = dtc.predict_proba(X_val) print('log loss for dtc: {}'.format(log_loss(y_pred = tree_pred,y_true = y_val))) # class_weights = {0:1,1:1,2:1,3:1,4:1,5:1,6:10,7:1,8:1} # lets remove the class weights and check our score... from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier(max_depth=4,max_features=92,min_samples_split=2,random_state=12345) dtc.fit(X_train,y_train) tree_pred = dtc.predict_proba(X_val) print('log loss for dtc: {}'.format(log_loss(y_pred = tree_pred,y_true = y_val))) from sklearn.svm import SVC svc = SVC(kernel='linear',C=0.1,max_iter=10000,random_state=12345,probability=True) svc.fit(X_train,y_train) svc_pred = svc.predict_proba(X_val) print('log loss for svc: {}'.format(log_loss(y_pred = svc_pred,y_true = y_val))) from sklearn.svm import SVC svc = SVC(kernel='rbf',C=0.1,max_iter=10000,random_state=12345,probability=True,) svc.fit(X_train,y_train) svc_pred = svc.predict_proba(X_val) print('log loss for svc: {}'.format(log_loss(y_pred = svc_pred,y_true = y_val))) from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(n_jobs=4,n_estimators=300) rfc.fit(X_train,y_train) rfc_pred = rfc.predict_proba(X_val) print('log loss for RFC: {}'.format(log_loss(y_pred = rfc_pred,y_true = y_val))) rfc_test_pred = rfc.predict_proba(te_data) # + import xgboost as xgb dtrain=xgb.DMatrix(X_train,label=y_train) dval=xgb.DMatrix(X_val,label=y_val) watchlist = [(dtrain, 'train'),(dval, 'eval')] params = {'objective':'multi:softprob', 'learning_rate':0.05, 'subsample':0.7, 'colsample_bytree':0.8, 'colsample_bylevel':0.7, 'max_depth':6, 'nthread':3, 'eval_metric':'mlogloss', 'num_class':9, 'silent':0, 'seed':1234} bst = xgb.train(params=params,dtrain=xgb.DMatrix(X_train,label=y_train),num_boost_round=3000,early_stopping_rounds=80, evals=watchlist,verbose_eval=50) # - xgb_pred = bst.predict(xgb.DMatrix(X_val)) print('log loss for XGB: {}'.format(log_loss(y_pred = xgb_pred,y_true = y_val))) xgb_test_pred = bst.predict(xgb.DMatrix(te_data)) combined_pred = xgb_test_pred *0.85 + rfc_test_pred *0.15 subm = pd.DataFrame(combined_pred) subm.columns = ['class_'+ str(x) for x in range(1,10)] subm['id'] = pd.read_csv('../input/test.csv',usecols=['id']) #subm.index_label = 'id' subm.to_csv('../subm/rf_xgb_sub1.csv',index=False) # + from keras.models import Sequential,Model from keras.layers import Dense,Dropout,Merge,Embedding,BatchNormalization from keras.utils import np_utils from keras.optimizers import Adam OHE_y_train = np_utils.to_categorical(y_train) OHE_y_val = np_utils.to_categorical(y_val) # - from keras.callbacks import ReduceLROnPlateau cb = ReduceLROnPlateau(patience=0,factor=0.1,epsilon=0.02) # + model1 = Sequential() model1.add(Dense(500,input_shape=(X_train.shape[1],),activation='relu')) model1.add(Dropout(0.1)) model1.add(Dense(250,activation='relu')) model1.add(Dropout(0.05)) model1.add(Dense(50,activation='relu')) model1.add(Dense(9,activation='softmax')) model1.compile(optimizer='adam', loss='categorical_crossentropy') model1.fit(X_train.values,OHE_y_train,validation_data=[X_val.values,OHE_y_val],callbacks=[cb],epochs=10) # - ann_pred = model1.predict_classes(X_val.values) from sklearn.metrics import classification_report,log_loss print(confusion_matrix(y_pred=ann_pred,y_true=y_val)) sns.heatmap(confusion_matrix(y_pred=ann_pred+1,y_true=y_val),cmap='Greens',xticklabels=range(1,10),yticklabels=range(1,10)) print('classification report results:\r\n' + classification_report(y_pred=ann_pred,y_true=y_val)) print('log-loss for classifier: {}'.format(log_loss(y_pred=model1.predict(X_val.values),y_true=y_val))) # + model1 = Sequential() model1.add(Dense(500,input_shape=(X_train.shape[1],),activation='relu')) model1.add(Dropout(0.2)) model1.add(Dense(250,activation='relu')) model1.add(Dropout(0.1)) model1.add(Dense(50,activation='relu')) model1.add(Dense(9,activation='softmax')) model1.compile(optimizer='adam', loss='categorical_crossentropy') model1.fit(X_train.values,OHE_y_train,validation_data=[X_val.values,OHE_y_val],callbacks=[cb],epochs=10) # - oof_preds = [] test_preds = [] kf = KFold(n_splits=5,shuffle=True,random_state=12345) for train_index, val_index in kf.split(X=tr_data_comb,y=y_encoded): #print(train_index,val_index) X_train, X_val = tr_data_comb.iloc[train_index,:], tr_data_comb.iloc[val_index,:] y_train, y_val = np.array(y_encoded)[train_index], np.array(y_encoded)[val_index] OHE_y_train = np_utils.to_categorical(y_train) OHE_y_val = np_utils.to_categorical(y_val) model1 = Sequential() model1.add(Dense(1500,input_shape=(X_train.shape[1],),activation='relu')) model1.add(BatchNormalization()) model1.add(Dropout(0.3)) model1.add(Dense(500,activation='relu')) model1.add(Dropout(0.1)) model1.add(Dense(250,activation='relu')) model1.add(Dense(9,activation='softmax')) model1.compile(optimizer=Adam(lr=0.001),loss='categorical_crossentropy') model1.fit(X_train.values,OHE_y_train,validation_data=[X_val.values,OHE_y_val],callbacks=[cb],epochs=10) ann_pred = model1.predict(X_val.values) ann_test_pred = model1.predict(te_data_comb.values) oof_preds.append(ann_pred) test_preds.append(ann_test_pred) test_pred_arr = np.array(test_preds) preds = pd.DataFrame(np.clip(np.mean(test_pred_arr,axis=0),a_max=0.999,a_min=0.001)) subm = pd.DataFrame(preds) subm.columns = ['Class_'+ str(x) for x in range(1,10)] subm['id'] = te_ids subm.to_csv('../subm/ANN_5fold.csv',index=False) subm # + model1 = Sequential() model1.add(Dense(1500,input_shape=(X_train.shape[1],),activation='relu')) model1.add(Dropout(0.3)) model1.add(Dense(750,activation='relu')) model1.add(Dense(9,activation='softmax')) model1.compile(optimizer='adam', loss='categorical_crossentropy') model1.fit(X_train.values,OHE_y_train,validation_data=[X_val.values,OHE_y_val],callbacks=[cb],epochs=10) ann_pred = model1.predict_classes(X_val.values) from sklearn.metrics import classification_report,log_loss print(confusion_matrix(y_pred=ann_pred,y_true=y_val)) sns.heatmap(confusion_matrix(y_pred=ann_pred+1,y_true=y_val),cmap='Greens',xticklabels=range(1,10),yticklabels=range(1,10)) print('classification report results:\r\n' + classification_report(y_pred=ann_pred,y_true=y_val)) print('log-loss for classifier: {}'.format(log_loss(y_pred=model1.predict(X_val.values),y_true=y_val))) # - print('log-loss for classifier: {}'.format(log_loss(y_pred=np.clip(model1.predict(X_val.values),a_min=0.0001,a_max=0.9999),y_true=y_val))) test_pred = np.clip(,a_min=0.001,a_max=0.999) subm = pd.DataFrame(test_pred) subm.columns = ['class_'+ str(x) for x in range(1,10)] subm['id'] = te_ids subm.to_csv('../subm/ANN_0.4583.csv',index=False)
day01/otto/models/sample_solution_otto_comp.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Data over a magnetic dipole # # In this notebook, we generate magnetic field data over a spherical target, which we approximate as a point dipole. # # To run the notebook, you will need to have the package `geoana` installed. It is a package that contains analytic functions for common settings in geophysics (If you are curious to see more, you can check out the [docs](https://geoana.readthedocs.io/en/latest/?badge=latest)). You can install the necessary packages by running from the command line or by uncommenting the first cell in the notebook and running it. # # ``` # pip install -r requirements.txt # ``` # + # # !pip install -r requirements.txt # + import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import ipywidgets from geoana.em.static import MagneticDipoleWholeSpace from geoana import utils, spatial # %matplotlib inline # - # change default font size from matplotlib import rcParams rcParams['font.size'] = 14 def inclination_declination_to_cartesian(inclination, declination): """ Convert inclination and declination (in degrees) to a unit vector in cartesian coordinates. """ return np.r_[ np.cos(np.deg2rad(inclination)) * np.sin(np.deg2rad(declination)), np.cos(np.deg2rad(inclination)) * np.cos(np.deg2rad(declination)), -np.sin(np.deg2rad(inclination)) ] # ## Example: fields from a dipole # # The purpose of the next few cells is to walk through the setup. You can skip these if you just want to generate data # ### Defining the inducing field # # In the next cell, we define the inducing magnetic field, which is the [earth's magnetic field](https://gpg.geosci.xyz/content/magnetics/magnetics_basic_principles.html#earth-s-magnetic-field-source) at the location where we are measuring data. Typically, we use the [International Geomagnetic Reference Field (IGRF)](https://gpg.geosci.xyz/content/magnetics/magnetics_basic_principles.html#the-igrf) values. In the following, I assume a vertical magnetic field (e.g. at the north pole) and use the average strength of the magnetic field over the earth as the magnitude. # # If you would like to get more creative, you can look up the IGRF values in Berkeley using the [NOAA magnetic field calculator](https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml#igrfwmm) # # We define 3 parameters to describe the inducing field # - declination: degrees clockwise from North # - inclination: degrees downwards from horizontal # - amplitude: magnitude of the earth's field # # <img src="https://gpg.geosci.xyz/_images/Mag_Coordinate_System.png" width=200></img> # + B0_declination = 0. # degrees B0_inclination = 90. # degrees B0_amplitude = 56000 # (56000 nT) # orientation in cartesian coordinates B0_unit_direction = inclination_declination_to_cartesian(B0_inclination, B0_declination) # vector magnetic field in cartesian coordinates B0 = B0_amplitude * B0_unit_direction # - # ### Set up a target # # We define a spherical target whose center is at the origin. The radius of the target is in meters, and the permeability of the target describes how easily magnetized a target is. Both the radius and the permeability should always be positive. # + target_radius = 10 # radius in m target_permeability = 2 # relative permeability of the target target_volume = 4/3 * np.pi * target_radius**3 # volume in m^3 # - # ### measurement locations # # The following define the receiver location in 3D space, with z-positive up. rx_x = 0 rx_y = 0 rx_z = 30 # #### Plot the setup # + fig, ax = plt.subplots(1, 2, figsize=(8, 4)) plt_limits = 2*np.max(np.abs([target_radius, rx_x, rx_y, rx_z]))*np.r_[-1, 1] for a, title in zip(ax, ["cross_section", "depth_slice"]): circle = plt.Circle([0.,0.], target_radius, color='C0') a.add_artist(circle) a.set_xlim(plt_limits) a.set_ylim(plt_limits) # cross section ax[0].plot(rx_x, rx_z, 'v', color="C1") ax[0].arrow( 0.9*plt_limits[0], 0.9*plt_limits[1], 10*B0_unit_direction[0], 10*B0_unit_direction[2], width=1, head_width=4, color="C2" ) ax[0].set_xlabel("x (m)") ax[0].set_ylabel("z (m)") # cross section ax[1].plot(rx_x, rx_y, 'o', color="C1") ax[1].arrow( 0.9*plt_limits[0], 0.9*plt_limits[1], 10*B0_unit_direction[0], 10*B0_unit_direction[1], width=1, head_width=0 if np.isclose(B0_unit_direction[0], B0_unit_direction[0]) else 4, color="C2" ) ax[1].set_xlabel("x (m)") ax[1].set_ylabel("y (m)") plt.tight_layout() # - # ### Set up the simulation # # For this example, we treat the sphere as a point dipole and compute its moment. The `dipole` object that we create encodes the geometry, and we can use the method `dipole.magnetic_flux_density` to compute tha magnetic flux at the receiver locations. # dipole is the sphere dipole = MagneticDipoleWholeSpace( location=np.r_[0., 0., 0.], # center of dipole at origin orientation=B0_unit_direction, # dipole is in same direction as Earth's field moment=target_permeability * B0_amplitude * target_volume # moment = how strong is the magnet of the dipole? ) # + ## plot sample magnetic fields def plot_amplitude(ax, x, y, v): v = spatial.vector_magnitude(v) plt.colorbar( ax.pcolormesh( x, y, v.reshape(len(x), len(y), order='F'), norm=LogNorm() ), ax=ax ) ax.axis('square') # plot streamlines def plot_streamlines(ax, x, y, vx, vy): vx = vx.reshape(len(x), len(y), order='F') vy = vy.reshape(len(x), len(y), order='F') ax.streamplot(x, y, vx.T, vy.T, color='k', linewidth=1) # define the plotting code fig, ax = plt.subplots(1, 1, figsize=(5, 4)) plt_limits = 2*np.max(np.abs([target_radius, rx_x, rx_y, rx_z]))*np.r_[-1, 1] x = np.linspace(plt_limits[0], plt_limits[1], 100) # cross section at center of dipole b_cross_section = dipole.magnetic_flux_density(xyz=utils.ndgrid([x, np.r_[0], x])) plot_amplitude(ax, x, x, b_cross_section) plot_streamlines(ax, x, x, b_cross_section[:, 0], b_cross_section[:, 2]) ax.plot(rx_x, rx_z, 'v', color="C1") ax.set_xlabel("x (m)") ax.set_ylabel("z (m)") # - # ## Generate data set # # The following function generates a data set given a list or numpy array of each of the input parameters def generate_dipole_data( B0_declination, B0_inclination, B0_amplitude, target_radius, target_permeability, rx_x, rx_y, rx_z, data_type="TMI" # Can be 'x', 'y', 'z' (which returns the component of the magnetic field) or 'TMI' (the projection on the inducing field) ): """ Given all of the parameters to describe the setup, we produce a numpy array of data. In order, the columns are - data[:, 0] : B0_declination - data[:, 1] : B0_inclination - data[:, 2] : B0_amplitude - data[:, 3] : target_radius - data[:, 4] : target_permeability - data[:, 5] : rx_x - data[:, 6] : rx_y - data[:, 7] : rx_z - data[:, 8] : dobs This function returns both the d """ # Initialize data storage nD = ( len(B0_declination) * len(B0_inclination) * len(B0_amplitude) * len(target_radius) * len(target_permeability) * len(rx_x) * len(rx_y) * len(rx_z) ) data_header = [ "B0_declination", "B0_inclination", "B0_amplitude", "target_radius", "target_permeability", "rx_x", "rx_y", "rx_z", "dobs" ] data = [] xyz = utils.ndgrid([rx_x, rx_y, rx_z]) # Loop over parameters to evaluate data # inducing field for b0d in B0_declination: for b0i in B0_inclination: for b0a in B0_amplitude: B0_unit_direction = inclination_declination_to_cartesian(b0i, b0d) B0 = b0a * B0_unit_direction # target properties for r in target_radius: for mur in target_permeability: # initialize an empty array to store the data tmp_data = np.zeros((xyz.shape[0], len(data_header))) # populate data with parameters tmp_data[:, 0] = b0d tmp_data[:, 1] = b0i tmp_data[:, 2] = b0a tmp_data[:, 3] = r tmp_data[:, 4] = mur tmp_data[:, 5:8] = xyz # compute the observed data target_volume = 4/3 * np.pi * r **3 target_moment = mur * b0a * target_volume # create the dipole object dipole = MagneticDipoleWholeSpace( location=np.r_[0., 0., 0.], orientation=B0_unit_direction, moment=target_moment ) # evaluate the data b_vector = dipole.magnetic_flux_density(xyz) if data_type.lower() == "tmi": dobs = spatial.vector_dot( b_vector, B0_unit_direction ) elif data_type.lower() == "x": dobs = b_vector[:, 0] elif data_type.lower() == "y": dobs = b_vector[:, 1] elif data_type.lower() == "z": dobs = b_vector[:, 2] else: raise Exception("data_type must be in ['tmi', 'x', 'y', 'z']") tmp_data[:, 8] = dobs data.append(tmp_data) # stack up the data so we return a single numpy array data = np.vstack(data) return data_header, data # ### select parameters # + # describe the inducing field B0_declination = np.r_[0., 45.] # degrees B0_inclination = np.r_[45, 90.] # degrees B0_amplitude = np.r_[56000] # amplitude in nT (56000 nT) # describe the target target_radius = np.r_[5, 10] target_permeability = np.r_[2, 5] # relative permeability of the target # receiver locations rx_x = np.linspace(-40, 40, 15) # generate 15 equally spaced data points between -40 and 40 (x-axis) rx_y = np.linspace(-40, 40, 15) rx_z = np.r_[20] nD = ( len(B0_declination) * len(B0_inclination) * len(B0_amplitude) * len(target_radius) * len(target_permeability) * len(rx_x) * len(rx_y) * len(rx_z) ) print(f"Number of data: {nD:1.2e}") # - # ### compute the data data_header, data = generate_dipole_data( B0_declination=B0_declination, B0_inclination=B0_inclination, B0_amplitude=B0_amplitude, target_radius=target_radius, target_permeability=target_permeability, rx_x=rx_x, rx_y=rx_y, rx_z=rx_z, data_type="TMI" ) import time # save the data filename = "mag-data-{}.txt".format(time.strftime("%Y%m%d-%H%M%S")) print(f"saving {filename}") np.savetxt(filename, data, delimiter=',', header=", ".join(data_header)) # ### Plot the data # # In the below cell, I plot the magnetic field measurements for each receiver location in a given setup (e.g. one example of the # + nd_per_simulation = len(rx_x) * len(rx_y) * len(rx_z) def plot_data(simulation_ind, yline): data_to_plot = data[nd_per_simulation*simulation_ind: nd_per_simulation*(simulation_ind + 1), :] fig, ax = plt.subplots(1, 2, figsize=(12, 6)) cb = plt.colorbar(ax[0].scatter( data_to_plot[:, 5], data_to_plot[:, 6], c=data_to_plot[:, 8] ), ax=ax[0]) ax[0].set_aspect(1) ax[0].set_xlabel("x (m)") ax[0].set_ylabel("y (m)") cb.set_label("B (nT)") # show info in title ax[1].set_title( f"inclination: {data_to_plot[0, 0]} \n" f"declination: {data_to_plot[0, 1]} \n" f"radius: {data_to_plot[0, 3]} \n" f"rel. permeability: {data_to_plot[0, 4]} \n" ) # line plot inds = slice(yline*len(rx_x), len(rx_x) * (yline+1)) ax[0].plot(data_to_plot[inds, 5], data_to_plot[inds, 6], 'k', lw=0.5) x_plot = data_to_plot[inds, 5] d_plot = data_to_plot[inds, 8] ax[1].plot(x_plot, d_plot, 'o') ax[1].grid("k", lw=0.5, alpha=0.5) ax[1].set_xlabel("x (m)") ax[1].set_ylabel("B (nT)") plt.tight_layout() ipywidgets.interactive( plot_data, simulation_ind=ipywidgets.IntSlider(min=0, max=data.shape[0]/nd_per_simulation), yline=ipywidgets.IntSlider(min=0, max=len(rx_y)) ) # -
Data_over_mag_dipole.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import torch import matplotlib.pyplot as plt import numpy as np import scipy import mne import os import pandas as pd import tqdm import IPython import torchvision import torch.nn as nn import torch.nn.functional as F from torchvision import transforms from torchvision.models import AlexNet from torchvision.utils import make_grid from torchvision.datasets import ImageFolder from PIL import Image from io import BytesIO from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.utils.data import TensorDataset import pickle import random from tqdm import tqdm # - def read_file(filename): with open(filename, 'rb') as handle: data = pickle.load(handle) return data annotations = pd.read_csv('./annotations.csv', names=['filename', 'class']) files = list(annotations['filename']) # + #creating datasets from numpy arrays. annotations = pd.read_csv('./annotations.csv', names=['filename', 'class']) files = list(annotations['filename']) y_full_np = np.array(list(annotations['class'])) partitions = np.array(read_file(files[0])).shape[1] aux_list = [] for entry in y_full_np: entry_class = [entry for i in range(partitions)] aux_list.extend(entry_class) y_full_np = np.array(aux_list) x_full_pad = [] for file in files: x_full_pad.append(np.swapaxes(np.array(read_file(file)),0,1)) x_full_pad = np.concatenate(x_full_pad, axis=0) # - indexes = [i for i in range(len(x_full_pad))] train_len = 3*len(indexes)//4 val_len = len(indexes) - train_len train_indexes = random.sample(indexes,train_len) val_indexes = list(set(indexes).difference(set(train_indexes))) # + x_train_pad = [] y_train_np = [] for index in train_indexes: x_train_pad.append(x_full_pad[index]) y_train_np.append(y_full_np[index]) x_train_pad = np.array(x_train_pad) y_train_np = np.array(y_train_np) x_val_pad = [] y_val_np = [] for index in val_indexes: x_val_pad.append(x_full_pad[index]) y_val_np.append(y_full_np[index]) x_val_pad = np.array(x_val_pad) y_val_np = np.array(y_val_np) # create Tensor datasets train_data = TensorDataset(torch.from_numpy(x_train_pad.astype(np.float32)), torch.from_numpy(y_train_np.astype(np.int64))) valid_data = TensorDataset(torch.from_numpy(x_val_pad.astype(np.float32)), torch.from_numpy(y_val_np.astype(np.int64))) # - train_dataloader = DataLoader(train_data, batch_size=100, shuffle=True) test_dataloader = DataLoader(valid_data, batch_size=100, shuffle=True) # + def set_device(): device = "cuda" if torch.cuda.is_available() else "cpu" if device != "cuda": print("WARNING: For this notebook to perform best, " "if possible, in the menu under `Runtime` -> " "`Change runtime type.` select `GPU` ") else: print("GPU is enabled in this notebook.") return device DEVICE = set_device() # + def train(model, device, train_loader): model.train() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(),lr=0.001) epochs = len(train_loader) losses = [] for epoch in range(epochs): with tqdm(train_loader, unit='batch') as tepoch: for data, target in tepoch: data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() tepoch.set_postfix(loss=loss.item()) losses.append(loss.item()) #time.sleep(0.1) return losses def test(model, device, data_loader): model.eval() correct = 0 total = 0 for data in data_loader: inputs, labels = data inputs = inputs.to(device).float() labels = labels.to(device).long() outputs = model(inputs) _, predicted = torch.max(outputs, 1) total += labels.size(0) correct += (predicted == labels).sum().item() acc = 100 * correct / total return acc # + class Test_Net(nn.Module): def __init__(self): super(Test_Net, self).__init__() self.fc1 = nn.Linear(9*64, 2048) self.fc2 = nn.Linear(2048, 1024) self.fc3 = nn.Linear(1024, 512) self.fc4 = nn.Linear(512, 256) self.fc5 = nn.Linear(256, 128) self.fc6 = nn.Linear(128, 64) self.fc7 = nn.Linear(64, 2) def forward(self, x): x = x.view(-1, 9*64) x = self.fc1(x) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) x = F.relu(x) x = self.fc4(x) x = F.relu(x) x = self.fc5(x) x = F.relu(x) x = self.fc6(x) x = F.relu(x) x = self.fc7(x) #x = F.relu(x) return x ## Uncomment the lines below to train your network test_net = Test_Net().to(DEVICE) accuracy = [] print("Total Parameters in Network {:10d}".format(sum(p.numel() for p in test_net.parameters()))) losses = train(test_net, DEVICE, train_dataloader) acc = test(test_net, DEVICE, test_dataloader) train_acc = test(test_net, DEVICE, train_dataloader) accuracy.append(acc) # - acc train_acc plt.xlabel('Epoch') plt.ylabel('Loss') plt.plot(losses) plt.show() samples,no_chan,freqs = x_train_pad.shape x_new = x_train_pad.reshape((samples,no_chan*freqs)) x_new.shape y_train_np.shape samples,no_chan,freqs = x_val_pad.shape x_val_new = x_val_pad.reshape((samples,no_chan*freqs)) x_val_new.shape from sklearn.linear_model import LogisticRegression clf = LogisticRegression(random_state=0).fit(x_new, y_train_np) clf.score(x_new, y_train_np) clf.score(x_val_new,y_val_np) class Test_Net(nn.Module): def __init__(self): super(Test_Net, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(9*1919, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 2), nn.ReLU() ) def forward(self, x): x = self.flatten(x) logits = self.linear_relu_stack(x) return logits alexnet = torchvision.models.alexnet(pretrained=True) num_ftrs = alexnet.fc.in_features alexnet.classifier[6] = nn.Linear(4096, 2) # reset final fully connected layer, number of classes = types of Pokemon = 9 alexnet.fc = nn.Linear(num_ftrs, 2) alexnet.to(DEVICE) optimizer = torch.optim.Adam(alexnet.parameters(), lr=1e-4) loss_fn = nn.CrossEntropyLoss() # + # @title Finetune ResNet pretrained_accs = [] for epoch in tqdm.tqdm(range(10)): # Train loop for batch in train_dataloader: images, labels = batch images = images.to(DEVICE) labels = labels.to(DEVICE) optimizer.zero_grad() output = alexnet(images) loss = loss_fn(output, labels) loss.backward() optimizer.step() # Eval loop with torch.no_grad(): loss_sum = 0 total_correct = 0 total = len(y_val_np) for batch in test_dataloader: images, labels = batch images = images.to(DEVICE) labels = labels.to(DEVICE) output = alexnet(images) loss = loss_fn(output, labels) loss_sum += loss.item() predictions = torch.argmax(output, dim=1) num_correct = torch.sum(predictions == labels) total_correct += num_correct # Plot accuracy pretrained_accs.append(total_correct / total) plt.plot(pretrained_accs) plt.xlabel('epoch') plt.ylabel('accuracy') plt.title('Pokemon prediction accuracy') IPython.display.clear_output(wait=True) IPython.display.display(plt.gcf()) plt.close() # - alexnet.eval()
Alexnet_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.5 64-bit ('generic_385') # metadata: # interpreter: # hash: b5a57bdf4f60dd5fdfdbcf1ff17b6295cdacb33611369cc354cba241c9284816 # name: python3 # --- # # basicsynbio designs # # This notebook contains a collection of basicsynbio designs relevant to interfacing bioCRNpyler and basicynbio. # # ## Thoughts and questions # # - What parameters will BioCRNPyler calculate in predicting constitutive expression from inducible expression results? # # ## Aims and objectives for cell/s below # # - Can I change the orientation of expression casettes? import basicsynbio as bsb from basicsynbio.main import DEFAULT_ANNOTATIONS from basicsynbio.cam import seqrecord_hexdigest from pathlib import Path import re parts = { "cds": bsb.BASIC_CDS_PARTS["v0.1"]["sfGFP"], "promoter": bsb.BASIC_PROMOTER_PARTS["v0.1"]["B-P3"] } reversed_parts = {} for key, value in parts.items(): reversed_assembly = bsb.BasicAssembly( f"{value.id}_reversed", bsb.BASIC_SEVA_PARTS["v0.1"]["18"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMS"], value, bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMP"], ) reversed_part = reversed_assembly.return_part( name=f"{value.name} reversed", ) reversed_part.id = seqrecord_hexdigest(reversed_part) reversed_parts[key] = reversed_part reverse_construct = bsb.BasicAssembly( "reverse_sfGFP_cassette", bsb.BASIC_SEVA_PARTS["v0.1"]["26"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMS"], reversed_parts["cds"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["UTR1-RBS1"], reversed_parts["promoter"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMP"], ) path_to_seqs = Path.cwd().parents[0] / "sequences" # bsb.export_sequences_to_file( # reverse_construct.return_part(), # path_to_seqs / "reverse_sfGFP_cassette.gb", # "genbank", # ) # ## Results from above cells # # - Can't change the orientation of an expression cassette. # # ## Aims and objectives for cell/s below # # - Design the following constructs that enable: # - Single plasmid containing IPTG-inducible sfGFP and ATC-inducible mTagBFP2. The reason for mTagBFP2 over mCherry is that it causes more burden and therefore should strongly influence sfGFP expression. # - Multiple plasmids where sfGFP is expressed from each relevant constitutive promoter. # - Multiple plasmids where mTagBFP2 is expressed from each relevant constitutive promoter. inducible_con = bsb.BasicAssembly( "inducible_sfGFP_mTagBFP2", bsb.BASIC_SEVA_PARTS["v0.1"]["26"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMP"], bsb.BASIC_PROMOTER_PARTS["v0.1"]["B-P31"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["UTR1-RBS3"], bsb.BASIC_CDS_PARTS["v0.1"]["sfGFP"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["L1"], bsb.BASIC_PROMOTER_PARTS["v0.1"]["B-P35"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["UTR2-RBS3"], bsb.BASIC_CDS_PARTS["v0.1"]["mTagBFP2"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMS"] ) sfgfp_cons = [ bsb.BasicAssembly( f"sfGFP_cassette_{promoter.name}", bsb.BASIC_SEVA_PARTS["v0.1"]["26"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMP"], promoter, bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["UTR1-RBS3"], bsb.BASIC_CDS_PARTS["v0.1"]["sfGFP"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMS"] ) for promoter in bsb.BASIC_PROMOTER_PARTS["v0.1"].values() if re.match("B-P(\d)*_Terminator1_J23(\d)*_RiboA", promoter.name)] mtagbfp2_cons = [ bsb.BasicAssembly( f"sfGFP_cassette_{promoter.name}", bsb.BASIC_SEVA_PARTS["v0.1"]["26"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMP"], promoter, bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["UTR2-RBS3"], bsb.BASIC_CDS_PARTS["v0.1"]["mTagBFP2"], bsb.BASIC_BIOLEGIO_LINKERS["v0.1"]["LMS"] ) for promoter in bsb.BASIC_PROMOTER_PARTS["v0.1"].values() if re.match("B-P(\d)*_Terminator2_J23(\d)*_RiboB", promoter.name)] build_1 = bsb.BasicBuild( inducible_con, *sfgfp_cons, *mtagbfp2_cons ) bsb.export_sequences_to_file( build_1.basic_assemblies, path_to_seqs / "build_1.gb", "genbank" ) print(f"Number of assemblies to construct {len(build_1.basic_assemblies)}")
scripts_nbs/bsb_designs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import requests import json import random import string import pandas as pd def pull_dois(): '''Pulls current crop of DOIs from Datacite API''' response = requests.get('https://api.datacite.org/dois?client-id=EnterYourClientIDHere') dois = json.loads(response.text) doi_data = dois['data'] known_idents = [] for doi in doi_data: ident = doi['id'].split('/')[1] known_idents.append(ident) return known_idents def data_munger(x, xx): '''Reads in the metadata from your export CSV and readies it for import. Note: the row.creator refers to a column titled creator in OUR csv of metadata. You will need to make sure that your row.name matches the corresponding column name in your csv file in order for the metadata to be read correctly.''' input_csv = pd.read_csv(xx, encoding='utf-8') data_package = [] for row in input_csv.itertuples(): data_package.append({'id': row.context_key, 'creators': [{'name': row.creator, 'nameType': 'Personal', 'givenName': row.author1_fname, 'familyName': row.author1_lname}], 'year': row.date, 'uri': row.source, 'title': row.title, 'type': row.type, 'descriptions': [{'description': row.description, 'descriptionType': 'Abstract'}], 'publisher': row.publisher, 'doi': '10.#####/{0}'.format(row.context_key)}) '''Be sure to enter your doi prefix above where it says 10.#####.''' return data_package def doi_packager(y): '''Submits new DOI packages to Datacite. Be sure to add your credentials for DataCite production where it says USERNAME and PASSWORD.''' headers = {'Content-Type': 'application/vnd.api+json'} export_list = [] for doi_data in y: export_dict = {} data_pack = {'data': {'id': doi_data['doi'], 'type': 'dois', 'attributes': {'event': 'publish', 'doi': doi_data['doi'], 'creators': doi_data['creators'], 'titles': [{'title': doi_data['title']}], 'publisher': doi_data['publisher'], 'publicationYear': doi_data['year'], 'descriptions': doi_data['descriptions'], 'types': {'resourceTypeGeneral': 'Text', 'resourceType': doi_data['type']}, 'url': doi_data['uri'], 'schemaVersion': 'http://datacite.org/schema/kernel-4'}}} jsonized = json.dumps(data_pack, ensure_ascii=False) response = requests.post('https://api.datacite.org/dois', headers=headers, data=jsonized.encode('utf-8'), auth=('USERNAME', 'PASSWORD')) print('{0} processed, response: {1}'.format(doi_data['doi'], response.status_code)) export_dict['id'] = doi_data['id'] export_dict['doi'] = 'https://doi.org/{0}'.format(doi_data['doi']) export_dict['status'] = response.status_code export_list.append(export_dict) return export_list def csv_machine(z): '''Barfs out a CSV file of your results''' output = pd.DataFrame(z) output = output.set_index('id') output.to_csv('metadata_update.csv') file_name = input('Please enter the name of your CSV file. (Make sure the filename has no spaces!)') existing_dois = pull_dois() new_dois = data_munger(existing_dois, file_name) results = doi_packager(new_dois) csv_machine(results)
DataCiteAPI-DOIs-from-CSV-Using-DefinedSuffix-Public.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Defaults # + import folium m = folium.Map(world_copy_jump=False, no_wrap=False) folium.Marker( location=[0, 0], popup="I will disapear when moved outside the wrapped map domain." ).add_to(m) m # - # ## World copy jump # + m = folium.Map(world_copy_jump=True, no_wrap=False) folium.Marker( location=[0, 0], popup="I will magically reappear when moved outside the wrapped map domain.", ).add_to(m) m # - # ## No wrap # + m = folium.Map( world_copy_jump=False, no_wrap=True, ) folium.Marker(location=[0, 0], popup="The map domain here is not wrapped!").add_to(m) m
examples/ContinuousWorld.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/Patrick-Munyao/SQL-Mini-Project/blob/main/SQL_Mini_Project_Moringa_School.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="764GkeegcSPo" # ## SQL Mini-Project # + [markdown] id="8K2XSidqcZ4k" # #Step 1: Load the sql extension and import libraries # # + colab={"base_uri": "https://localhost:8080/", "height": 69} id="h23q7cZacm1d" outputId="cf646181-24eb-4eed-e140-2300dc6e3c4b" # We will first load the sql extension into our environment # %load_ext sql # Then connect to our in memory sqlite database # %sql sqlite:// # + id="J1XXdMRzcrCD" #importing libraries import pandas as pd import numpy as np # + [markdown] id="2Wc1ypzpc01k" # #Step 2: Load the datasets # 1. Grand electors by state # 2. Population by state # + colab={"base_uri": "https://localhost:8080/", "height": 335} id="cchR__IgdCtF" outputId="4b33a1f4-73b9-4c67-cd89-ec9ce5c03ee0" # Loading the Grand electors dataset with open ("GrandElectors_by_state.csv", 'r') as p: StateGrandElectors = pd.read_csv(p, index_col=0, encoding= 'ut-8') # %sql DROP TABLE IF EXISTS StateGrandElectors # %sql Persist StateGrandElectors # %sql SELECT * FROM StateGrandElectors LIMIT 10; # + colab={"base_uri": "https://localhost:8080/", "height": 335} id="2boPohGqdDc9" outputId="24335dd5-e3f7-4945-b83a-062c3f6c514c" # Loading the population by state dataset; with open ("Population_by_state.csv", 'r') as p: StatePopulation = pd.read_csv(p, index_col=0, encoding= 'ut-8') # %sql DROP TABLE IF EXISTS StatePopulation # %sql Persist StatePopulation # %sql SELECT * FROM StatePopulation LIMIT 10; # + [markdown] id="4ZtEONzHdkMt" # #Step 3: Change States in Grand Electors Table to Uppercase # + colab={"base_uri": "https://localhost:8080/", "height": 196} id="TXeLkZ3ndxIU" outputId="5f5a5109-3b1b-4da0-ce8d-b265ecf9da39" # Capitalizing the State names # %%sql UPDATE StateGrandElectors SET State = UPPER(State); SELECT * FROM StateGrandElectors LIMIT 5; # + [markdown] id="byGlEb1nd3dr" # #Step 4: Join the Grandelectors and Population Tables # 1. Join the tables # 2. Preview new table # 3. Check for data types # 4. Check for null values for all columns # + colab={"base_uri": "https://localhost:8080/"} id="u8R6OIkld74v" outputId="b214981b-3eac-462d-fdd7-b46a6557a417" # Joining the grand electors and population tables on the state column # we will need to create a new table which will be used for analysis henceforth # %%sql CREATE TABLE "JOINED_TABLE" AS SELECT State, Population, GrandElectors FROM (SELECT * FROM StatePopulation INNER JOIN StateGrandElectors ON StatePopulation.State = StateGrandElectors.State) # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="53gYYm-Vem4t" outputId="86848c66-7cc7-40ed-edc1-862bd93eed7e" #preview the table # %%sql SELECT * FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/", "height": 158} id="DEp31mD7e80-" outputId="d02f27df-f36c-45ea-b8fa-8ee01a2bb37b" # Checking the datatype for the table # %%sql PRAGMA table_info(JOINED_TABLE) # + colab={"base_uri": "https://localhost:8080/", "height": 74} id="xkjzw-W0e9oM" outputId="5677fab1-6290-44a2-a7b9-9b01577a51b9" #Checking for null values in our joined dataset for each of the columns # State # %%sql SELECT * FROM JOINED_TABLE WHERE State IS NULL; # + colab={"base_uri": "https://localhost:8080/", "height": 74} id="AQXZUV8AfB9E" outputId="14670fce-8488-4c32-ac09-aa1a277dd7d0" # GrandElectors # %%sql SELECT * FROM JOINED_TABLE WHERE GrandElectors IS NULL; # + colab={"base_uri": "https://localhost:8080/", "height": 74} id="S8EeXmfrfFTO" outputId="c3ac901f-2cf6-441e-e26e-8a81e7fac14f" # Population # %%sql SELECT * FROM JOINED_TABLE WHERE Population IS NULL; # + [markdown] id="6IXitXlhf-Fr" # # Step 5: Change the "District of Columbia" to DC in State column # + colab={"base_uri": "https://localhost:8080/", "height": 196} id="bL7-YOcigDyP" outputId="828ad1c9-b1c7-4798-c54b-35f92cebdfb4" #Changing column "District of Columbia" to DC in State column; # %%sql UPDATE JOINED_TABLE SET State = "DC" WHERE State = "DISTRICT OF COLUMBIA"; SELECT * FROM JOINED_TABLE LIMIT 5; # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="fS4fB8MJgXZl" outputId="e65eab90-0b85-43d7-a7a7-9ddd7d9b77fb" #preview the change # %%sql SELECT * FROM JOINED_TABLE; # + [markdown] id="AuoNOZbDgfgj" # #Step 6: Add column ratio which contains the ratio between the number of Grand Electors and population # + colab={"base_uri": "https://localhost:8080/"} id="eZXVwonGgj3z" outputId="84ec94d6-4ebf-44ae-cff1-66cdab4567a3" # Computing the ratio between the number of Grand Electors and population and add the ratio to a new column #first add the column # %%sql ALTER TABLE JOINED_TABLE ADD Ratio float(25); # + colab={"base_uri": "https://localhost:8080/", "height": 179} id="9Mph1sW2hD_j" outputId="a598cc8c-a6bd-466a-b5d7-c39108372afe" language="sql" # SELECT * FROM JOINED_TABLE Limit 5; # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="OF66dlwHhHmb" outputId="d6f9f4e1-a5df-46bc-c7f3-43a873c041ea" # Compute the ratio # %%sql SELECT State, GrandElectors, Population, ROUND(GrandElectors*100.0/Population,6) AS Ratio FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="gw30m0kQhk_y" outputId="a97d58ea-14b5-4693-8e02-84856ab3e93b" language="sql" # SELECT COUNT(State) FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/"} id="a3pPGH6xhrO_" outputId="cf84ec8b-e6af-4aa6-b38a-a7a50091e00e" #Adding values to ratio column # %%sql UPDATE JOINED_TABLE SET 'Ratio'= ROUND(GrandElectors*100.0/Population,6); # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="cQQR0oAmh2hV" outputId="e08dd0f1-1e54-4f29-861a-18a2c8d4f9f5" # Previewing the outcome # %%sql SELECT * FROM JOINED_TABLE; # + [markdown] id="QXWYUkd0h_9c" # #Step 7: Get the priority list by ordering the states by decreasing ratio of grand electors per capita # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="qZDDKE5gjJvY" outputId="c36403bf-ea0d-4e5c-86ca-1d0be61ce593" # Order the States by decreasing ratio of Grand Electors per capita # priority list # %%sql SELECT * FROM JOINED_TABLE ORDER BY Ratio DESC; # + [markdown] id="oQns8W53jwbC" # #Step 8: Compute the running total of Grandelectors # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="s-Pa7j4FjzcW" outputId="3e504b02-94a3-498a-9501-e62847f5cbcb" # #compute the running total of the grandelectors in the sorted list # %%sql SELECT T1.State ,T1.GrandElectors ,T1.Population ,T1.Ratio ,Sum(T2.GrandElectors) Running_Total FROM JOINED_TABLE T1 INNER JOIN JOINED_TABLE T2 ON T1.Ratio <= T2.Ratio WHERE T1.Population > 0 Group by T1.State, T1.GrandElectors,T1.Population ORDER BY T1.Ratio DESC; # + colab={"base_uri": "https://localhost:8080/"} id="tmJk5IyplxyT" outputId="d3622bd5-0b5a-401a-e0c3-80f9bf05e5b4" language="sql" # CREATE TABLE "Elections" AS SELECT T1.State # ,T1.GrandElectors # ,T1.Population # ,T1.Ratio # ,Sum(T2.GrandElectors) Running_Total # FROM JOINED_TABLE T1 # INNER JOIN JOINED_TABLE T2 # ON T1.Ratio <= T2.Ratio # WHERE T1.Population > 0 # Group by T1.State, T1.GrandElectors,T1.Population # # ORDER BY T1.Ratio DESC; # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="pWl_uMgXmAJq" outputId="3a3e26df-c87f-4116-fa99-9e0ddea35a2b" # Preview the created US_election table # %%sql SELECT * FROM Elections; # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="emZ6RwaOsEBJ" outputId="f5dcc5c1-0398-4c62-e370-1707e9cd23c1" language="sql" # SELECT COUNT(State) FROM Elections; # + [markdown] id="qufEmAZKsGjA" # # Step 9: Compute the half of the total Grand electors # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="V0dvp_xfsOaF" outputId="594508c1-e9f9-472e-f713-fbbdb0367ee0" #compute the half of the total Grand Electors overrall in the whole country #This is the threshold we need to reach for winning the presidential election. # %%sql SELECT SUM(GrandElectors)/2 FROM Elections; # + [markdown] id="IdLIwPWZsbrD" # #Step 10: Filter sorted list of states # + colab={"base_uri": "https://localhost:8080/", "height": 872} id="q52n_E-MsfmK" outputId="c15fa5fe-9f91-4800-f084-c6575736894c" # Filter out the sorted list of states # keep only the top ones enabling us to reach the threshold # Hint: You can do that in 2 steps: # Select all the states for which the running total is below or equal to the threshold. # Add the first state for which the running total is larger than the threshold. # %%sql SELECT * FROM Elections WHERE Running_total <= 269; # + [markdown] id="GZgE01rSt9Ci" # #Step 11: Evaluation and Further Analysis # + id="E15PRSL0uadq" # Answered questions given in data mining goals # What threshold needs to be met to win the election ? # The threshold we need to win the election is 269 grand electors which is half of the sum of all grandelectors # How many states make up the priority list? # Nine states make up the priority list # List the states that are in the priority list? # Texas, California, Florida, New York, North Carolina, Virginia, New Jersey, Georgia, Arizona # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="l0nFInKmu4Iy" outputId="e1df4424-6392-469e-932e-5ffb43343d85" #Which state has the highest number of Grandelectors? # %%sql SELECT State, MAX(GrandElectors) FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="oSYSL_ycvR9i" outputId="af42e5ba-2418-4ea4-b076-b76436aec4cf" #Which state has the highest population? # %%sql SELECT State, MAX(Population) FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/", "height": 242} id="OotlOaajvYIM" outputId="e2517a70-4a4c-4d6e-bd4a-65cfb393ffdb" language="sql" # SELECT State, GrandElectors # FROM JOINED_TABLE # WHERE GrandElectors <= 3; # + colab={"base_uri": "https://localhost:8080/", "height": 95} id="X1OdcYeHvdLc" outputId="32383401-1057-4b79-dd69-7e40e846bf5a" #which state has the least population # %%sql SELECT State, MIN(Population) FROM JOINED_TABLE; # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="089HwGp0viKu" outputId="883c2bb3-b2f0-44c0-b22e-d37c87f1e819" #How does the population relate to grand electors? That is, how many people does each vote represent based on a stateโ€™s population? # %%sql SELECT State, Population, GrandElectors, Population/GrandElectors AS People_per_elector FROM JOINED_TABLE ORDER BY People_per_elector DESC; # + colab={"base_uri": "https://localhost:8080/", "height": 284} id="tGV0TZOqv0WZ" outputId="b0e4daa4-dc37-4a70-adb3-6a2224a24dc4" #groups # %%sql SELECT State, GrandElectors, Population FROM JOINED_TABLE WHERE Grandelectors >=15 and GrandElectors <=55 # + colab={"base_uri": "https://localhost:8080/", "height": 305} id="ZDBJ5W6awPZs" outputId="b40dbf22-8261-49ae-ce80-7c40084abae7" language="sql" # SELECT State, GrandElectors, Population # FROM JOINED_TABLE # WHERE Grandelectors >=10 and GrandElectors <=14 # + colab={"base_uri": "https://localhost:8080/", "height": 704} id="DcxO195IwUlW" outputId="64123701-52ab-4482-9234-33b3020ea08c" language="sql" # SELECT State, GrandElectors, Population # FROM JOINED_TABLE # WHERE Grandelectors >=3 and GrandElectors <=9 # + id="ncmzfVcWzUBA" # Other potential questions: # Which state has the highest number of Grandelectors? # California with 55 Grand electors # which states have the least grandelectors -Minimun grand electors are 3 The states with 3 are # montana, delaware, north dakota, south dakota, alaska, dc, wyoming and vermont # Which state has the highest population? - Wyoming with 586107 # which state has the least population? - California 39144818 # How does the population relate to grand electors? That is, how many people does each vote represent based on a stateโ€™s population? # From the column people per elector we can infer that one electoral vote for a state like texas would represent about 722,871 people while one # electoral vote in a state like wyoming represents about 195,369 people # How are states tiered in relation to their grand electors? # There are three groups or tiers within the states based on the number of electoral votes given # Tier 1: 15-55 electoral votes texas, california, florida, new york, georgia # tier 2: 10-14 virginia, new jersey, massachusets, missouri, maryland, tenessee, wisconsin, minnesota # tier 3: 3-9 -listed in the code above
SQL_Mini_Project_Moringa_School.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/ShubhankarKG/RUL_Prediction_SVM/blob/master/SVM_RUL_Prediction.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="G2HJOacm4odh" outputId="37745023-76ac-4dae-a103-8411eb96e701" from google.colab import drive drive.mount('/content/drive') # + id="_SiS7ApU-yGZ" import pandas as pd import cupy as np import math import matplotlib.pyplot as plt from os import path # %matplotlib inline # + id="Ex2MPPo8_5fW" df_1_1 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing1_1.csv") df_1_2 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing1_2.csv") df_2_1 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing2_1.csv") df_2_2 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing2_1.csv") df_3_1 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing3_1.csv") df_3_2 = pd.read_csv("/content/drive/MyDrive/Data2/learning_set/acc_Bearing3_2.csv") # + id="TEAG8Uo7Q1u_" def gen_rms(col): return np.squeeze(np.sqrt(np.mean(np.sum(col ** 2)))) # + id="HT69coqjph3o" base_path = "/content/drive/MyDrive/ML_LAB_Dataset" rms_horizontal = [] # + id="nC_5wvWZ4aNt" from IPython.display import ProgressBar def assign_files(extension, files, base_path="/content/drive/MyDrive/ML_LAB_Dataset") : rms_horizontal_local = [] p = ProgressBar(total=files) for i in range(files): p.progress = i file = base_path + extension + f"/acc_{str(i+1).zfill(5)}.csv" if path.exists(file): temp_df = pd.read_csv(file, header=None) temp_rms = gen_rms(temp_df[4]) rms_horizontal_local.append(temp_rms) return rms_horizontal_local # + id="4KAz00xp5ZJT" rms_1_1 = assign_files("/Bearing1_1", 3269) # + id="LiUpVHjN54me" rms_1_2 = assign_files("/Bearing1_2", 1015) # + colab={"base_uri": "https://localhost:8080/", "height": 34} id="nLkzmPiH597V" outputId="d91c66d9-f60e-47e5-f9a8-6c7aa71e16cf" rms_2_1 = assign_files("/Bearing2_1", 1062) # + id="RzrQ2KHg6DDW" rms_2_2 = assign_files("/Bearing2_2", 797) # + colab={"base_uri": "https://localhost:8080/", "height": 34} id="-PlbLxSf6PzV" outputId="6e0df506-279d-4f51-a56f-f948a4a16cf5" rms_3_1 = assign_files("/Bearing3_1", 604) # + id="2VWFj5Im6VqY" rms_3_2 = assign_files("/Bearing3_2", 1637) # + id="9vZpcxpRGDic" import itertools rms_1 = list(itertools.chain(rms_1_1, rms_1_2)) rms_2 = list(itertools.chain(rms_2_1, rms_2_2)) rms_3 = list(itertools.chain(rms_3_1, rms_3_2)) # + id="Y8CnZ2GoGO5h" colab={"base_uri": "https://localhost:8080/"} outputId="00dfb3c5-d7f9-4a38-fb46-536c6f929f0f" len(rms_1) # + id="a49TTyNx472U" colab={"base_uri": "https://localhost:8080/", "height": 280} outputId="426db760-2be6-42f1-80e0-2d869e1c9ecd" plt.figure() temp1, = plt.plot([i for i in range(len(rms_1))], rms_1) temp2, = plt.plot([i for i in range(len(rms_2))], rms_2) temp3, = plt.plot([i for i in range(len(rms_3))], rms_3) plt.xlabel('Time') plt.ylabel('RMS Horizontal acceleration') plt.legend([temp1, temp2, temp3], [ "Bearing 1", "Bearing 2", "Bearing 3"]) plt.show() # + id="gKP3RjR7IB7Q" rms_horizontal = list(itertools.chain(rms_1, rms_2, rms_3)) # + id="0JTIwS73ttB8" colab={"base_uri": "https://localhost:8080/", "height": 266} outputId="ed31364a-39de-4d07-cf1f-c418e928dd77" plt.figure() plt.plot([i for i in range(len(rms_horizontal))], rms_horizontal) plt.show() # + id="swjk2D4cMmXI" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="9a9b7d90-0f3a-4d0e-f8a4-4f7d0ff6c06b" plt.figure() plt.plot([i for i in range(df_1_1.shape[0])], df_1_1["E"]) plt.show() # + id="thThgPDiWsjw" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="e3ecaad9-e189-429c-bb05-6c6dd2691c84" plt.figure() plt.plot([i for i in range(df_1_2.shape[0])], df_1_2["E"]) plt.show() # + id="ctBGw0I0a6WZ" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="85d6142a-a8be-4e73-ea6f-4e888bf5d013" plt.figure() plt.plot([i for i in range(df_2_1.shape[0])], df_2_1["E"]) plt.show() # + id="Mpp0xV-ra-FS" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="b954ebd1-f173-4777-931e-b10045864fcc" plt.figure() plt.plot([i for i in range(df_2_2.shape[0])], df_2_2["E"]) plt.show() # + id="M5KuyYz2bFej" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="85040a7b-dd27-4dfa-d14c-eb46ba36c72c" plt.figure() plt.plot([i for i in range(df_3_1.shape[0])], df_3_1["E"]) plt.show() # + id="WwOFS3wMbJOB" colab={"base_uri": "https://localhost:8080/", "height": 278} outputId="9fd6d2a4-e946-4df9-827a-6cb6f4567460" plt.figure() plt.plot([i for i in range(df_3_2.shape[0])], df_3_2["E"]) plt.show() # + id="7zAoliHz6ZJc" def rrms(rms): stable_data_point = 250 rms_np = np.array(rms) rms_norm = np.mean(rms_np[:stable_data_point]) return rms_np / rms_norm # + id="zbX9NLhEHBPv" rrms_1_1 = rrms(rms_1_1) rrms_1_2 = rrms(rms_1_2) rrms_2_1 = rrms(rms_2_1) rrms_2_2 = rrms(rms_2_2) rrms_3_1 = rrms(rms_3_1) rrms_3_2 = rrms(rms_3_2) # + id="6eoautmq9Xfg" rrms_2_1 = rrms(rms_2_1) rrms_3_1 = rrms(rms_3_1) # + id="OLa8CC2eJF2E" rrms_1 = rrms(rms_1) # + id="TJh76jeeJJKS" rrms_2 = rrms(rms_2) # + id="nSi5ZZQyqHsv" rrms_2_1 = rrms(rms_2_1) # + id="wRULqsaFJVvy" rrms_3 = rrms(rms_3) # + id="HXmFmSHQqN1I" rrms_3_1 = rrms(rms_3_1) # + id="pmvEU_TqJiZc" colab={"base_uri": "https://localhost:8080/"} outputId="d669297e-5865-4d92-b663-91f9268dbe5f" len(rrms_1) # + id="sZFaumhFJX3H" colab={"base_uri": "https://localhost:8080/", "height": 279} outputId="63d598db-31a0-4f83-9b3d-019d914a7369" plt.figure() temp1, = plt.plot([i for i in range(len(rrms_1))], list(rrms_1)) temp2, = plt.plot([i for i in range(len(rrms_2))], list(rrms_2)) temp3, = plt.plot([i for i in range(len(rrms_3))], list(rrms_3)) temp4, = plt.plot([i for i in range(6500)], [7 for i in range(6500)], '--') plt.xlabel('Time') plt.ylabel('RRMS Horizontal acceleration') plt.legend([temp1, temp2, temp3, temp4], [ "Bearing 1", "Bearing 2", "Bearing 3", "Failure Threshold"]) plt.show() # + id="chOLZaveVrmo" def irrms(rrms, window_length): rrms_np = np.array(rrms) irrms = [] x = [10*i for i in range(len(rrms))] y = np.array([np.mean(rrms[i: i+window_length]) for i in range(len(rrms) - window_length)]) for i in range(len(rrms) - window_length): x_range = np.array(x[i: i+window_length]) # y_range = np.array(y[i: i+window_length]) y_range = np.array([np.mean(rrms[i: i+window_length]) for _ in range(window_length)]) k_num = np.sum(np.dot(x_range, y_range)) -( np.sum(x_range) * np.sum(y_range) )/window_length k_denom = np.sum(x_range ** 2) - (np.sum(x_range) ** 2) / window_length k = k_num / k_denom b = (np.sum(y_range) - k * np.sum(x_range)) / window_length rrms_d = [] for j in range(window_length): rrms_d.append(rrms[i+j] - k*x[i+j] - b) rrms_d_np = np.array(rrms_d) mu = np.mean(rrms_d_np) sigma = np.sqrt(np.mean((rrms_d_np - mu) ** 2)) min_rrms_d = mu - 3*sigma max_rrms_d = mu + 3*sigma rrms_d_i = rrms[i] - k*x[i] - b if rrms_d_i <= min_rrms_d: temp_irrms = np.mean(rrms_np[i: i+window_length]) elif rrms_d_i > min_rrms_d and rrms_d_i < max_rrms_d: temp_irrms = k * x[i] + b elif rrms_d_i >= max_rrms_d: temp_irrms = k * x[i] + b + max_rrms_d irrms.append(temp_irrms) return irrms # + id="IPqPBwXlj1ke" window_length = 30 # + id="BDBv-C6mj6SJ" irrms_1 = irrms(rrms_1, window_length) # + id="YUmmn2lAqrZq" irrms_2_1 = irrms(rrms_2_1, window_length) irrms_3_1 = irrms(rrms_3_1, window_length) # + id="QnhQo0ERFI2I" irrms_1_1 = irrms(rrms_1_1, window_length) irrms_1_2 = irrms(rrms_1_2, window_length) irrms_2_2 = irrms(rrms_2_2, window_length) irrms_3_2 = irrms(rrms_3_2, window_length) # + id="lVBxqylXklh7" irrms_2 = irrms(rrms_2, window_length) # + id="CRpPpiBBksqh" irrms_3 = irrms(rrms_3, window_length) # + id="uStKzpQrkx3E" colab={"base_uri": "https://localhost:8080/", "height": 279} outputId="9885f137-04b2-43db-ef31-8f3297ed0c08" plt.figure() temp3, = plt.plot([i for i in range(len(irrms_3[:2000]))], list(irrms_3[:2000])) plt.xlabel('Time') plt.ylabel('IRRMS Horizontal acceleration') plt.legend([ temp3], [ "Bearing 3"]) plt.show() # + id="LE-KAyIBnNlT" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="1fc1e76c-e4f3-4d52-ac3d-dd3507f38cf7" plt.figure() temp, = plt.plot([i for i in range(len(irrms_2[:2000]))], list(irrms_2[:2000])) plt.xlabel('Time') plt.ylabel('IRRMS Horizontal acceleration') plt.legend([ temp], [ "Bearing 2"]) plt.show() # + id="0MW47iWunVu1" colab={"base_uri": "https://localhost:8080/", "height": 279} outputId="06a80508-0f61-4b85-d88f-6e3662f79dc3" plt.figure() temp3, = plt.plot([i for i in range(len(irrms_1[:2000]))], list(irrms_1[:2000])) plt.xlabel('Time') plt.ylabel('IRRMS Horizontal acceleration') plt.legend([ temp3], [ "Bearing 1"]) plt.show() # + id="zd9nqWGbXRMA" # import random # W = 0.5 # c1 = 0.8 # c2 = 0.9 # class Particle(): # def __init__(self): # self.position = np.array([random.uniform(0, 2), random.uniform(1e-95, 1e-85), random.uniform(20, 30), random.randrange(200)*10]) # self.pbest_position = self.position # self.pbest_value = float('inf') # self.velocity = np.array([0,0,0,0]) # def move(self): # self.poition = self.position + self.velocity # class Space(): # def __init__(self, target, target_error, n_particles): # self.target = target # self.target_error = target_error # self.n_particles = n_particles # self.particles = [] # self.gbest_value = float('inf') # self.gbest_position = np.array([random.uniform(0, 2), random.uniform(1e-95, 1e-85), random.uniform(20, 30), random.randrange(200)*10]) # def fitness(self, particle): # return particle.position[0] + particle.position[1]*pow(particle.position[3], particle.position[2]) # def set_pbest(self): # for particle in self.particles: # fitness_candidate = self.fitness(particle) # if(particle.pbest_value > fitness_candidate): # particle.pbest_value = fitness_candidate # particle.pbest_position = particle.position # def set_gbest(self): # for particle in self.particles: # best_fitness_candidate = self.fitness(particle) # if(self.gbest_value > best_fitness_candidate): # self.gbest_value = best_fitness_candidate # self.gbest_position = particle.position # def move_particles(self): # for particle in self.particles: # new_velocity = (W*particle.velocity) + (c1*random.random()) * (particle.pbest_position - particle.position) + (c2*random.random()) * (self.gbest_position - particle.position) # particle.velocity = new_velocity # particle.move() # search_space = Space(1, 1e-6, 100) # particles_vector = [Particle() for _ in range(search_space.n_particles)] # search_space.particles = particles_vector # for i in range(100): # search_space.set_pbest() # search_space.set_gbest() # if(abs(search_space.gbest_value - search_space.target) <= search_space.target_error): # break # search_space.move_particles() # print("The best values are", search_space.gbest_position) # + id="BbGYn1wMGu5e" def fit_values(k, b, Y, M, B, rrms): y_array = [] x = [] for i in range(len(rrms)): x.append(i) y = Y + M*pow(i,B) if(y < 1.1): y = k * x[i] + b y_array.append(y) return y_array, x # + id="0plrY5FrczZg" y_rrms_array_1, x = fit_values(2.31e-5, 0.99, 1.10, 1.68e-93, 28.58, rrms_1) temp1, = plt.plot(x, y_rrms_array_1) y_irrms_array_1, x = fit_values(2.41e-5, 1.01, 1.08, 3.22e-86, 26.30, irrms_1) temp2, = plt.plot(x, y_irrms_array_1) plt.xlabel('Time') plt.ylabel('RRMS and IRRMS Horizontal acceleration') plt.title("Bearing 1") plt.legend([temp1, temp2], [ "RRMS", "IRRMS"]) plt.show() # + id="cZ-HK7gLc2W2" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="dec2690c-a3ec-44fe-b4a4-a341d3f2f641" y_rrms_array_2, x = fit_values(2.31e-5, 0.99, 1.10, 1.68e-93, 28.58, rrms_2) temp1, = plt.plot(x, y_rrms_array_2) y_irrms_array_2, x = fit_values(2.41e-5, 1.01, 1.08, 3.22e-86, 26.30, irrms_2) temp2, = plt.plot(x, y_irrms_array_2) plt.xlabel('Time') plt.ylabel('RRMS and IRRMS Horizontal acceleration') plt.title("Bearing 2") plt.legend([temp1, temp2], [ "RRMS", "IRRMS"]) plt.show() # + id="Mykqpdvic66_" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="bda7fc81-1c9f-42dc-c4a2-1103bb1152f8" y_rrms_array_3, x = fit_values(2.31e-5, 0.99, 1.10, 1.68e-93, 28.58, rrms_3) temp1, = plt.plot(x, y_rrms_array_3) y_irrms_array_3, x = fit_values(2.41e-5, 1.01, 1.08, 3.22e-86, 26.30, irrms_3) temp2, = plt.plot(x, y_irrms_array_3) plt.xlabel('Time') plt.ylabel('RRMS and IRRMS Horizontal acceleration') plt.title("Bearing 3") plt.legend([temp1, temp2], [ "RRMS", "IRRMS"]) plt.show() # + id="4sYAn58WGvap" class_irrms = [] RRMS_THRESHOLD = 1.2 # + id="pJrdbyR2GQoj" def generate_svm_data(rrms, irrms, rrms_threshold=1.1): output_data = [] # Don't consider the first window_size elements (as they are missing in irrms as well). rrms = rrms[30:] # Find the degradation index from the reversed list (or form the back side of the list). deg_rev_idx = next(x for x, val in enumerate(reversed(rrms)) if val < rrms_threshold) deg_idx = len(rrms) - deg_rev_idx deg_time = deg_idx * 10 for i in range(deg_idx): output_data.append(0) for i in range(deg_idx, len(rrms)): if i < deg_idx + int(deg_rev_idx * 0.6): output_data.append(1) elif i < deg_idx + int(deg_rev_idx * 0.8): output_data.append(2) elif i < deg_idx + int(deg_rev_idx * 0.95): output_data.append(3) else: output_data.append(4) input_data = np.c_[np.array(rrms), np.array(irrms)] edge_data = [] for i in set(output_data): idx = output_data.index(i) edge_data.append(input_data.tolist()[idx][1]) # Remove the first edge for class 0, do not require that. edge_data = edge_data[1:] # Add the edge of the last data point. edge_data.append(input_data.tolist()[-1][1]) temp = [] # In the form [[edge_1, edge_2], [edge_2, edge_3] ...] for i, v in enumerate(edge_data): if i+1 < len(edge_data): temp.append([v, edge_data[i+1]]) edge_data = temp output_data = np.array(output_data) return input_data, output_data, edge_data, deg_time # + colab={"base_uri": "https://localhost:8080/"} id="3-cydBOmq1cz" outputId="b01929a3-d0eb-4a96-c48e-de5a56b2df2b" input_2_1, output_2_1, edge_2_1, deg_time_2_1 = generate_svm_data(rrms_2_1, irrms_2_1) input_3_1, output_3_1, edge_3_1, deg_time_3_1 = generate_svm_data(rrms_3_1, irrms_3_1) print(deg_time_2_1, deg_time_3_1) # + id="o0M-oGEfGydL" input_1_1, output_1_1, edge_time_1_1, deg_time_1_1 = generate_svm_data(rrms_1_1, irrms_1_1) input_1_2, output_1_2, edge_time_1_2, deg_time_1_2 = generate_svm_data(rrms_1_2, irrms_1_2) input_2_2, output_2_2, edge_time_2_1, deg_time_2_1 = generate_svm_data(rrms_2_2, irrms_2_2) input_3_2, output_3_2, edge_time_2_2, deg_time_2_2 = generate_svm_data(rrms_3_2, irrms_3_2) # + id="2OKlozzDGwCN" class SVM: ''' This SVM model uses stochastic gradient decsent for optimisation. ''' def predict(self, input_data): ''' Returns ------- ndarray The classes of data according to the sign of X.W ''' return np.sign( np.dot( np.c_[np.ones(input_data.shape[0]), input_data], self.W ) ) def _cost(self): ''' Hingle loss with l2 regularisation ''' m = self.X.shape[0] hinge_loss = self.C * \ (1 - np.multiply(self.Y, np.dot(self.X, self.W)))/m return -np.mean(1/2 * np.dot(self.W.T, self.W) + hinge_loss) def _calculate_gradient(self): ''' gradient = W if y_i * (x_i).(W) >= 1 gradient = W - (C * y_i)x_i otherwise ''' distance = 1 - (self.Y * np.dot(self.X, self.W)) dW = np.zeros(self.W.shape[0]).reshape(-1, 1) for idx, d in enumerate(distance): if max(0, d) == 0: di = self.W else: c = (self.C * self.Y[idx]) * self.X[idx] c = c.reshape(-1, 1) di = self.W - c dW += di return dW/(self.Y.shape[0]) def fit(self, input_data, output_data, lr, C, max_epochs=1000, plot_loss=False): ''' Fit the model using Stochastic gradient descent Parameters ---------- input_data : ndarray The features of the data. output_data : ndarray True class labels, should be -1 and 1 (not 0 and 1). lr : int Learning rate C : int Regularisation parameter max_epochs : int, default=1000 Max iterations for SGD plot_loss : boolean, default=False Plot the cost vs epoch graph Returns ------- SVM The model itself ''' self.X = np.c_[np.ones(input_data.shape[0]), input_data] self.Y = np.array(output_data).reshape(-1, 1) self.C = C self.W = np.zeros(self.X.shape[1]).reshape(-1, 1) total_loss = [] for epoch in range(max_epochs): self.W = self.W - lr * self._calculate_gradient() if plot_loss: total_loss.append(self._cost()) if plot_loss: plt.plot(total_loss) plt.xlabel('epoch') plt.ylabel('loss') plt.title('Cost') return self # + id="shKo6qHUiZzs" class OneVsRest: def __init__(self, input_data, output_data): self.models = [SVM() for i in set(output_data)] self.x = input_data self.y = output_data def fit(self, lr, C, max_epochs=1000, plot_loss=False): trained_models = [] for idx, model in enumerate(self.models): output = [] for y in self.y: if y == idx: output.append(1) else: output.append(-1) in_data = np.array(self.x) out_data = np.array(output) trained_models.append(model.fit(in_data, out_data, lr, C, max_epochs, plot_loss)) self.models = trained_models return trained_models def predict(self, input_data): pred = [] for model in self.models: pred.append(model.predict(input_data)) pred = np.array(pred) return np.argmax(pred, axis=0) # + id="USiogItAsZKR" class OneVsOne: def __init__(self, input_data, output_data): self.n_classes = len(set(output_data)) n_models = int(self.n_classes * (self.n_classes - 1) * 0.5) # nC2 for pairs of classes self.models = [SVM() for i in range(n_models)] self.indices = [] for i in range(self.n_classes): for j in range(i+1, self.n_classes): self.indices.append([i, j]) self.x = input_data self.y = output_data def fit(self, lr, C, max_epochs=1000, plot_loss=False): trained_models = [] N = len(self.models) df = np.c_[np.array(self.x), np.array(self.y)] for model, index in zip(self.models, self.indices): outp = [] inp = [] for x in df.tolist(): if x[-1] == index[0]: temp = x[:-1] inp.append(temp) outp.append(1) elif x[-1] == index[1]: temp = x[:-1] inp.append(temp) outp.append(-1) in_data = np.array(inp) out_data = np.array(outp) trained_models.append(model.fit(in_data, out_data, lr, C, max_epochs, plot_loss)) self.models = trained_models return trained_models def predict(self, input_data): pred = [] for model in self.models: pred.append(model.predict(input_data)) pred = np.array(pred) return np.argmax(pred, axis=0) # + id="NINLo6NprLvt" from sklearn.svm import SVC from sklearn.preprocessing import MinMaxScaler input_2_1 = MinMaxScaler().fit_transform(input_2_1.tolist()) input_3_1 = MinMaxScaler().fit_transform(input_3_1.tolist()) # + id="4YECw1DPrqwL" model = SVC(decision_function_shape='ovo').fit(input_3_1, output_3_1.tolist()) model.predict(input_2_1) # + id="g-n9ZKAlBjJF" def hybrid_degradation(k, lp, sts, irrmsj, irrmsj1, irrms_edges): si = 6 k0 = 0.0005 sts = int(sts) if k <= k0: for sm in range(si): lp[sts] = (lp[sts] + lp[sts-1])/2 elif k > k0: lp[sts] = (irrmsj - irrmsj1) * (lp[sts] - lp[sts-1]) lp[sts] = lp[sts]/(irrms_edges[sts][1] - irrms_edges[sts][0]) lp[sts] = lp[sts] + lp[sts - 1] return lp # + colab={"base_uri": "https://localhost:8080/"} id="vwPEPYA4I4ar" outputId="35683aa4-4871-4aea-9116-193896784fc0" lp = [0, 0.60, 0.80, 0.95, 1.0] x = [i for i in range(len(irrms_2_1))] k = 0 for i in range(len(irrms_2_1) - window_length): x_range = np.array(x[i: i+window_length]) y_range = np.array([np.mean(np.array(irrms_2_1[i: i+window_length])) for _ in range(window_length)]) k_num = np.sum(np.dot(x_range, y_range)) -( np.sum(x_range) * np.sum(y_range) )/window_length k_denom = np.sum(x_range ** 2) - (np.sum(x_range) ** 2) / window_length k = k_num / k_denom if i > 0: hybrid_degradation(k, lp, output_2_1[i], irrms_2_1[i], irrms_2_1[i-1], edge_2_1) print(lp) # + id="ocd5P5rU9244" def predict_rul(input_data, deg_time, lp): rul_pred = [] rul_pred_total = [] pred_classes = model.predict(input_data) for idx, val in enumerate(pred_classes): if val > 0: rul_pred.append(deg_time + ((idx * 10) - deg_time)/lp[val] - (idx*10)) rul_pred_total.append(deg_time + ((idx * 10) - deg_time)/lp[val]) else: rul_pred.append(0) rul_pred_total.append(0) return rul_pred, rul_pred_total # + id="Ycfuu5sJSQ9J" rul_remaining, rul_full = predict_rul(input_3_1, deg_time_3_1, [0, 0.60, 0.80, 0.95,1.0]) # + colab={"base_uri": "https://localhost:8080/"} id="Hr6HWQRRtzN8" outputId="51a05df2-d734-4203-e35c-2efb963a8677" actual_rul = len(input_3_1) * 10 - 10 actual_rul # + id="grD-xqh7sv7e" # Find out all non zero values from predicted output and find mean rul_full_non_zero = [] for i in rul_full: if i != 0: rul_full_non_zero.append(i) pred_rul = np.mean(np.array(rul_full_non_zero)) # + id="Efa94LPUp5gf" colab={"base_uri": "https://localhost:8080/"} outputId="fce3fa4f-97dc-4ad0-e05c-33fbb68542b4" pred_rul # + id="oGMYMgfLtYTy" def error_rate(actual, pred): return abs(((actual - pred) / actual) * 100) # + colab={"base_uri": "https://localhost:8080/"} id="975raD2Tz1Q3" outputId="512ad0f5-85f6-4ae5-88e2-82b89c0b8d2d" error_rate(actual_rul, pred_rul)
SVM_RUL_Prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline # # Finetuning Torchvision Models # ============================= # # **Author:** `<NAME> <https://github.com/inkawhich>`__ # # # # In this tutorial we will take a deeper look at how to finetune and # feature extract the `torchvision # models <https://pytorch.org/docs/stable/torchvision/models.html>`__, all # of which have been pretrained on the 1000-class Imagenet dataset. This # tutorial will give an indepth look at how to work with several modern # CNN architectures, and will build an intuition for finetuning any # PyTorch model. Since each model architecture is different, there is no # boilerplate finetuning code that will work in all scenarios. Rather, the # researcher must look at the existing architecture and make custom # adjustments for each model. # # In this document we will perform two types of transfer learning: # finetuning and feature extraction. In **finetuning**, we start with a # pretrained model and update *all* of the modelโ€™s parameters for our new # task, in essence retraining the whole model. In **feature extraction**, # we start with a pretrained model and only update the final layer weights # from which we derive predictions. It is called feature extraction # because we use the pretrained CNN as a fixed feature-extractor, and only # change the output layer. For more technical information about transfer # learning see `here <http://cs231n.github.io/transfer-learning/>`__ and # `here <http://ruder.io/transfer-learning/>`__. # # In general both transfer learning methods follow the same few steps: # # - Initialize the pretrained model # - Reshape the final layer(s) to have the same number of outputs as the # number of classes in the new dataset # - Define for the optimization algorithm which parameters we want to # update during training # - Run the training step # # # from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os import copy print("PyTorch Version: ",torch.__version__) print("Torchvision Version: ",torchvision.__version__) # Inputs # ------ # # Here are all of the parameters to change for the run. We will use the # *hymenoptera_data* dataset which can be downloaded # `here <https://download.pytorch.org/tutorial/hymenoptera_data.zip>`__. # This dataset contains two classes, **bees** and **ants**, and is # structured such that we can use the # `ImageFolder <https://pytorch.org/docs/stable/torchvision/datasets.html#torchvision.datasets.ImageFolder>`__ # dataset, rather than writing our own custom dataset. Download the data # and set the ``data_dir`` input to the root directory of the dataset. The # ``model_name`` input is the name of the model you wish to use and must # be selected from this list: # # :: # # [resnet, alexnet, vgg, squeezenet, densenet, inception] # # The other inputs are as follows: ``num_classes`` is the number of # classes in the dataset, ``batch_size`` is the batch size used for # training and may be adjusted according to the capability of your # machine, ``num_epochs`` is the number of training epochs we want to run, # and ``feature_extract`` is a boolean that defines if we are finetuning # or feature extracting. If ``feature_extract = False``, the model is # finetuned and all model parameters are updated. If # ``feature_extract = True``, only the last layer parameters are updated, # the others remain fixed. # # # # + # Top level data directory. Here we assume the format of the directory conforms # to the ImageFolder structure data_dir = "data/hymenoptera_data" # Models to choose from [resnet, alexnet, vgg, squeezenet, densenet, inception] model_name = "resnet" # Number of classes in the dataset num_classes = 2 # Batch size for training (change depending on how much memory you have) batch_size = 64 # Number of epochs to train for num_epochs = 100 # Flag for feature extracting. When False, we finetune the whole model, # when True we only update the reshaped layer params feature_extract = False # - # Helper Functions # ---------------- # # Before we write the code for adjusting the models, lets define a few # helper functions. # # ### Model Training and Validation Code # # The ``train_model`` function handles the training and validation of a # given model. As input, it takes a PyTorch model, a dictionary of # dataloaders, a loss function, an optimizer, a specified number of epochs # to train and validate for, and a boolean flag for when the model is an # Inception model. The *is_inception* flag is used to accomodate the # *Inception v3* model, as that architecture uses an auxiliary output and # the overall model loss respects both the auxiliary output and the final # output, as described # `here <https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958>`__. # The function trains for the specified number of epochs and after each # epoch runs a full validation step. It also keeps track of the best # performing model (in terms of validation accuracy), and at the end of # training returns the best performing model. After each epoch, the # training and validation accuracies are printed. # # # def train_model(model, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False): since = time.time() val_acc_history = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): # Get model outputs and calculate loss # Special case for inception because in training it has an auxiliary output. In train # mode we calculate the loss by summing the final output and the auxiliary output # but in testing we only consider the final output. if is_inception and phase == 'train': # From https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958 outputs, aux_outputs = model(inputs) loss1 = criterion(outputs, labels) loss2 = criterion(aux_outputs, labels) loss = loss1 + 0.4*loss2 else: outputs = model(inputs) loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / len(dataloaders[phase].dataset) epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset) print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) if phase == 'val': val_acc_history.append(epoch_acc) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model, val_acc_history # Set Model Parametersโ€™ .requires_grad attribute # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # This helper function sets the ``.requires_grad`` attribute of the # parameters in the model to False when we are feature extracting. By # default, when we load a pretrained model all of the parameters have # ``.requires_grad=True``, which is fine if we are training from scratch # or finetuning. However, if we are feature extracting and only want to # compute gradients for the newly initialized layer then we want all of # the other parameters to not require gradients. This will make more sense # later. # # # def set_parameter_requires_grad(model, feature_extracting): if feature_extracting: for param in model.parameters(): param.requires_grad = False # Initialize and Reshape the Networks # ----------------------------------- # # Now to the most interesting part. Here is where we handle the reshaping # of each network. Note, this is not an automatic procedure and is unique # to each model. Recall, the final layer of a CNN model, which is often # times an FC layer, has the same number of nodes as the number of output # classes in the dataset. Since all of the models have been pretrained on # Imagenet, they all have output layers of size 1000, one node for each # class. The goal here is to reshape the last layer to have the same # number of inputs as before, AND to have the same number of outputs as # the number of classes in the dataset. In the following sections we will # discuss how to alter the architecture of each model individually. But # first, there is one important detail regarding the difference between # finetuning and feature-extraction. # # When feature extracting, we only want to update the parameters of the # last layer, or in other words, we only want to update the parameters for # the layer(s) we are reshaping. Therefore, we do not need to compute the # gradients of the parameters that we are not changing, so for efficiency # we set the .requires_grad attribute to False. This is important because # by default, this attribute is set to True. Then, when we initialize the # new layer and by default the new parameters have ``.requires_grad=True`` # so only the new layerโ€™s parameters will be updated. When we are # finetuning we can leave all of the .required_gradโ€™s set to the default # of True. # # Finally, notice that inception_v3 requires the input size to be # (299,299), whereas all of the other models expect (224,224). # # Resnet # ~~~~~~ # # Resnet was introduced in the paper `Deep Residual Learning for Image # Recognition <https://arxiv.org/abs/1512.03385>`__. There are several # variants of different sizes, including Resnet18, Resnet34, Resnet50, # Resnet101, and Resnet152, all of which are available from torchvision # models. Here we use Resnet18, as our dataset is small and only has two # classes. When we print the model, we see that the last layer is a fully # connected layer as shown below: # # :: # # (fc): Linear(in_features=512, out_features=1000, bias=True) # # Thus, we must reinitialize ``model.fc`` to be a Linear layer with 512 # input features and 2 output features with: # # :: # # model.fc = nn.Linear(512, num_classes) # # Alexnet # ~~~~~~~ # # Alexnet was introduced in the paper `ImageNet Classification with Deep # Convolutional Neural # Networks <https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf>`__ # and was the first very successful CNN on the ImageNet dataset. When we # print the model architecture, we see the model output comes from the 6th # layer of the classifier # # :: # # (classifier): Sequential( # ... # (6): Linear(in_features=4096, out_features=1000, bias=True) # ) # # To use the model with our dataset we reinitialize this layer as # # :: # # model.classifier[6] = nn.Linear(4096,num_classes) # # VGG # ~~~ # # VGG was introduced in the paper `Very Deep Convolutional Networks for # Large-Scale Image Recognition <https://arxiv.org/pdf/1409.1556.pdf>`__. # Torchvision offers eight versions of VGG with various lengths and some # that have batch normalizations layers. Here we use VGG-11 with batch # normalization. The output layer is similar to Alexnet, i.e. # # :: # # (classifier): Sequential( # ... # (6): Linear(in_features=4096, out_features=1000, bias=True) # ) # # Therefore, we use the same technique to modify the output layer # # :: # # model.classifier[6] = nn.Linear(4096,num_classes) # # Squeezenet # ~~~~~~~~~~ # # The Squeeznet architecture is described in the paper `SqueezeNet: # AlexNet-level accuracy with 50x fewer parameters and <0.5MB model # size <https://arxiv.org/abs/1602.07360>`__ and uses a different output # structure than any of the other models shown here. Torchvision has two # versions of Squeezenet, we use version 1.0. The output comes from a 1x1 # convolutional layer which is the 1st layer of the classifier: # # :: # # (classifier): Sequential( # (0): Dropout(p=0.5) # (1): Conv2d(512, 1000, kernel_size=(1, 1), stride=(1, 1)) # (2): ReLU(inplace) # (3): AvgPool2d(kernel_size=13, stride=1, padding=0) # ) # # To modify the network, we reinitialize the Conv2d layer to have an # output feature map of depth 2 as # # :: # # model.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1)) # # Densenet # ~~~~~~~~ # # Densenet was introduced in the paper `Densely Connected Convolutional # Networks <https://arxiv.org/abs/1608.06993>`__. Torchvision has four # variants of Densenet but here we only use Densenet-121. The output layer # is a linear layer with 1024 input features: # # :: # # (classifier): Linear(in_features=1024, out_features=1000, bias=True) # # To reshape the network, we reinitialize the classifierโ€™s linear layer as # # :: # # model.classifier = nn.Linear(1024, num_classes) # # Inception v3 # ~~~~~~~~~~~~ # # Finally, Inception v3 was first described in `Rethinking the Inception # Architecture for Computer # Vision <https://arxiv.org/pdf/1512.00567v1.pdf>`__. This network is # unique because it has two output layers when training. The second output # is known as an auxiliary output and is contained in the AuxLogits part # of the network. The primary output is a linear layer at the end of the # network. Note, when testing we only consider the primary output. The # auxiliary output and primary output of the loaded model are printed as: # # :: # # (AuxLogits): InceptionAux( # ... # (fc): Linear(in_features=768, out_features=1000, bias=True) # ) # ... # (fc): Linear(in_features=2048, out_features=1000, bias=True) # # To finetune this model we must reshape both layers. This is accomplished # with the following # # :: # # model.AuxLogits.fc = nn.Linear(768, num_classes) # model.fc = nn.Linear(2048, num_classes) # # Notice, many of the models have similar output structures, but each must # be handled slightly differently. Also, check out the printed model # architecture of the reshaped network and make sure the number of output # features is the same as the number of classes in the dataset. # # # # + def initialize_model(model_name, num_classes, feature_extract, use_pretrained=True): # Initialize these variables which will be set in this if statement. Each of these # variables is model specific. model_ft = None input_size = 0 if model_name == "resnet": """ Resnet18 """ model_ft = models.resnet18(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, num_classes) input_size = 224 elif model_name == "alexnet": """ Alexnet """ model_ft = models.alexnet(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier[6].in_features model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes) input_size = 224 elif model_name == "vgg": """ VGG11_bn """ model_ft = models.vgg11_bn(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier[6].in_features model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes) input_size = 224 elif model_name == "squeezenet": """ Squeezenet """ model_ft = models.squeezenet1_0(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) model_ft.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1)) model_ft.num_classes = num_classes input_size = 224 elif model_name == "densenet": """ Densenet """ model_ft = models.densenet121(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier.in_features model_ft.classifier = nn.Linear(num_ftrs, num_classes) input_size = 224 elif model_name == "inception": """ Inception v3 Be careful, expects (299,299) sized images and has auxiliary output """ model_ft = models.inception_v3(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) # Handle the auxilary net num_ftrs = model_ft.AuxLogits.fc.in_features model_ft.AuxLogits.fc = nn.Linear(num_ftrs, num_classes) # Handle the primary net num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs,num_classes) input_size = 299 else: print("Invalid model name, exiting...") exit() return model_ft, input_size # Initialize the model for this run model_ft, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=True) # Print the model we just instantiated print(model_ft) # - # Load Data # --------- # # Now that we know what the input size must be, we can initialize the data # transforms, image datasets, and the dataloaders. Notice, the models were # pretrained with the hard-coded normalization values, as described # `here <https://pytorch.org/docs/master/torchvision/models.html>`__. # # # # + # Data augmentation and normalization for training # Just normalization for validation data_transforms = { 'train': transforms.Compose([ transforms.RandomResizedCrop(input_size), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(input_size), transforms.CenterCrop(input_size), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } print("Initializing Datasets and Dataloaders...") # Create training and validation datasets image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']} # Create training and validation dataloaders dataloaders_dict = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=4) for x in ['train', 'val']} # Detect if we have a GPU available device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") # - # Create the Optimizer # -------------------- # # Now that the model structure is correct, the final step for finetuning # and feature extracting is to create an optimizer that only updates the # desired parameters. Recall that after loading the pretrained model, but # before reshaping, if ``feature_extract=True`` we manually set all of the # parameterโ€™s ``.requires_grad`` attributes to False. Then the # reinitialized layerโ€™s parameters have ``.requires_grad=True`` by # default. So now we know that *all parameters that have # .requires_grad=True should be optimized.* Next, we make a list of such # parameters and input this list to the SGD algorithm constructor. # # To verify this, check out the printed parameters to learn. When # finetuning, this list should be long and include all of the model # parameters. However, when feature extracting this list should be short # and only include the weights and biases of the reshaped layers. # # # # + # Send the model to GPU model_ft = model_ft.to(device) # Gather the parameters to be optimized/updated in this run. If we are # finetuning we will be updating all parameters. However, if we are # doing feature extract method, we will only update the parameters # that we have just initialized, i.e. the parameters with requires_grad # is True. params_to_update = model_ft.parameters() print("Params to learn:") if feature_extract: params_to_update = [] for name,param in model_ft.named_parameters(): if param.requires_grad == True: params_to_update.append(param) print("\t",name) else: for name,param in model_ft.named_parameters(): if param.requires_grad == True: print("\t",name) # Observe that all parameters are being optimized optimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9) # - # Run Training and Validation Step # -------------------------------- # # Finally, the last step is to setup the loss for the model, then run the # training and validation function for the set number of epochs. Notice, # depending on the number of epochs this step may take a while on a CPU. # Also, the default learning rate is not optimal for all of the models, so # to achieve maximum accuracy it would be necessary to tune for each model # separately. # # # # + # Setup the loss fxn criterion = nn.CrossEntropyLoss() # Train and evaluate model_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs, is_inception=(model_name=="inception")) # - # Comparison with Model Trained from Scratch # ------------------------------------------ # # Just for fun, lets see how the model learns if we do not use transfer # learning. The performance of finetuning vs.ย feature extracting depends # largely on the dataset but in general both transfer learning methods # produce favorable results in terms of training time and overall accuracy # versus a model trained from scratch. # # # torch.cuda.empty_cache() # + # Initialize the non-pretrained version of the model used for this run scratch_model,_ = initialize_model(model_name, num_classes, feature_extract=False, use_pretrained=False) scratch_model = scratch_model.to(device) scratch_optimizer = optim.SGD(scratch_model.parameters(), lr=0.001, momentum=0.9) scratch_criterion = nn.CrossEntropyLoss() _,scratch_hist = train_model(scratch_model, dataloaders_dict, scratch_criterion, scratch_optimizer, num_epochs=num_epochs, is_inception=(model_name=="inception")) # Plot the training curves of validation accuracy vs. number # of training epochs for the transfer learning method and # the model trained from scratch ohist = [] shist = [] ohist = [h.cpu().numpy() for h in hist] shist = [h.cpu().numpy() for h in scratch_hist] plt.title("Validation Accuracy vs. Number of Training Epochs") plt.xlabel("Training Epochs") plt.ylabel("Validation Accuracy") plt.plot(range(1,num_epochs+1),ohist,label="Pretrained") plt.plot(range(1,num_epochs+1),shist,label="Scratch") plt.ylim((0,1.)) plt.xticks(np.arange(1, num_epochs+1, 1.0)) plt.legend() plt.show() # - # Final Thoughts and Where to Go Next # ----------------------------------- # # Try running some of the other models and see how good the accuracy gets. # Also, notice that feature extracting takes less time because in the # backward pass we do not have to calculate most of the gradients. There # are many places to go from here. You could: # # - Run this code with a harder dataset and see some more benefits of # transfer learning # - Using the methods described here, use transfer learning to update a # different model, perhaps in a new domain (i.e.ย NLP, audio, etc.) # - Once you are happy with a model, you can export it as an ONNX model, # or trace it using the hybrid frontend for more speed and optimization # opportunities. # # #
.ipynb_checkpoints/10_finetuning_torchvision_models_tutorial-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os, sys import time import torch import torch.nn as nn from torch.autograd import Variable import numpy as np from models_mask10_class1 import VGG as model_cifar import pandas as pd import argparse import csv from torch.optim.lr_scheduler import MultiStepLR from dataLoader import DataLoader from sklearn.metrics import confusion_matrix, classification_report # ็”Ÿๆˆๆททๆท†็Ÿฉ้˜ตๅ‡ฝๆ•ฐ import matplotlib.pyplot as plt # ็ป˜ๅ›พๅบ“ from PIL import Image, ImageDraw print('Init Finished!') # - # # Model Load args_depth = 20 num_classes = 10 args_dataset = 'cifar-10' args_batch_size = 512 PATH = '/data/ouyangzhihao/Exp/ICNN/Resnet_ICNN/tb_dir/cifar_exp/test_256bs_150epoch_layer3_Vgg_baseline' # PATH = '/data/ouyangzhihao/Exp/ICNN/Resnet_ICNN/tb_dir/cifar_exp/test_256bs_150epoch_layer3_Vgg_mask1' model_path = os.path.join(PATH, 'saved_model.pt') # Data Loader loader = DataLoader(args_dataset,batch_size=args_batch_size) dataloaders,dataset_sizes = loader.load_data() model = model_cifar("VGG16") model = model.cuda() model = torch.nn.DataParallel(model) model.load_state_dict(torch.load(model_path)) print('Successfully Load Model: ', os.path.basename(model_path)) def printF(i, total=100): i = int( i / total * 100) + 1 total = 100 k = i + 1 str_ = '>'*i + '' ''*(total-k) sys.stdout.write('\r'+str_+'[%s%%]'%(i+1)) sys.stdout.flush() if(i >= total -1): print() use_gpu = True epoch = 1 phase = 'val' running_corrects = 0.0 data_len = len(dataloaders[phase]) # print(data_len) true_labels = [] model_preds = [] for idx,data in enumerate(dataloaders[phase]): printF(idx, data_len) inputs,labels = data if use_gpu: inputs = Variable(inputs.cuda()) labels = Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) #forward outputs = model(inputs, labels, epoch) _, preds = torch.max(outputs.data, 1) # _,top5_preds = torch.topk(outputs.data,k=5,dim=1) # print ('group loss:',group_loss[0]) y = labels.data batch_size = labels.data.shape[0] # print(y.resize_(batch_size,1)) running_corrects += torch.sum(preds == y) # top5_corrects += torch.sum(top5_preds == y.resize_(batch_size,1)) epoch_acc = float(running_corrects) /dataset_sizes[phase] true_labels.extend(y.cpu().numpy()) model_preds.extend(preds.cpu().numpy()) print('%s top1 Acc:%.4f'%(phase,epoch_acc)) labels_name = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def plot_confusion_matrix(cm, labels_name, title): cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] # ๅฝ’ไธ€ๅŒ– plt.imshow(cm, interpolation='nearest') # ๅœจ็‰นๅฎš็š„็ช—ๅฃไธŠๆ˜พ็คบๅ›พๅƒ plt.title(title) # ๅ›พๅƒๆ ‡้ข˜ plt.colorbar() num_local = np.array(range(len(labels_name))) plt.xticks(num_local, labels_name, rotation=90) # ๅฐ†ๆ ‡็ญพๅฐๅœจx่ฝดๅๆ ‡ไธŠ plt.yticks(num_local, labels_name) # ๅฐ†ๆ ‡็ญพๅฐๅœจy่ฝดๅๆ ‡ไธŠ plt.ylabel('True label') plt.xlabel('Predicted label') def plot_confusion_matrix_and_text(cm, labels_name, title): plt.figure(figsize=(16,16),dpi=200) plt.subplot(221) plot_confusion_matrix(cm, labels_name, title) plt.subplot(222) text_img = Image.new('RGB', (350, 250), color = (255,255,255)) d = ImageDraw.Draw(text_img) text_content = classification_report(true_labels, model_preds, target_names=labels_name) d.text((0,0), text_content, fill=(0,0,0)) plt.imshow(text_img) plt.show() # # Baseline cm = confusion_matrix(y_true=true_labels, y_pred=model_preds) plot_confusion_matrix_and_text(cm, labels_name, "Baseline Confusion Matrix") # plt.savefig('/HAR_cm.png', format='png') plt.show() # print(classification_report(true_labels, model_preds, target_names=labels_name)) # # Classification Analysis table = pd.DataFrame(cm) table.columns = labels_name table # # Mask1 PATH = '/data/ouyangzhihao/Exp/ICNN/Resnet_ICNN/tb_dir/cifar_exp/test_256bs_150epoch_layer3_Vgg_mask1' model_path = os.path.join(PATH, 'saved_model.pt') model.load_state_dict(torch.load(model_path)) use_gpu = True epoch = 1 phase = 'val' running_corrects = 0.0 data_len = len(dataloaders[phase]) # print(data_len) true_labels = [] model_preds = [] for idx,data in enumerate(dataloaders[phase]): printF(idx, data_len) inputs,labels = data if use_gpu: inputs = Variable(inputs.cuda()) labels = Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) #forward outputs = model(inputs, labels, epoch) _, preds = torch.max(outputs.data, 1) # _,top5_preds = torch.topk(outputs.data,k=5,dim=1) # print ('group loss:',group_loss[0]) y = labels.data batch_size = labels.data.shape[0] # print(y.resize_(batch_size,1)) running_corrects += torch.sum(preds == y) # top5_corrects += torch.sum(top5_preds == y.resize_(batch_size,1)) epoch_acc = float(running_corrects) /dataset_sizes[phase] true_labels.extend(y.cpu().numpy()) model_preds.extend(preds.cpu().numpy()) print('%s top1 Acc:%.4f'%(phase,epoch_acc)) cm = confusion_matrix(y_true=true_labels, y_pred=model_preds) plot_confusion_matrix_and_text(cm, labels_name, "Mask1 Confusion Matrix") plt.show() # print(classification_report(true_labels, model_preds, target_names=labels_name)) table = pd.DataFrame(cm) table.columns = labels_name table # # Mask 1vs0 PATH = '/data/ouyangzhihao/Exp/ICNN/Resnet_ICNN/tb_dir/cifar_exp/test_256bs_150epoch_layer3_Vgg_mask1vs0' model_path = os.path.join(PATH, 'saved_model.pt') model.load_state_dict(torch.load(model_path)) use_gpu = True epoch = 1 phase = 'val' running_corrects = 0.0 data_len = len(dataloaders[phase]) # print(data_len) true_labels = [] model_preds = [] for idx,data in enumerate(dataloaders[phase]): printF(idx, data_len) inputs,labels = data if use_gpu: inputs = Variable(inputs.cuda()) labels = Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) #forward outputs = model(inputs, labels, epoch) _, preds = torch.max(outputs.data, 1) # _,top5_preds = torch.topk(outputs.data,k=5,dim=1) # print ('group loss:',group_loss[0]) y = labels.data batch_size = labels.data.shape[0] # print(y.resize_(batch_size,1)) running_corrects += torch.sum(preds == y) # top5_corrects += torch.sum(top5_preds == y.resize_(batch_size,1)) epoch_acc = float(running_corrects) /dataset_sizes[phase] true_labels.extend(y.cpu().numpy()) model_preds.extend(preds.cpu().numpy()) print('%s top1 Acc:%.4f'%(phase,epoch_acc)) cm = confusion_matrix(y_true=true_labels, y_pred=model_preds) plot_confusion_matrix_and_text(cm, labels_name, "# Mask 1vs0 Confusion Matrix") plt.show() # print(classification_report(true_labels, model_preds, target_names=labels_name)) table = pd.DataFrame(cm) table.columns = labels_name table # # icnn loss 0.3 PATH = '/data/ouyangzhihao/Exp/ICNN/Resnet_ICNN/tb_dir/cifar_exp/test_256bs_150epoch_layer3_Vgg_mask1_iloss0.3' model_path = os.path.join(PATH, 'saved_model.pt') model.load_state_dict(torch.load(model_path)) use_gpu = True epoch = 1 phase = 'val' running_corrects = 0.0 data_len = len(dataloaders[phase]) # print(data_len) true_labels = [] model_preds = [] for idx,data in enumerate(dataloaders[phase]): printF(idx, data_len) inputs,labels = data if use_gpu: inputs = Variable(inputs.cuda()) labels = Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) #forward outputs = model(inputs, labels, epoch) _, preds = torch.max(outputs.data, 1) # _,top5_preds = torch.topk(outputs.data,k=5,dim=1) # print ('group loss:',group_loss[0]) y = labels.data batch_size = labels.data.shape[0] # print(y.resize_(batch_size,1)) running_corrects += torch.sum(preds == y) # top5_corrects += torch.sum(top5_preds == y.resize_(batch_size,1)) epoch_acc = float(running_corrects) /dataset_sizes[phase] true_labels.extend(y.cpu().numpy()) model_preds.extend(preds.cpu().numpy()) print('%s top1 Acc:%.4f'%(phase,epoch_acc)) cm = confusion_matrix(y_true=true_labels, y_pred=model_preds) plot_confusion_matrix_and_text(cm, labels_name, "icnn loss 0.3ยถ Confusion Matrix") plt.show() # print(classification_report(true_labels, model_preds, target_names=labels_name)) table = pd.DataFrame(cm) table.columns = labels_name table
Old_Codes_For_Exploration/ModelAnalysis/VGG/VGG16_mask10_class1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Classification models applied to the market. # ### Authors: # - <NAME> # - <NAME> # - <NAME> # + import requests import click import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from datetime import date from datetime import timedelta import sys from scipy import stats # - # We will make use of the functions developed in the **FinancialModeling.py** file, so we import the path to the file. # + functions_dir = "../finansp/" sys.path.insert(1, functions_dir ) import FinancialModeling as FM # - # The first function used is **getCompany**. This function obtains the values date, high, low, close, adjClose, volume unadjustedVolume, change, changePercent, vwap, label, changeOverTime on a daily basis for the last five years from the company indicated by the ticker. df = FM.getCompany("GOOG") # We use the panda functions to get the essential information of the dataset generated for the company. df.tail(5) df.describe() # The next function used is **visualize**. This function performs a series of representations in order to study the data set. The first one is based on histograms. With it you can study the distribution of each of the attributes. Next, boxplots are represented. Since the values that have the attributes are far apart, it is not easy to appreciate the existence of outliers in attributes other than the volume. Finally, a heat map of the correlation matrix is represented to get the relationship between several attributes that allows us to eliminate some of them. Even so, since the data set is made up of few attributes, none will be eliminated. FM.visualize(df) #FM.visualize(df) FM.dataframeToLibsvm(df,'GOOG') # this generate a libsvm file (smvlight.dat) # # Classification from pyspark.sql import SparkSession import numpy as np import matplotlib.pyplot as plt import collections # ## Get Company Data # # Using method `getCompany` from API to get the folowing companies: Google, Aaple, Microsoft, Intel and Amazon. for i in ['GOOG','AAPL','MSFT','INTC','AMZN']: df = FM.getCompany(i) FM.dataframeToLibsvm(df,i) # ## Spark Session spark_session = SparkSession\ .builder\ .appName("Spark Regression")\ .getOrCreate() # ## Read the data in libsvm format # # We read the data obtained after obtaining them with `getCompany` and save in a list. df_companies = [] for i in ['GOOG','AAPL','MSFT','INTC','AMZN']: data = spark_session.read.format("libsvm").load("svmlight_"+i+".txt") df_companies.append([i,data]) #print(data['features']) df_companies for i in df_companies: print(i[0]) print(i[1].show()) print("\n") # ## Linear Regression # # Get the best model for each company. We use the method `LinearRegressionCli` from the API. this method get the best model using cross validation with param grid, root-mean-squared-error and predictions from the company data. We repeat the proccess 25 times to do a statical analysis later. # + rms_dict_lr = {} best_models_dict = {} n = 25 companyResults = {} for data in df_companies: print(data[0]+", Traninig...") rms_company = [] best_model = [] for i in range(n): print("Iteration:",i) # format: company, model, rmse, predictions model = FM.LinearRegressionCli(data[1],data[0]) best_model.append(model) rms_company.append(model['rmse']) rms_dict_lr[data[0]] = rms_company best_models_dict[data[0]] = best_model print("Finish\n") # - # ### Print the coefficients and intercept for linear regression # # Show the linear coefficients. for i in best_models_dict: print("Company:",i) for j in best_models_dict[i]: print("Coefficients: %s" % str(j['model'].coefficients)) print("Intercept: %s" % str(j['model'].intercept)) print("\n") # ### RMSE Mean # # Show the error for each company. for i in rms_dict_lr: print("Company:",i) print("Mean - RMSE: %f" % np.mean(rms_dict_lr[i])) print("\n\n") # ### Summarize the model over the training set and print out some metrics # # Show model summarize for each company. for i in best_models_dict: print("Company:",i) for j in best_models_dict[i]: trainingSummary = j['model'].summary print("numIterations: %d" % trainingSummary.totalIterations) print("objectiveHistory: %s" % str(trainingSummary.objectiveHistory)) trainingSummary.residuals.show() print("RMSE: %f" % trainingSummary.rootMeanSquaredError) print("r2: %f" % trainingSummary.r2) print("\n\n") # ### Predictions # # Show the predictins for each company. for i in best_models_dict: print(i,"\n") for j in best_models_dict[i]: print(j['predictions'].select("prediction", "label", "features").show(10)) print("\n\n") # ## Gradient Boosting Regressor # # Get the best model for each company. We use the method `GradienBoostingRegressorCli` from the API. this method get the best model using cross validation with param grid, root-mean-squared-error and predictions from the company data. We repeat the proccess 25 times to do a statical analysis later. # + rms_dict_gbr = {} best_models_dict = {} for data in df_companies: print(data[0]+", Traninig...") rms_company = [] best_model = [] for i in range(n): print("Iteration:",i) # format: company, model, rmse, predictions model = FM.GradienBoostingRegressorCli(data[1],data[0]) best_model.append(model) rms_company.append(model['rmse']) rms_dict_gbr[data[0]] = rms_company best_models_dict[data[0]] = best_model print("Finish") # - # ### Print out metrics for each company for i in rms_dict_gbr: print("Company:",i) print("Mean - RMSE: %f" % np.mean(rms_dict_gbr[i])) print("\n\n") # ### Predictions for i in best_models_dict: print(i,"\n") for j in best_models_dict[i]: print(j['predictions'].select("prediction", "label", "features").show(10)) print("\n\n") # ## Isotonic Regressor # # Get the best model for each company. We use the method `IsotonicRegressionCli` from the API. this method get the best model using cross validation with param grid, root-mean-squared-error and predictions from the company data. We repeat the proccess 25 times to do a statical analysis later. # + rms_dict_ir = {} best_models_dict = {} for data in df_companies: print(data[0]+", Traninig...") rms_company = [] best_model = [] for i in range(n): print("Iteration:",i) # format: company, model, rmse, predictions model = FM.IsotonicRegressionCli(data[1],data[0]) best_model.append(model) rms_company.append(model['rmse']) rms_dict_ir[data[0]] = rms_company best_models_dict[data[0]] = best_model print("Finish") # - # ### Print out metrics for i in rms_dict_ir: print("Company:",i) print("Mean - RMSE: %f" % np.mean(rms_dict_ir[i])) print("\n\n") # ### Predictions for i in best_models_dict: print(i,"\n") for j in best_models_dict[i]: print(j['predictions'].select("prediction", "label", "features").show(10)) print("\n\n") for i in best_models_dict: print(i,"\n") for j in best_models_dict[i]: rfResult = j['predictions'].toPandas() print( collections.Counter(rfResult.prediction==rfResult.label), len(rfResult.label) ) print("\n\n") # ## Stadistical Analysis # To start with this section, it is necessary to pre-process the data by transforming it into the desired format. company = ['GOOG','AAPL','MSFT','INTC','AMZN'] resultsCompany = dict() for i in range(len(rms_dict_lr)): resultsCompany[company[i]] ={'lr_rmse': rms_dict_lr[company[i]] ,'gbr_rmse': rms_dict_gbr[company[i]], 'ir_rmse' :rms_dict_ir[company[i]]} # The steps I will take will be to study the distribution of the data through boxplots, study the normality of the data and finally apply a parametric or non-parametric test, depending on the result expected in the previous step. goog = resultsCompany['GOOG'] aapl = resultsCompany['AAPL'] msft = resultsCompany['MSFT'] intc = resultsCompany['INTC'] amzn = resultsCompany['AMZN'] lr = goog['lr_rmse'] gbr = goog['gbr_rmse'] ir = goog['ir_rmse'] data = [lr,gbr,ir] plt.boxplot(data) plt.xticks([1, 2, 3], ['lr_rmse', 'gbr_rmse', 'ir_rmse']) plt.xlabel("Classifiers") plt.ylabel("Error value") lr = aapl['lr_rmse'] gbr = aapl['gbr_rmse'] ir = aapl['ir_rmse'] data = [lr,gbr,ir] plt.boxplot(data) plt.xticks([1, 2, 3], ['lr_rmse', 'gbr_rmse', 'ir_rmse']) plt.xlabel("Classifiers") plt.ylabel("Error value") lr = msft['lr_rmse'] gbr = msft['gbr_rmse'] ir = msft['ir_rmse'] data = [lr,gbr,ir] plt.boxplot(data) plt.xticks([1, 2, 3], ['lr_rmse', 'gbr_rmse', 'ir_rmse']) plt.xlabel("Classifiers") plt.ylabel("Error value") lr = intc['lr_rmse'] gbr = intc['gbr_rmse'] ir = intc['ir_rmse'] data = [lr,gbr,ir] plt.boxplot(data) plt.xticks([1, 2, 3], ['lr_rmse', 'gbr_rmse', 'ir_rmse']) plt.xlabel("Classifiers") plt.ylabel("Error value") lr = amzn['lr_rmse'] gbr = amzn['gbr_rmse'] ir = amzn['ir_rmse'] data = [lr,gbr,ir] plt.boxplot(data) plt.xticks([1, 2, 3], ['lr_rmse', 'gbr_rmse', 'ir_rmse']) plt.xlabel("Classifiers") plt.ylabel("Error value") # To be able to interpret the results it is necessary to know what a boxplot represents and what values are being used. First, a boxplot represents the values of the first quartile, second quartile or median, third quartile and the interquartile range. In addition, it allows us to detect possible outliers. Second, the data to be represented corresponds to the root of the mean square error (RMSE), so a lower value means a better result. # # In most cases, the worst result is obtained with the Gradient Boosting Regressor classifier, followed by Linear Regression and Isotonic Regressor. # # The next step in this section will be to obtain if all the values follow a normal distribution in order to work with the mean and with parametric tests. Otherwise I will work with non-parametric tests and with the median. # + classifier_eval = [goog['lr_rmse'], goog['gbr_rmse'], goog['ir_rmse'], aapl['lr_rmse'], aapl['gbr_rmse'], aapl['ir_rmse'], msft['lr_rmse'], msft['gbr_rmse'], msft['ir_rmse'], intc['lr_rmse'], intc['gbr_rmse'], intc['ir_rmse'], amzn['lr_rmse'], amzn['gbr_rmse'], amzn['ir_rmse'] ] values = ['GOOGLE-LR', 'GOOGLE-GBR', 'GOOGLE-IR', 'APPLE-LR', 'APPLE-GBR', 'APPLE-IR', 'MICROSOFT-LR', 'MICROSOFT-GBR', 'MICROSOFT-IR', 'INTEL-LR', 'INTEL-GBR', 'INTEL-IR', 'AMAZON-LR', 'AMAZON-GBR', 'AMAZON-IR'] for i in range(len(classifier_eval)): print(values[i]) s , p = stats.normaltest( classifier_eval[i]) print(stats.normaltest( classifier_eval[i])) if p < 0.05: print('Not normal distribution\n') else: print('Normal distribution\n') # - # Since all the attributes do not follow a normal distribution, I have represented the following table with the median of the values obtained for each classifier by company. # + col_names = ['Linear Regression', 'Gradient Boosting Regressor', 'Isotonic Regressor'] df = pd.DataFrame(columns = col_names, index=company) df.iloc[0] = [np.median(goog['lr_rmse']), np.median(goog['gbr_rmse']), np.median(goog['ir_rmse']) ] df.iloc[1] = [np.median(aapl['lr_rmse']), np.median(aapl['gbr_rmse']), np.median(aapl['ir_rmse']) ] df.iloc[2] = [np.median(msft['lr_rmse']), np.median(msft['gbr_rmse']), np.median(msft['ir_rmse']) ] df.iloc[3] = [np.median(intc['lr_rmse']), np.median(intc['gbr_rmse']), np.median(intc['ir_rmse']) ] df.iloc[4] = [np.median(amzn['lr_rmse']), np.median(amzn['gbr_rmse']), np.median(amzn['ir_rmse']) ] print(df) # - # Finally, I have applied the Wilcoxon Test to evaluate which grader is better than another with a higher security, since there is so much difference between the Gradient Boosting Regressor error and the others, it is not clear which one is the best in each case. for i in range(0,3): for j in range(i+1, 3): print(values[i], values[j]) s , p = stats.ranksums( classifier_eval[i], classifier_eval[j]) print(stats.ranksums( classifier_eval[i], classifier_eval[j])) if p > 0.05: print('The difference is not significant.\n') else: print('Algorithm ',values[i] , 'has a worse performance than algorithm ', values[j], 'with 95% certainty.\n') for i in range(3,6): for j in range(i+1, 6): print(values[i], values[j]) s , p = stats.ranksums( classifier_eval[i], classifier_eval[j]) print(stats.ranksums( classifier_eval[i], classifier_eval[j])) if p > 0.05: print('The difference is not significant.\n') else: print('Algorithm ',values[i] , 'has a worse performance than algorithm ', values[j], 'with 95% certainty.\n') for i in range(6,9): for j in range(i+1, 9): print(values[i], values[j]) s , p = stats.ranksums( classifier_eval[i], classifier_eval[j]) print(stats.ranksums( classifier_eval[i], classifier_eval[j])) if p > 0.05: print('The difference is not significant.\n') else: print('Algorithm ',values[i] , 'has a worse performance than algorithm ', values[j], 'with 95% certainty.\n') for i in range(9,12): for j in range(i+1, 12): print(values[i], values[j]) s , p = stats.ranksums( classifier_eval[i], classifier_eval[j]) print(stats.ranksums( classifier_eval[i], classifier_eval[j])) if p > 0.05: print('The difference is not significant.\n') else: print('Algorithm ',values[i] , 'has a worse performance than algorithm ', values[j], 'with 95% certainty.\n') for i in range(12,15): for j in range(i+1, 15): print(values[i], values[j]) s , p = stats.ranksums( classifier_eval[i], classifier_eval[j]) print(stats.ranksums( classifier_eval[i], classifier_eval[j])) if p > 0.05: print('The difference is not significant.\n') else: print('Algorithm ',values[i] , 'has a worse performance than algorithm ', values[j], 'with 95% certainty.\n')
notebooks/study_relevant_companies/notebooks/Classification_ModelingAPI.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # A Simple Tutorial For using QCAD # + from Modules import Module, execute from Modules import TypicalModule as tm from Modules.CircuitDrawer import draw import numpy as np # - # ## 1. Circuit Description # # - ***Modules*** are elements of a quantum circuit and composed of elementary modules. # # - A ***quantum circuit*** is also a module which is excutable with any initial states. # # - The ***typical modules*** are elementary pre-defined modules. <br>The list of typical modules follows: tm.I, tm.H, tm.X, tm.Y, tm.Z, tm.CX, tm.CZ, tm.CCX, tm.CCZ, tm.RX, tm.RY, tm.RZ, tm.U, and tm.MCU # # - Modules can be constructed from either typical modules or customly pre-defined modules. # # - Modules has the same number of input and output ports. Each port is connected to a single qubit. The number of ports of a module is said to be the ***size of module*** and must be fixed when the module is defined. The ***qubit number*** of qubits of a module is indicator of each qubit of module and starts from 0 and ends at (size-1). # # - A ***submodule*** is one of modules consisting a larger module. # # - The ports of a submodule can be arbitrarily connected from the definition of module. # + # Definition of a typical module RX # Module name: 'RXPI/2' rx_half_pi = tm.RX('RXPI/2', np.pi/2) # Definition of a typical module U(Unitary gate defined by matrix) # Module size: 1 custom_u = tm.U('CUSTOMU', 1, [[-1, 0], [0, 1]]) # Definition of a typical module MCU(Multi-controlled U) submodule H. # Module name: 'CCH', Module size: 3, Control bits: qubits #0 and #1, # Controlled gate: tm.H[2] (H applied to qubit #2) multi_control_h = tm.MCU('CCH', 3, [0, 1], tm.H[2]) # - # Definition of a custom module using pre-defined modules. # Module name: 'SWAP', Module size: 2, # The first CX is applied to qubits #0 and #1. #0 is the control bit and X is applied on #1. # The second CX is applied to qubits #1 and #0(DIFFERENT TO THE FIRST ONE). # #1 is the control bit and X is applied on #0 now. # The thrid one is same as the first one. SWAP = Module('SWAP', 2, [tm.CX[0, 1], tm.CX[1, 0], tm.CX[0, 1]]) # + # Examples of custom controlled gates using MCU(Multi control unitary gates) CH = tm.MCU('CH', 2, [0], tm.H[1]) CS = tm.MCU('CS', 2, [0], tm.S[1]) CT = tm.MCU('CT', 2, [0], tm.T[1]) # Module Fourier3 F3 = Module('F3', 3, [tm.H[0], CS[1, 0], CT[2, 0], tm.H[1], CS[2, 1], tm.H[2], SWAP[0, 2]]) # + # Another example of modules CSWAP = tm.MCU('CSWAP', 3, [0], SWAP[1, 2]) QC = Module('QC', 5, [F3[0, 2, 4], CSWAP[4, 0, 2], tm.MCU('MCF3', 5, [0, 1], F3[2, 3, 4])[0, 1, 2, 3, 4]]) # - # The functino show() prints out the typical-level decomposition of a module. QC.show() # ## 2. Drawing a module # # - Quantum circuit is a module. # - You can easily draw a module with the function draw(). # Drawing a module. draw(QC) draw(QC, option='decomposed') # ## 3. Simulation of a quantum circuit with arbitrary initial state # # - **Quantum circuit is indeed a module.** # - A ***Backend*** is an algorithm or a program itself used to calculate the quantum circuit (i.e. module). # - There are two backends available: The 'MatrixModel' and the 'Cimulator'. # - They both have same algorithms except that 'Cimulator' is a C++ program which is much faster than 'MatrixModel' made out of python only. # - The algorithm is quite simple. Modules are first decomposed into the typical modules. Typical modules are applied to the qubits one by one. It saves much memory and calculation resources than the algorithm which calculates the whole unitary matrix of a module to simulate quantum computer. # - The space and time complexity of this alogrithm is $O(2^n)$, where n denotes the size of module. execute('MatrixModel', QC, option='barplot') execute('MatrixModel', QC, [[1, 0], [1/np.sqrt(2), 1/np.sqrt(2)], [1, 0], [1, 0], [1, 0]], option='nonzero') execute('MatrixModel', QC, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], option='silent') execute('Cimulator', QC, option='barplot') execute('Cimulator', QC, [[1, 0], [1/np.sqrt(2), 1/np.sqrt(2)], [1, 0], [1, 0], [1, 0]], option='nonzero') execute('Cimulator', QC, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], option='silent')
Tutorial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="XVJXkWBn8yOQ" # # Vector Fields # We can denote a vector field with the vector F has a function of x and y like this: F(x,y) # # We can also write it in 3d like this: F(x,y,z) # # $ \vec{F}(x,y,z) = P(x,y,z)*\vec{i}+Q(x,y,z)*\vec{j}+R(x,y,z)*\vec{k} $ # + [markdown] id="xqVHuhHN81ub" # ## Example Problem 1: # # $ \vec{F}(x,y) = -y*\vec{i}+x*\vec{j} $ # # Graph the Vector Field # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="ny5Jevt88u_N" outputId="9796f633-9dc7-4462-eb8d-5ee13899ea5b" import numpy as np import matplotlib.pyplot as plt # %matplotlib inline x,y = np.meshgrid(np.linspace(-5,5,10),np.linspace(-5,5,10)) u = -y v = x plt.quiver(x,y,u,v) plt.show() # + [markdown] id="djScBVV09G34" # As you can see, the function follows a circular path centered at the origin. The length of each arrow is dependent on the x and y value chosen. The further away the end of the arrow is from the origin, the larger the arrow will be. Each arrow is tangent to a circle centered at the origin. # # To calculate the radius of the circle, we take the following steps: # # $ # r = \sqrt{x^2+y^2} # $ # # + [markdown] id="ZUQf0Z9G-CWo" # ## Example Problem 2: # # $ \vec{f}(x,y) = x^2y\vec{i}-y^3\vec{j} $ # # Plot the gradient vector field and the contour map of the original function # + [markdown] id="3_KEP8aW-Vjk" # Our first step is to calculate the gradient of $ \vec{f} $. We do this by taking the derivative of the P and Q function in f: # # $ P = df/dx $ # # $ df/dx = 2xy $ # # $ Q = df/dy $ # # $ df/dy = x^2-3y^2 $ # # So our final gradient of f is as follows: # # $ \nabla{\vec{f}} = 2xy\vec{i}+(x^2-3y^2)\vec{j} $ # # Now we can graph the gradient and our contour map # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="dn3ElEiT-Agx" outputId="d426f0f0-4c2f-409c-a15a-39a1878d0861" x,y = np.meshgrid(np.linspace(-5,5,10),np.linspace(-5,5,10)) u = 2*x*y v = x**2-3*y**2 plt.quiver(x,y,u,v) xlist = np.linspace(-5.0, 5.0, 100) ylist = np.linspace(-5.0, 5.0, 100) X, Y = np.meshgrid(xlist, ylist) Z = Y*X**2 - Y**3 plt.contour(X,Y,Z) plt.show() # + [markdown] id="kKKW7kBVBeES" # The Vector Field shown here are perpendicular to the contour map, which would make sense considering the vector field is of the gradient vector of f. # # **If $ \vec{F} $ is conservative, then $ f $ exists such that $ \vec{F} = \nabla{f} $** # + id="Lzl9a9l7CA2x"
_notebooks/2021-01-01-Vector-Fields.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 03b_overlap_cluster-tx_pwenrich_tx # # calculated overlap of clusters and treatments # # **IMPORTANT:** the gene lists for both treatments and clusters were are unique. List was ranked by fold change (treatment) or score (clusters) and the gene was assigned to the cluster/treatement with the to score/fold change. this is different to the overlap between clusters in Notebook 03a where duplicates were NOT excluded. # # - part 1: generation of overlaps between to top 100 genes in clusters and treatments # - part 2: pathway enrichment for treatments in LSKs and HSCs. # # docker image used: # # docker run --rm -d --name gseapy -p 8885:8888 -e JUPYTER_ENABLE_LAB=YES -v /Users/efast/Documents/:/home/jovyan/work gseapy:0.10.4 # + #load some packages that are needed for plotting + computation import os import math from matplotlib import pyplot as plt import pandas as pd import scipy.stats as stats import seaborn as sns import numpy as np import gseapy as gp from math import floor, log10 # %matplotlib inline from gprofiler import GProfiler from helper_functions import * # - # ## Cluster overlap cols_HSCs = ['primerid', 'Unnamed: 0', 'Pr(>Chisq)', 'coef', 'FDR', 'Unnamed: 0LT_1', 'Pr(>Chisq)LT_1', 'coefLT_1', 'FDRLT_1', 'Unnamed: 0LT_2', 'Pr(>Chisq)LT_2', 'coefLT_2', 'FDRLT_2', 'Unnamed: 0LT_3', 'Pr(>Chisq)LT_3', 'coefLT_3', 'FDRLT_3', 'Unnamed: 0LT_4', 'Pr(>Chisq)LT_4', 'coefLT_4', 'FDRLT_4', 'Unnamed: 0LT_5', 'Pr(>Chisq)LT_5', 'coefLT_5', 'FDRLT_5', 'Unnamed: 0LT_all', 'Pr(>Chisq)LT_all', 'coefLT_all', 'FDRLT_all'] cols_MPPs = ['primerid', 'Unnamed: 0MPPs_0', 'Pr(>Chisq)MPPs_0', 'coefMPPs_0', 'FDRMPPs_0', 'Unnamed: 0MPPs_1', 'Pr(>Chisq)MPPs_1', 'coefMPPs_1', 'FDRMPPs_1', 'Unnamed: 0MPPs_2', 'Pr(>Chisq)MPPs_2', 'coefMPPs_2', 'FDRMPPs_2', 'Unnamed: 0MPPs_3', 'Pr(>Chisq)MPPs_3', 'coefMPPs_3', 'FDRMPPs_3', 'Unnamed: 0MPPs_4', 'Pr(>Chisq)MPPs_4', 'coefMPPs_4', 'FDRMPPs_4', 'Unnamed: 0MPPs_5', 'Pr(>Chisq)MPPs_5', 'coefMPPs_5', 'FDRMPPs_5', 'Unnamed: 0MPPs_6', 'Pr(>Chisq)MPPs_6', 'coefMPPs_6', 'FDRMPPs_6', 'Unnamed: 0MPPs_7', 'Pr(>Chisq)MPPs_7', 'coefMPPs_7', 'FDRMPPs_7', 'Unnamed: 0MPPs_all', 'Pr(>Chisq)MPPs_all', 'coefMPPs_all', 'FDRMPPs_all'] # ## HSCs # + # define total number of genes for background dataset - genes that can be measured in scRNAseq - based on the single cell objects # LSK was 13,827, HSC was 14,408 - take 14,000 total_n = 14000 # - cluster_genes = pd.read_csv('/home/jovyan/work/Z_TRASH/write/all_HSC_clusters_final_all_genes.csv') # + cl_list = ['Metabolism', 'Quiescent', 'Activated', 'Interferon', 'Acute-Activation', 'Cell-cycle'] df_cl =pd.DataFrame(columns=['primerid', 'specific', 'score']) for cl in cl_list: results_df = pd.DataFrame(columns=['primerid', 'specific', 'score']) column_name = cl + '_n' sort_column = cl + '_s' column_pval = cl + '_p' column_fch = cl + '_l' genelist = cluster_genes[(cluster_genes[column_pval] < 0.05) & \ (cluster_genes[column_fch] > math.log2(1))][column_name].tolist()[:200] scorelist = cluster_genes[(cluster_genes[column_pval] < 0.05) & \ (cluster_genes[column_fch] > math.log2(1))][sort_column].tolist()[:200] string_list = [cl] * len(genelist) results_df['primerid'] = genelist results_df['specific'] = string_list results_df['score'] = scorelist df_cl = df_cl.append(results_df, ignore_index=True) df_cl = df_cl.sort_values(by='score', ascending=False) # this is to get rid of duplicates df_cl = df_cl.drop_duplicates(subset=['primerid'], keep='first') #keep the ones with the highest score # + files = ['1.2', '1.5', 'nocutoff'] file = '1.2' treatments = ['dmPGE2', 'GCSF', 'pIC', 'indo'] df_st =pd.DataFrame() for treatment in treatments: base_file = '/home/jovyan/work/Z_TRASH/write/' file_name = base_file + '/MAST_overlap_' + file + '_' + treatment + '_all.csv' df_temp = pd.read_csv(file_name) df_temp = df_temp[cols_HSCs] df_temp = df_temp.dropna(axis=0, thresh=2) #drop genes with 'NAs' df_temp['stimulant'] = treatment df_st = df_st.append(df_temp) df_st['max_coef'] = df_st.filter(regex='coef').max(axis=1) df_st = df_st.sort_values(by='max_coef', ascending=False) # this is to get rid of duplicates df_st = df_st.drop_duplicates(subset=['primerid'], keep='first') #keep the ones with the highest score df = df_st.copy() # - # ### cluster overlap # + stimuli = [ 'GCSF', 'pIC', 'indo', 'dmPGE2'] clusters = ['Metabolism', 'Quiescent', 'Activated', 'Interferon', 'Cell-cycle'] result_df_cl = pd.DataFrame(columns = ['Gene', 'HSC cluster']) result_df_tx = pd.DataFrame(columns = ['Gene', 'HSC treatment']) result_df_save = pd.DataFrame() results_df_list =[] results_df = pd.DataFrame() p_value_df_list = [] p_value_df = pd.DataFrame() top_genes = 100 for st in stimuli: del result_df_cl result_df_cl = pd.DataFrame(columns = ['Gene', 'HSC cluster']) results_df_list =[] p_value_df_list =[] list1 = df_st[df_st['stimulant'] == st].sort_values(by='max_coef', ascending=False)['primerid'].tolist()[:top_genes] result_df_tx_temp = pd.DataFrame() result_df_tx_temp['Gene'] = list1 result_df_tx_temp['HSC treatment'] = st result_df_tx = result_df_tx.append(result_df_tx_temp, ignore_index=True) for cl in clusters: list2 = df_cl[df_cl['specific'] == cl].sort_values(by='score', ascending=False)['primerid'].tolist()[:top_genes] result_df_cl_temp = pd.DataFrame() result_df_cl_temp['Gene'] = list2 result_df_cl_temp['HSC cluster'] = cl result_df_cl = result_df_cl.append(result_df_cl_temp, ignore_index=True) intersection = len(list(set(list1).intersection(list2))) only_st = len(list1) - intersection only_cl = len(list2) - intersection rest = total_n - (only_st + only_cl + intersection) oddsratio, pvalue = stats.fisher_exact([[intersection, only_cl], [only_st, rest]], alternative='greater') results_df_list.append(intersection) p_value_df_list.append(pvalue) p_value_df_series = pd.Series(p_value_df_list) p_value_df = p_value_df.append(p_value_df_series, ignore_index=True) results_df_list = pd.Series(results_df_list) results_df = results_df.append(results_df_list, ignore_index=True) p_value_df, rej = multiple_testing_correction(ps = p_value_df, alpha=0.01, method='benjamini-hochberg') p_value_df = pd.DataFrame(p_value_df) result_df_save = result_df_cl.merge(result_df_tx, how='outer', on='Gene') result_df_save.to_csv('/home/jovyan/work/Z_TRASH/write/HSC_treatment_cluster_overlap.csv', index=False, header=True) # + results_df.columns = clusters results_df.index = stimuli p_value_df.columns = clusters p_value_df.index = stimuli p_value_mask_sig = p_value_df > 0.01 p_value_mask_nonsig = p_value_df < 0.01 # - p_value_df # + sns.set(font_scale=1.4) plt.figure(figsize=(8,3)) #sns.heatmap(results_df, annot=True, annot_kws={"size": 16}, mask = p_value_mask) plt.yticks(rotation=0, fontsize = 12) plt.xticks(rotation=0, fontsize = 12) sns.heatmap(results_df, mask = p_value_mask_sig, linewidth=0.5, annot_kws={"style": "italic", "weight": "bold"}, annot=True, vmin=0, vmax=80) sns.heatmap(results_df, mask = p_value_mask_nonsig, linewidth=0.5, cbar=False, annot=True, vmin=0, vmax=80) plt.savefig("/home/jovyan/work/Z_TRASH/figures/overlap_clusters_treatment_diff_genes_HSCs_July21.pdf", dpi=300, bbox_inches='tight') # - # ### pathway enrich tx # + # make dictionary with curated pathways dst ='/home/jovyan/work/Z_TRASH/raw_data/gene_sets' out ='/home/jovyan/work/Z_TRASH/write/' pw_files = os.listdir(dst) pw_dic = {} for file in pw_files: df_temp = pd.read_csv(dst + '/' + file, delimiter = "\t") list_temp = df_temp.iloc[:,0].tolist()[1:] list_temp = [x.capitalize() for x in list_temp] #convert to capitalize pw_dic[file[:-4]] = list_temp del pw_dic['.DS_S'] pd.DataFrame.from_dict(pw_dic,orient='index').T.to_csv(out + 'curated_pathways.csv', index=False, header=True) # + df_save = pd.DataFrame(columns =['Treatment', 'Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']) cl_list = ['dmPGE2', 'GCSF', 'pIC', 'indo'] for cl in cl_list: temp_df = pd.DataFrame() df_final = pd.DataFrame(columns =['Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']) gene_list = df_st[(df_st['stimulant']==cl) & (df_st['max_coef'] > math.log2(1.2))]['primerid'].tolist() sources = ["GO:BP"] temp_df = pathway_enrich_genes_new(gene_list, sources).head(4) temp_df = col_select(temp_df) df_final = df_final.append(temp_df, ignore_index=True) sources = ["REAC"] temp_df = pd.DataFrame() temp_df = pathway_enrich_genes_new(gene_list, sources).head(4) temp_df = col_select(temp_df) df_final = df_final.append(temp_df, ignore_index=True) enr_res = gp.enrichr(gene_list=gene_list, organism='Mouse', gene_sets= pw_dic, background = total_n, description='pathway', cutoff = 0.01) temp_df = enr_res.results[enr_res.results['Adjusted P-value'] < 0.01] temp_df = temp_df.sort_values(by = 'Adjusted P-value', axis=0, ascending=True).head(6) temp_df['Gene Overlap'] = temp_df['Overlap'] temp_df['Gene names'] = temp_df['Genes'] # extract conditions pw_list = [] origin_list = [] for index, row in temp_df.iterrows(): pw = 0 origin = 0 pw = row['Term'].split("_", 1)[0] origin = row['Term'].split("_", 1)[1] pw_list.append(pw) origin_list.append(origin) temp_df['Origin'] = pw_list temp_df['Pathway'] = origin_list temp_df = temp_df[['Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']] df_final = df_final.append(temp_df, ignore_index=True) df_final['Adjusted P-value'] = df_final['Adjusted P-value'].apply(lambda x: round(x, 1 - int(floor(log10(abs(x)))))) df_final['Treatment'] = cl df_final = df_final[['Treatment', 'Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']] df_save = df_save.append(df_final, ignore_index=True) df_save.to_csv('/home/jovyan/work/Z_TRASH/write/HSC_treatment_enrichment.csv', index=False, header=True) # + # check GCSF separately in HSCs cl = 'GCSF' gene_list = df_st[(df_st['stimulant']==cl) & (df_st['max_coef'] > math.log2(1.2))]['primerid'].tolist() enr_res = gp.enrichr(gene_list=gene_list, organism='Mouse', gene_sets= pw_dic, background = total_n, description='pathway', cutoff = 0.01) enr_res.results # - # ### LSKs cluster_genes = pd.read_csv('/home/jovyan/work/Z_TRASH/write/all_MPP_clusters_final_all_genes.csv') # + # had to select the top 200 because otherwise edge case that Mpo is lost from Myeloid because it shows up in Metabolism with higher score but not in top 100 cl_list = ['Primed', 'Metabolism', 'Progenitor', 'Cell-cycle', 'Acute-Activation', 'Interferon', 'Interferon cell-cycle','Myeloid'] df_cl =pd.DataFrame(columns=['primerid', 'specific', 'score']) for cl in cl_list: results_df = pd.DataFrame(columns=['primerid', 'specific', 'score']) column_name = cl + '_n' sort_column = cl + '_s' column_pval = cl + '_p' column_fch = cl + '_l' genelist = cluster_genes[(cluster_genes[column_pval] < 0.05) & \ (cluster_genes[column_fch] > math.log2(1))][column_name].tolist()[:200] scorelist = cluster_genes[(cluster_genes[column_pval] < 0.05) & \ (cluster_genes[column_fch] > math.log2(1))][sort_column].tolist()[:200] string_list = [cl] * len(genelist) results_df['primerid'] = genelist results_df['specific'] = string_list results_df['score'] = scorelist df_cl = df_cl.append(results_df, ignore_index=True) df_cl = df_cl.sort_values(by='score', ascending=False) # this is to get rid of duplicates df_cl = df_cl.drop_duplicates(subset=['primerid'], keep='first') #keep the ones with the highest score # - df_cl[df_cl['primerid']=='Mpo'] # + files = ['1.2', '1.5', 'nocutoff'] file = '1.2' treatments = ['dmPGE2', 'GCSF', 'pIC', 'indo'] df_st =pd.DataFrame() for treatment in treatments: base_file = '/home/jovyan/work/Z_TRASH/write/' file_name = base_file + '/MAST_overlap_' + file + '_' + treatment + '_all.csv' df_temp = pd.read_csv(file_name) df_temp = df_temp[cols_MPPs] df_temp = df_temp.dropna(axis=0, thresh=2) #drop genes with 'NAs' df_temp['stimulant'] = treatment df_st = df_st.append(df_temp) df_st['max_coef'] = df_st.filter(regex='coef').max(axis=1) df_st = df_st.sort_values(by='max_coef', ascending=False) # this is to get rid of duplicates df_st = df_st.drop_duplicates(subset=['primerid'], keep='first') #keep the ones with the highest score df = df_st.copy() # + del result_df_save stimuli = [ 'GCSF', 'pIC', 'indo', 'dmPGE2'] clusters = ['Primed', 'Metabolism', 'Progenitor', 'Cell-cycle','Myeloid'] result_df_cl = pd.DataFrame(columns = ['Gene', 'LSK cluster']) result_df_tx = pd.DataFrame(columns = ['Gene', 'LSK treatment']) result_df_save = pd.DataFrame() results_df_list =[] results_df = pd.DataFrame() p_value_df_list = [] p_value_df = pd.DataFrame() top_genes = 100 for st in stimuli: del result_df_cl result_df_cl = pd.DataFrame(columns = ['Gene', 'LSK cluster']) results_df_list =[] p_value_df_list =[] list1 = df_st[df_st['stimulant'] == st].sort_values(by='max_coef', ascending=False)['primerid'].tolist()[:top_genes] result_df_tx_temp = pd.DataFrame() result_df_tx_temp['Gene'] = list1 result_df_tx_temp['LSK treatment'] = st result_df_tx = result_df_tx.append(result_df_tx_temp, ignore_index=True) for cl in clusters: list2 = df_cl[df_cl['specific'] == cl].sort_values(by='score', ascending=False)['primerid'].tolist()[:top_genes] result_df_cl_temp = pd.DataFrame() result_df_cl_temp['Gene'] = list2 result_df_cl_temp['LSK cluster'] = 'LSK_'+ cl result_df_cl = result_df_cl.append(result_df_cl_temp, ignore_index=True) intersection = len(list(set(list1).intersection(list2))) only_st = len(list1) - intersection only_cl = len(list2) - intersection rest = total_n - (only_st + only_cl + intersection) oddsratio, pvalue = stats.fisher_exact([[intersection, only_cl], [only_st, rest]], alternative='greater') results_df_list.append(intersection) p_value_df_list.append(pvalue) p_value_df_series = pd.Series(p_value_df_list) p_value_df = p_value_df.append(p_value_df_series, ignore_index=True) results_df_list = pd.Series(results_df_list) results_df = results_df.append(results_df_list, ignore_index=True) p_value_df, rej = multiple_testing_correction(ps = p_value_df, alpha=0.01, method='benjamini-hochberg') p_value_df = pd.DataFrame(p_value_df) result_df_save = result_df_cl.merge(result_df_tx, how='outer', on='Gene') result_df_save = result_df_save.replace({'LSK cluster': {'Progenitor': 'Primitive'}}) result_df_save.to_csv('/home/jovyan/work/Z_TRASH/write/LSK_treatment_cluster_overlap.csv', index=False, header=True) # + results_df.columns = clusters results_df.index = stimuli p_value_df.columns = clusters p_value_df.index = stimuli p_value_mask_sig = p_value_df > 0.01 p_value_mask_nonsig = p_value_df < 0.01 # - p_value_df # + sns.set(font_scale=1.4) plt.figure(figsize=(8,3)) #sns.heatmap(results_df, annot=True, annot_kws={"size": 16}, mask = p_value_mask) plt.yticks(rotation=0, fontsize = 12) plt.xticks(rotation=-0, fontsize = 12) sns.heatmap(results_df, mask = p_value_mask_sig, linewidth=0.5, annot_kws={"style": "italic", "weight": "bold"}, annot=True, vmin=0, vmax=80) sns.heatmap(results_df, mask = p_value_mask_nonsig, linewidth=0.5, cbar=False, annot=True, vmin=0, vmax=80) plt.savefig("/home/jovyan/work/Z_TRASH/figures/overlap_clusters_treatment_diff_genes_LSKs_July21.pdf", dpi=300, bbox_inches='tight') # - # ### pathway enrich tx # + df_save = pd.DataFrame(columns =['Treatment', 'Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']) cl_list = ['dmPGE2', 'GCSF', 'pIC'] for cl in cl_list: temp_df = pd.DataFrame() df_final = pd.DataFrame(columns =['Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']) gene_list = df_st[(df_st['stimulant']==cl) & (df_st['max_coef'] > math.log2(1.2))]['primerid'].tolist() sources = ["GO:BP"] temp_df = pathway_enrich_genes_new(gene_list, sources).head(4) temp_df = col_select(temp_df) df_final = df_final.append(temp_df, ignore_index=True) sources = ["REAC"] temp_df = pd.DataFrame() temp_df = pathway_enrich_genes_new(gene_list, sources).head(4) temp_df = col_select(temp_df) df_final = df_final.append(temp_df, ignore_index=True) enr_res = gp.enrichr(gene_list=gene_list, organism='Mouse', gene_sets= pw_dic, background = total_n, description='pathway', cutoff = 0.01) temp_df = enr_res.results[enr_res.results['Adjusted P-value'] < 0.01] temp_df = temp_df.sort_values(by = 'Adjusted P-value', axis=0, ascending=True).head(6) temp_df['Gene Overlap'] = temp_df['Overlap'] temp_df['Gene names'] = temp_df['Genes'] # extract conditions pw_list = [] origin_list = [] for index, row in temp_df.iterrows(): pw = 0 origin = 0 pw = row['Term'].split("_", 1)[0] origin = row['Term'].split("_", 1)[1] pw_list.append(pw) origin_list.append(origin) temp_df['Origin'] = pw_list temp_df['Pathway'] = origin_list temp_df = temp_df[['Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']] df_final = df_final.append(temp_df, ignore_index=True) df_final['Adjusted P-value'] = df_final['Adjusted P-value'].apply(lambda x: round(x, 1 - int(floor(log10(abs(x)))))) df_final['Treatment'] = cl df_final = df_final[['Treatment', 'Origin', 'Pathway', 'Gene Overlap', 'Adjusted P-value', 'Gene names']] df_save = df_save.append(df_final, ignore_index=True) df_save.to_csv('/home/jovyan/work/Z_TRASH/write/MPP_treatment_enrichment.csv', index=False, header=True) # + # check GCSF separately in MPPs cl = 'GCSF' gene_list = df_st[(df_st['stimulant']==cl) & (df_st['max_coef'] > math.log2(1.2))]['primerid'].tolist() enr_res = gp.enrichr(gene_list=gene_list, organism='Mouse', gene_sets= pw_dic, background = total_n, description='pathway', cutoff = 0.01) enr_res.results # - pd.show_versions() # ! pip list
revisions/03b_overlap_cluster-tx_pwenrich_tx.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Taller Presencial --- Manejo de datos con Pandas # === # + # # El archivo disponible en la direcciรณn presentada a continuaciรณn contiene la #ย informaciรณn bibliografica de una bรบsqueda en Scopus # import pandas as pd # # Complete el siguiente cรณdigo. # https://raw.githubusercontent.com/jdvelasq/datalabs/master/datasets/scopus-papers.csv # scopus = ... # + # # La columna 'Authors' contiene los nombres de los autores separados por `,`. # # La columna 'Author(s) ID' contiene los identificadores de los autores. Tenga # en cuenta que existen autores homonimos con diferente ID. # # Genere una lista con los 10 autores con mรกs publicaciones. # # + # # Genere una lista con los 10 paises con mรกs publicaciones. La columna # 'Affiliations' contiene el paรญs de afiliaciรณn de cada autor #
notebooks/ciencia_de_los_datos/taller_presencial-pandas.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="e9VXlUnnwvFH" # importing libraries import sys import numpy as np # for plotting import matplotlib.pyplot as plt # for accuracy, precision, recall. from sklearn import svm, metrics from sklearn.model_selection import train_test_split # for dataset from sklearn.datasets import load_digits # + id="Qg0mvSVuw_VI" main_data = load_digits() # + colab={"base_uri": "https://localhost:8080/"} id="vhKra0cTxDsh" executionInfo={"status": "ok", "timestamp": 1633673401568, "user_tz": -330, "elapsed": 380, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="305d9b3e-c59b-44d2-d146-3c51b9004b8b" main_data # + colab={"base_uri": "https://localhost:8080/"} id="2sOTjwXGxFR5" executionInfo={"status": "ok", "timestamp": 1633673407360, "user_tz": -330, "elapsed": 377, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="d8907875-7250-4656-a3c8-6de648349f02" main_data.data.shape # + colab={"base_uri": "https://localhost:8080/"} id="OheECKCxxI1Q" executionInfo={"status": "ok", "timestamp": 1633673410487, "user_tz": -330, "elapsed": 392, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="6e9254a9-f188-423a-dcf8-ec55165cdc24" # target values main_data.target # + id="gdozXyCcxLRF" # splitting data into train and test part. X_train, X_test, y_train, y_test = train_test_split(main_data.data, main_data.target, test_size = 0.3, train_size = 0.2 ,random_state = 58) # + id="gFVSLxcbxe0g" # Linear SVM kernal Classifier Model lsvmc = svm.SVC(kernel = "linear") # + colab={"base_uri": "https://localhost:8080/"} id="QQmjn017xocQ" executionInfo={"status": "ok", "timestamp": 1633673430868, "user_tz": -330, "elapsed": 644, "user": {"displayName": "dhaval karen", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="ca78ae1a-075f-4a7f-b645-f7d1ee62fc9d" lsvmc.fit(X_train, y_train) # + id="3DN74u0txulQ" y_linear_pred = lsvmc.predict(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="kjTiQnwDx163" executionInfo={"status": "ok", "timestamp": 1633673453403, "user_tz": -330, "elapsed": 350, "user": {"displayName": "dhaval karen", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="20a772bf-4f9a-43fc-9969-d9068e84a327" print("Accuracy:", metrics.accuracy_score(y_test, y_linear_pred)) # + [markdown] id="ScYtxrYvx7lq" # # **96.66% Accuracy** # + [markdown] id="kPPeam6KyH4X" # # Polynomial Classifier # + id="x427pr5Fx5-3" # model psvmc = svm.SVC(kernel='poly') # + colab={"base_uri": "https://localhost:8080/"} id="-RjJ115YyYEy" executionInfo={"status": "ok", "timestamp": 1633673465842, "user_tz": -330, "elapsed": 453, "user": {"displayName": "dhaval karen", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="f5a1f53c-6b00-4ee2-e298-ed3c62385170" psvmc.fit(X_train, y_train) # + id="-ijfNV5xyamX" y_polynomial_pred = psvmc.predict(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="G0Ho-P9VyeJ4" executionInfo={"status": "ok", "timestamp": 1633673471242, "user_tz": -330, "elapsed": 390, "user": {"displayName": "d<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="bad03a29-4848-4273-a6a8-595424fcd5ca" print("Accuracy:", metrics.accuracy_score(y_test, y_polynomial_pred)) # + [markdown] id="E0fYDry-yowX" # # **97.77% Accuracy** # + [markdown] id="ot2FpQgeytg9" # # RBF SVM Classifier # + id="k5linyiqyj0x" # RBF kernel model rbfsvmc = svm.SVC(kernel='rbf') # + colab={"base_uri": "https://localhost:8080/"} id="eo3rgBmRy0bH" executionInfo={"status": "ok", "timestamp": 1633673477607, "user_tz": -330, "elapsed": 11, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="fa9796de-ce3d-4560-a456-11aaed7e3b20" rbfsvmc.fit(X_train, y_train) # + id="HnQU3JCIy3eA" y_rbf_pred = rbfsvmc.predict(X_test) # + colab={"base_uri": "https://localhost:8080/"} id="8U_xZW4EzAO5" executionInfo={"status": "ok", "timestamp": 1633673486236, "user_tz": -330, "elapsed": 353, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GgvY6o4MuHT6YUeaqCq-6tAM61bz0NJJ6eXkl6VmA=s64", "userId": "03115065192551383929"}} outputId="79a4c424-e2f5-414d-9fa4-ae49b0862051" print("Accuracy:", metrics.accuracy_score(y_test, y_rbf_pred)) # + [markdown] id="m8-la-vUzFnB" # # **96.48% Accuracy**
LAB-9/058_09.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- import numpy as np import pandas as pd import ast # Load all front-frontend-question dataset ques_dataset= pd.read_csv('../../datasets/stackoverflow/tag-wise-only_question/scripts/processed_data/no_duplicate_ques.csv') ques_dataset.head(100) # Separating ques_dataset which contains only one tag ques_with_one_tag = ques_dataset[ques_dataset['Tags'].apply(lambda x: len(ast.literal_eval(x))==1)] print ques_with_one_tag.shape ques_with_one_tag.head() # + ## Changing dataType of 'Tags' data #ques_with_one_tag.memory_usage(index=True) ques_with_one_tag.loc[:,'Tags'] = ques_with_one_tag['Tags'].apply(lambda x: (ast.literal_eval(x))) # - # ## Categories of question dataset # think of some more smart way of incorporaating left out tags after this categorizzation category_dict= { 'f1':['html', 'html5'], 'f2':['css','css3'], 'f3':['javascript', 'jquery'], 'f4':['flex', 'saas', 'less', 'stylus', 'bootstrap', 'media-queries', 'twitter-bootstrap', 'twitter-bootstrap-2', 'twitter-bootstrap-3', 'twitter-bootstrap-4'], 'f5' : ['gulp', 'gruntjs', 'grunt', 'webpack', 'browserify', 'npm', 'bower'], 'f6': ['angularjs', 'angular2', 'angular-directive', 'angular-scope', 'angular-ui-router','angular-ng-repeat', 'angularjs-2.0','angularjs-directive','angularjs-filter','angularjs-module', 'angularjs-ng-repeat','angularjs-routing','angularjs-scope','emberjs', 'ember.js', 'backbonejs', 'backbone.js', 'reactjs','react-native', 'react-router','react-redux', 'redux','react-native-android', 'react-native-ios', 'react-native-listview', 'react-native-maps', 'react-native-router-flux', 'react-router-component', 'react-router-redux', 'react-router-v4', 'reactjs-flux', 'reactjs-native', 'reactjs.net', 'redux-form', 'redux-framework', 'redux-observable', 'redux-saga', 'redux-thunk' ], 'f7':['mocha', 'jasmine', 'karma-runner', 'karma-jasmine'] } # ## Labelling question dataset which contains one tag # + # # Categorising question with only one tag value def labeler2(list): blaclisted_tags= ['django-endless-pagination', 'jflex', 'lockless', 'paperless', 'serverless-framework', 'shapeless', 'stackless', 'headless-browser'] content = list[0] output ='' for key, value in category_dict.iteritems(): if content in blaclisted_tags: continue if content in value: output = key else: for item in value: if item in content: output = key return output ques_with_one_tag['Tags'][380]=['javascript'] ques_with_one_tag['Category']= ques_with_one_tag['Tags'].apply(lambda x: labeler2(x)) # + ## Working on with questions which were not labelled correctly in first attempt df_unlabeled_ques=ques_with_one_tag[ques_with_one_tag['Category'].apply(lambda x: x=='')] c=df_unlabeled_ques['Tags'] left_out_tags= np.unique(np.hstack(np.array(c))) # ======preserving========== (pd.DataFrame(left_out_tags)).to_csv('../data/interim/left_out_tags.csv', index=False) # + # Working on questions labelled correctly (15k) col_req= ['Post Link', 'Category', 'Tags', 'Title', 'Body', 'Score', 'ViewCount'] df_labeled_ques1 = ques_with_one_tag[ques_with_one_tag['Category'].apply(lambda x: x!='')] print df_labeled_ques1.shape # ======preserving========== df_labeled_ques1[col_req].to_csv('../data/processed/ques_with_one_tag_labelled.csv', index=False) # + def find_occurance(df): for i in range(1,8): category= 'f'+str(i) row,col= df[df['Category'].apply(lambda x: x == category)].shape print "Total rows of Category 'f{i}': {row}".format(i=i,row=row) find_occurance(df_labeled_ques1) # - # ## Seperating out questions which are not labelled ques_dataset.shape # + ques_dataset_multi_tags_unlabelled= ques_dataset.loc[~ques_dataset.index.isin(df_labeled_ques1.index)] col_req2= ['Post Link', 'Tags', 'Title', 'Body', 'Score', 'ViewCount'] # ======preserving========== ques_dataset_multi_tags_unlabelled[col_req2].to_csv('../data/processed/ques_multi_tags_unlabelled.csv', index=False) # - ques_dataset_multi_tags_unlabelled.shape
notebooks/frontend_ques_dataset_preprocessing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + code_folding=[] subject_name = 'Andrea' from sankar_read_vmrk_events import sankar_read_vmrk_events import mne import os import numpy as np from mne.io.brainvision import brainvision import warnings warnings.filterwarnings('ignore') data_path = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd()))) save_path = data_path + '/analysis/python/data/'+subject_name raw_fname = data_path + '/exp/data/eeg_original/'+subject_name+'.vhdr' raw = mne.io.read_raw_brainvision(raw_fname,preload=True) #raw.set_eeg_reference('average', projection=True) # set EEG average reference raw.pick_types(meg=False, eeg=True, eog=True, stim=True) raw.set_channel_types(mapping={'vEOGup': 'eog'}) raw.set_channel_types(mapping={'vEOGdown': 'eog'}) raw.set_channel_types(mapping={'LHEOG': 'eog'}) raw.set_channel_types(mapping={'RHEOG': 'eog'}) raw.rename_channels(mapping={'vEOGup': 'vEOGup'}) raw.rename_channels(mapping={'vEOGdown': 'vEOGdown'}) raw.rename_channels(mapping={'LHEOG': 'LHEOG'}) raw.rename_channels(mapping={'RHEOG': 'RHEOG'}) #events raw_fname = data_path + '/exp/data/eeg_original/'+subject_name+'.vmrk' events = sankar_read_vmrk_events(raw_fname) print(raw.info) # - # for ferrara brainamp acticap montage = mne.channels.read_montage('easycap-M1') ch_names = montage.ch_names remove_ch = ["Fpz", "Iz","F9", "F10", "P9", "P10", "O9", "O10", "AFz","FT9","FT10","TP9","TP10","PO9","PO10"] a = np.nonzero(np.in1d(ch_names, remove_ch))[0] ch_names = np.delete(ch_names,a) montage = mne.channels.read_montage('easycap-M1',ch_names) a=raw.set_montage(montage) # + # cut 500 + speech onset - speech offset + 500ms from the original recordings a=np.where(events[:,2]==5)[0] b=np.where(events[:,2]==6)[0] a=np.sort(np.append(a,b)) selected_portion = events[a] X=500 #500 ms i=0 a1 = np.array([(selected_portion[:,0][i]-X),0,100,0]) a2 = np.array([(selected_portion[:,0][i]),0,105,1]) a3 = np.array([(selected_portion[:,0][i+1]),0,106,0]) a4 = np.array([(selected_portion[:,0][i+1]+X),0,200,0]) A = np.vstack((a1,a2,a3,a4)) k=2 for i in range(2, len(selected_portion)-1,2): a1 = np.array([(selected_portion[:,0][i]-X),0,100,0]) a2 = np.array([(selected_portion[:,0][i]),0,105,k]) a3 = np.array([(selected_portion[:,0][i+1]),0,106,0]) a4 = np.array([(selected_portion[:,0][i+1]+X),0,200,0]) A = np.vstack((A,a1,a2,a3,a4)) k=k+1 selected_portion = A[:,0:3] # add this events to raw and delete the original one stim_data = np.zeros((1, len(raw.times))) info = mne.create_info(['Trigger'], raw.info['sfreq'], ['stim']) stim_raw = mne.io.RawArray(stim_data, info) raw.add_channels([stim_raw], force_update_info=True) raw.add_events(selected_portion, stim_channel='Trigger') raw.drop_channels(['STI 014']) info = mne.create_info(['trial_no'], raw.info['sfreq'], ['misc']) stim_raw = mne.io.RawArray(stim_data, info) a=A[:,[0, 1, 3]] raw.add_channels([stim_raw], force_update_info=True) raw.add_events(a, stim_channel='trial_no') print(raw.info) # - a=mne.find_events(raw) print(a[:10]) # + #cut portion of from the original recordings X = 0.05 raw1 = raw.copy().crop(selected_portion[:,0][0]/1000 - X, selected_portion[:,0][3]/1000 + X) for i in range(4, len(selected_portion),4): raw2 = raw.copy().crop(selected_portion[:,0][i]/1000 - X, selected_portion[:,0][i+3]/1000 + X) raw1.append([raw2]) print(i) event_id = {'Speech_onset': 105,'Speech_offset': 106} # - # check and remove the edge boundary annotations and make all of it continues recordings a=mne.find_events(raw1) print(a[:10]) raw=raw1 raw.annotations.delete(np.arange(0,raw.annotations.description.shape[0])) # Set up pick list: EEG + STI 014 - bad channels (modify to your needs) include = ['Trigger'] # or stim channels ['STI 014'] raw.info['bads'] = ['RM'] # pick eeg channels picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False,misc=False,exclude='bads') a=raw.plot_psd(picks=picks, tmax=np.inf, fmax=40) from mne.preprocessing import ICA # 1Hz high pass is often helpful for fitting ICA raw.filter(1., 40., n_jobs=2, fir_design='firwin') reject = dict(eeg=180e-6) n_components = 25 # if float, select n_components by explained variance of PCA method = 'fastica' # for comparison with EEGLAB try "extended-infomax" here decim = 3 # we need sufficient statistics, not all time points -> saves time # we will also set state of the random number generator - ICA is a # non-deterministic algorithm, but we want to have the same decomposition # and the same order of components each time this tutorial is run random_state = 23 ica = ICA(n_components=n_components, method=method, random_state=random_state) a=ica.fit(raw, picks=picks, decim=decim, reject=reject) a=ica.plot_components() # can you spot some potential bad guys? # %matplotlib inline eog_inds =[0,2,4,11] a=ica.plot_properties(raw, picks=eog_inds,psd_args={'fmax': 35.}) # + #picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=True,include=include, exclude='bads') #eog_average = create_eog_epochs(raw, reject=reject,picks=picks).average() #ica.plot_overlay(eog_average, exclude=eog_inds, show=False) # red -> before, black -> after. Yes! We remove quite a lot! # to definitely register this component as a bad one to be removed # there is the ``ica.exclude`` attribute, a simple Python list ica.exclude.extend(eog_inds) # from now on the ICA will reject this component even if no exclude # parameter is passed, and this information will be stored to disk # on saving # uncomment this for reading and writing ica.save(save_path +'-ica.fif') # ica = read_ica('my-ica.fif') # - ica.apply(raw) a=raw.plot() # check the result picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=True, eog=False, misc=True,exclude='bads') raw.save(save_path +'_raw.fif',picks=picks,overwrite=True)
preprocessing_subjects/Andrea.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import matplotlib.pyplot as plt import glob import os.path folder_paths = ["DeeperNetv1", "DeeperNetv2", "BaseNetv1", "BaseNetv2"] #folder_paths = ["BaseNetv1", "BaseNetv1-2"] #folder_paths = ["BaseNetv1", "BaseNetv2"] #folder_paths = ["DeeperNetv1", "DeeperNetv2"] file_type = '\*csv' # read in multiple dataframes to compare dataframes = {} for path in folder_paths: files = glob.glob(path + file_type) files.sort(key=os.path.getmtime) data = pd.DataFrame() for file in files: data = pd.concat([data, pd.read_csv(file)], ignore_index=True) # due to a bug in the data collection, there can be duplicate records, so they are dropped data = data.drop_duplicates().reset_index(drop=True) # time can go negative if time runs out, so clean data to reflect 0 = no time left data['time'] = data['time'].apply(lambda x: 0 if x < 0 else x) dataframes[path] = data minim = 1e10 for key, data in dataframes.items(): if len(data) < minim: minim = len(data) for key, data in dataframes.items(): dataframes[key] = data[:minim] # - # # Summary Plots # The plots below provide an overview to the models performance during the last training session. It will show a graph for the collected statistics with a graph of the score for easy viewing. Most of these are action counts, which may show correlations between certain actions resulting in a higher score. # + plt.rcParams["figure.figsize"] = (20,10) colors = ['b', 'xkcd:gold', 'g', 'r'] #colors = ['g', 'tab:brown'] COLOR_START = 0 for key, data in dataframes.items(): print(key) print(data[data['score'] > 0].describe()) # + plt.subplot(2, 1, 1) plt.title("Kills per Episode") plt.ylabel('Mean Kills') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['kills'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.subplot(2, 1, 1) plt.title("Time Remaining per Episode") plt.ylabel('Mean Time Remaining') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['time'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.subplot(2, 1, 1) plt.title("Movement Actions per Episode") plt.ylabel('Mean Movement Action Count') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['movement'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.subplot(2, 1, 1) plt.title("Rotate Actions per Episode") plt.ylabel('Mean Rotate Action Count') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['rotate'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.subplot(2, 1, 1) plt.title("Shoot Actions per Episode") plt.ylabel('Mean Shoot Action Count') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['shoot'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.subplot(2, 1, 1) plt.title("Reward per Episode") plt.ylabel('Mean Reward') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['reward'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.subplot(2, 1, 2) plt.title("Score per Episode") plt.ylabel('Mean Score') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).mean(), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # - # # Frequency Plots # The graphs above are great for showing certain actions and detailed improvements. However, to see if there is any baseline improvement frequency plots can be employed. These plots will reveal if a model is getting more consistent by showing if it at least gets a single kill or scores. # + # lambda function for getting frequency of elements > 0 gt_zero = lambda x: sum([0 if i <= 0 else 1 for i in x]) # lambda function for getting frequency of elements > 1 gt_one = lambda x: sum([0 if i <= 1 else 1 for i in x]) plt.rcParams["figure.figsize"] = (20,5) plt.title("Score Frequency Estimate") plt.ylabel('Score Frequency') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['score'].rolling(window=30).apply(gt_zero), label=key, color=colors[count]) count += 1 plt.legend() plt.show() # + plt.title("Multi-Kill Frequency Estimate") plt.ylabel('Multi-Kill Frequency') plt.xlabel('Episode') count = COLOR_START for key, data in dataframes.items(): plt.plot(data.index, data['kills'].rolling(window=30).apply(gt_one), label=key, color=colors[count]) count += 1 plt.show() # -
data/FinalReport.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # %matplotlib inline import matplotlib.pylab as plt import xray import pandas as pd import seaborn as sns # Open netCDF file with several variables inside: f = xray.open_dataset('./air.sig995.2012.nc') f # Mean over time mmean = f.mean('time') mmean mmean.air.shape # Plot mean air temperature: plt.imshow(mmean.air, cmap=plt.cm.jet); # Create time series for northern and southernd hemispheres: mmean.lat north = mmean.loc[dict(lat=slice(90,0))] plt.imshow(north.air, cmap=plt.cm.jet) south = mmean.loc[dict(lat=slice(0,-90))] plt.imshow(south.air, cmap=plt.cm.jet) north_tm = f.air.loc[dict(lat=slice(90,0))].mean(['lat','lon']) south_tm = f.air.loc[dict(lat=slice(0,-90))].mean(['lat','lon']) plt.plot(north_tm) north_tm dfn = north_tm.to_dataframe() dfs = south_tm.to_dataframe() df = pd.DataFrame(index=dfn.index) df['north'] = dfn.air df['south'] = dfs.air df.plot() smoothed = pd.rolling_mean(df, 4) smoothed.plot() # Convert back to xray Dataset: tr = xray.Dataset.from_dataframe(smoothed) tr # Save to netCDF file: tr.to_netcdf('smoothed.nc')
xray2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="gx3BBVDxavOF" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 646} outputId="7acb0748-6f34-49a0-ef9f-0ab04e10d896" executionInfo={"status": "ok", "timestamp": 1583474267084, "user_tz": -60, "elapsed": 16752, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} # !pip install --upgrade tables # !pip install eli5 # !pip install xgboost # !pip install hyperopt # + id="XxqMTKZOa33n" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 168} outputId="56bc87a6-a478-4bb7-bc0b-72120097b95a" executionInfo={"status": "ok", "timestamp": 1583474339737, "user_tz": -60, "elapsed": 3014, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} import pandas as pd import numpy as np import xgboost as xgb from sklearn.metrics import mean_absolute_error as mae from sklearn.model_selection import cross_val_score, KFold from hyperopt import hp, fmin, tpe, STATUS_OK import eli5 from eli5.sklearn import PermutationImportance # + id="1dVyQu1RbQsF" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="02faf725-6e19-4edc-abe5-9ed48ab8372a" executionInfo={"status": "ok", "timestamp": 1583474367530, "user_tz": -60, "elapsed": 1070, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} # cd "/content/drive/My Drive/Colab Notebooks/dw_matrix_car/dw_matrix_car" # + id="tmtTTvCcbRUj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="402b767d-4b3c-445e-f5a7-d5a5938a7b70" executionInfo={"status": "ok", "timestamp": 1583474383078, "user_tz": -60, "elapsed": 5559, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} df = pd.read_hdf('data/car.h5') df.shape # + [markdown] id="tQHRH1Pxbfhj" colab_type="text" # ## Feature engineering # + id="IHsp3jGzbYLw" colab_type="code" colab={} SUFFIX_CAT = '__cat' for feat in df.columns: if isinstance(df[feat][0], list): continue factorized_values = df[feat].factorize()[0] if SUFFIX_CAT in feat: df[feat] = factorized_values else: df[feat + SUFFIX_CAT] = factorized_values # + id="ag7OLkDPblvC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c6005195-8e12-47f2-b906-a78f6c52ec93" executionInfo={"status": "ok", "timestamp": 1583474436157, "user_tz": -60, "elapsed": 759, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} cat_feats = [x for x in df.columns if SUFFIX_CAT in x] cat_feats = [x for x in cat_feats if 'price' not in x] len(cat_feats) # + id="-lJw59REbmT7" colab_type="code" colab={} df['param_rok-produkcji'] = df['param_rok-produkcji'].map(lambda x: -1 if str(x) == 'None' else int(x)) df['param_moc'] = df['param_moc'].map(lambda x: -1 if str(x) == 'None' else int(x.split(' ')[0])) df['param_pojemnoล›ฤ‡-skokowa'] = df['param_pojemnoล›ฤ‡-skokowa'].map(lambda x: -1 if str(x) == 'None' else int(str(x).split('cm')[0].replace(' ', ''))) # + id="0ycg61mObpdv" colab_type="code" colab={} def run_model(model, feats): X = df[feats].values y = df['price_value'].values scores = cross_val_score(model, X, y, cv=3, scoring='neg_mean_absolute_error') return np.mean(scores), np.std(scores) # + id="csP2E5-GbscB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="6cd65f18-3ea7-410a-c883-ac28f634ba1c" executionInfo={"status": "ok", "timestamp": 1583474500565, "user_tz": -60, "elapsed": 12420, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} feats = ['param_faktura-vat__cat', 'feature_kamera-cofania__cat', 'feature_ล‚opatki-zmiany-biegรณw__cat', 'param_napฤ™d__cat', 'param_skrzynia-biegรณw__cat', 'feature_asystent-pasa-ruchu__cat', 'param_stan__cat', 'feature_ล›wiatล‚a-led__cat', 'feature_bluetooth__cat', 'feature_regulowane-zawieszenie__cat', 'feature_wspomaganie-kierownicy__cat', 'feature_system-start-stop__cat', 'feature_ล›wiatล‚a-do-jazdy-dziennej__cat', 'feature_ล›wiatล‚a-xenonowe__cat', 'feature_czujniki-parkowania-przednie__cat', 'param_moc', 'param_rok-produkcji', 'param_pojemnoล›ฤ‡-skokowa', 'feature_asystent-parkowania__cat', 'seller_name__cat'] xgb_params = { 'max_depth': 5, 'n_estimators': 50, 'learning_rate': 0.1, 'seed': 0 } run_model(xgb.XGBRegressor(**xgb_params), feats) # + [markdown] id="UCtEt-s0b89-" colab_type="text" # ## Hyperopt # + id="qQ2JUMh9bzML" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 952} outputId="1b45bdd4-c63b-465a-9df6-06f20dad0bda" executionInfo={"status": "ok", "timestamp": 1583476484173, "user_tz": -60, "elapsed": 1459978, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhbtxQlGWEvXQeKZ2YJI_VmhCwDYaktDCQ_RzhuGg=s64", "userId": "13976193166602868638"}} def obj_func(params): print('Training with params: ') print(params) mean_mae, score_std = run_model(xgb.XGBRegressor(**params), feats) return {'loss': np.abs(mean_mae), 'status': STATUS_OK} xgb_reg_params = { 'learning_rate': hp.choice('learning_rate', np.arange(0.05, 0.31, 0.05)), 'max_depth': hp.choice('max_depth', np.arange(5, 16, 1, dtype=int)), 'subsample': hp.quniform('subsample', 0.5, 1, 0.05), 'colsample_bytree': hp.quniform('colsample_bytree', 0.5, 1, 0.05), 'objective': 'reg:squarederror', 'n_estimators': 100, 'seed': 0 } best = fmin(obj_func, xgb_reg_params, algo=tpe.suggest, max_evals=25) best
day5.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.7 64-bit (''venv-covid_app'': venv)' # name: python37764bitvenvcovidappvenvdec448b7499a496b82740a9af93e4c30 # --- # %load_ext autoreload # + # %autoreload 2 import pandas as pd from tools import DataLoader from configparser import ConfigParser # configuration parser = ConfigParser() parser.read("../settings.ini") data = DataLoader(parser) import pathlib print(pathlib.Path().absolute()) # %aimport # - data.latest_data("cases").area.max() import math 17-math.log(data.latest_data("cases").area.max()+1000) indicator_name = data.indicators()["daily_cases"]["name"] indicator_name data_selected = data.select("World", data.indicators()["daily_cases"]) data_selected # %%time a =[1234.] indicators = data.indicators() regions = data.regions list(regions.keys()) data.timeseries[data.timeseries.region.isin(list(regions.keys()))] data.select("US", indicators["cases_capita"]).tail()# data.assign(test=lambda x: x.region) data.timeseries[data.timeseries.region=="AF"].head(3) indicators = data.indicators() indicators["cases_capita"]["name"]
notebooks/Middleware.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + from keras.preprocessing.image import img_to_array, load_img import numpy as np import sys sys.path.append('/home/linkermann/Desktop/MA/opticalFlow/opticalFlowGAN') import tflib.save_images import IPython.core.display import PIL def process_image(image, target_shape): """Given an image, process it and return the array.""" # Load the image. h, w, c = target_shape image = load_img(image, target_size=(h, w)) # Turn it into numpy, normalize and return. img_arr = img_to_array(image) x = img_arr.astype(np.uint8) #print(x.shape) x = x.reshape(h,w,c) x = np.transpose(x, [2,0,1]) #(3,32,32) x = x.reshape(h*w*c,) return x def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) def show(image): # to show np array as image x = image.astype(np.uint8) IPython.display.display(PIL.Image.fromarray(x)) inpath = "/home/linkermann/Desktop/MA/data/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01-0008.jpg" outpath = "/home/linkermann/Desktop/MA/opticalFlow/opticalFlowGAN/data/downsampletest/v_ApplyEyeMakeup_g08_c01-0008" #display(Image("/home/linkermann/Desktop/MA/data/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01-0008.jpg")) image1 = process_image(inpath, (320,240, 3)) # show(image1) # print(image1.shape) #image1t = np.transpose(image1, [2,0,1]) tflib.save_images.save_images(image1.reshape((1,3,320,240)), outpath+"-1.jpg") g = image1.astype(np.float) image_grey = rgb2gray(g) #show(image_grey) #tflib.save_images.save_images(image_grey, outpath+"-1-grey.jpg") # not working atm image2 = process_image(inpath, (32,32,3)) #image2 = np.transpose(image2, [2,0,1]) tflib.save_images.save_images(image2.reshape((1,3,32,32)), outpath+"-2.jpg") image3 = process_image(inpath, (40,40,3)) #image3 = np.transpose(image3, [2,0,1]) tflib.save_images.save_images(image3.reshape((1,3,40,40)), outpath+"-3.jpg") image4 = process_image(inpath, (64,64,3)) #image4 = np.transpose(image4, [2,0,1]) tflib.save_images.save_images(image4.reshape((1,3,64,64)), outpath+"-4.jpg") # -
tests/downsample.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Ch `11`: Concept `02` # # ## Embedding Lookup # Import TensorFlow, and begin an interactive session import tensorflow as tf sess = tf.InteractiveSession() # ๆž„ๅปบsession # Let's say we only have 4 words in our vocabulary: *"the"*, *"fight"*, *"wind"*, and *"like"*. # # Maybe each word is associated with numbers. # # | Word | Number | # | ------ |:------:| # | *'the'* | 17 | # | *'fight'* | 22 | # | *'wind'* | 35 | # | *'like'* | 51 | embeddings_0d = tf.constant([17,22,35,51]) # Or maybe, they're associated with one-hot vectors. # # | Word | Vector | # | ------ |:------:| # | *'the '* | [1, 0, 0, 0] | # | *'fight'* | [0, 1, 0, 0] | # | *'wind'* | [0, 0, 1, 0] | # | *'like'* | [0, 0, 0, 1] | embeddings_4d = tf.constant([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # This may sound over the top, but you can have any tensor you want, not just numbers or vectors. # # | Word | Tensor | # | ------ |:------:| # | *'the '* | [[1, 0] , [0, 0]] | # | *'fight'* | [[0, 1] , [0, 0]] | # | *'wind'* | [[0, 0] , [1, 0]] | # | *'like'* | [[0, 0] , [0, 1]] | embeddings_2x2d = tf.constant([[[1, 0], [0, 0]], [[0, 1], [0, 0]], [[0, 0], [1, 0]], [[0, 0], [0, 1]]]) # Let's say we want to find the embeddings for the sentence, "fight the wind". ids = tf.constant([1, 0, 2]) # We can use the `embedding_lookup` function provided by TensorFlow: # # tf.nn.embedding_lookup๏ผˆ๏ผ‰้€š่ฟ‡็ดขๅผ•ids๏ผŒๅ–embeddings_0d็š„ๅ€ผ lookup_0d = sess.run(tf.nn.embedding_lookup(embeddings_0d, ids)) print(lookup_0d) lookup_4d = sess.run(tf.nn.embedding_lookup(embeddings_4d, ids)) print(lookup_4d) lookup_2x2d = sess.run(tf.nn.embedding_lookup(embeddings_2x2d, ids)) print(lookup_2x2d)
ch11_seq2seq/Concept02_embedding_lookup.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # ็ฝ‘็ปœๆ–‡็Œฎๆ ‡้ข˜ๆŠ“ๅ–ๅ™จ # Written by yecy # 2021-01-20 ver 2.0 # ๅขžๅŠ ๅฏนElsevier็š„ๆ”ฏๆŒ๏ผŒไผ˜ๅŒ–ไบคไบ’ๅŠไฝฟ็”จไฝ“้ชŒ # 2020-04-28 ver 1.0 # ๅฎž็ŽฐๆŠ“ๅ–Wileyๆ–‡็Œฎๆ ‡้ข˜ๅนถๆไพ›็ฟป่ฏ‘ from requests_html import HTMLSession import requests import pandas as pd import json # - def get_titles(sel): titles = [] try: results = rec.html.find(sel) for result in results: get_title = result.text titles.append(get_title) return titles except: return None # + # ๆœ‰้“็ฟป่ฏ‘ # edited from https://blog.csdn.net/qq_36771895/article/details/90510742 def translator(str): """ input : str ้œ€่ฆ็ฟป่ฏ‘็š„ๅญ—็ฌฆไธฒ output๏ผštranslation ็ฟป่ฏ‘ๅŽ็š„ๅญ—็ฌฆไธฒ """ # API url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null' # ไผ ่พ“็š„ๅ‚ๆ•ฐ๏ผŒ iไธบ่ฆ็ฟป่ฏ‘็š„ๅ†…ๅฎน key = { 'type': "AUTO", 'i': str, "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "ue": "UTF-8", "action": "FY_BY_CLICKBUTTON", "typoResult": "true" } # key ่ฟ™ไธชๅญ—ๅ…ธไธบๅ‘้€็ป™ๆœ‰้“่ฏๅ…ธๆœๅŠกๅ™จ็š„ๅ†…ๅฎน response = requests.post(url, data=key) # ๅˆคๆ–ญๆœๅŠกๅ™จๆ˜ฏๅฆ็›ธๅบ”ๆˆๅŠŸ if response.status_code == 200: # ้€š่ฟ‡ json.loads ๆŠŠ่ฟ”ๅ›ž็š„็ป“ๆžœๅŠ ่ฝฝๆˆ json ๆ ผๅผ result = json.loads(response.text) # print ("่พ“ๅ…ฅ็š„่ฏไธบ๏ผš%s" % result['translateResult'][0][0]['src']) # print ("็ฟป่ฏ‘็ป“ๆžœไธบ๏ผš%s" % result['translateResult'][0][0]['tgt']) translation = result['translateResult'][0][0]['tgt'] return translation else: # ็›ธๅบ”ๅคฑ่ดฅๅฐฑ่ฟ”ๅ›ž็ฉบ return None # - def get_translations(titles): results = [] for title in titles: trans_results = translator(title) results.append(trans_results) return results session = HTMLSession() url = input('Enter the URL of the page you want to grab from: ') # Need to be edited rec = session.get(url) # print(rec.html.text) # print(rec.html.links) # + if 'wiley' in url: sel = '#main-content > div.page-body.pagefulltext > div > section > div > div > div > div.main-content.col-md-8 > div.toc-wrapper > div.table-of-content > div > div > div > a > h2' elif 'sciencedirect' in url: sel = '#article-0 > ol > li > dl > dt > h3 > a > span > span' # ๆ นๆฎไธๅŒ้กต้ข็›ธๅบ”ไฟฎๆ”น results = rec.html.find(sel) # results # + # print(get_titles(sel)) titles = get_titles(sel) check = input('Translate?(Y or N)') while 1: if check == 'Y': translations = get_translations(titles) df = pd.DataFrame({'English': titles, 'Chinese': translations}) break elif check == 'N': df = pd.DataFrame(titles) break else: print('Please enter Y or N') # df # - # output df.to_excel('article_grab.xlsx')
.ipynb_checkpoints/article_grabber-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.6 64-bit (''base'': conda)' # language: python # name: python_defaultSpec_1596692945299 # --- # + [markdown] colab_type="text" id="98yskoA9197_" # **Instructions:** # 1. **For all questions after 10th, Please only use the data specified in the note given just below the question** # 2. **You need to add answers in the same file i.e. PDS_UberDriveProject_Questions.ipynb' and rename that file as 'Name_Date.ipynb'.You can mention the date on which you will be uploading/submitting the file.For e.g. if you plan to submit your assignment on 31-March, you can rename the file as 'STUDENTNAME_31-Mar-2020'** # + [markdown] colab_type="text" id="WiVXvuYj198C" # # Load the necessary libraries. Import and load the dataset with a name uber_drives . # + colab={"base_uri": "https://localhost:8080/", "height": 71} colab_type="code" id="1t_S2Qw_198D" outputId="ecf248c8-f69d-4665-86db-c6f36b633183" import pandas as pd import numpy as np # + colab={} colab_type="code" id="rOMfio427XfR" # Get the Data data_uber_driver = pd.read_csv('uberdrive-1.csv') # + [markdown] colab_type="text" id="DZktgL3E198I" # ## Q1. Show the last 10 records of the dataset. (2 point) # + colab={"base_uri": "https://localhost:8080/", "height": 359} colab_type="code" id="pk7z2uii198I" outputId="ba211794-88ce-48d0-ea0e-48c9c7411b82" data_uber_driver.tail(10) # + [markdown] colab_type="text" id="ipD0ZQ9O198O" # ## Q2. Show the first 10 records of the dataset. (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 359} colab_type="code" id="XzYRsxR1198O" outputId="c17cacc6-7b93-47fd-fee0-2ebc9d1d1ce4" data_uber_driver.head(10) # + [markdown] colab_type="text" id="R2F4GX15198S" # ## Q3. Show the dimension(number of rows and columns) of the dataset. (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="5YAWUNwZ198T" outputId="08bd39c2-0411-4283-b152-5c581f411ab2" data_uber_driver.shape # + [markdown] colab_type="text" id="H6x0S6vs198W" # ## Q4. Show the size (Total number of elements) of the dataset. (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="2IQc1x7D198X" outputId="9e289385-f933-407a-acb9-40aa9878bddc" data_uber_driver.size # + [markdown] colab_type="text" id="c2ATRpjm198a" # ## Q5. Print the information about all the variables of the data set. (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 255} colab_type="code" id="D7Pfnrb6198b" outputId="d30f6876-efe8-4b22-b4f3-7c3f11872ab8" tags=[] data_uber_driver.info() # + [markdown] colab_type="text" id="emZkbUV_198g" # ## Q6. Check for missing values. (2 points) - Note: Output should be boolean only. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="XWU-AunT198h" outputId="a6936a81-ca07-494e-c2ce-7e897bcf6ddd" data_uber_driver.isna() # + [markdown] colab_type="text" id="UCvC2OPe198l" # ## Q7. How many missing values are present? (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="o2-vHyGA198m" outputId="d6ea44a2-8251-4378-a2d4-ee4b2c71d210" data_uber_driver.isna().sum().sum() # + [markdown] colab_type="text" id="617aSeL_198q" # ## Q8. Get the summary of the original data. (2 points). Hint:Outcome will contain only numerical column. # + colab={"base_uri": "https://localhost:8080/", "height": 297} colab_type="code" id="hMkibRQg198q" outputId="c9ac3104-57b9-4e11-85c8-d3f5fd535b5b" tags=[] data_uber_driver.describe() # + [markdown] colab_type="text" id="8PmU-86n198v" # # # ## Q9. Drop the missing values and store the data in a new dataframe (name it"df") (2-points) # # ### Note: Dataframe "df" will not contain any missing value # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="3xZC0dvq198w" outputId="84bb72a9-1750-4251-9a42-a9fadc88deab" df = data_uber_driver.dropna() # + [markdown] colab_type="text" id="2vIFI9G61983" # ## Q10. Check the information of the dataframe(df). (2 points) # + colab={"base_uri": "https://localhost:8080/", "height": 255} colab_type="code" id="DrmfQwDc1983" outputId="5a31be9b-4e9e-4575-95ae-2102f4f56d99" tags=[] df.info() # + [markdown] colab_type="text" id="Pqm4jhgT1986" # ## Q11. Get the unique start destinations. (2 points) # ### Note: This question is based on the dataframe with no 'NA' values # ### Hint- You need to print the unique destination place names in this and not the count. # + colab={"base_uri": "https://localhost:8080/", "height": 544} colab_type="code" id="jsuoItZX1987" outputId="593a9be6-c138-4ecc-e7b4-259fa3bea0a1" df['START*'].unique() # + [markdown] colab_type="text" id="s3s-pY1R198_" # ## Q12. What is the total number of unique start destinations? (2 points) # ### Note: Use the original dataframe without dropping 'NA' values # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="OOZy88AA199A" outputId="ba664de1-6397-41c8-f844-9fa4357319dc" data_uber_driver['START*'].nunique() # + [markdown] colab_type="text" id="LuKFv1_P199D" # ## Q13. Print the total number of unique stop destinations. (2 points) # ### Note: Use the original dataframe without dropping 'NA' values. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="5YeWcpZT199E" outputId="a2ceeeb8-ce0f-4951-9989-2aab44434730" data_uber_driver['STOP*'].unique().size # + [markdown] colab_type="text" id="VmkTnPlt199H" # ## Q14. Print all the Uber trips that has the starting point of San Francisco. (2 points) # ### Note: Use the original dataframe without dropping the 'NA' values. # # ### Hint: Use the loc function # + colab={"base_uri": "https://localhost:8080/", "height": 297} colab_type="code" id="fwhKZQfs199I" outputId="8828f55d-9237-4e38-bf6c-a058710af1cc" data_uber_driver[data_uber_driver['START*']=='San Francisco'] # + [markdown] colab_type="text" id="ZMsuzJcG199O" # ## Q15. What is the most popular starting point for the Uber drivers? (2 points) # ### Note: Use the original dataframe without dropping the 'NA' values. # # ### Hint:Popular means the place that is visited the most # + colab={"base_uri": "https://localhost:8080/", "height": 221} colab_type="code" id="a5QGyjza199P" outputId="252b4f81-f80d-4ef0-b797-34f27b14711e" data_uber_driver['START*'].value_counts().idxmax() # + [markdown] colab_type="text" id="S13-HiPG199T" # ## Q16. What is the most popular dropping point for the Uber drivers? (2 points) # ### Note: Use the original dataframe without dropping the 'NA' values. # # ### Hint: Popular means the place that is visited the most # + colab={"base_uri": "https://localhost:8080/", "height": 221} colab_type="code" id="YP-hwvNT199T" outputId="9e0c1ea2-0a45-4ef8-c1ed-3c52b6fb866e" data_uber_driver['STOP*'].value_counts().idxmax() # + [markdown] colab_type="text" id="6Iqizk7B199W" # ## Q17. List the most frequent route taken by Uber drivers. (3 points) # ### Note: This question is based on the new dataframe with no 'na' values. # ### Hint-Print the most frequent route taken by Uber drivers (Route= combination of START & END points present in the Data set). # + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="f41v9gc4199X" outputId="cd00fa8e-fccf-4d34-ad09-cc69efbc7797" df.groupby(['START*', 'STOP*']).size().sort_values(ascending=False) # + [markdown] colab_type="text" id="oBrYyZ-L199Z" # ## Q18. Print all types of purposes for the trip in an array. (3 points) # ### Note: This question is based on the new dataframe with no 'NA' values. # + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="p3fe_lTe199a" outputId="4da2403f-9fe6-4b06-b497-ad7b9a241e82" tags=[] df['PURPOSE*'] # + [markdown] colab_type="text" id="WBN9Ufxc199d" # ## Q19. Plot a bar graph of Purpose vs Miles(Distance). (3 points) # ### Note: Use the original dataframe without dropping the 'NA' values. # ### Hint:You have to plot total/sum miles per purpose # + colab={"base_uri": "https://localhost:8080/", "height": 351} colab_type="code" id="JaNSQ_qSa-Rg" outputId="90752e9b-f384-4cdd-a503-f5ddee0730f9" import matplotlib.pyplot as plt fig = plt.figure(figsize=(19,5)) ax = fig.add_axes([0,0,1,1]) # replacing na 'PURPOSE' values data_uber_driver["PURPOSE*"].fillna("NO_PURPOSE_PROVIDED", inplace = True) # replacing na 'MILES' values data_uber_driver["MILES*"].fillna("NO_MILES_PROVIDED", inplace = True) ax.bar(data_uber_driver['PURPOSE*'],data_uber_driver['MILES*']) plt.show() # + [markdown] colab_type="text" id="b7-pD446199j" # ## Q20. Print a dataframe of Purposes and the distance travelled for that particular Purpose. (3 points) # ### Note: Use the original dataframe without dropping "NA" values # + colab={"base_uri": "https://localhost:8080/", "height": 390} colab_type="code" id="Em4d7Ng9199k" outputId="abe48585-adf0-4848-bc0e-7023e883f12c" data_uber_driver.groupby(by=["PURPOSE*"]).sum() # + [markdown] colab_type="text" id="CIZBaeSt199o" # ## Q21. Plot number of trips vs Category of trips. (3 points) # ### Note: Use the original dataframe without dropping the 'NA' values. # ### Hint : You can make a countplot or barplot. # + colab={"base_uri": "https://localhost:8080/", "height": 317} colab_type="code" id="fRuxSI0W199p" outputId="172a512c-4bf0-4fac-d580-c46b82fa9b30" # import seaborn as sns # sns.countplot(x='CATEGORY*',data=data_uber_driver) data_uber_driver['CATEGORY*'].value_counts().plot(kind='bar',figsize=(19,7),color='red'); # + [markdown] colab_type="text" id="VgzSzOt9199t" # ## Q22. What is proportion of trips that is Business and what is the proportion of trips that is Personal? (3 points) # # ### Note:Use the original dataframe without dropping the 'NA' values. The proportion calculation is with respect to the 'miles' variable. # ### Hint:Out of the category of trips, you need to find percentage wise how many are business and how many are personal on the basis of miles per category. # + colab={"base_uri": "https://localhost:8080/", "height": 142} colab_type="code" id="K6ExiAiI199u" outputId="ef935903-76f2-461c-d45f-e6c201a17e56" tags=[] data_uber_driver['CATEGORY*'].value_counts(normalize=True)*100
M1 Python For Data Science/Week_3_Python_For_Data_Science_Data_Visulization_With_Python/PDS_UberDriveProject_Question.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:masterThesis] * # language: python # name: conda-env-masterThesis-py # --- # ## DeepExplain - Tensorflow example # ### MNIST with a 2-layers MLP # + from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile, sys, os sys.path.insert(0, os.path.abspath('..')) from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf # Download and import MNIST data tmp_dir = tempfile.gettempdir() mnist = input_data.read_data_sets(tmp_dir, one_hot=True) # + # Parameters learning_rate = 0.005 num_steps = 2000 batch_size = 128 # Network Parameters n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons num_input = 784 # MNIST data input (img shape: 28*28) num_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float", [None, num_classes]) # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1], mean=0.0, stddev=0.05)), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], mean=0.0, stddev=0.05)), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes], mean=0.0, stddev=0.05)) } biases = { 'b1': tf.Variable(tf.zeros([n_hidden_1])), 'b2': tf.Variable(tf.zeros([n_hidden_2])), 'out': tf.Variable(tf.zeros([num_classes])) } # + # Create and train model def model(x, act=tf.nn.relu): # < different activation functions lead to different explanations layer_1 = act(tf.add(tf.matmul(x, weights['h1']), biases['b1'])) layer_2 = act(tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])) out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # Construct model logits = model(X) # Define loss and optimizer loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # Evaluate model (with test logits, for dropout to be disabled) correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initialize the variables (i.e. assign their default value) init = tf.global_variables_initializer() # Train def input_transform (x): return (x - 0.5) * 2 sess = tf.Session() # Run the initializer sess.run(init) for step in range(1, num_steps+1): batch_x, batch_y = mnist.train.next_batch(batch_size) batch_x = input_transform(batch_x) # Run optimization op (backprop) sess.run(train_op, feed_dict={X: batch_x, Y: batch_y}) if step % 100 == 0 or step == 1: # Calculate batch loss and accuracy loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y}) print("Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) print("Done") # Calculate accuracy for MNIST test images test_x = input_transform(mnist.test.images) test_y = mnist.test.labels print("Test accuracy:", \ sess.run(accuracy, feed_dict={X: test_x, Y: test_y})) # - # Import DeepExplain from deepexplain.tf.v1_x import DeepExplain from utils import plot, plt # %matplotlib inline # ### Use DeepExplain to find attributions for each input pixel # + # Import DeepExplain from deepexplain.tensorflow import DeepExplain from utils import plot, plt # %matplotlib inline # Define the input to be tested test_idx = 11 xi = test_x[[test_idx]] yi = test_y[test_idx] # Create a DeepExplain context. # IMPORTANT: the network must be created within this context. # In this example we have trained the network before, so we call `model(X)` to # recreate the network graph using the same weights that have been already trained. with DeepExplain(session=sess) as de: logits = model(X) print(f'X.shape={X.get_shape()}') print(f'xi.shape={xi.shape}') print(f'yi.shape={yi.shape}') print(f'logits.shape={logits.get_shape()}') # We run `explain()` several time to compare different attribution methods attributions = { # Gradient-based 'Saliency maps': de.explain('saliency', tf.multiply(logits, yi), X, xi), 'Gradient * Input': de.explain('grad*input', logits * yi, X, xi), 'Integrated Gradients': de.explain('intgrad', logits * yi, X, xi), 'Epsilon-LRP': de.explain('elrp', logits * yi, X, xi), 'DeepLIFT (Rescale)': de.explain('deeplift', logits * yi, X, xi), #Perturbation-based '_Occlusion [1x1]': de.explain('occlusion', logits * yi, X, xi), '_Occlusion [3x3]': de.explain('occlusion', logits * yi, X, xi, window_shape=(3,)) } print ('Done') # Plot attributions n_cols = len(attributions) + 1 fig, axes = plt.subplots(nrows=1, ncols=n_cols, figsize=(3*n_cols, 3)) plot(xi.reshape(28, 28), cmap='Greys', axis=axes[0]).set_title('Original') for i, method_name in enumerate(sorted(attributions.keys())): plot(attributions[method_name].reshape(28,28), xi = xi.reshape(28, 28), axis=axes[1+i]).set_title(method_name) # -
examples/mnist_tensorflow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: VPython # language: python # name: vpython # --- # + from vpython import * scene.width = scene.height = 500 scene.background = color.gray(0.8) scene.range = 2.2 scene.caption = "Click to pick an object and make it red." scene.append_to_caption("\nNote picking of individual curve segments.") box(pos=vector(-1,0,0), color=color.cyan, opacity=1) box(pos=vector(1,-1,0), color=color.green) arrow(pos=vector(-1,-1.3,0), color=color.orange) cone(pos=vector(2,0,0), axis=vector(0,1,-.3), color=color.blue, size=vector(2,1,1)) sphere(pos=vector(-1.5,1.5,0), color=color.white, size=.4*vector(3,2,1)) square = curve(color=color.yellow, radius=.05) square.append(vector(0,0,0)) square.append(pos=vector(0,1,0), color=color.cyan, radius=.1) square.append(vector(1,1,0)) square.append(pos=vector(1,0,0), radius=.1) square.append(vector(0.3,-.3,0)) v0 = vertex(pos=vector(-.5,1.2,0), color=color.green) v1 = vertex(pos=vector(1,1.2,0), color=color.red) v2 = vertex(pos=vector(1,2,0), color=color.blue) v3 = vertex(pos=vector(-.5,2,0), color=color.yellow) quad(vs=[v0, v1, v2, v3]) ring(pos=vector(-0.6,-1.3,0), size=vector(0.2,1,1), color=color.green) extrusion(path=[vector(-1.8,-1.3,0), vector(-1.4,-1.3,0)], shape=shapes.circle(radius=.5, thickness=0.4), color=color.yellow) lasthit = None lastpick = None lastcolor = None def getevent(): global lasthit, lastpick, lastcolor if lasthit != None: if lastpick != None: lasthit.modify(lastpick, color=lastcolor) else: lasthit.color = vector(lastcolor) lasthit = lastpick = None hit = scene.mouse.pick if hit != None: lasthit = hit lastpick = None if isinstance(hit, curve): # pick individual point of curve lastpick = hit.segment lastcolor = hit.point(lastpick)['color'] hit.modify(lastpick, color=color.red) elif isinstance(hit, quad): lasthit = hit.v0 lastcolor = vector(lasthit.color) # make a copy lasthit.color = color.red else: lastcolor = vector(hit.color) # make a copy hit.color = color.red scene.bind("mousedown", getevent) # -
Demos/MousePicking.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from IPython.core.display import HTML import d3_lib HTML(d3_lib.set_styles(['basic_axis','basic_line','basic_scatter','force_directed_graph','day-hr-heatmap'])) HTML('<script src="lib/d3/d3.min.js"></script>') import pandas as pd import random random.seed(42) data = [] for i in range(20): data.append({'x': i, 'y': random.uniform(0,1), 'c': int(random.uniform(0,3))}) HTML(d3_lib.draw_graph('basic_line',{'data': data})) HTML(d3_lib.draw_graph('basic_scatter',{'data': data})) n_nodes = 30 p_edge = 0.05 graph = {"nodes": [], "links": []} for i in range(n_nodes): graph["nodes"].append( {"name": "i" + str(i), "group": int(random.uniform(1,11))} ) for i in range(n_nodes): for j in range(n_nodes): if random.uniform(0,1) < p_edge: graph["links"].append( {"source": i, "target": j, "value": random.uniform(0.5,3)} ) HTML(d3_lib.draw_graph('force_directed_graph',{'data': graph})) data = [] for d in range(1,8): for h in range(1,25): data.append({'day': d, 'hour': h, 'value': int(random.gauss(0,100))}) HTML(d3_lib.draw_graph('day-hr-heatmap',{'data': data}))
Untitled1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # - import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt # %matplotlib inline # + def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = np.pi/2 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_eps_plus = input_numbers input_eps_plus[k] = input_numbers[k] + eps exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_eps_plus))[0] result_eps_plus = torch.tensor([exp_value_plus]) input_eps_minus = input_numbers input_eps_minus[k] = input_numbers[k] - eps exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_eps_minus))[0] result_eps_minus = torch.tensor([exp_value_minus]) gradient_result = 0.5 * (result_eps_plus - result_eps_minus) gradient.append(gradient_result) # print(gradient) result = torch.tensor([gradient]) # print(result) return result.float() * grad_output.float() # + # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.0]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) y1.backward() print(x.grad) # + qc = TorchCircuit.apply def cost(x): target = -1 expval = qc(x) return torch.abs(qc(x) - target) ** 2, expval x = torch.tensor([[0.0]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 50 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) expval_list.append(expval.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) # - # ### MNIST in pytorch import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # + import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones n=100 idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # concatenate their indices mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) # - class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 1) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) # return F.softmax(x) # x = np.pi*F.tanh(x) # print(x) x = qc(x) x = (x+1)/2 x = torch.cat((x, 1-x), -1) return x # + network = Net() # optimizer = optim.SGD(network.parameters(), lr=learning_rate, # momentum=momentum) optimizer = optim.Adam(network.parameters(), lr=learning_rate/10) # + epochs = 30 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) # print(batch_idx) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) # loss = F.cross_entropy(output, target) # print(output) # print(output[0][1].item(), target.item()) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) plt.plot(loss_list) # - for i in range(len(loss_list)): loss_list[i] += 1 plt.plot(loss_list)
Notebooks/pytorch-qiskit-0.1-Ry-AQGD.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # HR Analytics # ## Dataset Description : # # 1. enrollee_id : Unique ID for candidate # 2. city: City code # 3. city_ development _index : Developement index of the city (scaled) # 4. gender: Gender of candidate # 5. relevent_experience: Relevant experience of candidate # 6. enrolled_university: Type of University course enrolled if any # 7. education_level: Education level of candidate # 8. major_discipline :Education major discipline of candidate # 9. experience: Candidate total experience in years # 10. company_size: No of employees in current employer's company # 11. company_type : Type of current employer # 12. lastnewjob: Difference in years between previous job and current job # 13. training_hours: training hours completed # 14. target: 0 โ€“ Not looking for job change, 1 โ€“ Looking for a job change # ## Importing essential Libraries import pandas as pd import os import flask import joblib import pickle import seaborn as sns import matplotlib.pyplot as plt import numpy as np import evalml from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from xgboost import XGBClassifier from lightgbm import LGBMClassifier from catboost import CatBoostClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.naive_bayes import MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from sklearn.metrics import plot_confusion_matrix from sklearn.metrics import precision_recall_fscore_support from sklearn.metrics import recall_score, roc_auc_score, roc_curve from sklearn.impute import SimpleImputer from imblearn.over_sampling import SMOTE from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score # # Importing Dataset df_train=pd.read_csv("aug_train.csv") df_train.head(15) # # EDA & Feature Engg. & Handling Missing Values df_train.info() df_train["enrollee_id"].nunique() df_train.drop("enrollee_id",axis=1,inplace=True) df_train.head(5) df_train['training_hours']=df_train['training_hours'].astype('float') df_train.info() df_train.head() df_train.experience.unique() for i in range(len(df_train.index)): if df_train['experience'][i] == '>20': df_train['experience'][i] = '21' elif df_train['experience'][i] == '<1': df_train['experience'][i] = '0' df_train['experience'] = df_train['experience'].astype('float') df_train.info() df_train["experience"].mean() df_train.describe() df_train['experience'].fillna(df_train['experience'].mean(), inplace=True) df_train.info() df_train["last_new_job"].unique() for i in range(len(df_train.index)): if df_train['last_new_job'][i] == '>4': df_train['last_new_job'][i] = '5' elif df_train['last_new_job'][i] == 'never': df_train['last_new_job'][i] = '0' df_train["last_new_job"]=df_train["last_new_job"].astype('float') df_train["last_new_job"].fillna(df_train["last_new_job"].mean(), inplace=True) df_train.info() df_train.head(50) df_train.company_size.unique() for i in range(len(df_train.index)): if df_train['company_size'][i] == '50-99': df_train['company_size'][i] = '75' elif df_train['company_size'][i] == '<10': df_train['company_size'][i] = '9' elif df_train['company_size'][i] == '10000+': df_train['company_size'][i] = '10001' elif df_train['company_size'][i] == '5000-9999': df_train['company_size'][i] = '7500' elif df_train['company_size'][i] == '1000-4999': df_train['company_size'][i] = '3000' elif df_train['company_size'][i] == '10/49': df_train['company_size'][i] = '30' elif df_train['company_size'][i] == '100-500': df_train['company_size'][i] = '300' elif df_train['company_size'][i] == '500-999': df_train['company_size'][i] = '750' df_train df_train["company_size"]=df_train["company_size"].astype('float') df_train["company_size"].fillna(df_train["company_size"].mean(), inplace=True) df_train.info() df_train.enrolled_university.unique() df_train.enrolled_university.isna().sum() sns.countplot(data=df_train,x='enrolled_university') df_train['enrolled_university'].fillna('no_enrollment',inplace=True) # Replacing with most frequent value sns.countplot(data=df_train,x='enrolled_university') df_train.education_level.unique() sns.countplot(data=df_train,x='education_level') df_train.education_level.isna().sum() df_train['education_level'].fillna('Graduate',inplace=True) # Replacing with most frequent value df_train.major_discipline.isna().sum() sns.countplot(data=df_train,x='major_discipline') df_train['major_discipline'].fillna('STEM',inplace=True) # Replacing with most frequent value df_train.company_type.isna().sum() sns.countplot(data=df_train,x='company_type') df_train['company_type'].fillna('Do_not_know', inplace=True) # Making a new type since a large chunk is missing sns.countplot(data=df_train,x='company_type') df_train.gender.isna().sum() df_train.gender.unique() sns.countplot(data=df_train,x='gender') count=0 for i in range(len(df_train.index)): if df_train['target'][i]==1 and df_train['gender'][i]=='Female': count=count+1 print(count) df_train.gender.fillna('NaN',inplace=True) for i in range(len(df_train.index)): if df_train['target'][i]==1 and df_train['gender'][i]=='NaN': df_train['gender'][i]='Male' elif df_train['target'][i]==0 and df_train['gender'][i]=='NaN': df_train['gender'][i]='Female' df_train.gender.isna().sum() sns.countplot(data=df_train,x='gender') df_train.isna().sum() df_train.info() # ## Label Encoding retarget = {'Male': 1, 'Female': 2, 'Other': 0 } df_train['gender'] = df_train['gender'].map(retarget) df_train["gender"]=df_train["gender"].astype('float') df_train.city.unique() # + retarget = ['city_103', 'city_40', 'city_21', 'city_115', 'city_162', 'city_176', 'city_160', 'city_46', 'city_61', 'city_114', 'city_13', 'city_159', 'city_102', 'city_67', 'city_100', 'city_16', 'city_71', 'city_104', 'city_64', 'city_101', 'city_83', 'city_105', 'city_73', 'city_75', 'city_41', 'city_11', 'city_93', 'city_90', 'city_36', 'city_20', 'city_57', 'city_152', 'city_19', 'city_65', 'city_74', 'city_173', 'city_136', 'city_98', 'city_97', 'city_50', 'city_138', 'city_82', 'city_157', 'city_89', 'city_150', 'city_70', 'city_175', 'city_94', 'city_28', 'city_59', 'city_165', 'city_145', 'city_142', 'city_26', 'city_12', 'city_37', 'city_43', 'city_116', 'city_23', 'city_99', 'city_149', 'city_10', 'city_45', 'city_80', 'city_128', 'city_158', 'city_123', 'city_7', 'city_72', 'city_106', 'city_143', 'city_78', 'city_109', 'city_24', 'city_134', 'city_48', 'city_144', 'city_91', 'city_146', 'city_133', 'city_126', 'city_118', 'city_9', 'city_167', 'city_27', 'city_84', 'city_54', 'city_39', 'city_79', 'city_76', 'city_77', 'city_81', 'city_131', 'city_44', 'city_117', 'city_155', 'city_33', 'city_141', 'city_127', 'city_62', 'city_53', 'city_25', 'city_2', 'city_69', 'city_120', 'city_111', 'city_30', 'city_1', 'city_140', 'city_179', 'city_55', 'city_14', 'city_42', 'city_107', 'city_18', 'city_139', 'city_180', 'city_166', 'city_121', 'city_129', 'city_8', 'city_31', 'city_171' ] c=0 retarget_f={} for i in retarget: retarget_temp={ i : c } retarget_f.update(retarget_temp) c=c+1 df_train['city'] = df_train['city'].map(retarget_f) # - df_train["city"]=df_train["city"].astype('float') df_train.relevent_experience.unique() retarget = {'Has relevent experience': 1, 'No relevent experience': 0, } df_train['relevent_experience'] = df_train['relevent_experience'].map(retarget) df_train["relevent_experience"]=df_train["relevent_experience"].astype('float') df_train.enrolled_university.unique() retarget = {'no_enrollment': 2, 'Full time course': 1, 'Part time course': 0 } df_train['enrolled_university'] = df_train['enrolled_university'].map(retarget) df_train["enrolled_university"]=df_train["enrolled_university"].astype('float') df_train.education_level.unique() retarget = {'Graduate': 2, 'Masters': 3, 'High School': 1, 'Phd': 4, 'Primary School': 0 } df_train['education_level'] = df_train['education_level'].map(retarget) df_train["education_level"]=df_train["education_level"].astype('float') df_train.major_discipline.unique() retarget = {'STEM': 5, 'Business Degree': 4, 'Arts': 3, 'Humanities': 2, 'No Major': 0, 'Other': 1, } df_train['major_discipline'] = df_train['major_discipline'].map(retarget) df_train["major_discipline"]=df_train["major_discipline"].astype('float') df_train.company_type.unique() retarget = {'Do_not_know': 0, 'Pvt Ltd': 6, 'Funded Startup': 4, 'Early Stage Startup': 3, 'Other': 1, 'Public Sector': 5, 'NGO': 2, } df_train['company_type'] = df_train['company_type'].map(retarget) df_train["company_type"]=df_train["company_type"].astype('float') df_train.info() df_train df_train.to_csv("processed_df.csv") df=pd.read_csv("processed_df.csv") df.head() df.drop('Unnamed: 0', axis=1, inplace=True) df.head() X=df.iloc[:,:-1] y=df.iloc[:,-1] sns.countplot(data=pd.DataFrame(y), x='target') plt.show() X, y = SMOTE().fit_resample(X, y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) sns.countplot(data=pd.DataFrame(y), x='target') plt.show() from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train.iloc[:,[1,7,8,10,11]]=scaler.fit_transform(X_train.iloc[:,[1,7,8,10,11]]) X_test.iloc[:,[1,7,8,10,11]]=scaler.transform(X_test.iloc[:,[1,7,8,10,11]]) pd.DataFrame(X_train) X_train pd.DataFrame(X_test) # ## Visualization & Balancing sns.pairplot(data=df_train,kind='hist') sns.countplot(data=df_train, x='target') plt.show() # ## Target needs Balancing # The dataset is unbalanced. This may adversely affect our prediction accuracy. # # One way to solve this problem is to oversample the examples in the minority class. This can be achieved by simply duplicating examples from the minority class in the training dataset prior to fitting a model. This can balance the class distribution but does not provide any additional information to the model. # # Instead, new samples can be synthesized from the existing samples. This is a type of data augmentation for the minority class and is referred to as the Synthetic Minority Oversampling Technique, or SMOTE # # SMOTE works by selecting examples that are close in the feature space, drawing a line between the examples in the feature space and creating a new sample at a point along that line. # # # Therefore using SMOTE to balance the target column. # ## Using EvalML to search for best classifier sns.countplot(data=pd.DataFrame(y), x='target') y_eval=y.copy() X_eval=X.copy() X_eval, y_eval = SMOTE().fit_resample(X_eval, y_eval) X_train_eval, X_test_eval, y_train_eval, y_test_eval = evalml.preprocessing.split_data(X_eval, y_eval, problem_type='binary') sns.countplot(data=pd.DataFrame(y_eval), x='target') from evalml.automl import AutoMLSearch automl = AutoMLSearch(X_train=X_train_eval, y_train=y_train_eval, problem_type='binary') automl.search() automl.rankings pipeline = automl.best_pipeline pipeline automl.describe_pipeline(automl.rankings.iloc[2]["id"]) automl.describe_pipeline(automl.rankings.iloc[1]["id"]) automl.describe_pipeline(automl.rankings.iloc[4]["id"]) automl.describe_pipeline(automl.rankings.iloc[5]["id"]) # ## Applying High Accuracy Classifiers # + estimators = { 'Logistic Regression': [LogisticRegression(penalty='l2',C=1.0,n_jobs=-1,multi_class='auto',solver='lbfgs')], 'Decision Tree' :[DecisionTreeClassifier(criterion='gini',max_features='auto', max_depth=6, min_samples_split=2,min_weight_fraction_leaf=0.0)], 'Random Forest' :[RandomForestClassifier(n_estimators=100,max_depth=6, n_jobs=-1)], 'XG Boost': [XGBClassifier(eta=0.1,max_depth=6,min_child_weight=1,n_estimators=100)], 'LightGBM': [LGBMClassifier(boosting_type='gbdt', learning_rate=0.1, n_estimators=100, max_depth=0, num_leaves=31, min_child_samples=20, n_jobs=-1, bagging_freq=0, bagging_fraction=0.9)] } def mfit(estimators, X_train, y_train): for m in estimators: estimators[m][0].fit(X_train, y_train) print(m+' fitted') # - mfit(estimators, X_train, y_train) def mpredict(estimators, X_test, y_test): outcome = dict() r_a_score = dict() for m in estimators: y_pred = estimators[m][0].predict(X_test) r_a_score[m] = roc_auc_score(y_test, y_pred) outcome[m] = [y_pred, confusion_matrix(y_pred,y_test), classification_report(y_pred,y_test)] return outcome, r_a_score outcome, r_a_score = mpredict(estimators, X_test, y_test) for m in outcome: print('------------------------'+m+'------------------------') plt.figure(figsize = (4, 2)) sns.heatmap(outcome[m][1], cmap = 'YlOrBr', annot = True, fmt = 'd', linewidths = 5, cbar = False, annot_kws = {'fontsize': 15}, yticklabels = ['No job change', 'Job change'], xticklabels = ['Predicted no job change', 'Predicted job change']) plt.yticks(rotation = 0) plt.show() print(outcome[m][2]) print('roc_auc_score') for m in r_a_score: print('------------------------'+m+'------------------------') print(r_a_score[m]) # + fig, ax = plt.subplots() fig.set_size_inches(15,8) for i in estimators: y_pred = estimators[i][0].predict_proba(X_test) fp_rate, tp_rate, _ = roc_curve(y_test, y_pred[:,1].ravel()) plt.plot(fp_rate,tp_rate, label=i) plt.xlabel('False Positive Rate') plt.plot([0, 1], [0, 1], linestyle = '--', color = 'b') plt.ylabel('True Positive Rate') plt.style.use('fivethirtyeight') plt.legend() plt.show() # - log_reg=estimators['Logistic Regression'][0] lgbm=estimators['LightGBM'][0] xgb=estimators['XG Boost'][0] rf=estimators['Random Forest'][0] dt=estimators['Decision Tree'][0] print(log_reg) print(lgbm) print(xgb) print(rf) print(dt) pickle.dump(rf, open('rf.pkl','wb')) pickle.dump(dt, open('dt.pkl','wb')) pickle.dump(log_reg, open('log_reg.pkl','wb')) pickle.dump(lgbm, open('lgbm.pkl','wb')) pickle.dump(xgb, open('xgb.pkl','wb')) # ## Thanks for reading my kernel. # By- # <NAME>
HR_Analytics_Ritwik.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from numpy import array, eye, random, arange, sqrt import matplotlib.pyplot as plt # System parameters dt = 1 # [second] samples = 100 # number of samples # Filter parameters phi = array([[1]]) H = array([[1]]) R = array([[.1]]) # [meter^2] Q = array([[.1]]) # [meter^2/second] # Initial values x = array([[0]]) # [meter] P = array([[1]]) # [meter^2] # Plot vectors x_all = []; P_all = []; z_all = [] # Main KF loop for k in range(0, samples): # Measurement z = random.normal(0, sqrt(R[0, 0])) # Time update x = phi@x P = phi@P@phi.T + Q # Kalman gain K = P@H.T/(H@P@H.T + R) # Measurement update x = x + K@(z - H@x) P = (eye(1) - K@H)@P@(eye(1) - K@H).T + K@R@K.T # Accumulate plot vectors x_all.append(x) P_all.append(P) z_all.append(z) # Extract plot vectors x_est = [x[0] for x in x_all] P_est = [P[0, 0] for P in P_all] # Time vector time = arange(0, samples)*dt plt.title('Filter Performance') plt.plot(time, z_all, 'r.', label='Measurements') plt.plot(time, x_est, 'g', label='Process') plt.plot(time, P_est, 'b', label='Variance') plt.legend() plt.grid() plt.show()
Example 5.2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os import sys os.environ["PYSPARK_PYTHON"] = "/home/ec2-user/spark-2.4.4-bin-hadoop2.7/python" os.environ["JAVA_HOME"] = "/usr/java/jdk1.8.0_161/jre" os.environ["SPARK_HOME"] = "/home/ec2-user/spark-2.4.4-bin-hadoop2.7" os.environ["PYLIB"] = os.environ["SPARK_HOME"] + "/python/lib" sys.path.insert(0, os.environ["PYLIB"] + "/py4j-0.10.7-src.zip") sys.path.insert(0, os.environ["PYLIB"] + "/pyspark.zip") # # GroupBy and Aggregate Functions # # GroupBy allows you to group rows together based off some column value. # # Once you've performed the GroupBy operation you can use an aggregate function off that data. # # An aggregate function aggregates multiple rows of data into a single output, such as taking the sum of inputs, or counting the number of inputs. from pyspark.sql import SparkSession # May take a little while on a local computer spark = SparkSession.builder.appName("GroupBy").getOrCreate() # Read in the customer sales data df = spark.read.csv('sales_info.csv', inferSchema=True, header=True) df.show() # Let's group together by company! df.groupby('Company') # This returns a GroupedData object, off of which you can all various methods # average df.groupby('Company').mean().show() # Count df.groupby('Company').count().show() # Max df.groupby('Company').max().show() # Min df.groupby('Company').min().show() # Sum df.groupby('Company').sum().show() # ## Functions # There are a variety of functions you can import from pyspark.sql.functions. from pyspark.sql.functions import countDistinct, avg, stddev df.select(countDistinct('Sales')).show() df.select('Sales').show() df.select(avg('Sales')).show() df.select(stddev('Sales')).show() # #### Temporaryly chinging column name # # using the methods on the data gives wired column names, use the .alias() method to change the column name temporaryly: df.select(stddev('Sales').alias('std_sales')).show() df2 = df.select(stddev('Sales').alias('std_sales')) df2.show() # #### Rounding off digits from pyspark.sql.functions import format_number df2.select(format_number('std_sales',2).alias('std_sales')).show() # ## Order By # # As the name suggests this method is used to sort the dataframe df.orderBy('Sales').show() # By default the orderby sorts data in accending order, for desending we need to use syntax desc. df.orderBy(df['Sales'].desc()).show(3)
Course_4-Big_Data_Processing_using_Apache_Spark/Module_2-Spark_Structured_APIs/1-Introduction_to_Structured_APIs/Dataframes_GroupBy_Aggregates/dataframes_groupby_aggregates.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Nim with a Quantum Computer # # [Nim](https://en.wikipedia.org/wiki/Nim) is a simple game for which we can implement simple AIs. For that reason it was used as the basis of some of the first examples of computer games: such as 1940's [Nimatron](https://en.wikipedia.org/wiki/Nimatron) and 1951's [Nimrod](https://en.wikipedia.org/wiki/Nimrod_(computer)). There was even [Dr Nim](https://en.wikipedia.org/wiki/Dr._Nim): a simple mechanical version made in the 1960s. # # Now it's time to do it with quantum computing. In this notebook we'll implement a Nim AI using just a single qubit. The game can be played here, or on Twitter. # # First we import the things we'll need: `numpy`, various things from `qiskit` and some `twitter_tools` made specifically for this project (which can be found in the file [twitter_tools.py](twitter_tools.py)). # + import numpy as np from twitter_tools import * from qiskit import QuantumCircuit, execute, IBMQ, Aer from qiskit.providers.ibmq import least_busy # - # Next is to set up how the game will be played. With `twitter=False`, all inputs and outputs will be restricted to this notebook. With `simulator=True`, a local simulator will be used. But with # ``` # twitter = True # simulator = False # ``` # the inputs and outputs really will be done via Twitter, and real quantum hardware will be used to run the opponent AI. # + twitter = False simulator = True if simulator: backend = Aer.get_backend('qasm_simulator') else: IBMQ.load_account() provider = IBMQ.providers()[0] backend = least_busy(provider.backends()[1::]) print('Playing against '+backend.name()) # - # Now for the actual game! # # There are initially 12 marbles. Players take it in turns to remove 1, 2 or 3 marbles. Whoever takes the last one wins. # # There is a strategy by which the second player can always win. They simply need to ensure that each pair of turns results in four marbles being taken. With this tactic, after 6 moves (3 by each player) the game will be down to just four marbles. # # At this point, it will be the turn of Player 1. However many marbles they take, it will be possible for Player 2 to take the rest. This mean taking the last marble, and so winning the game! # # To implement an AI for Player 2, we mostly just need to be able to determine when the number of marbles is a multiple of 4. For a quantum computer, we can do this using one qubit (as long as we can repeat the process for many shots. If you are not familiar with single qubit gates, [this guide](https://nbviewer.jupyter.org/github/quantumjim/blog/blob/master/Quantum_Procedural_Generation/2_SingleQubit.ipynb) should give you all you need for what follows. # # For our quantum AI we'll use just one gate: the `rx` gate for an angle of $\pi/4$. To see how, let's look at the effects of apply different numbers of this gate before measurement (the point at which a `0` or `1` is extracted). # # * No `rx` gates: The qubit is in the initial $\left|0\right\rangle$ state, and so the measurement outputs `0`. # * One `rx` gates: The output will be randomly `0` or `1` with equal probability. # * Two `rx` gates: The is rotated to the $\left|1\right\rangle$ state, and the measurement outputs `1`. # * Three `rx` gates: The output will be random. # * Four `rx` gates: The qubit will be back to the initial `0` state. # # To see this for yourself, you can create these circuits with the code below. # + num_rx = 5 qc = QuantumCircuit(1,1) for _ in range(num_rx): qc.rx(2*np.pi/4,0) qc.measure(0,0) qc.draw(output='mpl') # - # And then run them (on a simulator for simplicity). This is done 1024 times, and the number of samples for each possible output (`0` or `1`) are given. execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() # We will use the variable `nimmed` to represent the number of marbles taken at the beginning of a turn. There are therefore three possible numbers of marbles that could be taken at the end of the turn: `nimmed+1`, `nimmed+2` or `nimmed+3`. The quantum AI then runs three circuits: one with `nimmed+1` `rx` gates, one with `nimmed+2` and one with `nimmed+3`. It looks at the results of each to see which returns the most `0` outputs. Given the results we saw above, this will be the one such that the total number of marbles taken is a multiple of four (assuming that one of the moves can acheive this). # # That's basically it! Just run the following cell to play. # + marbles = 12 nimmed = 0 winner = None num = 1 thread_id, num = twitter_print('It\'s '+str(time.time())+', which is the perfect time for a game of Nim!\n\n'+ 'Twitter users will be playing against IBM quantum computers.\n\n'+ 'The opponent in this game is '+backend.name()+'.\n\n'+ 'Keep refreshing twitter.com/QubitChannel to follow the action.', num, twitter=twitter) ai_turn = 'The game begins with twelve marbles.\n\n'+'O'*(marbles-nimmed)+'\n\nPlayers take turns to remove either 1, 2 or 3. Whoever takes the last one wins!' while winner==None: # player turn turn = True while turn: nim, author, thread_id, num = twitter_input(ai_turn,thread_id,num,twitter=twitter) try: nim = int(nim) if nim in [1,2,3]: nimmed += nim turn = False except: print('That isn\'t a valid move. Try again.') # check to see if the player wins if nimmed==marbles: winner=='Twitter users' # otherwise, its the ai's turn else: # create a circuit corresponding to each move qc = {} for nim in [1,2,3]: qc[nim] = QuantumCircuit(1,1) for _ in range(nim+nimmed): qc[nim].rx(2*np.pi/4,0) qc[nim].measure(0,0) # run them and see which gives the best results result = execute(list(qc.values()),backend).result() zeroes = {} for nim in qc: counts = result.get_counts(qc[nim]) if '0' in counts: zeroes[nim] = counts['0'] nim = max(zeroes, key=zeroes.get) nimmed += nim ai_turn = 'The '+backend.name()+' device has responded by taking '+str(nim)+' marble'+'s'*(nim!=1)+'.\n\n'+'O'*(marbles-nimmed) if nimmed==marbles: winner = backend.name() thread_id = twitter_print('The last marble was taken by '+winner+'!\nVictory for '+winner+'!', num, reply_to=thread_id, twitter=twitter) # -
nim.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Example usage # # To use `pycounts`: # # ## Imports from pycounts.pycounts import count_words from pycounts.plotting import plot_words # ## Create a text file # # Create a text file to use: # quote = "Insanity is doing the same thing over and over and \ expecting different results." with open("einstein.txt", "w") as file: file.write(quote) # ## Count words # # Use `count_words()` to count the words in a file. counts = count_words("einstein.txt") print(counts) # ## Plot words # # Plot the results with `plot_words()`: # fig = plot_words(counts, n = 5)
docs/example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.10.0 64-bit # language: python # name: python3 # --- # # The eleventh chapter from <NAME>'s book import sys for place in sys.path: print(place) import math math.pi # + import math print(' ฯ€: {:.30f}'.format(math.pi)) print(' e: {:.30f}'.format(math.e)) print('nan: {:.30f}'.format(math.nan)) print('inf: {:.30f}'.format(math.inf)) # + import math print('{:^3} {:6} {:6} {:6}'.format( 'e', 'x', 'x**2', 'isinf')) print('{:-^3} {:-^6} {:-^6} {:-^6}'.format( '', '', '', '')) for e in range(0, 201, 20): x = 10.0 ** e y = x * x print('{:3d} {:<6g} {:<6g} {!s:6}'.format( e, x, y, math.isinf(y), )) # - # # Python Modules: Overview # # [Link to more information](https://realpython.com/python-modules-packages/) # # There are actually three different ways to define a module in Python: # # A module can be written in Python itself. # A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module. # A built-in module is intrinsically contained in the interpreter, like the itertools module. # A moduleโ€™s contents are accessed the same way in all three cases: with the import statement. # # Here, the focus will mostly be on modules that are written in Python. The cool thing about modules written in Python is that they are exceedingly straightforward to build. All you need to do is create a file that contains legitimate Python code and then give the file a name with a .py extension. Thatโ€™s it! No special syntax or voodoo is necessary. #
11. Chapter_/modules and packages.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd from database.market import Market import matplotlib.pyplot as plt from datetime import datetime from transformer.date_transformer import DateTransformer from transformer.column_transformer import ColumnTransformer import math from tqdm import tqdm market = Market() market.connect() sp5 = market.retrieve_data("sp500") market.close() analysis = [] prices = [] fails = [] datasets = ["pdr","finnhub","tiingo"] for ticker in tqdm(sp5["Symbol"]): try: market.connect() pdr = market.retrieve_price_data("pdr_prices",ticker) finnhub = market.retrieve_price_data("finnhub_prices",ticker) tiingo = market.retrieve_price_data("tiingo_prices",ticker) pdr = DateTransformer.convert_to_date("pdr",ColumnTransformer.rename_columns(pdr," "),"date") finnhub = DateTransformer.convert_to_date("finnhub",ColumnTransformer.rename_columns(finnhub,"_"),"date") tiingo = DateTransformer.convert_to_date("tiingo",ColumnTransformer.rename_columns(tiingo,"_"),"date") market.close() tiingo["date"] = [str(x).split(" ")[0] for x in tiingo["date"]] finnhub["date"] = [str(x).split(" ")[0] for x in finnhub["date"]] pdr["date"] = [str(x).split(" ")[0] for x in pdr["date"]] pdr.rename(columns={"adjclose":"pdr"},inplace=True) finnhub.rename(columns={"adjclose":"finnhub"},inplace=True) tiingo.rename(columns={"adjclose":"tiingo"},inplace=True) ds = pdr.merge(finnhub,on="date",how="left").merge(tiingo,on="date",how="left") ds["pf"] = (ds["pdr"] - ds["finnhub"]) / ds["pdr"] ds["pt"] = (ds["pdr"] - ds["tiingo"]) / ds["pdr"] ds["ft"] = (ds["finnhub"] - ds["tiingo"]) / ds["finnhub"] prices.append(ds) analysis_dict = {"ticker":ticker} for col in ["pf","pt","ft"]: ds[col] = [abs(x) for x in ds[col]] analysis_dict[col] = ds[col].mean() analysis.append(analysis_dict) except: fails.append(ticker) continue a = pd.DataFrame(analysis) a["diff"] =[row[1][["pf","pt","ft"]].mean() for row in a.iterrows()] accurate = a[(a["diff"]<0.01) & (a["pt"]<0.1) & (a["pf"]<0.1) & (a["ft"]<0.1)].sort_values("diff") market.connect() market.store_data("accurate",accurate) market.close()
Price Comparisons.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] pycharm={"name": "#%% md\n"} # # Optimal Transmission Switching (OTS) (OST) with PowerModels.jl # This tutorial describes how to run the OST feature of PowerModels.jl together with pandapower. # The OST allows to optimize the "switching state" of a (meshed) grid by taking lines out of service. This not exactly the # same as optimizing the switching state provided by pandapower. In the OST case **every in service branch element** # in the grid is taken into account in the optimization. This includes all lines and transformers. The optimization # then chooses some lines/transformers to be taken out of service in order to minimize fuel cost (see objective on PM website). # # To summerize this means: # * the switching state of the pandapower switches are **not** changed # * all lines / transformer in service states are variables of the optimization # * output of the optimization is a changed "in_service" state in the res_line / res_trafo... tables. # # For more details on PowerModels OST see: # # https://lanl-ansi.github.io/PowerModels.jl/stable/specifications/#Optimal-Transmission-Switching-(OTS)-1 # # - # # Installation # Apart from the Julia, PowerModels, Ipopt and JuMP Installation itself (see the opf_powermodels.ipynb), you need to install # some more libraries. # # The OST problem is a mixed-integer non-linear problem, which is hard to solve. To be able to solve # these kind of problems, you need a suitable solver. Either you use commercial ones (like Knitro) or the open-source # Juniper solver (which is partly developed by <NAME> from PowerModels itself): # # * Juniper: https://github.com/lanl-ansi/Juniper.jl # # Additionally CBC is needed: # # * CBC: https://projects.coin-or.org/Cbc # * CBC Julia interface: https://github.com/JuliaOpt/Cbc.jl # # Note that Juniper is a heuristic based solver. Another non-heuristic option would be to use Alpine.jl: # * Alpine: https://github.com/lanl-ansi/Alpine.jl # # # Run the OTS # To put it simple, the goal of the optimization is to find a changed in_service state for the branch elements # (lines, transformers). Note that the OPF calculation also takes into account the voltage and line loading limits. # # In order to start the optimization, we follow two steps: # 1. Load the pandapower grid data # 2. Start the optimization # # + import pandapower.networks as nw import pandapower as pp # here we use the simple case5 grid net = nw.case5() line_status = net["line"].loc[:, "in_service"].values print("Line status prior to optimization is:") print(line_status.astype(bool)) # runs the powermodels.jl switch optimization pp.runpm_ots(net) # note that the result is taken from the res_line instead of the line table. The input DataFrame is not changed line_status = net["res_line"].loc[:, "in_service"].values print("Line status after the optimization is:") print(line_status.astype(bool)) # - # # What to do with the result # The optimized line / trafo status can be found in the result DataFrames, e.g. net["res_line"]. The result ist **not** # automatically written to the inputs ("line" DataFrame). To do this you can use: # # + pycharm={"name": "#%%\n"} import pandapower as pp # Change the input data net["line"].loc[:, "in_service"] = net["res_line"].loc[:, "in_service"].values net["trafo"].loc[:, "in_service"] = net["res_trafo"].loc[:, "in_service"].values # optional: run a power flow calculation with the changed in service status pp.runpp(net) # - # If you have line-switches / trafo-switches at these lines/trafos you could also search for the switches connected to # these elements (with the topology search) and change the switching state according to the in_service result. # This should deliver identical results as changing the in service status of the element. # However, this requires to have line switches at **both** ends of the line. If you just open # the switch on one of the two sides, the power flow result is slightly different since the line loading of the # line without any connected elements is calculated. # # # # Notes # Juniper is based on a heuristic, it does not necessarily find the global optimum. For this use another solver # # In the PowerModels OPF formulation, generator limits, voltage limits and loading limits are taken into account. # This means you have to specify limits for all gens, ext_grids and controllable sgens / loads. Optionally costs for these can be defined. # Also limits for line/trafo loadings and buse voltages are to be defined. The case5 grid has pre-defined limits set. # In other cases you might get an error. Here is a code snippet: # # + pycharm={"name": "#%%\n"} def define_ext_grid_limits(net): # define line loading and bus voltage limits min_vm_pu = 0.95 max_vm_pu = 1.05 net["bus"].loc[:, "min_vm_pu"] = min_vm_pu net["bus"].loc[:, "max_vm_pu"] = max_vm_pu net["line"].loc[:, "max_loading_percent"] = 100. net["trafo"].loc[:, "max_loading_percent"] = 100. # define limits net["ext_grid"].loc[:, "min_p_mw"] = -9999. net["ext_grid"].loc[:, "max_p_mw"] = 9999. net["ext_grid"].loc[:, "min_q_mvar"] = -9999. net["ext_grid"].loc[:, "max_q_mvar"] = 9999. # define costs for i in net.ext_grid.index: pp.create_poly_cost(net, i, 'ext_grid', cp1_eur_per_mw=1)
tutorials/ost_powermodels.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.0.0 # language: julia # name: julia-1.0 # --- using Distributions using Cytof5, Random using JLD2, FileIO import StatsBase using RCall @rimport mclust @rimport base as rbase @rimport stats as rstats @rimport graphics as rgraphics # + # Directory containing CB results data_dir = "/scratchdata/alui2/cytof/results/cb/" # Path to mm1 and best output path_to_mm0_output = "$(data_dir)/best/output.jld2" path_to_mm1_output = "$(data_dir)/mm1/output.jld2" path_to_mm2_output = "$(data_dir)/mm2/output.jld2"; # + # Get output for miss-mech-0 and miss-mech-1 mm0 = load(path_to_mm0_output) mm1 = load(path_to_mm1_output) mm2 = load(path_to_mm2_output) # Get K from output K = mm0["c"].K # + # Compute ARI for any two samples function sample_ari(mcmc1::T, mcmc2::T, i::Integer) where T # Number of mcmc samples nmcmc = length(mcmc1) # Get a pair of mcmc samples idx_1, idx_2 = StatsBase.samplepair(nmcmc) # Compute ARI ari = mclust.adjustedRandIndex( mcmc1[idx_1][:lam][i], mcmc2[idx_2][:lam][i] ) return ari[1] end function sample_ari(mcmc1::T, mcmc2::T, i::Integer, nsamps::Integer) where T return [sample_ari(mcmc1, mcmc2, i) for _ in 1:nsamps] end # + function sample_ari_major(mcmc1::T, mcmc2::T, i::Integer, min_w::Float64) where T # Number of mcmc samples nmcmc = length(mcmc1) # Get a pair of mcmc samples idx_1, idx_2 = StatsBase.samplepair(nmcmc) # Get W for each mcmc sample w_1 = mcmc1[idx_1][:W][i, :] # Clusters to keep cluster_to_keep = findall(x -> x, w_1 .> min_w) # Observations to keep idx_keep = findall(cluster_label -> cluster_label in cluster_to_keep, mcmc1[idx_1][:lam][i]) # Compute ARI ari = mclust.adjustedRandIndex( mcmc1[idx_1][:lam][i][idx_keep], mcmc2[idx_2][:lam][i][idx_keep] ) return ari[1] end function sample_ari_major(mcmc1::T, mcmc2::T, i::Integer, min_w::Float64, nsamps::Integer) where T return [sample_ari_major(mcmc1, mcmc2, i, min_w) for _ in 1:nsamps] end # + # Get the clusterings from each missing mechanism for sample i i = 1 # ari_mm0 = sample_ari(mm0["out"][1], mm0["out"][1], i) # ari_mm0_max = maximum(sample_ari(mm0["out"][1], mm0["out"][1], i, 100)) # mean(sample_ari_major(mm0["out"][1], mm1["out"][1], 1, .1, 100)) # mean(sample_ari_major(mm0["out"][1], mm2["out"][1], 1, .1, 100)) aris_mm0 = sample_ari(mm0["out"][1], mm0["out"][1], i, 100) aris_mm0_mm1 = sample_ari(mm0["out"][1], mm1["out"][1], i, 100) aris_mm0_mm2 = sample_ari(mm0["out"][1], mm2["out"][1], i, 100) println("Mean ARI mm0: $(mean(aris_mm0))") println("Mean ARI mm0-mm1: $(mean(aris_mm0_mm1))") println("Mean ARI mm0-mm2: $(mean(aris_mm0_mm2))") println("Mean ARI mm0-mm1 normalized by ARI mm0: $(mean(aris_mm0_mm1 ./ aris_mm0))") println("Mean ARI mm0-mm2 normalized by ARI mm0: $(mean(aris_mm0_mm2 ./ aris_mm0))") # - ari_mm0_all_methods = Dict( :advi => [0.290, 0.144, 0.224], :flowsom => [0.201, 0.106, 0.131], :mcmc => [0.6344, .5353, .4959] ); println("ADVI normalized by MCMC ARI (mm0): $(ari_mm0_all_methods[:advi] ./ ari_mm0_all_methods[:mcmc])") println("ADVI normalized by MCMC ARI (mm0): $(ari_mm0_all_methods[:flowsom] ./ ari_mm0_all_methods[:mcmc])") # + function to_onehot(xs, K_max) N = length(xs) out = zeros(Bool, N, K_max + 1) for i in 1:N k = xs[i] if k == 0 k = K_max + 1 end out[i, xs[i]] = 1 end out end # to_onehot([1,3,5], 10) # - # Std of cluster membership for ฮปโ‚ in MCMC missing mechanism default. nmcmc = length(mm0["out"][1]) lam0_i = [mcmc[:lam][i] for mcmc in mm0["out"][1][1:100:nmcmc]] x = cat([to_onehot(x, K) for x in lam0_i]..., dims=3) sd_x = dropdims(std(x, dims=3), dims=3) cor_sd_x = cor(sd_x[:, 1:K]) # Hierarchical clustering on distance between sd_x hc = rstats.hclust(rstats.dist(sd_x')); # Plot hclust for the sd of lambda (one-hot) # Cell types in the same branch are likely # being confused with one another. rgraphics.plot(hc, xlab="", sub="");
sims/publish/investigate_low_ARI.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.1 # language: julia # name: julia-1.5 # --- using AvailablePotentialEnergyFramework, Statistics, JLD, NCDatasets, BenchmarkTools, ProgressMeter data_dir = "/global/cscratch1/sd/aramreye/for_postprocessing/largencfiles/" output_dir = "/global/u2/a/aramreye/RamirezReyes_Yang_2020_SpontaneousCyclogenesis/plotsandanimations/" file_list = ["f1e-4_2km_1000km_homoRad_homoSfc_3d.nc", "f3e-4_2km_1000km_homoRad_homoSfc_3d.nc", "f5e-4_2km_1000km_homoRad_homoSfc_3d.nc"] const R = Float32(Dryair.R) const cp = Float32(Dryair.cp) function N2(exp_name,buf1,buf2,buf3,buf4,ind1,ind2) data_dir = "$(ENV["SCRATCH"])/for_postprocessing/largencfiles/" c1 :: Float32 = Float32(R/cp) z = Float32[50 100 150 200 250 300 350 400 450 500 550 600 650 700 750 800 850 900 950 1000 1050 1178.57142857143 1385.71428571429 1671.42857142857 2035.71428571429 2478.57142857143 3000 3600 4200 4800 5400 6000 6600 7200 7800 8400 9000 9600 10200 10800 11400 12000 12600 13200 13800 14400 15000 15600 16200 16800 17400 18000 18600 19200 19800 20400 21000 21600 22200 22800 23400 24000 24600 25200 25800 26400 27000 27600 28200 28800 29400 30000 30600 31200 31800 32400 33000 33600 34200 34800][1:50]; ds = Dataset(joinpath(data_dir,exp_name)) P0 = 1f2ds["p"].var[1:50] :: Array{Float32,1} N2 = zeros(Float32,50) nchunks = 12 timesteps_per_chunk = (ind2-ind1 + 1) รท nchunks #@inbounds @showprogress 1 for chunk in 1:nchunks @inbounds @showprogress 1 for timeind in ind1:ind2 #@show initial_tind = ((chunk - 1) * timesteps_per_chunk) + 1 #@show final_tind = (chunk * timesteps_per_chunk) initial_timeind = timeind final_timeind = timeind NCDatasets.load!(ds["TABS"].var,buf1,1:512,1:512,1:50,initial_timeind:final_timeind) NCDatasets.load!(ds["PP"].var,buf2,1:512,1:512,1:50,initial_timeind:final_timeind) NCDatasets.load!(ds["QV"].var,buf3,1:512,1:512,1:50,initial_timeind:final_timeind) @inbounds for ind in CartesianIndices(buf1) buf2[ind] = buf2[ind] + P0[ind[3]] buf1[ind] = buf1[ind] * (one(c1) + 1f-3Float32(epsilon)*buf3[ind]) buf1[ind] = buf1[ind] * (P0[1]/buf2[ind])^c1 end mean!(buf4,buf1) #xBar_ThetaV = N2[:] .+= compute_N2(buf4,z)[:] end N2 ./ (ind2-ind1) close(ds) end varinfo() 1+1 buf1 = Array{Float32,3}(undef,512,512,50) buf2 = Array{Float32,3}(undef,512,512,50) buf3 = Array{Float32,3}(undef,512,512,50) buf4 = Array{Float32,3}(undef,1,1,50); # + #@btime N2("f5e-4_2km_1000km_homoRad_homoSfc_3d.nc",$buf1,$buf2,$buf3,$buf4,600,1200); #@code_warntype N2("f5e-4_2km_1000km_homoRad_homoSfc_3d.nc",buf1,buf2,buf3,buf4,600,601); # - N2_homoRad_homoSfc = N2("f5e-4_2km_1000km_homoRad_homoSfc_3d.nc",buf1,buf2,buf3,buf4,1,1200) N2_homoRad_homoSfc_f1 = N2("f1e-4_2km_1000km_homoRad_homoSfc_3d.nc",buf1,buf2,buf3,buf4,1,1200) N2_homoRad_homoSfc_f3 = N2("f3e-4_2km_1000km_homoRad_homoSfc_3d.nc",buf1,buf2,buf3,buf4,1,1200); varinfo() function get_tropo(buf1,buf2,exp_name,z,ind1,ind2) data_dir = "$(ENV["SCRATCH"])/for_postprocessing/largencfiles/" mean_qrad = Dataset(joinpath(data_dir,exp_name)) do ds mean_qrad = Array{Float32,1}(undef,80); for timeind in ind1:ind2 NCDatasets.load!(ds["QRAD"].var,buf1,1:512,1:512,1:80,timeind:timeind) mean_qrad[:] .+= mean!(buf2,buf1)[:] end mean_qrad end z[findmin(abs.(mean_qrad[1:50]))[2]] end z_grd = Float32[50 100 150 200 250 300 350 400 450 500 550 600 650 700 750 800 850 900 950 1000 1050 1178.57142857143 1385.71428571429 1671.42857142857 2035.71428571429 2478.57142857143 3000 3600 4200 4800 5400 6000 6600 7200 7800 8400 9000 9600 10200 10800 11400 12000 12600 13200 13800 14400 15000 15600 16200 16800 17400 18000 18600 19200 19800 20400 21000 21600 22200 22800 23400 24000 24600 25200 25800 26400 27000 27600 28200 28800 29400 30000 30600 31200 31800 32400 33000 33600 34200 34800]; tropo_homoRad_homoSfc = get_tropo(buf1,buf4,"f5e-4_2km_1000km_homoRad_homoSfc_3d.nc",z_grd,1,1200) tropo_homoRad_homoSfc_f1 = get_tropo(buf1,buf4,"f1e-4_2km_1000km_homoRad_homoSfc_3d.nc",z_grd,1,1200) tropo_homoRad_homoSfc_f3 = get_tropo(buf1,buf4,"f3e-4_2km_1000km_homoRad_homoSfc_3d.nc",z_grd,1,1200) @show tropo_homoRad_homoSfc @show tropo_homoRad_homoSfc_f1 @show tropo_homoRad_homoSfc_f3 function rossby_radius_of_deformation(brunt_vaisala,tropopause_height,coriolis_parameter) return brunt_vaisala*tropopause_height/coriolis_parameter end N_homoAll = sqrt(mean(N2_homoRad_homoSfc[25:findfirst(==(tropo_homoRad_homoSfc),z_grd)[2]])) N_homoAll_f1 = sqrt(mean(N2_homoRad_homoSfc_f1[25:findfirst(==(tropo_homoRad_homoSfc_f1),z_grd)[2]])) N_homoAll_f3 = sqrt(mean(N2_homoRad_homoSfc_f3[25:findfirst(==(tropo_homoRad_homoSfc_f3),z_grd)[2]])) @show r0_homoAll = rossby_radius_of_deformation(N_homoAll,tropo_homoRad_homoSfc,4.97e-4) @show r0_homoAll_f1 = rossby_radius_of_deformation(N_homoAll_f1,tropo_homoRad_homoSfc_f1,1f-4) @show r0_homoAll_f3 = rossby_radius_of_deformation(N_homoAll_f3,tropo_homoRad_homoSfc_f3,3f-4)
plots_notebooks/HomoAll_RossbyRadius.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Milestone Project 2 - Blackjack Game # In this milestone project you will be creating a Complete BlackJack Card Game in Python. # # Here are the requirements: # # * You need to create a simple text-based [BlackJack](https://en.wikipedia.org/wiki/Blackjack) game # * The game needs to have one player versus an automated dealer. # * The player can stand or hit. # * The player must be able to pick their betting amount. # * You need to keep track of the player's total money. # * You need to alert the player of wins, losses, or busts, etc... # # And most importantly: # # * **You must use OOP and classes in some portion of your game. You can not just use functions in your game. Use classes to help you define the Deck and the Player's hand. There are many right ways to do this, so explore it well!** # # # Feel free to expand this game. Try including multiple players. Try adding in Double-Down and card splits! Remember to you are free to use any resources you want and as always: # # # HAVE FUN!
Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/01-Milestone Project 2 - Assignment.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # Exploring Art across Culture and Medium with Fast, Conditional, k-Nearest Neighbors # # <img src="https://mmlspark.blob.core.windows.net/graphics/art/cross_cultural_matches.jpg" width="600"/> # # This notebook serves as a guideline for match-finding via k-nearest-neighbors. In the code below, we will set up code that allows queries involving cultures and mediums of art amassed from the Metropolitan Museum of Art in NYC and the Rijksmuseum in Amsterdam. # ### Overview of the BallTree # The structure functioning behind the kNN model is a BallTree, which is a recursive binary tree where each node (or "ball") contains a partition of the points of data to be queried. Building a BallTree involves assigning data points to the "ball" whose center they are closest to (with respect to a certain specified feature), resulting in a structure that allows binary-tree-like traversal and lends itself to finding k-nearest neighbors at a BallTree leaf. # #### Setup # Import necessary Python libraries and prepare dataset. # + from pyspark.sql.types import * from pyspark.ml.feature import Normalizer from pyspark.sql.functions import lit, array, array_contains, udf, col, struct from mmlspark.nn import ConditionalKNN, ConditionalKNNModel from PIL import Image from io import BytesIO import requests import numpy as np import matplotlib.pyplot as plt # - # Our dataset comes from a table containing artwork information from both the Met and Rijks museums. The schema is as follows: # # - **id**: A unique identifier for a piece of art # - Sample Met id: *388395* # - Sample Rijks id: *SK-A-2344* # - **Title**: Art piece title, as written in the museum's database # - **Artist**: Art piece artist, as written in the museum's database # - **Thumbnail_Url**: Location of a JPEG thumbnail of the art piece # - **Image_Url** Location of an image of the art piece hosted on the Met/Rijks website # - **Culture**: Category of culture that the art piece falls under # - Sample culture categories: *latin american*, *egyptian*, etc # - **Classification**: Category of medium that the art piece falls under # - Sample medium categories: *woodwork*, *paintings*, etc # - **Museum_Page**: Link to the work of art on the Met/Rijks website # - **Norm_Features**: Embedding of the art piece image # - **Museum**: Specifies which museum the piece originated from # loads the dataset and the two trained CKNN models for querying by medium and culture df = spark.read.parquet("wasbs://<EMAIL>/met_and_rijks.parquet") display(df.drop("Norm_Features")) # #### Define categories to be queried on # We will be using two kNN models: one for culture, and one for medium. The categories for each grouping are defined below. # + from pyspark.sql.types import BooleanType #mediums = ['prints', 'drawings', 'ceramics', 'textiles', 'paintings', "musical instruments","glass", 'accessories', 'photographs', "metalwork", # "sculptures", "weapons", "stone", "precious", "paper", "woodwork", "leatherwork", "uncategorized"] mediums = ['paintings', 'glass', 'ceramics'] #cultures = ['african (general)', 'american', 'ancient american', 'ancient asian', 'ancient european', 'ancient middle-eastern', 'asian (general)', # 'austrian', 'belgian', 'british', 'chinese', 'czech', 'dutch', 'egyptian']#, 'european (general)', 'french', 'german', 'greek', # 'iranian', 'italian', 'japanese', 'latin american', 'middle eastern', 'roman', 'russian', 'south asian', 'southeast asian', # 'spanish', 'swiss', 'various'] cultures = ['japanese', 'american', 'african (general)'] # Uncomment the above for more robust and large scale searches! classes = cultures + mediums medium_set = set(mediums) culture_set = set(cultures) selected_ids = {"AK-RBK-17525-2", "AK-MAK-1204", "AK-RAK-2015-2-9"} small_df = df.where(udf(lambda medium, culture, id_val: (medium in medium_set) or (culture in culture_set) or (id_val in selected_ids), BooleanType())("Classification", "Culture", "id")) small_df.count() # - # ### Define and fit ConditionalKNN models # Below, we create ConditionalKNN models for both the medium and culture columns; each model takes in an output column, features column (feature vector), values column (cell values under the output column), and label column (the quality that the respective KNN is conditioned on). medium_cknn = (ConditionalKNN() .setOutputCol("Matches") .setFeaturesCol("Norm_Features") .setValuesCol("Thumbnail_Url") .setLabelCol("Classification") .fit(small_df)) culture_cknn = (ConditionalKNN() .setOutputCol("Matches") .setFeaturesCol("Norm_Features") .setValuesCol("Thumbnail_Url") .setLabelCol("Culture") .fit(small_df)) # #### Define matching and visualizing methods # # After the intial dataset and category setup, we prepare methods that will query and visualize the conditional kNN's results. # # `addMatches()` will create a Dataframe with a handful of matches per category. def add_matches(classes, cknn, df): results = df for label in classes: results = (cknn.transform(results.withColumn("conditioner", array(lit(label)))) .withColumnRenamed("Matches", "Matches_{}".format(label))) return results # `plot_urls()` calls `plot_img` to visualize top matches for each category into a grid. # + def plot_img(axis, url, title): try: response = requests.get(url) img = Image.open(BytesIO(response.content)).convert('RGB') axis.imshow(img, aspect="equal") except: pass if title is not None: axis.set_title(title, fontsize=4) axis.axis("off") def plot_urls(url_arr, titles, filename): nx, ny = url_arr.shape plt.figure(figsize=(nx*5, ny*5), dpi=1600) fig, axes = plt.subplots(ny,nx) # reshape required in the case of 1 image query if len(axes.shape) == 1: axes = axes.reshape(1, -1) for i in range(nx): for j in range(ny): if j == 0: plot_img(axes[j, i], url_arr[i,j], titles[i]) else: plot_img(axes[j, i], url_arr[i,j], None) plt.savefig(filename, dpi=1600) # saves the results as a PNG display(plt.show()) # - # ### Putting it all together # Below, we define `test_all()` to take in the data, CKNN models, the art id values to query on, and the file path to save the output visualization to. The medium and culture models were previously trained and loaded. # + # main method to test a particular dataset with two CKNN models and a set of art IDs, saving the result to filename.png def test_all(data, cknn_medium, cknn_culture, test_ids, root): is_nice_obj = udf(lambda obj: obj in test_ids, BooleanType()) test_df = data.where(is_nice_obj("id")) results_df_medium = add_matches(mediums, cknn_medium, test_df) results_df_culture = add_matches(cultures, cknn_culture, results_df_medium) results = results_df_culture.collect() original_urls = [row["Thumbnail_Url"] for row in results] culture_urls = [ [row["Matches_{}".format(label)][0]["value"] for row in results] for label in cultures] culture_url_arr = np.array([original_urls] + culture_urls)[:, :] plot_urls(culture_url_arr, ["Original"] + cultures, root + "matches_by_culture.png") medium_urls = [ [row["Matches_{}".format(label)][0]["value"] for row in results] for label in mediums] medium_url_arr = np.array([original_urls] + medium_urls)[:, :] plot_urls(medium_url_arr, ["Original"] + mediums, root + "matches_by_medium.png") return results_df_culture # - # ### Demo # The following cell performs batched queries given desired image IDs and a filename to save the visualization. # # # <img src="https://mmlspark.blob.core.windows.net/graphics/art/cross_cultural_matches.jpg" width="600"/> # sample query result_df = test_all(small_df, medium_cknn, culture_cknn, selected_ids, root=".")
notebooks/samples/ConditionalKNN - Exploring Art Across Cultures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np df = pd.read_csv('/home/jovyan/data1030/data1030-oscars-prediction-project/data/pre_training_data.csv') print("The shape of the dataset is: ") print(df.shape) print("The balance of the dataset is: ") label = 'Oscar_Best_Picture_won' y = df[label] print(y.value_counts()/len(y)) X = df.drop(columns=['movie']) print("Of the features that have missing values, the fraction of missing values is:") nulls = df.isnull().sum(axis=0)/df.shape[0] print(nulls[nulls > 0]) print("") print("The total fraction of missing features in the data set is:") print(sum(df.isnull().sum(axis=1)!=0)/df.shape[0]) print("") # + from sklearn.metrics import accuracy_score, make_scorer, recall_score, \ precision_score, confusion_matrix, fbeta_score, average_precision_score from sklearn.model_selection import StratifiedKFold, GridSearchCV, train_test_split from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVC import xgboost import seaborn as sn from matplotlib import pyplot as plt num_cols = 'duration,rate,metascore,votes,gross,user_reviews,critic_reviews,popularity,awards_nominations,Oscar_nominated,Golden_Globes_nominated,BAFTA_won,BAFTA_nominated,Screen_Actors_Guild_won,Screen_Actors_Guild_nominated,Critics_Choice_won,Critics_Choice_nominated,Directors_Guild_won,Directors_Guild_nominated,Producers_Guild_won,Producers_Guild_nominated,Art_Directors_Guild_won,Art_Directors_Guild_nominated,Writers_Guild_won,Writers_Guild_nominated,Costume_Designers_Guild_won,Costume_Designers_Guild_nominated,Online_Film_Television_Association_won,Online_Film_Television_Association_nominated,Online_Film_Critics_Society_won,Online_Film_Critics_Society_nominated,People_Choice_won,People_Choice_nominated,London_Critics_Circle_Film_won,London_Critics_Circle_Film_nominated,American_Cinema_Editors_won,American_Cinema_Editors_nominated,Hollywood_Film_won,Hollywood_Film_nominated,Austin_Film_Critics_Association_won,Austin_Film_Critics_Association_nominated,Denver_Film_Critics_Society_won,Denver_Film_Critics_Society_nominated,Boston_Society_of_Film_Critics_won,Boston_Society_of_Film_Critics_nominated,New_York_Film_Critics_Circle_won,New_York_Film_Critics_Circle_nominated,Los_Angeles_Film_Critics_Association_won,Los_Angeles_Film_Critics_Association_nominated' num_cols = [x for x in num_cols.split(',')] mis_cols = df.columns[df.isna().any()].tolist() np.random.seed(0) # - import time start = time.clock() random_state = 100 X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('impute', impute_transformer, mis_cols), ('num', cnts_transformer, num_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', LogisticRegression(penalty = 'l1', solver='liblinear', max_iter = 1000, multi_class = 'auto'))]) X_p = impute_transformer.fit_transform(cnts_transformer.fit_transform(X_other)) lr = LogisticRegression(penalty = 'l1', solver='liblinear', max_iter = 1000, multi_class = 'auto') lr.fit(X_p, y_other) lr_pred = lr.predict(impute_transformer.transform(cnts_transformer.transform(X_test))) r_lr = recall_score(y_true = y_test, y_pred = lr_pred) p_lr = precision_score(y_true = y_test, y_pred = lr_pred) f_lr = fbeta_score(y_true = y_test, y_pred = lr_pred, beta = 1) cm = confusion_matrix(y_true = y_test, y_pred = lr_pred) print(r_lr) print(p_lr) print(f_lr) print(cm) stop = time.clock() print(stop-start) def plot_confusion_matrix(cm): data = cm df_cm = pd.DataFrame(data, columns=np.unique(y_test), index = np.unique(y_test)) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' plt.figure(figsize = (10,7)) sn.set(font_scale=1.4)#for label size ax = sn.heatmap(df_cm, cmap="Blues", annot=True,annot_kws={"size": 16}, fmt='.2f') bottom, top = ax.get_ylim() ax.set_ylim(bottom + 0.5, top - 0.5) # ## Logistic Regression def LR_pipeline_kfold_GridSearchCV(X,y,random_state,n_folds): X = X.fillna(-999) # create a test set X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state,stratify=y) # splitter for _other kf = StratifiedKFold(n_splits=n_folds,shuffle=True,random_state=random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state, missing_values = -999))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('num', cnts_transformer, num_cols), ('impute', impute_transformer, mis_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', LogisticRegression(penalty = 'l1', solver='liblinear', max_iter = 1000, multi_class = 'auto'))]) #parameters to tune param_grid = {'clf__C': np.logspace(-4,4,20)} #prepare scorers scoring = {'recall': make_scorer(recall_score), 'precision' : make_scorer(precision_score), 'ap' : make_scorer(average_precision_score)} # prepare gridsearch grid = GridSearchCV(pipe, param_grid=param_grid, scoring = scoring, refit = 'ap', #scoring = make_scorer(average_precision_score), cv=kf, return_train_score = True,iid=True, verbose=10, n_jobs=-1) # do kfold CV on _other grid.fit(X_other, y_other) best_model = grid.best_estimator_ best_pred = best_model.predict(X_test) best_precision = precision_score(y_test, best_pred) best_recall = recall_score(y_test, best_pred) best_f1 = fbeta_score(y_test, best_pred, 1) return grid, grid.score(X_test, y_test), best_model, best_pred, best_precision, best_recall, best_f1 # + lr_ap_scores = [] lr_precision_scores = [] lr_recall_scores = [] lr_f1_scores = [] lr_models = [] print("Training Logistic Regression Model") for i in range(6): lr_grid,lr_ap_score, lr_best_model, lr_best_pred, lr_best_precision, lr_best_recall, lr_best_f1 = LR_pipeline_kfold_GridSearchCV(X,y,10*i,4) print("________________________________________________________") print("Random State:",10*i) print("Best Parameters:") print(lr_grid.best_params_) print('best CV score:',lr_grid.best_score_) print('average precision score:',lr_ap_score) print('precision: ', lr_best_precision) print('recall: ', lr_best_recall) print('f1: ', lr_best_f1) lr_ap_scores.append(lr_ap_score) lr_precision_scores.append(lr_best_precision) lr_recall_scores.append(lr_best_recall) lr_f1_scores.append(lr_best_f1) lr_models.append(lr_best_model) print("________________________________________________________") print("________________________________________________________") print('Logistic Regression Results') print('test average precision :',np.around(np.mean(lr_ap_scores),2),'+/-',np.around(np.std(lr_ap_scores),2)) print('test precision :',np.around(np.mean(lr_precision_scores),2),'+/-',np.around(np.std(lr_precision_scores),2)) print('test recall: ',np.around(np.mean(lr_recall_scores),2),'+/-',np.around(np.std(lr_recall_scores),2)) print('test f1: ',np.around(np.mean(lr_f1_scores),2),'+/-',np.around(np.std(lr_f1_scores),2)) # + active="" # Training Logistic Regression Model # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 1.1min # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.6min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.6min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 4.0min # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 6.2min # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 7.8min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 9.1min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 10.4min # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 12.0min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 0 # Best Parameters: # {'clf__C': 206.913808111479} # best CV score: 0.3687584345479082 # average precision score: 0.7540485829959515 # precision: 1.0 # recall: 0.75 # f1: 0.8571428571428571 # ________________________________________________________ # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 57.7s # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.4min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.3min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 3.2min # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 4.6min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 5.9min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 7.1min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 8.1min # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 9.8min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 10 # Best Parameters: # {'clf__C': 1438.44988828766} # best CV score: 0.4647435897435897 # average precision score: 0.3790485829959514 # precision: 0.5 # recall: 0.75 # f1: 0.6 # ________________________________________________________ # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 57.4s # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.4min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.2min # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 2.8min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 4.0min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 5.0min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 6.4min # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 7.3min # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 9.1min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 20 # Best Parameters: # {'clf__C': 0.23357214690901212} # best CV score: 0.43016194331983804 # average precision score: 0.34143049932523617 # precision: 0.6666666666666666 # recall: 0.5 # f1: 0.5714285714285715 # ________________________________________________________ # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 55.3s # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.4min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.2min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 2.7min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 4.0min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 5.3min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 6.4min # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 7.5min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 9.1min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 30 # Best Parameters: # {'clf__C': 0.615848211066026} # best CV score: 0.39996626180836703 # average precision score: 0.13714574898785425 # precision: 0.5 # recall: 0.25 # f1: 0.3333333333333333 # ________________________________________________________ # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 55.5s # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.3min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.2min # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 3.1min # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 4.7min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 5.7min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 6.9min # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 8.0min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 9.6min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 40 # Best Parameters: # {'clf__C': 3792.690190732246} # best CV score: 0.506578947368421 # average precision score: 0.34143049932523617 # precision: 0.6666666666666666 # recall: 0.5 # f1: 0.5714285714285715 # ________________________________________________________ # Fitting 4 folds for each of 20 candidates, totalling 80 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers. # [Parallel(n_jobs=-1)]: Done 5 tasks | elapsed: 55.3s # [Parallel(n_jobs=-1)]: Done 10 tasks | elapsed: 1.3min # [Parallel(n_jobs=-1)]: Done 17 tasks | elapsed: 2.2min # [Parallel(n_jobs=-1)]: Done 24 tasks | elapsed: 3.1min # [Parallel(n_jobs=-1)]: Done 33 tasks | elapsed: 4.7min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 5.6min # [Parallel(n_jobs=-1)]: Done 53 tasks | elapsed: 6.9min # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # /Users/Jason/.local/lib/python3.7/site-packages/joblib/externals/loky/process_executor.py:706: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. # "timeout or by a memory leak.", UserWarning # [Parallel(n_jobs=-1)]: Done 64 tasks | elapsed: 7.9min # [Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 9.6min finished # /Users/Jason/.local/lib/python3.7/site-packages/sklearn/impute/_iterative.py:603: ConvergenceWarning: [IterativeImputer] Early stopping criterion not reached. # " reached.", ConvergenceWarning) # ________________________________________________________ # Random State: 50 # Best Parameters: # {'clf__C': 0.23357214690901212} # best CV score: 0.45006747638326583 # average precision score: 0.13714574898785425 # precision: 0.5 # recall: 0.25 # f1: 0.3333333333333333 # ________________________________________________________ # ________________________________________________________ # Logistic Regression Results # test average precision : 0.35 +/- 0.21 # test precision : 0.64 +/- 0.18 # test recall: 0.5 +/- 0.2 # test f1: 0.54 +/- 0.18 # - # **LOGISTIC REGRESSION RESULTS** # # Metric|Mean|St Dev # ---|---|--- # Average Precision|0.35|0.2 # Precision|0.64|0.18 # Recall|0.5|0.2 # F1|0.54|0.18 # # Best hyperparameters: `C` $= 1.0$ # ## Random Forest Model def RF_pipeline_kfold_GridSearchCV(X,y,random_state,n_folds): X = X.fillna(-999) # create a test set X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state,stratify=y) # splitter for _other kf = StratifiedKFold(n_splits=n_folds,shuffle=True,random_state=random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state, missing_values = -999))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('num', cnts_transformer, num_cols), ('impute', impute_transformer, mis_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', RandomForestClassifier(n_estimators = 100, random_state = random_state))]) #parameters to tune param_grid = {'clf__max_depth': np.sort(np.concatenate([[2], np.logspace(1,2,2)/2 , np.logspace(1,2,2)])), 'clf__min_samples_split': np.arange(2,23,5)} #prepare scorers scoring = {'recall': make_scorer(recall_score), 'precision' : make_scorer(precision_score), 'ap' : make_scorer(average_precision_score)} # prepare gridsearch grid = GridSearchCV(pipe, param_grid=param_grid, scoring = scoring, refit = 'ap', #scoring = make_scorer(average_precision_score), cv=kf, return_train_score = True,iid=True, verbose=10, n_jobs=-1) # do kfold CV on _other grid.fit(X_other, y_other) best_model = grid.best_estimator_ best_pred = best_model.predict(X_test) best_precision = precision_score(y_test, best_pred) best_recall = recall_score(y_test, best_pred) best_f1 = fbeta_score(y_test, best_pred, 1) return grid, grid.score(X_test, y_test), best_model, best_pred, best_precision, best_recall, best_f1 # + jupyter={"outputs_hidden": true} rf_ap_scores = [] rf_precision_scores = [] rf_recall_scores = [] rf_f1_scores = [] print("Training Random Forest Model") for i in range(6): print("Iteration", i) rf_grid,rf_ap_score, rf_best_model, rf_best_pred, rf_best_precision, rf_best_recall, rf_best_f1 = RF_pipeline_kfold_GridSearchCV(X,y,10*i,4) print("________________________________________________________") print("Random State:",10*i) print("Best Parameters:") print(rf_grid.best_params_) print('best CV score:',rf_grid.best_score_) print('average precision score:',rf_ap_score) print('precision: ', rf_best_precision) print('recall: ', rf_best_recall) print('f1: ', rf_best_f1) rf_ap_scores.append(rf_ap_score) rf_precision_scores.append(rf_best_precision) rf_recall_scores.append(rf_best_recall) rf_f1_scores.append(rf_best_f1) print("________________________________________________________") print("________________________________________________________") print('Random Forest Model Results') print('test average precision :',np.around(np.mean(rf_ap_scores),2),'+/-',np.around(np.std(rf_ap_scores),2)) print('test precision :',np.around(np.mean(rf_precision_scores),2),'+/-',np.around(np.std(rf_precision_scores),2)) print('test recall: ',np.around(np.mean(rf_recall_scores),2),'+/-',np.around(np.std(rf_recall_scores),2)) print('test f1: ',np.around(np.mean(rf_f1_scores),2),'+/-',np.around(np.std(rf_f1_scores),2)) # - # **RANDOM FOREST RESULTS** # # Metric|Mean|St Dev # ---|---|--- # Average Precision|0.1|0.12 # Precision|0.33|0.47 # Recall|0.08|0.12 # F1|0.13|0.19 # # Best hyperparameters: `max_depth` $= 5.0$, `min_samples_split` $= 2.0$ # ## XGBoost from xgboost import XGBClassifier def XGB_pipeline_kfold_GridSearchCV(X,y,random_state,n_folds): X = X.fillna(-999) # create a test set X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state,stratify=y) # splitter for _other kf = StratifiedKFold(n_splits=n_folds,shuffle=True,random_state=random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state, missing_values = -999))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('num', cnts_transformer, num_cols), ('impute', impute_transformer, mis_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', xgboost.XGBClassifier())]) #parameters to tune param_grid = {'clf__colsample_bytree': [0.75, 1.0], 'clf__max_depth':[4,6,8] , 'clf__min_child_weight': [2,5,10]} #prepare scorers scoring = {'recall': make_scorer(recall_score), 'precision' : make_scorer(precision_score), 'ap' : make_scorer(average_precision_score)} # prepare gridsearch grid = GridSearchCV(pipe, param_grid=param_grid, scoring = scoring, refit = 'ap', #scoring = make_scorer(average_precision_score), cv=kf, return_train_score = True,iid=True, verbose=10, n_jobs=-1) # do kfold CV on _other grid.fit(X_other, y_other) best_model = grid.best_estimator_ best_pred = best_model.predict(X_test) best_precision = precision_score(y_test, best_pred) best_recall = recall_score(y_test, best_pred) best_f1 = fbeta_score(y_test, best_pred, 1) return grid, grid.score(X_test, y_test), best_model, best_pred, best_precision, best_recall, best_f1 # + jupyter={"outputs_hidden": true} xgb_ap_scores = [] xgb_precision_scores = [] xgb_recall_scores = [] xgb_f1_scores = [] print("Training XGBoost Model") for i in range(6): print("Iteration", i) xgb_grid,xgb_ap_score, xgb_best_model, xgb_best_pred, xgb_best_precision, xgb_best_recall, xgb_best_f1 = XGB_pipeline_kfold_GridSearchCV(X,y,10*i,4) print("________________________________________________________") print("Random State:",10*i) print("Best Parameters:") print(xgb_grid.best_params_) print('best CV score:',xgb_grid.best_score_) print('average precision score:',xgb_ap_score) print('precision: ', xgb_best_precision) print('recall: ', xgb_best_recall) print('f1: ', xgb_best_f1) xgb_ap_scores.append(xgb_ap_score) xgb_precision_scores.append(xgb_best_precision) xgb_recall_scores.append(xgb_best_recall) xgb_f1_scores.append(xgb_best_f1) print("________________________________________________________") print("________________________________________________________") print('XGBoost Model Results') print('test average precision :',np.around(np.mean(xgb_ap_scores),2),'+/-',np.around(np.std(xgb_ap_scores),2)) print('test precision :',np.around(np.mean(xgb_precision_scores),2),'+/-',np.around(np.std(xgb_precision_scores),2)) print('test recall: ',np.around(np.mean(xgb_recall_scores),2),'+/-',np.around(np.std(xgb_recall_scores),2)) print('test f1: ',np.around(np.mean(xgb_f1_scores),2),'+/-',np.around(np.std(xgb_f1_scores),2)) # - # **XGBoost RESULTS** # # Metric|Mean|St Dev # ---|---|--- # Average Precision|0.3|0.25 # Precision|0.67|0.37 # Recall|0.33|0.24 # F1|0.43|0.27 # # Best hyperparameters: `colsample_bytree` $= 0.75$, `max_depth` $= 4$, `min_child_weight` $=2$ # ### XGBoost No Imputation from xgboost import XGBClassifier def XGB_pipeline_kfold_GridSearchCV(X,y,random_state,n_folds): # create a test set X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state,stratify=y) # splitter for _other kf = StratifiedKFold(n_splits=n_folds,shuffle=True,random_state=random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state, missing_values = -999))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('num', cnts_transformer, num_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', xgboost.XGBClassifier())]) #parameters to tune param_grid = {'clf__colsample_bytree': [0.5, 0.75, 1.0], 'clf__max_depth':[2,4,6,8] , 'clf__min_child_weight': [2,5,10], 'clf__subsample': [0.5, 0.75, 1.0], 'clf__learning_rate': [0.01, 0.05,0.1]} #prepare scorers scoring = {'recall': make_scorer(recall_score), 'precision' : make_scorer(precision_score), 'ap' : make_scorer(average_precision_score)} # prepare gridsearch grid = GridSearchCV(pipe, param_grid=param_grid, scoring = scoring, refit = 'ap', #scoring = make_scorer(average_precision_score), cv=kf, return_train_score = True,iid=True, verbose=10, n_jobs=-1) # do kfold CV on _other grid.fit(X_other, y_other) best_model = grid.best_estimator_ best_pred = best_model.predict(X_test) best_precision = precision_score(y_test, best_pred) best_recall = recall_score(y_test, best_pred) best_f1 = fbeta_score(y_test, best_pred, 1) return grid, grid.score(X_test, y_test), best_model, best_pred, best_precision, best_recall, best_f1 # + xgb2_ap_scores = [] xgb2_precision_scores = [] xgb2_recall_scores = [] xgb2_f1_scores = [] xgb2_models = [] print("Training XGBoost Model") for i in range(6): print("Iteration", i) xgb2_grid,xgb2_ap_score, xgb2_best_model, xgb2_best_pred, xgb2_best_precision, xgb2_best_recall, xgb2_best_f1 = XGB_pipeline_kfold_GridSearchCV(X,y,10*i,4) print("________________________________________________________") print("Random State:",10*i) print("Best Parameters:") print(xgb2_grid.best_params_) print('best CV score:',xgb2_grid.best_score_) print('average precision score:',xgb2_ap_score) print('precision: ', xgb2_best_precision) print('recall: ', xgb2_best_recall) print('f1: ', xgb2_best_f1) xgb2_ap_scores.append(xgb2_ap_score) xgb2_precision_scores.append(xgb2_best_precision) xgb2_recall_scores.append(xgb2_best_recall) xgb2_f1_scores.append(xgb2_best_f1) xgb2_models.append(xgb2_best_model) print("________________________________________________________") print("________________________________________________________") print('XGBoost No Impute Model Results') print('test average precision :',np.around(np.mean(xgb2_ap_scores),2),'+/-',np.around(np.std(xgb2_ap_scores),2)) print('test precision :',np.around(np.mean(xgb2_precision_scores),2),'+/-',np.around(np.std(xgb2_precision_scores),2)) print('test recall: ',np.around(np.mean(xgb2_recall_scores),2),'+/-',np.around(np.std(xgb2_recall_scores),2)) print('test f1: ',np.around(np.mean(xgb2_f1_scores),2),'+/-',np.around(np.std(xgb2_f1_scores),2)) # - # **XGBoost No Impute RESULTS** # # Metric|Mean|St Dev # ---|---|--- # Average Precision|0.39|0.11 # Precision|0.69|0.16 # Recall|0.58|0.19 # F1|0.59|0.12 # # Best hyperparameters: `colsample_bytree` $= 1.0$, `max_depth` $= 2$, `min_child_weight` $=2$, `learning_rate` $=0.01$, `subsample` $=1.0$. # test model # metrics # confusion matrix, accuracy, precision, recall, AUROC, AU-PR Curve # # RandomForestClassification.feature_importances_ # https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html # # XGBoost.get_score(importance_type = ...) # https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.Booster.get_score import pickle pickle.dump(xgb2_models, open('/home/jovyan/data1030/data1030-oscars-prediction-project/results/models.sav', 'wb')) # XGBoost sources: # # https://www.kaggle.com/phunter/xgboost-with-gridsearchcv # https://www.kaggle.com/tilii7/hyperparameter-grid-search-with-xgboost # https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/ # https://blog.cambridgespark.com/hyperparameter-tuning-in-xgboost-4ff9100a3b2f param1 = {'colsample_bytree': 1.0, 'eta': 0.01, 'eval_metric': 'mae', 'max_depth': 10, 'min_child_weight': 6, 'objective': 'reg:linear', 'subsample': 0.8} param2 = {'nthread':[4], #when use hyperthread, xgboost may become slower 'objective':['binary:logistic'], 'learning_rate': [0.05], #so called `eta` value 'max_depth': [6], 'min_child_weight': [11], 'silent': [1], 'subsample': [0.8], 'colsample_bytree': [0.7], 'n_estimators': [5], #number of trees, change it to 1000 for better results 'missing':[-999], 'seed': [1337]} param3 = { 'min_child_weight': [1, 5, 10], 'gamma': [0.5, 1, 1.5, 2, 5], 'subsample': [0.6, 0.8, 1.0], 'colsample_bytree': [0.6, 0.8, 1.0], 'max_depth': [3, 4, 5] } set(param1.keys()).intersection(set(param2.keys())).intersection(set(param3.keys())) # ### SVM Classifier def SVM_pipeline_kfold_GridSearchCV(X,y,random_state,n_folds): X = X.fillna(-999) # create a test set X_other, X_test, y_other, y_test = train_test_split(X, y, test_size=0.2, random_state = random_state,stratify=y) # splitter for _other kf = StratifiedKFold(n_splits=n_folds,shuffle=True,random_state=random_state) # continuous transformer setup cnts_transformer = Pipeline(steps = [('ss', StandardScaler())]) # multivariate imputer setup impute_transformer = Pipeline(steps = [('mi', IterativeImputer(estimator = RandomForestRegressor(n_estimators=100), random_state=random_state, missing_values = -999))]) # set up column transformer preprocessor = ColumnTransformer( transformers = [ ('num', cnts_transformer, num_cols), ('impute', impute_transformer, mis_cols)]) # create the pipeline: preprocessor + supervised ML method pipe = Pipeline(steps = [('preprocessor', preprocessor), ('clf', SVC())]) #parameters to tune param_grid = {'clf__C': np.logspace(-4,4,5), 'clf__gamma': np.logspace(-4,4,5)} #prepare scorers scoring = {'recall': make_scorer(recall_score), 'precision' : make_scorer(precision_score), 'ap' : make_scorer(average_precision_score)} # prepare gridsearch grid = GridSearchCV(pipe, param_grid=param_grid, scoring = scoring, refit = 'ap', #scoring = make_scorer(average_precision_score), cv=kf, return_train_score = True,iid=True, verbose=10, n_jobs=-1) # do kfold CV on _other grid.fit(X_other, y_other) best_model = grid.best_estimator_ best_pred = best_model.predict(X_test) best_precision = precision_score(y_test, best_pred) best_recall = recall_score(y_test, best_pred) best_f1 = fbeta_score(y_test, best_pred, 1) return grid, grid.score(X_test, y_test), best_model, best_pred, best_precision, best_recall, best_f1 # + jupyter={"outputs_hidden": true} svm_ap_scores = [] svm_precision_scores = [] svm_recall_scores = [] svm_f1_scores = [] svm_models= [] print("Training SVM Model") for i in range(1): print("Iteration", i) svm_grid, svm_ap_score, svm_best_model, svm_best_pred, svm_best_precision, svm_best_recall, svm_best_f1 = SVM_pipeline_kfold_GridSearchCV(X,y,10*i,4) print("________________________________________________________") print("Random State:",10*i) print("Best Parameters:") print(svm_grid.best_params_) print('best CV score:',svm_grid.best_score_) print('average precision score:',svm_ap_score) print('precision: ', svm_best_precision) print('recall: ', svm_best_recall) print('f1: ', svm_best_f1) svm_ap_scores.append(svm_ap_score) svm_precision_scores.append(svm_best_precision) svm_recall_scores.append(svm_best_recall) svm_f1_scores.append(svm_best_f1) svm_models.append(svm_best_model) print("________________________________________________________") print("________________________________________________________") print('SVM Results') print('test average precision :',np.around(np.mean(svm_ap_scores),2),'+/-',np.around(np.std(svm_ap_scores),2)) print('test precision :',np.around(np.mean(svm_precision_scores),2),'+/svm_-',np.around(np.std(svm_precision_scores),2)) print('test recall: ',np.around(np.mean(svm_recall_scores),2),'+/-',np.around(np.std(svm_recall_scores),2)) print('test f1: ',np.around(np.mean(svm_f1_scores),2),'+/-',np.around(np.std(svm_f1_scores),2)) # -
src/train_model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.9 (''qc'': venv)' # language: python # name: python3 # --- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split dataset = pd.read_csv('data/training_observables.csv', header=None) # Every Feature name header_list = { 0 : 'number', 1 : 'eos_type', 2 : 'mean_pt', 3 : 'dndy', 4 : 'v2', 5 : 'v3', 6 : 'v4', 7 : 'v5', 8 : 'psi2', 9 : 'psi3', 10 : 'psi4', 11 : 'psi5', 12 :'ptspec_bin0', 13 : 'ptspec_bin', 14 : 'ptspec_bin2', 15 : 'ptspec_bin3', 16 : 'ptspec_bin4', 17 : 'ptspec_bin5', 18 : 'ptspec_bin6', 19 : 'ptspec_bin7', 20 : 'ptspec_bin8', 21 : 'ptspec_bin9', 22 : 'ptspec_bin10', 23 : 'ptspec_bin11', 24 : 'ptspec_bin12', 25 : 'ptspec_bin13', 26 : 'ptspec_bin14', 27 : 'v2_ptbin0', 28 : 'v2_ptbin1', 29 : 'v2_ptbin2', 30 : 'v2_ptbin3', 31 : 'v2_ptbin4', 32 : 'v2_ptbin5', 33 : 'v2_ptbin6', 34 : 'v2_ptbin7', 35 : 'v2_ptbin8', 36 : 'v2_ptbin9', 37 : 'v2_ptbin10', 38 : 'v2_ptbin11', 39 : 'v2_ptbin12', 40 : 'v2_ptbin13', 41 : 'v2_ptbin14', 42 : 'v3_ptbin0', 43 : 'v3_ptbin1', 44 : 'v3_ptbin2', 45 : 'v3_ptbin3', 46 : 'v3_ptbin4', 47 : 'v3_ptbin5', 48 : 'v3_ptbin6', 49 : 'v3_ptbin7', 50 : 'v3_ptbin8', 51 : 'v3_ptbin9', 52 : 'v3_ptbin10', 53 : 'v3_ptbin11', 54 : 'v3_ptbin12', 55 : 'v3_ptbin13', 56 : 'v3_ptbin14', 57 : 'v4_ptbin0', 58 : 'v4_ptbin1', 59 : 'v4_ptbin2', 60 : 'v4_ptbin3', 61 : 'v4_ptbin4', 62 : 'v4_ptbin5', 63 : 'v4_ptbin6', 64 : 'v4_ptbin7', 65 : 'v4_ptbin8', 66 : 'v4_ptbin9', 67 : 'v4_ptbin10', 68 : 'v4_ptbin11', 69 : 'v4_ptbin12', 70 : 'v4_ptbin13', 71 : 'v4_ptbin14', 72 : 'v5_ptbin0', 73 : 'v5_ptbin1', 74 : 'v5_ptbin2', 75 : 'v5_ptbin3', 76 : 'v5_ptbin4', 77 : 'v5_ptbin5', 78 : 'v5_ptbin6', 79 : 'v5_ptbin7', 80 : 'v5_ptbin8', 81 : 'v5_ptbin9', 82 : 'v5_ptbin10', 83 : 'v5_ptbin11', 84 : 'v5_ptbin12', 85 : 'v5_ptbin13', 86 : 'v5_ptbin14' } dataset = dataset.rename(columns=header_list) dataset.head(5) dataset = dataset.drop(['number'], axis = 1) dataset # + important_features = [ 'eos_type', 'v2', 'v3', 'v4', 'v5', 'psi2', 'psi3' ] # Best features according to reference # The index of the best features in the header_list important_features_id = np.array([ 0, 2, 3, 4, 5, 6, 7 ]) # + num_sample = 5000 X_train = np.loadtxt('./QCD Dataset/X_train_' + str(num_sample) + '.txt') Y_train = np.loadtxt('./QCD Dataset/Y_train_' + str(num_sample) + '.txt') X_test = np.loadtxt('./QCD Dataset/X_test_' + str(num_sample) + '.txt') Y_test = np.loadtxt('./QCD Dataset/Y_test_' + str(num_sample) + '.txt') print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) # - # ## Dataset Preprocessing # def normalize(X, use_params=False, params=None): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviation respectively. Note: You will encounter dimensions where the standard deviation is zero, for those when you do normalization the normalized data will be NaN. Handle this by setting using `std = 1` for those dimensions when doing normalization. """ if use_params: mu = params[0] std_filled = [1] else: mu = np.mean(X, axis=0) std = np.std(X, axis=0) #std_filled = std.copy() #std_filled[std==0] = 1. Xbar = (X - mu)/(std + 1e-8) return Xbar, mu, std X_train, mu_train, std_train = normalize(X_train) X_train.shape, Y_train.shape X_test = (X_test - mu_train)/(std_train + 1e-8) X_test.shape, Y_test.shape # ## PCA from sklearn.decomposition import PCA from matplotlib import pyplot as plt num_component = 9 pca = PCA(n_components=num_component, svd_solver='full') pca.fit(X_train) np.cumsum(pca.explained_variance_ratio_) X_train = pca.transform(X_train) X_test = pca.transform(X_test) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) # ## Norm X_train = (X_train.T / np.sqrt(np.sum(X_train ** 2, -1))).T X_test = (X_test.T / np.sqrt(np.sum(X_test ** 2, -1))).T plt.scatter(X_train[:100, 0], X_train[:100, 1]) plt.scatter(X_train[100:200, 0], X_train[100:200, 1]) plt.scatter(X_train[200:300, 0], X_train[200:300, 1]) # ## Standard Scaling X_train = 2*((X_train - np.min(X_train, axis=0))/(np.max(X_train, axis=0) - np.min(X_train, axis=0))) - 1 X_test = 2*((X_test - np.min(X_test, axis=0))/(np.max(X_test, axis=0) - np.min(X_test, axis=0))) - 1 # ## Best Features # + X_train = X_train[:, important_features_id[:6]] X_test = X_test[:, important_features_id[:6]] X_train.shape, X_test.shape # - # ## Quantum # + import pennylane as qml from pennylane import numpy as np from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer import pennylane.tape #qml.tape() # Set a random seed np.random.seed(42) # + # Define output labels as quantum state vectors # def density_matrix(state): # """Calculates the density matrix representation of a state. # Args: # state (array[complex]): array representing a quantum state vector # Returns: # dm: (array[complex]): array representing the density matrix # """ # return state * np.conj(state).T label_0 = [[1], [0]] label_1 = [[0], [1]] def density_matrix(state): """Calculates the density matrix representation of a state. Args: state (array[complex]): array representing a quantum state vector Returns: dm: (array[complex]): array representing the density matrix """ return np.outer(state, np.conj(state)) state_labels = [label_0, label_1] #state_labels = np.loadtxt('./tetra_states.txt', dtype=np.complex_) # - dm_labels = [density_matrix(state_labels[i]) for i in range(2)] len(dm_labels) dm_labels binary_class = np.array([[1, 0], [0, 1]]) class_labels = binary_class num_fc_layer = 6 #params_fix = np.random.uniform(size=(2, num_fc_layer, 6)) # + n_samples = 10 n_qubits = n_samples # number of class #dev_fc = qml.device("default.qubit", wires=n_qubits) #layer_id = 4 #dev_braket_local = qml.device("braket.local.qubit", wires=1) #dev_braket_aws = qml.device('braket.aws.qubit', device_arn=device_arn, wires=1, s3_destination_folder=s3_folder) dev_qiskit = qml.device('qiskit.aer', wires=n_qubits, backend='unitary_simulator') @qml.qnode(dev_qiskit) def q_fc(params, inputs): """A variational quantum circuit representing the DRC. Args: params (array[float]): array of parameters inputs = [x, y] x (array[float]): 1-d input vector y (array[float]): single output state density matrix Returns: float: fidelity between output state and input """ #print(len(inputs)) #print(len(params[0])) #print(int(len(inputs[0])/3)) # data sample iteration for data in range(len(inputs)): # layer iteration for l in range(len(params[0])): # qubit iteration for q in range(1): # gate iteration for g in range(int(len(inputs[0])/3)): qml.Rot(*(params[0][l][3*g:3*(g+1)] * inputs[data][3*g:3*(g+1)] + params[1][l][3*g:3*(g+1)]), wires=data) #return [qml.expval(qml.Hermitian(dm_labels[i%2], wires=[i])) for i in range(n_qubits)] return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)] #return [qml.expval(qml.Identity(wires=i)) for i in range(n_qubits)] #return qml.probs(wires=[i for i in range(n_qubits)]) # + best_params = np.array([[[-8.1651270e-01, -5.7219396e+00, -5.0026126e+00, -8.7349653e+00, 8.6107445e+00, -7.4346608e-01], [-4.3116546e-01, 1.9235638e-01, 1.1460174e+01, 1.6732130e+01, -7.6773262e+00, 2.3683351e-01], [-1.2424114e+00, -1.6424029e+00, 4.3668928e+00, 1.2578176e+01, 1.3795346e+01, 4.1559759e-01], [ 1.5771559e+00, -2.9976025e-01, 4.8244944e+00, 1.2191445e+01, -1.2368810e+01, 2.3165625e-01], [-4.7297475e-01, 1.0174850e-01, 1.1752117e+00, 4.5879779e+00, -4.9621615e+00, -4.0477452e-01], [ 7.0455074e-01, 4.7375542e-01, 4.6240917e-01, 6.2393603e+00, -8.0264759e+00, -8.2564849e-01 ]], [[ -1.6269213e-01, 4.1776904e-01, -1.1912645e-01, -1.4228214e+00, 1.2047335e-01, 2.8740829e-01], [ 6.2306011e-01, 1.2985326e+00, 1.0940484e-03, 7.7353078e-01, 7.6046184e-02, 3.1073821e-01], [-7.7920145e-01, -8.7578541e-01, -5.1616389e-01, -9.5997304e-01, -1.0806603e+00, -8.3950925e-01], [ 8.6785805e-01, 1.0877717e+00, 9.0811890e-01, 5.0817257e-01, 1.1726918e+00, 4.3069747e-01], [ 7.0361930e-01, 3.2143527e-01, -7.2015360e-02, -3.6329076e-01, 2.7806100e-02, 1.8179013e+00], [ 1.1288029e+00, 2.6218903e-01, 6.7197585e-01, 5.4800685e-02, -3.0021885e-01, -5.6975257e-01 ]]]) alpha = np.array([0.9943338, 1.0097762]) # - print(best_params.shape, alpha.shape) # + z_label_0 = np.zeros((1000,)) z_label_1 = np.zeros((1000,)) for i in range(100): temp = np.loadtxt('./QPU Probs/Testing_label0_sample' + str(i) + '.txt') z_label_0[i*10:(i+1)*10] = temp temp = np.loadtxt('./QPU Probs/Testing_label1_sample' + str(i) + '.txt') z_label_1[i*10:(i+1)*10] = temp # + fidel_1_label_0 = np.clip(alpha[1]*(1 - z_label_0)/2, 0, 1) fidel_1_label_1 = np.clip(alpha[1]*(1 - z_label_1)/2, 0, 1) Y_pred_1 = np.concatenate((fidel_1_label_0, fidel_1_label_1), axis=0) Y_label = np.concatenate((np.zeros((1000,), dtype=int), np.ones((1000,), dtype=int)), axis=0) # - from sklearn.metrics import roc_auc_score roc_auc_score(Y_label, Y_pred_1) ((fidel_1_label_0 <= 0.5).sum() + (fidel_1_label_1 > 0.5).sum())/len(Y_pred_1) import tensorflow as tf # + from keras import backend as K # Alpha Custom Layer class class_weights(tf.keras.layers.Layer): def __init__(self): super(class_weights, self).__init__() w_init = tf.random_normal_initializer() self.w = tf.Variable( initial_value=w_init(shape=(1, 2), dtype="float32"), trainable=True, ) def call(self, inputs): return (inputs * self.w) # + n_component = 6 X = tf.keras.Input(shape=(n_component,), name='Input_Layer') # Quantum FC Layer, trainable params = 18*L*n_class + 2, output size = 2 num_fc_layer = 6 q_fc_layer_0 = qml.qnn.KerasLayer(q_fc, {"params": (2, num_fc_layer, n_component)}, output_dim=2)(X) # Alpha Layer alpha_layer_0 = class_weights()(q_fc_layer_0) model = tf.keras.Model(inputs=X, outputs=alpha_layer_0) # -
qcd_classification/layerwise_drc.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #all_slow # - # # Image classification - Real project example with CIFAR-10 dataset # # This notebook will exemplify how to do image classification in Ipyannotator using one of the most commonly used datasets in deep learning: [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html). The dataset contains 60000 32x32 images in 10 classes. # ## Setup data for a fictive greenfield project # # The first step is to download the dataset. The next cell will use the [pooch](https://github.com/fatiando/pooch) library to easily fetch the data files from s3. from pathlib import Path import pooch file_path = pooch.retrieve( # URL to one of Pooch's test files url="https://s3.amazonaws.com/fast-ai-imageclas/cifar10.tgz", known_hash="sha256:637c5814e11aefcb6ee76d5f59c67ddc8de7f5b5077502a195b0833d1e3e4441", ) # Pooch retrieves the data to your local machine. The next cell will display the exact path where the files were downloaded. file_path # Since the CITAR-10 dataset is downloaded as a compressed `tar` file, the next cells will extract the files. # # Ipyannotator has some internal tools to manipulate data, which is the case of the `_extract_tar` function used below to extract the files and move them to a new folder `tmp`. from ipyannotator.datasets.download import _extract_tar _extract_tar(file_path, Path('/tmp')) # Ipyannotator uses the following path setup: # # ``` # project_root # โ”‚ # โ”‚โ”€โ”€โ”€ images # โ”‚ # โ””โ”€โ”€โ”€ results # ``` # # The `project root` is the folder that contains folders for the image raw data and the annotation results. `Images` is the folder that contains all images that can displayed by the navigator and are used to create the dataset by the annotator. The `results` folder stores the dataset. The folder names can be chosen by the user. By default Ipyannotator uses `images` and `results`. # # The next cell defines a project root called `user_project` and creates a new folder called `images` inside of it. project_root = Path('user_project') (project_root / 'images').mkdir(parents=True, exist_ok=True) # Once the folder structure is created, the files are downloaded and extracted, they will be moved to the `images` folder. # # The next cell copies the 200 random images from the CIFAR-10 dataset to the Ipyannotator path structure. # + import shutil import random classes = "airplane automobile bird cat deer dog frog horse ship truck".split() for i in range(1, 200): rand_class = random.randint(0, 9) shutil.copy( Path('/tmp') / "cifar10/train" / classes[rand_class] / f"{i:04}.png", project_root / 'images') # - # ## Story # In the current step we have 200 images from random classes and we need to classify them. The first step is to have a look at the images before checking which classes need to be set in the classification. # # Ipyannotator uses an API to ensure easy access to the annotators. The next cell will import the `Annotator` factory, that provides a simple function `InputImage` to explore images. from ipyannotator.mltypes import InputImage from ipyannotator.annotator import Annotator # CIFAR-10 uses 32x32 px color images. The small size of the images makes the visualization difficult. Therefore, the `fit_canvas` property will be used in the next cell to improve the visual appearance, displaying the image at the same size of the `InputImage`. input_ = InputImage(image_width=100, image_height=100, image_dir='images', fit_canvas=True) # To use the `Annotator` factory, a simple pair of `Input/Output` is used. Omitting the output, Ipyannotator will use `NoOutput` as default. In this case, the user can only navigate across the input images and labels/classes are not displayed in the explore function. Annotator(input_).explore() # As mentioned before, the Ipyannotator path setup provides some default names for the folders. These names can be changed using the `Settings` property. The next cells demonstrates how to use the settings property to customize the folder structure. from ipyannotator.base import Settings settings = Settings( project_path=Path('user_project'), image_dir='images', result_dir='results' ) anni = Annotator(input_, settings=settings) anni.explore() # Once the user has gained an overview on the input image dataset, the user can define classes to label the images. Using `OutputLabel` you can define the classes that will be used to label the images. # # The `class_labels` property at `OutputLabel` allows an array of classes to be used in the classification. Since CIFAR-10 uses 10 classes, these are going to be used in the next cells. from ipyannotator.mltypes import OutputLabel output_ = OutputLabel(class_labels=classes) anni = Annotator(input_, output_, settings) anni.explore() # To create your own dataset you just have to call the `create` step at the `Annotator` factory. This step will allow users to associate the classes to a image. anni.create()
nbs/20_image_classification_user_story.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Plotting alignment data # + # %matplotlib inline import pandas as pd import utils.db_utils as db import utils.plot_utils as plot targetLang = 'en' bibleType = 'en_ult' dbPath = f'./data/{bibleType}_NT_alignments.sqlite' connection = db.initAlignmentDB(dbPath) # + pycharm={"name": "#%%\n"} def getDataFrameForOriginalWords(connection, word, searchLemma = True): # print(f"searchLemma = {searchLemma}") words = [word] alignments_ = db.getAlignmentsForOriginalWords(connection, words, searchLemma) alignments = pd.DataFrame(alignments_[word]) return alignments # + pycharm={"name": "#%%\n"} # find all alignments for this lemma word = 'ฮธฮตฯŒฯ‚' lemmaAlignments = getDataFrameForOriginalWords(connection, word, searchLemma = True) lemmaAlignments # + pycharm={"name": "#%%\n"} # find all alignments for this original word # word = 'ฮ˜ฮตฯŒฯ‚' # found 69 # word = 'ฮ˜ฮตแฝธฯ‚' # found 239 word = 'ฮ˜ฮตฮฟแฟฆ' # found 712 origAlignments = getDataFrameForOriginalWords(connection, word, searchLemma = False) origAlignments # + pycharm={"name": "#%%\n"} db.describeAlignments(origAlignments) # - # ### Analysis of alignments for ฮ˜ฮตฮฟแฟฆ in the en_ult: # #### Frequency of alignments: # + pycharm={"name": "#%%\n"} frequency = origAlignments['alignmentTxt'].value_counts() print(frequency) # - # ##### Notes: # - the left column is the specific alignment, and the right column is the number of times that specific alignment has been made so far in the NT. # - alignments that contain more words are more suspect. # - in future will combine "God s" to "God's" before doing analysis # <p></p> # + pycharm={"name": "#%%\n"} plot.plotFieldFrequency(frequency, "", 'alignment', title="Frequency of Alignments", xNumbers=False, xShowTicks=False) # - # ### Analysis: # #### Analysis of numerical metrics: # + pycharm={"name": "#%%\n"} descr = origAlignments.describe() print(f"Alignments description:\n{descr}") # - # #### Analysis of distance between first and last original language word: # + pycharm={"name": "#%%\n"} field = 'origSpan' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") # - # ##### Notes: # - this field is less useful because it includes aligned words, so added originalWordsBetween as more useful normalized metric (see analysis below). # <p></p> # #### Analysis of distance between first and last target language word: # + pycharm={"name": "#%%\n"} field = 'targetSpan' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") # - # ##### Notes: # - this field is also less useful because it includes the aligned words, so added targetWordsBetween as more useful normalized metric (see analysis below). # <p></p> # #### Analysis of original language word count: # + pycharm={"name": "#%%\n"} field = 'alignmentOrigWords' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") # - # ##### Notes: # - this field analysis suggests for ฮธฮตฯŒฯ‚ nearly all the original language word counts are tight. The word counts of 3 may need review. So we could probaby use that as a threshold for to flag for review. # <p></p> # + [markdown] pycharm={"name": "#%% md\n"} # #### Analysis of target language word count: # + pycharm={"name": "#%%\n"} field = 'alignmentTargetWords' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") # - # ##### Notes: # - this field analysis suggests that for ฮธฮตฯŒฯ‚ likely all the target language word counts are tight. The word count of 3 probably good for English (`of a god`). But still we could probaby use that as a threshold for to flag for review. # <p></p> # #### Analysis of count of extra unaligned words between aligned original language words: # + pycharm={"name": "#%%\n"} field = 'origWordsBetween' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") # - # ##### Notes: # - this field analysis suggests that most original language alignments probably good. Probably the cases of a word between (count > 0) aligned words should be reviewed. # <p></p> # #### Analysis of count of extra unaligned words between aligned target language words: # + pycharm={"name": "#%%\n"} field = 'targetWordsBetween' field_frequency = origAlignments[field].value_counts().sort_index() print(f"\nFrequency of {field}:\n{field_frequency}") plot.plotFieldFrequency(field_frequency, field, f"Words Between", max=10) # + [markdown] pycharm={"name": "#%% md\n"} # ##### Notes: # - this field analysis suggests that most target language alignments probably good. Large gaps between aligned words are likely due to wordmap suggesting wrong occurence of a word and the user selecting. Probably the cases of a word between (count > 0) aligned words should be reviewed. # <p></p> # + pycharm={"name": "#%%\n"} # + pycharm={"name": "#%%\n"}
plot_original_word_alignments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Text Files # # Data is often stored in formats that are not easy to read unless you have some specialised software. Excel spreadsheets are one example; how do you read an Excel spreadsheet if you don't have Excel? This reliance on particular software is not very useful for programmatic analysis of data. Instead if we're going to use a programming language to analyse or process our data we would prefer some "easy to deal with" format. Text files or [flatfiles](http://en.wikipedia.org/wiki/Text_file) provide just the sort of format we need (there are other choices). You can think of these as a single sheet from a spreadsheet with the data arranged in rows (separated by our old friend the ```\n``` character) and columns (separated by some other character). # + [markdown] slideshow={"slide_type": "subslide"} # There are two common characters used to separate the data in text files into columns. The ```\t```, or tab stop character and the humble comma (,). In both cases fields in our input file are separated by a single tab stop or a single comma. # # This gives rise to two commonly used file extensions (the bit after the dot in file names e.g. in ```myfile.docx``` the 'docx' is the file extension.). These file extensions are ```.tsv``` for 'tab separated file' and ```.csv``` for 'comma separated file'. Other separators in text files of data may be little used characters such as '|', ':' or spaces. As a quick aside separating fields in data files by spaces is tricky because an individual value might also contain spaces and therefore be inappropriately divided over more than one column. # # As an illustration if you were to print a couple of lines from a ```.tsv``` file out it would look something like this: # + slideshow={"slide_type": "fragment"} active="" # data_field1\tdata_field2\tdata_field3\n # data_field1\tdata_field2\tdata_field3\n # + [markdown] slideshow={"slide_type": "subslide"} # Each field is separated by a tab stop ```\t``` and the end of a line is indicated by the ```\n``` combination. # # In a ```.csv``` file you would see: # + slideshow={"slide_type": "fragment"} active="" # data_field1,data_field2,data_field3\n # data_field1,data_field2,data_field3\n # + [markdown] slideshow={"slide_type": "subslide"} # ### Note: # # It's important to note that there is NO STANDARD for either the layout OR naming of text files. In the exercises that follow the text file we will be working with has the extension ```.csv``` which should mean comma separated but in fact the data is separated by tabs - because that's what I'm in the habit of doing. Please ignore my bad habits! # + [markdown] slideshow={"slide_type": "skip"} # --- # + [markdown] slideshow={"slide_type": "slide"} # # Opening (and Reading) Files # # When you open a file in a programme such as Word or Excel you have to select the file you want from a 'File -> Open' dialogue of some kind. In other words you have to point the programme at the specific file you want which is stored at some specific location on your computer. This is also true when you open a file in Python. # The difference is that when you open a file in python you have to specify the file location in words (as a **filepath**) rather then selecting from a dialogue. So the first thing we have to do is assign the file location to a variable. This textual representation of the file location is called the filepath. # # Once we have the filepath we can use the python function ```open()``` to 'get a handle' on the file. This **file handle** should also be assigned to a variable. We can then operate on that variable. Let's see an example. # + slideshow={"slide_type": "subslide"} file_loc = 'data/elderlyHeightWeight.csv' f_hand = open(file_loc, 'r') print(f_hand) # + [markdown] slideshow={"slide_type": "fragment"} # In the example above we have opened a small file containing height and weight information on a group of elderly men and women from a body composition study. # + [markdown] slideshow={"slide_type": "skip"} # In the first line we assign the file path to the variable ```file_loc```. We then use that variable to open a file handle (```f_hand```) using the ```open()``` function. The file location is the first argument to the ```open()``` function and the second argument ```'r'``` indicates that we want to *read* from the file i.e. we want access to the data in the file but we don't want to change the file itself. Finally we use a ```print``` statement to print the file handle. # # The results of the ```print``` statement might surprise you. Rather than printing the contents of the file what we get is a representation of the location in the computer memory of where the file is i.e. at memory location 0x7... etc in the example above. # # Whilst we can also open Excel or Word files in python this requires the use of special software libraries. We'll see some of those later in the course. Mostly when we are analysing data in files we open simple text files. Both Excel and Word can save files out as simple text files. # # The first few lines of the file we will work with are shown below. # + slideshow={"slide_type": "subslide"} # !head -n 4 data/elderlyHeightWeight.csv # + [markdown] slideshow={"slide_type": "subslide"} # While the file handle does not contain the data from the file (it only points at it) it is easy to construct a ```for``` loop to cycle through the lines of the file and carry out some computation. For example we can easily count the number of lines in the file. # + slideshow={"slide_type": "fragment"} count = 0 # initialise for line in f_hand: # iterate count = count + 1 print('There are %d lines in the file.' % count ) # + [markdown] slideshow={"slide_type": "subslide"} # ### Why doesn't `open()` open the file directly? # # It might seem stupid that after using ```open()``` a file handle is created but the file contents aren't directly available. The reason the ```open()``` function does not read the whole file immediately but just points to it is to do with file size. If you do not know in advance the size of the files you are dealing with (often the case - how often do you check the size of files you open on your computer?) automatically opening *very* large files could: # # * Take a long time # * Crash the whole computer system - essentially you'd run out of memory # + [markdown] slideshow={"slide_type": "subslide"} # For some biological applications the data files (which may well be text files e.g. in RNA Seq data - see comment [here](http://seqanswers.com/forums/showthread.php?t=10787)) can be very large. So it's safer to point to the file rather than automatically open it. This is also true of other data or informatics applications. # # In the ```for``` loop above python splits the file into lines based on the newline character (```\n``` - the split is implicit), increments the ```count``` variable by 1 for every line and then discards that line. So there is only ever one line from the file in the computer memory at any given time. # # If you know that your file is likely to be small you can read the whole file into memory with the ```read()``` method (remember the dot notation!). # # This reads the entire contents of the file, newlines and all, into one large string. # + slideshow={"slide_type": "skip"} file_loc = 'data/elderlyHeightWeight.csv' f_hand = open(file_loc, 'r') f_data = f_hand.read() print(f_data) # + slideshow={"slide_type": "skip"} f_hand.close() f_hand = open(file_loc) print(f_hand.readline(), end = '') print(f_hand.readline(), end = '') f_hand.close() f_hand = open(file_loc) lines = f_hand.readlines() print(type(lines)) # + slideshow={"slide_type": "skip"} file_loc = 'data/elderlyHeightWeight.csv' f_hand = open(file_loc, 'r') f_data = f_hand.read() f_data[:22] print(len(f_data)) print( f_data[:10]) r'{}'.format(f_data[:22]) # note the tab stop in the output # + [markdown] slideshow={"slide_type": "skip"} # In the above example we first create the file handle and then ```read``` the entire contents of the file into one string. We check the length of that string (286 characters including whitespace characters like ```\n```) and we print the first 10 characters (refer back to the material on slicing if you're unsure how the ```[:10]``` slice works). The ```print``` statement interprets the tab stop properly but if we just ask for the first 22 characters to be returned (i.e. we do not use ```print```) we can see the tab stop and the ```\n```. Compare this to the illustration of a .tsv file shown above. # # Using the ```print``` statement and subsetting is fine but not convenient. You might want to print the whole of the first line. The ```readline()``` method will read one line at a time and you can use this to e.g. just display the header line (if you know or suspect that your file has a header line). # + slideshow={"slide_type": "skip"} f_hand = open(file_loc, 'r') line = f_hand.readline() # reads first line print(line) # next line line=f_hand.readline() print(line) # + [markdown] slideshow={"slide_type": "skip"} # After reading in the current line ```readline()``` then moves on to the next line. So calling ```readline()``` again uses the next line in the file. One other thing to bear in mind is that ```readline()``` leaves whitespace and in particular the ```\n``` character at the end of the line. You can see that above (there's a blank line between the printed lines) in the following example. # + slideshow={"slide_type": "skip"} line = f_hand.readline() # note next line has been read line # compare to print above # - # + [markdown] slideshow={"slide_type": "subslide"} # If you're using python to join lines together in some new format that might not be what you want. There is a method, ```strip()```(see [here](https://docs.python.org/3/library/string.html)) that removes whitespace at the end of lines and can be used to remove this potentially extraneous ```\n``` character. Note also that methods can be **chained** together so you can use ```readline()``` and ```strip()``` sequentially using the following syntax. # + slideshow={"slide_type": "skip"} f_hand = open(file_loc, 'r') # read in in file again to get header line line = f_hand.readline().strip() # read the line then strip the whitespace at the end of the line line # no \n! # + [markdown] slideshow={"slide_type": "skip"} # Use of ```strip()``` has removed the ```\n``` from our selected line. There are also ```lstrip()``` and ```rstrip()``` methods that strip whitespace from only the left or right sides of a string respectively. # # Just to confuse you further there's also a ```readlines()``` method that reads all the lines in the file into a ```list```. Again the lines are separated on the invisible ```\n``` character. This can be handy because you can assign the ```list``` to a variable and then loop through the list to print file lines or simply extract the lines you want using slice notation. # + slideshow={"slide_type": "skip"} f_hand = open(file_loc, 'r') lines = f_hand.readlines() print(lines[0:2]) # check we have a list print(len(lines)) # + slideshow={"slide_type": "skip"} for i in range(4): print (lines[i].strip()) # + [markdown] slideshow={"slide_type": "skip"} # --- # # ### Alternative Implementations (just for fun) # + [markdown] slideshow={"slide_type": "skip"} # ### no. 1 # + slideshow={"slide_type": "skip"} for line in lines[:4]: print(line.strip()) # + [markdown] slideshow={"slide_type": "skip"} # ### no. 2 # + slideshow={"slide_type": "skip"} for i, line in enumerate(lines): if i == 4: break print(line.strip()) # + [markdown] slideshow={"slide_type": "skip"} # --- # + [markdown] slideshow={"slide_type": "skip"} # Just like ```readline()``` the ```readlines()``` method leaves the trailing \n at the end of the line but you can use ```strip()``` to remove it if you have to as we did above. We had to use the ```strip()``` method on the individual line rather than on the list of lines as lists ```strip()``` does not operate on lists. Try moving the ```strip()``` to the end of ```lines = f_hand.readlines()``` and see what kind if error you get. # # Finally (and perhaps most usefully) there is the ```splitlines()``` method that does the same as ```readlines()``` but drops the trailing ```\n``` automatically. # + slideshow={"slide_type": "skip"} f_hand = open(file_loc, 'r') lines = f_hand.read().splitlines() # read file, then split lines to lists, drops trailing \n for i in range(4): print (lines[i]) # + [markdown] slideshow={"slide_type": "skip"} # Notice we didn't have to use ```strip()```. # # One final thing to note is that whenever we finish with a file we should close it. Leaving files 'open' after data has been read from them can lead to increasing amounts of memory being used and also corruption of the file. Closing files is accomplished by using the ```close()``` method on the file handle. Also illustrated is a simple filter to print out only the male data using the string method ```startswith()``` - which returns a boolean value depending on whether the line begins with the given argument (M in this case) or not. # + file_loc = 'data/elderlyHeightWeight.csv' # relative path f_hand = open(file_loc, 'r') lines = f_hand.read().splitlines() # lines to a list print (lines[0]) # header for line in lines: # loop to filter if line.startswith('M'): print (line) f_hand.close() # + [markdown] slideshow={"slide_type": "skip"} # ## `filter` alternative # + slideshow={"slide_type": "skip"} def filter_function(line): return line.startswith('M') # + slideshow={"slide_type": "skip"} f_hand = open(file_loc) lines = f_hand.readlines() male_gender = filter(filter_function, lines) print(lines[0].strip()) for ml in male_gender: print(ml.strip()) f_hand.close() # + [markdown] slideshow={"slide_type": "skip"} # #### Using `lambda` expressions # + slideshow={"slide_type": "skip"} f_hand = open(file_loc) male_gender = filter(lambda l: l.startswith('M'), f_hand) for ml in male_gender: print(ml.strip()) f_hand.close() # + [markdown] slideshow={"slide_type": "skip"} # ## Exercises # + [markdown] slideshow={"slide_type": "skip"} # ### Show the content of the file using a Shell command # # #### Tip 1: The shell command to be used could be `cat` # #### Tip 2: Remember the `!` (esclamation mark) # + slideshow={"slide_type": "skip"} # !cat data/elderlyHeightWeight.csv # + [markdown] slideshow={"slide_type": "skip"} # ### Ex. no 2 # # Print all the lines in the file where the `Age` value is in the range `[70, 80)` # + slideshow={"slide_type": "skip"} f_hand = open(file_loc) for i, line in enumerate(f_hand): if i == 0: continue line = line.strip() _, age, *_ = line.split('\t') if 70 <= int(age) < 80: print(line) # + [markdown] slideshow={"slide_type": "skip"} # ### Ex. no 3 # # Print the two lines in the files for each `gender` corresponding to the two entries with the (relative) maximum value of *body weight* (`body wt`) plus *height* (`ht`). # + [markdown] slideshow={"slide_type": "skip"} # ### Sol `#1`: Using a Dictionary # + slideshow={"slide_type": "skip"} info = {} # Dictonary holding per-sex lines info f_hand = open(file_loc) lines = f_hand.read().splitlines() for l in lines[1:]: l = l.strip() key = l[0] info.setdefault(key, []) info[key].append(tuple(l.split('\t'))) # + slideshow={"slide_type": "skip"} from pprint import pprint # pprint is for **pretty printing** structures pprint(info) # + slideshow={"slide_type": "skip"} max_male = max(info['M'], key=lambda e: float(e[2]) + float(e[3])) print(max_male) # + [markdown] slideshow={"slide_type": "skip"} # ### Sol. `#2`: Using a list comprehension # + slideshow={"slide_type": "skip"} ## Creating Partial Lists using **List Comprehension** males = [l.strip().split('\t') for l in lines[1:] if l.startswith('M')] females = [l.strip().split('\t') for l in lines[1:] if l.startswith('F')] # + slideshow={"slide_type": "skip"} males # + slideshow={"slide_type": "skip"} max_male = max(males, key=lambda e: float(e[2]) + float(e[3])) print(max_male) # + [markdown] slideshow={"slide_type": "skip"} # --- # + [markdown] slideshow={"slide_type": "slide"} # # The ```csv``` module # # Getting the data from a file and doing something with it is all well and good. However once we've done our analysis we usually want to save the results to another file. We can do this using base python but it's easier if we use a python **library**, in this case the [```csv```](http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/) library. We'll learn more about libraries in the next unit but for now just consider libraries as extra python code that you can get access to if you need it. In fact that's exactly what many libraries are. So the quesion arises 'how do we get access to a library?'. We have to tell python we want to use the library up front. To do this we use the ```import``` statement. # + slideshow={"slide_type": "subslide"} import csv # + [markdown] slideshow={"slide_type": "fragment"} # It's that simple! Now python makes available to us all the useful code in the ```csv``` library. The ```csv``` library, unsurprisingly, contains python functions and methods to make dealing with csv (and other) text files easier. Let's first see how to open a text file using the ```csv``` library and printing out the first few lines. # # To read data from a csv file, we use the ```reader()``` function. The ```reader()``` function takes each line of the file and makes a ```reader``` object containing lists made up of each row in the input data. Objects in programming are containers for both data and methods that act on that data (a bit esoteric so don't worry if you don't quite get that). One method the ```reader``` object supports is the ```.next()``` method. We can use this to access each row at a time. Notably once we have processed the line it's gone from the ```reader``` object. # + [markdown] slideshow={"slide_type": "subslide"} # ## Note: # # From **here on**, we are going to keep using the `with/as` statement to handle I/O operations, namely **Context Manager** objects. # # For more information, see this [notebook](09 Exceptions.ipynb#ctx). # # # + slideshow={"slide_type": "skip"} # import csv - already done with open('data/elderlyHeightWeight.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter='\t') # define the field delimiter header = next(reader) print (header) print () # blank line for i in range(4): print (next(reader)) # print the first 4 lines after the header # + [markdown] slideshow={"slide_type": "subslide"} # We can see that the ```reader()``` function has processed each line into a single list element based on the field delimiter we supplied. Importantly also note that all the values are now of type ```str``` in each list (everything is in quotes). This is important if you want to do calculations on these values. # # Using the ```csv``` module makes it easy to select whole columns by selecting the data we want from the ```reader```. We'll use the ```.next()``` method to find the column order and then iterate over the rows with a ```for``` loop to pull out height and weight. # + slideshow={"slide_type": "subslide"} with open('data/elderlyHeightWeight.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter='\t') # define the field delimiter # use next() method on reader object to id the headers headers = next(reader) print(headers) # we now know weight index is 2, height index is 3 weight = ['Weight'] # list to hold data, put in header height = ['Height'] for row in reader: weight.append(row[2]) height.append(row[3]) print (weight) print (height) # + [markdown] slideshow={"slide_type": "skip"} # The ```iterable``` in the # # ``` # for... # ``` # # loop above is each row of the input file. From each row we simply capture the two values we want and add these to lists. We could then further process the data in these two lists. # + [markdown] slideshow={"slide_type": "slide"} # # Writing files # + [markdown] slideshow={"slide_type": "subslide"} # In order to open a file for writing we use the ```'w'``` parameter in our ```open()``` statement. Rather obviously ```'w'``` stands for write. If the file doesn't exist a new file is created with the given name and extension. # # Note that if the file exists then opening it with the ```'w'``` argument removes any data that was in the file and overwrites it with what you put in. This may not be what you wanted to do. We'll cover how you append data to a file without overwriting the contents shortly. # # Once we have an open file we can write data to it with the ```write()``` method applied to the file handle. # # Let's open a file and write some data to it. # + slideshow={"slide_type": "subslide"} with open('data/test.txt', 'w') as f_out: for i in range(10): line = 'Line ' + str(i) + '\n' f_out.write(line) # + [markdown] slideshow={"slide_type": "subslide"} # If you run the above code a new file should appear in your data directory (notice we opened the writeable file in the ```/data``` directory) called ```test.txt```. That file should have 10 lines in it with the word 'Line' and a number from 0-9. # # In the above code we first opened (created) the file ```test.txt``` and then ran through a range of numbers (from 0 to 9) using a ```for``` loop. At each iteration of the loop we concatenated (joined) the word 'Line' to the string representation of the number (note the use of ```str```) and a newline character. Finally we wrote each of the resulting strings to our new file. In the last line we closed the file. # + [markdown] slideshow={"slide_type": "slide"} # ## Putting it together! # # Write a script that uses the ```csv``` module to open a file after getting a filepath from the user. Use the script to open the ```elderlyHeightWeight.csv``` file. Write out a new file containing only male data. Remember to close all the files once your done. In addition include a ```try\except``` clause to handle the situation where the requested file doesn't exist. # # Hint: ```csv.reader``` objects are lists. Recall how you ```.join()``` lists elements into a string. # + [markdown] slideshow={"slide_type": "subslide"} # ## Adding data to an existing file # # As noted above if you open an existing file and write data to it all that pre-existing data gets over written. That's not usually what you want to do. In fact in general you probably never want to write to any file that has raw data you are going to analyse in it - because you might lose or screw-up your original data. Sometimes however you might want to add new measurements (perhaps taken over time) to an existing file. For these cases there's the ```'a'``` argument to the ```open()``` function. The ```a``` stands for append. Let's take the file containing only the male data we wrote in the last exercise, open it in append mode and write the female data to that file. # + slideshow={"slide_type": "subslide"} import csv # assumes your file was called male_data.tsv try: with open('data/male_data.tsv', 'a') as new_file, open('data/elderlyHeightWeight.csv', 'r') as f_hand: reader = csv.reader(f_hand, delimiter='\t') # define the field delimiter male_data = [line for line in reader if line[0] == 'M'] for line in male_data: new_file.write('\t'.join(line)+'\n') except FileNotFoundError: print('The file does not exist.')
11_external_files.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Scikit-Learn Classification # # - Pandas Documentation: http://pandas.pydata.org/ # - Scikit Learn Documentation: http://scikit-learn.org/stable/documentation.html # - Seaborn Documentation: http://seaborn.pydata.org/ # import pandas as pd import numpy as np # %matplotlib inline import matplotlib.pyplot as plt # ## 1. Read data from Files df = pd.read_csv('../data/geoloc_elev.csv') # ## 2. Quick Look at the data type(df) df.info() df.head() df.tail() df.describe() df['source'].value_counts() df['target'].value_counts() # ## 3. Visual exploration import seaborn as sns sns.pairplot(df, hue='target') # ## 4. Define target y = df['target'] y.head() # ## 5. Feature engineering raw_features = df.drop('target', axis='columns') raw_features.head() # ### 1-hot encoding X = pd.get_dummies(raw_features) X.head() # ## 6. Train/Test split # + from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=0) # - # ## 7. Fit a Decision Tree model # + from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier(max_depth=3, random_state=0) model.fit(X_train, y_train) # - # ## 8. Accuracy score on benchmark, train and test sets # + from sklearn.metrics import confusion_matrix, classification_report y_pred = model.predict(X_test) # + cm = confusion_matrix(y_test, y_pred) pd.DataFrame(cm, index=["Miss", "Hit"], columns=['pred_Miss', 'pred_Hit']) # - print(classification_report(y_test, y_pred)) # ## 10. Feature Importances importances = pd.Series(model.feature_importances_, index=X.columns) importances.plot(kind='barh') # ## 11. Display the decision boundary # + hticks = np.linspace(-2, 2, 101) vticks = np.linspace(-2, 2, 101) aa, bb = np.meshgrid(hticks, vticks) not_important = np.zeros((len(aa.ravel()), 4)) ab = np.c_[aa.ravel(), bb.ravel(), not_important] c = model.predict(ab) cc = c.reshape(aa.shape) ax = df.plot(kind='scatter', c='target', x='lat', y='lon', cmap='bwr') ax.contourf(aa, bb, cc, cmap='bwr', alpha=0.2) # - # ## Exercise # # # Iterate and improve on the decision tree model. Now you have a basic pipeline example. How can you improve the score? Try some of the following: # # 1. change some of the initialization parameters of the decision tree re run the code. # - Does the score change? # - Does the decision boundary change? # 2. try some other model like Logistic Regression, Random Forest, SVM, Naive Bayes or any other model you like from [here](http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html) # 3. what's the highest score you can get?
day_1/Lab_05_ML_Scikit_Learn_Classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: locus # language: python # name: locus # --- # # Storm Centering # by: <NAME> | correspondance: <EMAIL> | date: 06 May 2021 # # The notebook analyzes the spatial patterns of annaul daily maximum precipitation. It performs this analysis on the North Branch of the Potomac Watershed, using a dataset constructed from the Livneh data.$^{1}$ This dataset is constructed using by the <b>imports.py</b> contained in this module.</br> # # The analysis in this notebook: # 1. generates a single datafile for analysis, # 2. explores two different normalization routines, # 3. projects the normalized data across its first n prinicpal components, # 4. clusters the data (projected onto its first n principal components) around k-Means, <em>5...N subsquent steps will help us visualize, explore the results of the normalization, pca and clustering... </em></br> # # References: <br> # $^{1}$ <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, 2013: A Long-Term Hydrologically Based Dataset of Land Surface Fluxes and States for the Conterminous United States: Update and Extensions, Journal of Climate, 26, 9384โ€“9392. <br> # # + import statistics import numpy as np import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from kneed import KneeLocator import dataimports.livneh as livneh # - # ## Data # # The data being analyzed includes the annual maximum day of precipitation from 1915 through 2011 for the North Branch of the Potomac Watershed in Western Maryland, USA. # The data for each of these 97 days (between 1915 and 2011) contains the preciptation depth for all 130 livneh grid cells located within or intersected by the North Branch of the Potomac 8 digit Hydrologic Unit Code (HUC08) boundary. years = list(range(1915, 2012)) importpath: str = '/Users/johnkucharski/Documents/source/locus/data/livneh_1day_max/' # #### Grids Geometry # # This geometry of the 130 livneh grids clipped to the North Banch of the Potomac Watershed, is shown below. This is used for plotting. points = pd.read_csv(importpath + 'prec.1915.csv') points = points[['id', 'lat', 'lon']] grids = livneh.points2grids(livneh.convert2geodataframe(points)) grids = grids.sort_values(by = 'id') grids.head(2) # #### Annual Maximum Gridded Precipitation Data # # Below is the view of dataset containing the gridded daily annual maximum precipitation data. It is a 97 x 130 (year x grid cell) matrix. The sum of a row's columns (i.e. event) gives the total precipitation depth for the watershed on the day (row) being summed, # the sum of a columns row's gives the total precipitation recieved in that grid cell over the 97 days covered in the 97 year instrumental record. df = livneh.aggregateprocessedfiles(importpath, years).sort_index() df.rename_axis(None, inplace = True) #can't seem to get rid of the 'id' above the index df.head(2) # ## Methods # # The primary goal of this study is to identify significant patterns in the spatial distribution of extreme precipitation events for the North Branch of the Potomac Watershed. # A secondary goal is to prescribe these patterns to some hypothetical drivers: (1) orographics, (2) seasonal atmospheric flow patterns associated with extreme precipitation, and (3) storm types (i.e. midlatitude cyclone, tropical cyclone). # # To achieve these goals the data is: (1) normalized, then (2) a Principal Component Analysis (PCA) is performed, finally (3) the 97 observations are clustered around the principal components (identified in step 2). # # ### 1. Normalization Routines # <p>The data must be normalized, otherwise outliers will dominate the principal component analysis and clustering. # The data can reasonably be expected to contain outliers for several reasons: # # 1. Event Magnitudes - the events being analyzed represent annaul maximum days of precipitation. # Therefore, to one degree or another all of the events being analyzed are 'outliers' from the perspective of the underlying precipitation distribution. # Maximum annual precipitation values like these are typically fit to an extreme values distribution (EVD), used to model observations sampled from the tail of some other distribution (such as a gamma distribution of daily rainfall). # The EVDs model the asympotic behavior of the under distributions tail (or tails), therefore we should expect our 97 year sample to exhibit some of this asymptotic behanvior. # # 2. Spatial Outliers - one would expect precipitation totals to be higher at higher elevations, as adiabatic cooling forces more moisture to rain out of the air. # This orographic effect is likely to lead to some grid cells (or columns) with substaintially larger means and variability (perhaps). # Secondly, (I think) extreme preciptiation events over a "large" area, like the size of North Branch of the Potomac Watershed, to be dominated by advective synoptical (i.e. large) scale events. # These synoptic scale events are driven by specific patterns of atmopheric flow (cite Schlef). We seek to test if this mode of spatial variability drives different clusterings in the data (see secondary goals above).</p> # # Two normalization schemes are explored below. For simplicity they are refered to as: # (1) a "nieve" routine, and (2) a "hypothesis-based" routine. # Both normalization routines normalize the data using the equation: # # (x - $\mu$) / s # # where x is the observed rainfall total for the cell in the dataset, $\mu$ is the mean of the data being normalized, and s is the standard deviation (of the data being normalized). # The methods differ primarily in the data used to measure $\mu$ and s. # # #### a. Nieve Routine # # The "nieve" normalization routine applies the normalization equation to all rows and columns simultaneously. # Therefore, the mean: $/mu represents the average livneh grid cell total across all grid cells and events. # For instance, a value of 2 after this normalization routine indicates that precipitaiton is two standard deviation above the mean - in that grid cell, relative to all grid cells and all events. # This value might be product of: (a) an anomolously large event - in which case a dispropotionate share of the grid cells in that row would have postive values; # on the other hand, (b) the value could be representative of a typically wet grid cells (due to orgographics or other factors) - in which case a disproportionate share of the cells in that column would have positive values; # or (c) it could indicate some combination of the two (an anomolously large event and anomolously wet grid cell). # This normalization scheme provide an emperical view of the data. # # <em> A programming note: The original data is 97 rows (years) x 130 columns (grid cells). # I want the PCA to reduce the time or observational dimension (find a more parsimonious pattern that describes the 'types' annual max events). # So, (I think) I have to transpose the dataset because the PCA will reduce the dimensionality of the columns (reduce the number of columns). # After transposing I have 130 rows (grid cells) x 97 columns (years)</em> nieve_std = StandardScaler().fit_transform(df.to_numpy()).T # generates a normalized dataset a 130 (grid cells) x 97 (columns) numpy array # this seems to drop the index values which is what we want. print(nieve_std.shape) # #### b. Hypothesis-based Routine # # The "hypothesis-based" normalization routine is a two step process. # # 1. Events (or rows) of data are normalized. # In this step, $/mu$ represents an average grid cell's precipitation <em>during that event</em>. # The resulting values express the livneh grid cell's precipitation in deviations from the mean grid cell precipitaiton, <em>during that event</em>. # For example, a value of 2 after this normalization scheme would indicate that a livneh grid cell contains a precipitation total which was 2 standard deviations above the mean grid cell total for that particular row's event. # # <em>TODO: I think it could be valuable to also consider clustering pcs generated from this dataset, since this should capture the combined orographic + atmospheric flow patterns of precipitation.</em> def standardize_events(df: pd.DataFrame) -> pd.DataFrame: ''' Normalizes the row data using the formula: (x - u) / s, where x is a value in one of the row's columns, u is the row mean and s is the row standard deviation. Assumes each row contains an list of the grid cell precipitaiton values for a particular event or year. The resulting dataframe reports precipitation values for each grid cell in terms of unit variance for that event's grid cell values. The idea is that this normalization capture both normal orographically influenced spatial patterns as well as spatial characteristics of the storm. If these values are averaged across all events or years it should provide information about the normal (orographically influenced) spatial patterns in the rainfall. ''' new_df = pd.DataFrame(columns = df.columns) for index, row in df.iterrows(): data = list(row) u = statistics.mean(data) s = statistics.stdev(data) new_row: list = [] for x in data: new_row.append((x - u) / s) new_df.loc[index] = new_row return new_df # 2. Columns (or livneh grid cell) values are normalized. # In the example above, I hypothesize that the value of 2 (or whatever value is found) may <em>not</em> be as anomolious as it would seem on face value. # Perhaps, the grid cell is located in a zone of extreme orographic lift, and as a result it tends to recieve much more than an average grid cell amount of rain - across all 97 days in the analysis. # In this case, the value of 2 may be an average value <em>for that grid cell</em> to help disentangle the orographic and storm centering patterns impact on rainfall totals we normalize this column of data. # If in fact the value 2 in the first step was a local (i.e. grid cell average) we wil be left with a data set that describes the deviations from this localized average in standard deviation unit. # For example, now a value of 2 would represent an anomolously high rainfall total <em>for that grid cell</em> based on its average across all event in the period of analysis. def standardize_grids(df: pd.DataFrame) -> pd.DataFrame: ''' Normalizes the column data using the formula: (x - u) / s, where x is a value in a row of one of the columns, u is the column mean and s is the column standard deviation. Assumes each column contains an list of a grid cell precipitaiton values for all the events or years of interest. If the events have been standardized then this will report precipitation values for each grid cell as deviations (of unit variance) of that specific grid cell's normalized portion of the event total. The idea is that this process of standardizing by event and then standardizing by grid cell should provide deviations from the normal (oragraphically influenced) spatial characteristics of rainfall patterns in the watershed. If the events have NOT been standarized first then the standarized results will be heavily influenced by the size of the event, rather than the spatial characteristics fo the storm. ''' new_df = pd.DataFrame(index = df.index) for name, col in df.iteritems(): data = list(col) u = statistics.mean(data) s = statistics.stdev(data) new_col: list = [] for x in data: new_col.append((x - u) / s) new_df[name] = new_col return new_df hypothesis_std = standardize_grids(standardize_events(df)).to_numpy().T print(hypothesis_std.shape) # #### c. Comparison of Normalization Routines # # The plots below explore the coorelation between the <b>nieve</b> and <b>hypothesis-based</b> routines results. This comparision is carried forward in subsequent steps of the analysis. fig, axs = plt.subplots(nrows=10, ncols=2, figsize=(10, 35), sharex='col') row, col = 0, 0 # plots the fist 10 years of data for i in range(0, 10): col = 0 axs[row, col].set_ylim([-3, 3]) axs[row, col].plot(nieve_std[:,i], label = 'nieve') axs[row, col].plot(hypothesis_std[:,i], label = 'hypothesis-based') axs[row, col].set_ylabel('Normalized Precipitation Value') leg = axs[row, col].legend(loc='upper right', frameon=False) col += 1 axs[row, col].set_xlim([-3, 3]) axs[row, col].set_ylim([-3, 3]) axs[row, col].scatter(nieve_std[:,i], hypothesis_std[:,i], facecolors='none', edgecolors='blue') axs[row, col].plot([-3, 3], [-3, 3], 'k:') axs[row, col].set_ylabel('Nieve Value') row += 1 axs[9, 0].set_xlabel('Grid Cell Id') axs[9, 1].set_xlabel('Hypothesis Value') # lines, labels = fig.axes[-1].get_legend_handles_labels() # fig.legend(lines, labels, loc = 'upper center') plt.show() # ### 2. PCA Analysis # # Two principal component analyses are performed. # # 1. The PCA is performed on the time (or observational) dimension of both normalized data sets. This should identify some event patterns, that describe variability in the spatial distribution of precipitation across the 97 events. Actual patterns of events may incorporate more than one of these patterns, these are identfied with the k-Means clustering algorithm. # # 2. To prepare the data for the k-Means clustering the PCA analysis is performed on the spatial (i.e. grid cell) dimension of both normalized data sets. This reduces the dimensionality of the events (by summarizing variabiltiy acorss the 130 livneh grid cells), improving the clustering algorithm. # # #### a. Performed on "Nieve"ly normalized data nieve_pca = PCA(n_components=20) nieve_pcs = nieve_pca.fit_transform(StandardScaler().fit_transform(nieve_std)) df_nieve_pcs = pd.DataFrame(nieve_pcs) df_nieve_pcs.head(2) # now if I take each column and attach the grid cell geometries to it I should be able to plot it again nieve_grids = grids.copy(deep = True) for i in range(0, nieve_pcs.shape[1]): nieve_grids['pc_' + str(i + 1)] = nieve_pcs[:,i] nieve_grids.head(1) # #### b. Performed on "Hypothesis-based" normalized data hypothesis_pca = PCA(n_components=20) hypothesis_pcs = hypothesis_pca.fit_transform(StandardScaler().fit_transform(hypothesis_std)) df_hypothesis_pcs = pd.DataFrame(hypothesis_pcs) df_hypothesis_pcs.head(2) hypothesis_grids = grids.copy(deep = True) for i in range(0, hypothesis_pcs.shape[1]): hypothesis_grids['pc_' + str(i + 1)] = hypothesis_pcs[:,i] hypothesis_grids.head(1) # #### c. Comparision of "Nieve" and "Hypothesis-based" PCA # # The figures below compare the principal component analysis under the 'nieve' and 'hypothesis-based' normalization routines. The first 2 principal components explain more than half the variation in the data. 3 principal components under either normalization routine explain almost 70% of the variation in the data, 9 principal components are required to explain 90% of the variation in the data. fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (10, 10), sharex = True, sharey = True) ax.plot(np.cumsum(nieve_pca.explained_variance_ratio_), marker='o', linestyle='dashed', alpha=0.8, label = 'nieve') ax.plot(np.cumsum(hypothesis_pca.explained_variance_ratio_), marker='o', linestyle='dashed', alpha=0.8, label = 'hypothesis-based') ax.hlines(y=0.9, xmin=0, xmax=20, linestyle = 'dashed', color = 'black', alpha=0.5, label = '90% variance') ax.set_xlabel('number of components') ax.set_ylabel('cumulative explained variance') ax.set_title('PCA explained variance') ax.set_xlim([0, 20]) ax.set_ylim([0.3, 1.0]) plt.yticks(np.arange(0.3, 1.0, 0.2)) plt.xticks(np.arange(0, 20, 1.0)) plt.legend(frameon=False) plt.show() difference_grids = grids.copy(deep = True) difference_pcs = np.absolute(nieve_pcs - hypothesis_pcs) for i in range(0, difference_pcs.shape[1]): difference_grids['pc_' + str(i + 1)] = difference_pcs[:,i] difference_grids.head(1) # The first 2 principal components display obvious spatial patterns <em>(see below)</em>: # * PC1 show anamolously high rainfall in the southern region, # * PC2 shows anomolously high precipitation in the central region of the watershed. # * PC3 shows opposite patterns depending on the normolizaiton routine. Under the nieve approach, precipitation is anolomously high along the eastern edge of the watershed, under the hypothesis based approch it is anomolously high along the western watershed boundary. fig, axs = plt.subplots(nrows = 20, ncols = 3, figsize = (15, 90), sharex = True, sharey = True) for i in range(0, 20): col_name = 'pc_' + str(i + 1) nieve_grids.plot(ax = axs[i, 0], column = col_name, vmin=-8, vmax=8, legend = True) hypothesis_grids.plot(ax = axs[i, 1], column = col_name, vmin=-8, vmax=8, legend = True) difference_grids.plot(ax = axs[i, 2], column = col_name, vmin=-8, vmax=8, legend = True) if i == 0: axs[i, 0].set_title('Nieve') axs[i, 1].set_title('PC 1 \n Hypothesis Based') axs[i, 2].set_title('Difference') else: axs[i, 1].set_title('PC ' + str(i + 1)) # #### d. Spatial (grid cell) dimensionality reduction # # This subsection performs a PCA to reduce the dimenionality of the spatial (grid cell) data. This is not as easly to visualize since it reduces the 130 grid cells to a set of 20 PCAs (rathan reducing the number of events). # + nieve_spatial_pca = PCA(n_components=20) nieve_spatial_pcs = nieve_spatial_pca.fit_transform(StandardScaler().fit_transform(nieve_std.T)) hypothesis_spatial_pca = PCA(n_components=20) hypothesis_spatial_pcs = hypothesis_spatial_pca.fit_transform(StandardScaler().fit_transform(hypothesis_std.T)) # - fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (10, 10), sharex = True, sharey = True) ax.plot(np.cumsum(nieve_spatial_pca.explained_variance_ratio_), marker='o', linestyle='dashed', alpha=0.8, label = 'nieve') ax.plot(np.cumsum(hypothesis_spatial_pca.explained_variance_ratio_), marker='o', linestyle='dashed', alpha=0.8, label = 'hypothesis-based') ax.hlines(y=0.9, xmin=0, xmax=20, linestyle = 'dashed', color = 'black', alpha=0.5, label = '90% variance') ax.set_xlabel('number of components') ax.set_ylabel('cumulative explained variance') ax.set_title('PCA explained variance') ax.set_xlim([0, 20]) ax.set_ylim([0.3, 1.0]) plt.yticks(np.arange(0.3, 1.0, 0.2)) plt.xticks(np.arange(0, 20, 1.0)) plt.legend(frameon=False) plt.show() # Each PC in the data normalized with the 'nieve' routine, explains more variance than the PCs in the data normalized with the hypothesis-based routine. # This is perhaps not surprising since the nieve approach, retains orographic influences in grid cell precipitaiton totals and the hypothesis-based approach does not. # The difference between the to methods may be explainatory power of elevation on grid cell precipitation. # Between the two methods notice the different y-intercept and relatively similiar slope across the first few PCs. # ## 3. Clustering # # Somehow the sum of squared error increases (foreach value of k) for larger number of PCs. # I don't understand it, but for this reason I use only the first 4 PCs. nieve_sse = [] hypothesis_sse = [] for k in range(1, 11): nieve_kmeans = KMeans(n_clusters = k) nieve_kmeans.fit(nieve_spatial_pcs[:,:4]) nieve_sse.append(nieve_kmeans.inertia_) hypothesis_kmeans = KMeans(n_clusters = k) hypothesis_kmeans.fit(hypothesis_spatial_pcs[:, :4]) hypothesis_sse.append(hypothesis_kmeans.inertia_) fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (10, 5)) ax.plot(range(1, 11), nieve_sse, marker = 'o', linestyle = 'dashed', color = 'cornflowerblue', label = 'nieve normalization') ax.plot(range(1, 11), hypothesis_sse, marker = 'o', linestyle = 'dashed', color = 'darkorange', label = 'hypothesis based normalization') ax.set_xticks(list(range(1, 11))) ax.set_xlabel('Number of Clusters') ax.set_ylabel('Sum of Squared Error') ax.set_title('Kmeans Performance by number of clusters') plt.legend() plt.show() # A needle algorithm from kneed is used to identify an 'elbow' in the function. # This is a point of diminishing returns, in this case for the the 'k', sse relationship. # This can also be checked visually, so in this case the kneed algorithm confirms what is the figure demonstrates. nieve_kl = KneeLocator(range(1, 11), nieve_sse, curve="convex", direction="decreasing") hypothesis_kl = KneeLocator(range(1, 11), hypothesis_sse, curve="convex", direction="decreasing") print(nieve_kl.elbow) print(hypothesis_kl.elbow) # + nieve_kmeans = KMeans(n_clusters = 4) nieve_clusters = nieve_kmeans.fit(nieve_spatial_pcs[:,:4]) nieve_cluster_labels = nieve_clusters.labels_ hypothesis_kmeans = KMeans(n_clusters = 4) hypothesis_clusters = hypothesis_kmeans.fit(hypothesis_spatial_pcs[:,:4]) hypothesis_cluster_labels = hypothesis_clusters.labels_ df['nieve_cluster'] = nieve_cluster_labels df['hypothesis_cluster'] = hypothesis_cluster_labels df.head(2) # - dfs = [] for routine in ['nieve', 'hypothesis']: cluster_means = grids.copy(deep = True) for i in range(0, 4): labels = routine + '_cluster' _df = df[df[labels] == i] _cluster_mean = np.zeros(130) for j in range(0, len(_cluster_mean)): _cluster_mean[j] = _df[j].mean() cluster_means[i] = _cluster_mean dfs.append(cluster_means) dfs[1].head(2) # + row = 0 fig, axs = plt.subplots(nrows = 4, ncols = 4, figsize = (15, 10), sharex = True, sharey = True) for i in range(2): for j in range(4): dfs[i].plot(ax = axs[row + 0, j], column = j, vmin = 20, vmax = 110, legend = True) dfs[i].plot(ax = axs[row + 1, j], column = j, legend = True) axs[0, j].set_title(j) row = 2 # for i in range(0, 4): # cluster_means.plot(ax = axs[0, i], column = i, vmin = 20, vmax = 110, legend = True) # cluster_means.plot(ax = axs[1, i], column = i, legend = True) # axs[0, i].set_title(i) # - events = livneh.eventdates(importpath, years) events['nieve_cluster'] = nieve_cluster_labels events['hypothesis_cluster'] = hypothesis_cluster_labels events.head(2) # + bins = list(range(1, 13)) fig, axs = plt.subplots(nrows = 4, ncols = 2, figsize=(15, 15), sharex = True) for j in range(2): if j == 0: label = 'nieve_cluster' else: label = 'hypothesis_cluster' for i in range(4): axs[i, j].hist(events[events[label] == i].month, np.arange(1, 13 + 1, 1), facecolor = 'lightcyan', edgecolor = 'blue') #axs[i, j].set_xticks(bins) axs[i, j].set_xlabel('month') axs[i, j].set_ylabel('count') if i == 0: axs[i, j].set_title(label + '\n cluster = ' + str(i)) else: axs[i, j].set_title('cluster = ' + str(i)) fig.tight_layout() # for i in range(0, 5): # if i == 4: # axs[i].hist(events.month, facecolor = 'lightcyan', edgecolor = 'blue') # axs[i].set_title('All Events') # else: # axs[i].hist(events[events.cluster == i].month, facecolor = 'lightcyan', edgecolor = 'blue') # axs[i].set_title('Cluster = ' + str(i)) # axs[i].set_xlabel('Month') # axs[i].set_ylabel('Storm Count') # axs[i].set_xlim([1, 12]) # #axs[i].set_ylim([0,14]) # fig.tight_layout() # -
src/locus.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + from scipy.special import sph_harm import numpy as np import matplotlib.pyplot as plt from skimage import measure import meshplot as mp # - # # Note: # order = m, it varies fast - `m<=np.abs(l)` # # degree = l, it varies slow - `l>=1`. # # Atomic orbitals go like 2l+1 # https://en.wikipedia.org/wiki/Cubic_harmonic # # # + ## start by taking an xyz grid of the unit cube: spacing = 0.005 #quite fine resolution - slow! a,b,c = np.meshgrid( np.arange(0,2, spacing)-1, np.arange(0,2, spacing)-1, np.arange(0,2, spacing)-1, indexing='ij' ) #shape (-1, 3) array of points: pts = np.vstack([a.ravel(),b.ravel(),c.ravel()]).T # + ## then (temporarily) convert this into spherical coordinates def asSpherical(xyz): """Convert xyz points to spherical coordinates (r, theta, phi)""" #takes list xyz (single coord) x = xyz[:,0]+0.00 y = xyz[:,1]+0.00 z = xyz[:,2]+0.00 r = np.sqrt(x*x + y*y + z*z) theta = np.arccos(z/r) #to degrees phi = np.arctan2(y,x) return r, theta, phi r, theta, phi = asSpherical(pts) #replace NaNs with 0 n = 0 theta[np.isnan(theta)]=n phi[np.isnan(phi)]=n # + ## choose one of the spherical harmonics # remember l>=1, m<=abs(l) l = 15 m = 13 #calculate the value of the harmonic on the unit sphere at all of #the angular coordinates (note 'r' is ignored, hence this is #evaluated on the unit sphere): sph_vals = sph_harm(m, l, phi, theta).real #now ask whether the value of the harmonic function is greater than #or less than 'r'. This tell us if a point (r,theta,phi) is 'outside' #the surface of the harmonic or 'inside' it. diffs = r - np.abs(sph_vals) g = diffs.reshape(a.shape) # + ## finally, we have a grid of values measuring their # distance to the implicit surface of a spherical harmonic. # AKA a signed distance function, so we can apply marching cubes # to find the isosurface. v1, f1, _, _ = measure.marching_cubes(g, 0) # before plotting, we do want to know the value of the harmonic. # I took the absolute values earlier in order to determine the isosurface, # but now that we have vertices we can just ask whether they are negative # or positive. #convert grid coordinates into universe coordinates: v1_univ = v1 * spacing - 1 #convert to spherical: r_v1, theta_v1, phi_v1 = asSpherical(v1_univ) #evaluate cols = sph_harm(m, l, phi_v1, theta_v1).real cols[np.isnan(cols)]=0 #plot! mp.offline() mp.plot(v1, f1, c=cols, filename='./spherical_harmonics.html') # -
spherical_harmonics/mesh_spherical_harmonics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) # # <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Health/CALM/CALM-moving-out-3.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> # # CALM - Moving Out 3 # ## Part 3 - Accommodation # # ๐Ÿ“šYou will need somewhere to live. Think about the advantages and disadvantages of an [apartment](https://en.wikipedia.org/wiki/Apartment), [townhouse](https://simple.wikipedia.org/wiki/Townhouse)/[duplex](https://en.wikipedia.org/wiki/Duplex_(building)), and a [single detached house](https://en.wikipedia.org/wiki/Single-family_detached_home) and record your thoughts in the cell below. Remember to `Run` the cell once you have finished. # + # %%writefile moving_out_2.txt โœ๏ธ Advantages of an Apartment 1. 2. 3. Disadvantages of an Apartment 1. 2. 3. Advantages of a Townhouse or Duplex 1. 2. 3. Disadvantages of a Townhouse or Duplex 1. 2. 3. Advantages of a Single Detatched House 1. 2. 3. Disadvantages of a Single Detatched House 1. 2. 3. The best choice of housing for a retired couple with no children who do not want to cut grass or do other maintenance is because The best choice of housing for a middle-aged couple with two small children who what room for children and friends to visit is because The best choice of housing for a young couple with a small child is because The best choice of housing for a young, single person who travels frequently for work is because The type of home I picture myself in when I decide to move out is (be descriptive) # - # ### Finding a Rental Home # # ๐Ÿ“šFor the purpose of this project you will consider rental properties only. Find an online listing (e.g. from [Kijiji](https://www.kijiji.ca/)) for a suitable place to rent in the area you would like to live. # # Carefully read the listing and fill in the information in the following cell, and `Run` the cell once you have finished. # + # %%writefile moving_out_3.txt โœ๏ธ Link to listing: Address: Type of accomodation: Rent per month: Utilities included in rent: Damage deposit or security deposit amount: Other costs not included in rent (e.g. parking, coin laundry): Summary of other important information: # - # ### Roommate # # ๐Ÿ“šSome expenses can be decreased by having a roommate. For the purposes of this project you may choose to have one roommate. Complete the statements then `Run` the cell below. # + # %%writefile moving_out_4.txt โœ๏ธ Advantages of living on my own are: 1. 2. 3. Disadvantages of living on my own are: 1. 2. 3. Advantages of living with a roommate are: 1. 2. 3. Disadvantages of living with a roommate are: 1. 2. 3. I have decided to live (on my own / with a roommate) because Essential characteristics of a roommate are: 1. 2. 3. 4. # - # ### Moving Expenses # ๐Ÿ“šThere are one-time moving expenses to consider. Follow the instructions in the code cell below to edit the numbers, then run the cell to calculate and store your expenses. # + #โœ๏ธ # If you plan to have a roommate, change this to a 1 instead of a 0 roommate = 0 # Security Deposit or Damage Deposit: this is usually equal to one month's rent. # You can get your deposit back when you move out, if you take care of your home. # Some landlords also charge a non-refundable pet fee. damageDeposit = 0 petFee = 0 # If you plan to have a pet, estimate the cost of the pet, toys, furniture, etc. petPurchase = 1000 # There are sometimes utility activation or hookup costs electricalActivation = 10 naturalGasActivation = 10 waterActivation = 0 internetActivation = 0 mobilePhoneActivitation = 25 mobilePhonePurchase = 300 furnitureAndAppliances = 500 movingCosts = 300 # ๐Ÿ“š You've finished editing numbers, now run the cell to calculate and store expenses if roommate == 1: movingExpenses = ( damageDeposit + electricalActivation + naturalGasActivation + waterActivation + internetActivation + furnitureAndAppliances ) / 2 + mobilePhoneActivitation + mobilePhonePurchase + movingCosts + petFee + petPurchase else: movingExpenses = ( damageDeposit + electricalActivation + naturalGasActivation + waterActivation + internetActivation + furnitureAndAppliances + mobilePhoneActivitation + mobilePhonePurchase + movingCosts + petFee + petPurchase ) # %store roommate # %store movingExpenses print('Moving expenses will be about $' + str(movingExpenses)) # - # ๐Ÿ“š`Run` the next cell to check that your answers have been stored. If you get an error, make sure that you have run all of the previous code cells in this notebook. #๐Ÿ“š Run this cell to check that your answers have been stored. print('Roommate:', roommate) print('Moving expenses:', movingExpenses) with open('moving_out_2.txt', 'r') as file2: print(file2.read()) with open('moving_out_3.txt', 'r') as file3: print(file3.read()) with open('moving_out_4.txt', 'r') as file4: print(file4.read()) # ๐Ÿ“šYou have now completed this section. Proceed to [section 4](./CALM-moving-out-4.ipynb) # [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
_build/html/_sources/curriculum-notebooks/Health/CALM/CALM-moving-out-3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] colab_type="text" id="W_tvPdyfA-BL" # ##### Copyright 2018 The TensorFlow Authors. # + cellView="form" colab={} colab_type="code" id="0O_LFhwSBCjm" #@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. # + [markdown] colab_type="text" id="UjKgoB2v_Qt2" # # ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ์™€ ์ „์ดํ•™์Šต # + [markdown] colab_type="text" id="PWUmcKKjtwXL" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> # </td> # </table> # + [markdown] colab_type="text" id="bBxnTS5bBk2d" # Note: ์ด ๋ฌธ์„œ๋Š” ํ…์„œํ”Œ๋กœ ์ปค๋ฎค๋‹ˆํ‹ฐ์—์„œ ๋ฒˆ์—ญํ–ˆ์Šต๋‹ˆ๋‹ค. ์ปค๋ฎค๋‹ˆํ‹ฐ ๋ฒˆ์—ญ ํ™œ๋™์˜ ํŠน์„ฑ์ƒ ์ •ํ™•ํ•œ ๋ฒˆ์—ญ๊ณผ ์ตœ์‹  ๋‚ด์šฉ์„ ๋ฐ˜์˜ํ•˜๊ธฐ ์œ„ํ•ด ๋…ธ๋ ฅํ•จ์—๋„ # ๋ถˆ๊ตฌํ•˜๊ณ  [๊ณต์‹ ์˜๋ฌธ ๋ฌธ์„œ](https://www.tensorflow.org/?hl=en)์˜ ๋‚ด์šฉ๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # ์ด ๋ฒˆ์—ญ์— ๊ฐœ์„ ํ•  ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด # [tensorflow/docs-l10n](https://github.com/tensorflow/docs-l10n/) ๊นƒํ—™ ์ €์žฅ์†Œ๋กœ ํ’€ ๋ฆฌํ€˜์ŠคํŠธ๋ฅผ ๋ณด๋‚ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. # ๋ฌธ์„œ ๋ฒˆ์—ญ์ด๋‚˜ ๋ฆฌ๋ทฐ์— ์ฐธ์—ฌํ•˜๋ ค๋ฉด # [<EMAIL>](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ko)๋กœ # ๋ฉ”์ผ์„ ๋ณด๋‚ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. # + [markdown] colab_type="text" id="crU-iluJIEzw" # # # [ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ](http://tensorflow.org/hub)ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ๋Š” ์ด ์ „์— ํ•™์Šต๋œ ๋ชจ๋ธ๋“ค์˜ ์š”์†Œ๋“ค์„ ๊ณต์œ ํ•˜๋Š” ํ•˜๋‚˜์˜ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ํ•™์Šต๋œ ๋ชจ๋ธ๋“ค์˜ ๊ฒ€์ƒ‰๊ฐ€๋Šฅํ•œ ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•œ [ํ…์„œํ”Œ๋กœ ๋ชจ๋“ˆ ํ—ˆ๋ธŒ] (https://tfhub.dev/)๋ฅผ ๋ณด์„ธ์š”. ์ด ํŠœํ† ๋ฆฌ์–ผ์€ ์ž…์ฆํ•ฉ๋‹ˆ๋‹ค: # # 1. `tf.keras`๋กœ ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•. # 1. ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜๋ฅผ ํ•˜๋Š” ๋ฐฉ๋ฒ•. # 1. ๊ฐ„๋‹จํ•œ ์ „์ดํ•™์Šต์„ ํ•˜๋Š” ๋ฐฉ๋ฒ•. # + [markdown] colab_type="text" id="CKFUvuEho9Th" # ## ์„ค์น˜ํ•˜๊ธฐ # # + colab={} colab_type="code" id="OGNpmn43C0O6" from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib.pylab as plt try: # # %tensorflow_version only exists in Colab. # !pip install tf-nightly except Exception: pass import tensorflow as tf # + colab={} colab_type="code" id="s4Z9vFE1IQ2Q" # !pip install -U tf-hub-nightly import tensorflow_hub as hub from tensorflow.keras import layers # + [markdown] colab_type="text" id="s4YuF5HvpM1W" # ## ImageNet ๋ถ„๋ฅ˜๊ธฐ # # + [markdown] colab_type="text" id="xEY_Ow5loN6q" # ### ๋ถ„๋ฅ˜๊ธฐ ๋‹ค์šด๋กœ๋“œํ•˜๊ธฐ # # ์ด๋™ ๋„คํŠธ์›Œํฌ ์ปดํ“จํ„ฐ๋ฅผ ๋กœ๋“œํ•˜๊ธฐ ์œ„ํ•ด `hub.module`์„, ๊ทธ๋ฆฌ๊ณ  ํ•˜๋‚˜์˜ keras์ธต์œผ๋กœ ๊ฐ์‹ธ๊ธฐ ์œ„ํ•ด `tf.keras.layers.Lambda`๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”. Fthub.dev์˜ [ํ…์„œํ”Œ๋กœ2.0 ๋ฒ„์ „์˜ ์–‘๋ฆฝ ๊ฐ€๋Šฅํ•œ ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜๊ธฐ URL](https://tfhub.dev/s?q=tf2&module-type=image-classification) ๋Š” ์ด๊ณณ์—์„œ ์ž‘๋™ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. # + cellView="both" colab={} colab_type="code" id="feiXojVXAbI9" classifier_url ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/2" #@param {type:"string"} # + colab={} colab_type="code" id="y_6bGjoPtzau" IMAGE_SHAPE = (224, 224) classifier = tf.keras.Sequential([ hub.KerasLayer(classifier_url, input_shape=IMAGE_SHAPE+(3,)) ]) # + [markdown] colab_type="text" id="pwZXaoV0uXp2" # ### ์‹ฑ๊ธ€ ์ด๋ฏธ์ง€ ์‹คํ–‰์‹œํ‚ค๊ธฐ # # + [markdown] colab_type="text" id="TQItP1i55-di" # ๋ชจ๋ธ์„ ์‹œ๋„ํ•˜๊ธฐ ์œ„ํ•ด ์‹ฑ๊ธ€ ์ด๋ฏธ์ง€๋ฅผ ๋‹ค์šด๋กœ๋“œํ•˜์„ธ์š”. # + colab={} colab_type="code" id="w5wDjXNjuXGD" import numpy as np import PIL.Image as Image grace_hopper = tf.keras.utils.get_file('image.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg') grace_hopper = Image.open(grace_hopper).resize(IMAGE_SHAPE) grace_hopper # + colab={} colab_type="code" id="BEmmBnGbLxPp" grace_hopper = np.array(grace_hopper)/255.0 grace_hopper.shape # + [markdown] colab_type="text" id="0Ic8OEEo2b73" # ์ฐจ์› ๋ฐฐ์น˜๋ฅผ ์ถ”๊ฐ€ํ•˜์„ธ์š”, ๊ทธ๋ฆฌ๊ณ  ์ด๋ฏธ์ง€๋ฅผ ๋ชจ๋ธ์— ํ†ต๊ณผ์‹œํ‚ค์„ธ์š”. # + colab={} colab_type="code" id="EMquyn29v8q3" result = classifier.predict(grace_hopper[np.newaxis, ...]) result.shape # + [markdown] colab_type="text" id="NKzjqENF6jDF" # ๊ทธ ๊ฒฐ๊ณผ๋Š” ๋กœ์ง€ํŠธ์˜ 1001 ์š”์†Œ ๋ฒกํ„ฐ์ž…๋‹ˆ๋‹ค. ์ด๋Š” ์ด๋ฏธ์ง€์— ๋Œ€ํ•œ ๊ฐ๊ฐ์˜ ํด๋ž˜์Šค ํ™•๋ฅ ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. # # ๊ทธ๋ž˜์„œ ํƒ‘ ํด๋ž˜์Šค์ธ ID๋Š” ์ตœ๋Œ€๊ฐ’์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค: # + colab={} colab_type="code" id="rgXb44vt6goJ" predicted_class = np.argmax(result[0], axis=-1) predicted_class # + [markdown] colab_type="text" id="YrxLMajMoxkf" # ### ์˜ˆ์ธก ํ•ด๋…ํ•˜๊ธฐ # # ์šฐ๋ฆฌ๋Š” ํด๋ž˜์Šค ID๋ฅผ ์˜ˆ์ธกํ•˜๊ณ , # `ImageNet`๋ผ๋ฒจ์„ ๋ถˆ๋Ÿฌ์˜ค๊ณ , ๊ทธ๋ฆฌ๊ณ  ์˜ˆ์ธก์„ ํ•ด๋…ํ•ฉ๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="ij6SrDxcxzry" labels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt') imagenet_labels = np.array(open(labels_path).read().splitlines()) # + colab={} colab_type="code" id="uzziRK3Z2VQo" plt.imshow(grace_hopper) plt.axis('off') predicted_class_name = imagenet_labels[predicted_class] _ = plt.title("Prediction: " + predicted_class_name.title()) # + [markdown] colab_type="text" id="amfzqn1Oo7Om" # ## ๊ฐ„๋‹จํ•œ ์ „์ด ํ•™์Šต # # + [markdown] colab_type="text" id="K-nIpVJ94xrw" # ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ, ์šฐ๋ฆฌ์˜ ๋ฐ์ดํ„ฐ์…‹์— ์žˆ๋Š” ํด๋ž˜์Šค๋“ค์„ ์ธ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ๋ชจ๋ธ์˜ ์ตœ์ƒ์œ„ ์ธต์„ ์žฌํ•™์Šต ์‹œํ‚ค๋Š” ๊ฒƒ์ด ์‰ฌ์›Œ์กŒ์Šต๋‹ˆ๋‹ค. # + [markdown] colab_type="text" id="Z93vvAdGxDMD" # ### ๋ฐ์ดํ„ฐ์…‹ # # ์ด ์˜ˆ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด, ํ…์„œํ”Œ๋กœ์˜ flowers ๋ฐ์ดํ„ฐ์…‹์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค: # + colab={} colab_type="code" id="DrIUV3V0xDL_" data_root = tf.keras.utils.get_file( 'flower_photos','https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz', untar=True) # + [markdown] colab_type="text" id="jFHdp18ccah7" # ์šฐ๋ฆฌ์˜ ๋ชจ๋ธ์— ์ด ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์žฅ ๊ฐ„๋‹จํ•˜๊ฒŒ ๋กœ๋”ฉ ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ `tf.keras.preprocessing.image.image.ImageDataGenerator`๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๊ณ , # # ๋ชจ๋“  ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ์˜ ์ด๋ฏธ์ง€ ๋ชจ๋“ˆ๋“ค์€ 0๊ณผ 1์‚ฌ์ด์˜ ์ƒ์ˆ˜๋“ค์˜ ์ž…๋ ฅ์„ ๊ธฐ๋Œ€ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ๋งŒ์กฑ ์‹œํ‚ค๊ธฐ ์œ„ํ•ด `ImageDataGenerator`์˜ `rescale`์ธ์ž๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”. # # ๊ทธ ์ด๋ฏธ์ง€์˜ ์‚ฌ์ด์ฆˆ๋Š” ๋‚˜์ค‘์— ๋‹ค๋ค„์งˆ ๊ฒƒ์ž…๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="2PwQ_wYDcii9" image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255) image_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SHAPE) # + [markdown] colab_type="text" id="0p7iDOhIcqY2" # ๊ฒฐ๊ณผ๋กœ ๋‚˜์˜จ ์˜ค๋ธŒ์ ํŠธ๋Š” `image_batch`์™€ `label_batch`๋ฅผ ๊ฐ™์ด ๋ฆฌํ„ด ํ•˜๋Š” ๋ฐ˜๋ณต์ž์ž…๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="W4lDPkn2cpWZ" for image_batch, label_batch in image_data: print("Image batch shape: ", image_batch.shape) print("Label batch shape: ", label_batch.shape) break # + [markdown] colab_type="text" id="0gTN7M_GxDLx" # ### ์ด๋ฏธ์ง€ ๋ฐฐ์น˜์— ๋Œ€ํ•œ ๋ถ„๋ฅ˜๊ธฐ๋ฅผ ์‹คํ–‰ํ•ด๋ณด์ž # # + [markdown] colab_type="text" id="O3fvrZR8xDLv" # ์ด์ œ ์ด๋ฏธ์ง€ ๋ฐฐ์น˜์— ๋Œ€ํ•œ ๋ถ„๋ฅ˜๊ธฐ๋ฅผ ์‹คํ–‰ํ•ด๋ด…์‹œ๋‹ค. # + colab={} colab_type="code" id="nbyg6tcyxDLh" result_batch = classifier.predict(image_batch) result_batch.shape # + colab={} colab_type="code" id="Kv7ZwuR4xDLc" predicted_class_names = imagenet_labels[np.argmax(result_batch, axis=-1)] predicted_class_names # + [markdown] colab_type="text" id="QmvSWg9nxDLa" # ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ์˜ˆ์ธก๋“ค์ด ์ด๋ฏธ์ง€์— ๋งž๋Š”์ง€ ๊ฒ€ํ† ํ•ด๋ด…์‹œ๋‹ค: # + colab={} colab_type="code" id="IXTB22SpxDLP" plt.figure(figsize=(10,9)) plt.subplots_adjust(hspace=0.5) for n in range(30): plt.subplot(6,5,n+1) plt.imshow(image_batch[n]) plt.title(predicted_class_names[n]) plt.axis('off') _ = plt.suptitle("ImageNet predictions") # + [markdown] colab_type="text" id="FUa3YkvhxDLM" # ์ด๋ฏธ์ง€ ์†์„ฑ์„ ๊ฐ€์ง„ `LICENSE.txt` ํŒŒ์ผ์„ ๋ณด์„ธ์š”. # # ๊ฒฐ๊ณผ๊ฐ€ ์™„๋ฒฝ๊ณผ๋Š” ๊ฑฐ๋ฆฌ๊ฐ€ ๋ฉ€์ง€๋งŒ, ๋ชจ๋ธ์ด ("daisy"๋ฅผ ์ œ์™ธํ•œ) ๋ชจ๋“  ๊ฒƒ์„ ๋Œ€๋น„ํ•ด์„œ ํ•™์Šต๋œ ํด๋ž˜์Šค๊ฐ€ ์•„๋‹ˆ๋ผ๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•˜๋ฉด ํ•ฉ๋ฆฌ์ ์ž…๋‹ˆ๋‹ค. # + [markdown] colab_type="text" id="JzV457OXreQP" # ### ํ—ค๋“œ๋ฆฌ์Šค ๋ชจ๋ธ์„ ๋‹ค์šด๋กœ๋“œํ•˜์„ธ์š” # # ํ…์„œํ”Œ๋กœ ํ—ˆ๋ธŒ๋Š” ๋งจ ์œ„ ๋ถ„๋ฅ˜์ธต์ด ์—†์–ด๋„ ๋ชจ๋ธ์„ ๋ถ„๋ฐฐ ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ์ „์ด ํ•™์Šต์„ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค. # # fthub.dev์˜ [ํ…์„œํ”Œ๋กœ 2.0๋ฒ„์ „์˜ ์–‘๋ฆฝ ๊ฐ€๋Šฅํ•œ ์ด๋ฏธ์ง€ ํŠน์„ฑ ๋ฒกํ„ฐ URL](https://tfhub.dev/s?module-type=image-feature-vector&q=tf2) ์€ ๋ชจ๋‘ ์ด ๊ณณ์—์„œ ์ž‘๋™ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. # + cellView="both" colab={} colab_type="code" id="4bw8Jf94DSnP" feature_extractor_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2" #@param {type:"string"} # + [markdown] colab_type="text" id="sgwmHugQF-PD" # ํŠน์„ฑ ์ถ”์ถœ๊ธฐ๋ฅผ ๋งŒ๋“ค์–ด๋ด…์‹œ๋‹ค. # + colab={} colab_type="code" id="5wB030nezBwI" feature_extractor_layer = hub.KerasLayer(feature_extractor_url, input_shape=(224,224,3)) # + [markdown] colab_type="text" id="0QzVdu4ZhcDE" # ์ด ๊ฒƒ์€ ๊ฐ๊ฐ์˜ ์ด๋ฏธ์ง€๋งˆ๋‹ค ๊ธธ์ด๊ฐ€ 1280์ธ ๋ฒกํ„ฐ๊ฐ€ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค: # + colab={} colab_type="code" id="Of7i-35F09ls" feature_batch = feature_extractor_layer(image_batch) print(feature_batch.shape) # + [markdown] colab_type="text" id="CtFmF7A5E4tk" # ํŠน์„ฑ ์ถ”์ถœ๊ธฐ ๊ณ„์ธต์— ์žˆ๋Š” ๋ณ€์ˆ˜๋“ค์„ ๊ตณํžˆ๋ฉด, ํ•™์Šต์€ ์˜ค์ง ์ƒˆ๋กœ์šด ๋ถ„๋ฅ˜ ๊ณ„์ธต๋งŒ ๋ณ€๊ฒฝ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="Jg5ar6rcE4H-" feature_extractor_layer.trainable = False # + [markdown] colab_type="text" id="RPVeouTksO9q" # ### ๋ถ„๋ฅ˜ head๋ฅผ ๋ถ™์ด์„ธ์š”. # # ์ด์ œ `tf.keras.Sequential` ๋ชจ๋ธ์— ์žˆ๋Š” ํ—ˆ๋ธŒ ๊ณ„์ธต์„ ํฌ์žฅํ•˜๊ณ , ์ƒˆ๋กœ์šด ๋ถ„๋ฅ˜ ๊ณ„์ธต์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”. # + colab={} colab_type="code" id="mGcY27fY1q3Q" model = tf.keras.Sequential([ feature_extractor_layer, layers.Dense(image_data.num_classes, activation='softmax') ]) model.summary() # + colab={} colab_type="code" id="G9VkAz00HOJx" predictions = model(image_batch) # + colab={} colab_type="code" id="sB7sVGJ23vrY" predictions.shape # + [markdown] colab_type="text" id="OHbXQqIquFxQ" # ### ๋ชจ๋ธ์„ ํ•™์Šต์‹œํ‚ค์„ธ์š” # # ํ•™์Šต ๊ณผ์ • ํ™˜๊ฒฝ์„ ์„ค์ •ํ•˜๊ธฐ ์œ„ํ•ด ์ปดํŒŒ์ผ์„ ์‚ฌ์šฉํ•˜์„ธ์š”: # + colab={} colab_type="code" id="3n0Wb9ylKd8R" model.compile( optimizer=tf.keras.optimizers.Adam(), loss='categorical_crossentropy', metrics=['acc']) # + [markdown] colab_type="text" id="58-BLV7dupJA" # ์ด์ œ ๋ชจ๋ธ์„ ํ•™์Šต์‹œํ‚ค๊ธฐ ์œ„ํ•ด `.fit`๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์„ธ์š”. # # ์˜ˆ์ œ๋ฅผ ์งง๊ฒŒ ์œ ์ง€์‹œํ‚ค๊ธฐ ์œ„ํ•ด ์˜ค๋กœ์ง€ 2์„ธ๋Œ€๋งŒ ํ•™์Šต์‹œํ‚ค์„ธ์š”. ํ•™์Šต ๊ณผ์ •์„ ์‹œ๊ฐํ™”ํ•˜๊ธฐ ์œ„ํ•ด์„œ, ๋งž์ถคํ˜• ํšŒ์‹ ์„ ์‚ฌ์šฉํ•˜๋ฉด ์†์‹ค๊ณผ, ์„ธ๋Œ€ ํ‰๊ท ์ด ์•„๋‹Œ ๋ฐฐ์น˜ ๊ฐœ๋ณ„์˜ ์ •ํ™•๋„๋ฅผ ๊ธฐ๋กํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="jZ54Gubac4Lu" class CollectBatchStats(tf.keras.callbacks.Callback): def __init__(self): self.batch_losses = [] self.batch_acc = [] def on_train_batch_end(self, batch, logs=None): self.batch_losses.append(logs['loss']) self.batch_acc.append(logs['acc']) self.model.reset_metrics() # + colab={} colab_type="code" id="EyMDJxt2HdHr" steps_per_epoch = np.ceil(image_data.samples/image_data.batch_size) batch_stats_callback = CollectBatchStats() history = model.fit_generator(image_data, epochs=2, steps_per_epoch=steps_per_epoch, callbacks = [batch_stats_callback]) # + [markdown] colab_type="text" id="Kd0N272B9Q0b" # ์ง€๊ธˆ๋ถ€ํ„ฐ, ๋‹จ์ˆœํ•œ ํ•™์Šต ๋ฐ˜๋ณต์ด์ง€๋งŒ, ์šฐ๋ฆฌ๋Š” ํ•ญ์ƒ ๋ชจ๋ธ์ด ํ”„๋กœ์„ธ์Šค๋ฅผ ๋งŒ๋“œ๋Š” ์ค‘์ด๋ผ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # + colab={} colab_type="code" id="A5RfS1QIIP-P" plt.figure() plt.ylabel("Loss") plt.xlabel("Training Steps") plt.ylim([0,2]) plt.plot(batch_stats_callback.batch_losses) # + colab={} colab_type="code" id="3uvX11avTiDg" plt.figure() plt.ylabel("Accuracy") plt.xlabel("Training Steps") plt.ylim([0,1]) plt.plot(batch_stats_callback.batch_acc) # + [markdown] colab_type="text" id="kb__ZN8uFn-D" # ### ์˜ˆ์ธก์„ ํ™•์ธํ•˜์„ธ์š” # # ์ด ์ „์˜ ๊ณ„ํš์„ ๋‹ค์‹œํ•˜๊ธฐ ์œ„ํ•ด์„œ, ํด๋ž˜์Šค ์ด๋ฆ„๋“ค์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ฒซ๋ฒˆ์งธ๋กœ ์–ป์œผ์„ธ์š”: # + colab={} colab_type="code" id="JGbEf5l1I4jz" class_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1]) class_names = np.array([key.title() for key, value in class_names]) class_names # + [markdown] colab_type="text" id="4Olg6MsNGJTL" # ๋ชจ๋ธ์„ ํ†ตํ•ด ์ด๋ฏธ์ง€ ๋ฐฐ์น˜๋ฅผ ์‹คํ–‰์‹œํ‚ค์„ธ์š”. ๊ทธ๋ฆฌ๊ณ  ์ธ๋ฑ์Šค๋“ค์„ ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ๋ฐ”๊พธ์„ธ์š”. # + colab={} colab_type="code" id="fCLVCpEjJ_VP" predicted_batch = model.predict(image_batch) predicted_id = np.argmax(predicted_batch, axis=-1) predicted_label_batch = class_names[predicted_id] # + [markdown] colab_type="text" id="CkGbZxl9GZs-" # ๊ฒฐ๊ณผ๋ฅผ ๊ณ„ํšํ•˜์„ธ์š” # + colab={} colab_type="code" id="rpFQR1MPMtT1" label_id = np.argmax(label_batch, axis=-1) # + colab={} colab_type="code" id="wC_AYRJU9NQe" plt.figure(figsize=(10,9)) plt.subplots_adjust(hspace=0.5) for n in range(30): plt.subplot(6,5,n+1) plt.imshow(image_batch[n]) color = "green" if predicted_id[n] == label_id[n] else "red" plt.title(predicted_label_batch[n].title(), color=color) plt.axis('off') _ = plt.suptitle("Model predictions (green: correct, red: incorrect)") # + [markdown] colab_type="text" id="uRcJnAABr22x" # ## ๋‹น์‹ ์˜ ๋ชจ๋ธ์„ ๋‚ด๋ณด๋‚ด์„ธ์š” # # ๋‹น์‹ ์€ ๋ชจ๋ธ์„ ํ•™์Šต์‹œ์ผœ์™”๊ธฐ ๋•Œ๋ฌธ์—, ์ €์žฅ๋œ ๋ชจ๋ธ์„ ๋‚ด๋ณด๋‚ด์„ธ์š”: # + colab={} colab_type="code" id="PLcqg-RmsLno" import time t = time.time() export_path = "/tmp/saved_models/{}".format(int(t)) model.save(export_path, save_format='tf') export_path # + [markdown] colab_type="text" id="AhQ9liIUsPsi" # ์ด์ œ ์šฐ๋ฆฌ๋Š” ๊ทธ๊ฒƒ์„ ์ƒˆ๋กญ๊ฒŒ ๋กœ๋”ฉ ํ•  ์ˆ˜ ์žˆ๊ณ , ์ด๋Š” ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ์ค„ ๊ฒƒ์ž…๋‹ˆ๋‹ค: # + colab={} colab_type="code" id="7nI5fvkAQvbS" reloaded = tf.keras.models.load_model(export_path) # + colab={} colab_type="code" id="jor83-LqI8xW" result_batch = model.predict(image_batch) reloaded_result_batch = reloaded.predict(image_batch) # + colab={} colab_type="code" id="dnZO14taYPH6" abs(reloaded_result_batch - result_batch).max() # + [markdown] colab_type="text" id="TYZd4MNiV3Rc" # ์ €์žฅ๋œ ๋ชจ๋ธ์€ ์ถ”ํ›„์— ์ถ”๋ก ์„ ํ•  ์ˆ˜๋„ ์žˆ๊ณ , [TFLite](https://www.tensorflow.org/lite/convert/) ๋‚˜ [TFjs](https://github.com/tensorflow/tfjs-converter) ๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # #
site/ko/tutorials/images/transfer_learning_with_hub.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/akshubhai/DataScience2021/blob/master/000_0010_EDA.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="-oiFV8C996s_" import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sb # + [markdown] id="uEFOaoDmZawL" # EDA IRIS # + colab={"base_uri": "https://localhost:8080/", "height": 722} id="BvQNd4O_ZaDy" outputId="61ea9873-83d0-43de-bfaf-2aebf80ece61" print(sb.get_dataset_names()) df = sb.load_dataset("iris") # display(df) print(df.shape, df.columns, df["species"].value_counts()) # Scatter plot basic df.plot(kind = "scatter", x= "sepal_length", y="sepal_width") plt.show() # Scatter plot advanced using seaborn sb.set_style("whitegrid") sb.FacetGrid(df, hue = "species", height = 4)\ .map(plt.scatter, "sepal_length", "sepal_width")\ .add_legend()
000_0010_EDA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + deletable=true editable=true from datapoint import DataPoint import numpy as np from bokeh.io import output_notebook, show from bokeh.plotting import figure from bokeh.models import HoverTool from bokeh.models import ColumnDataSource output_notebook() # + deletable=true editable=true def parse_in_data(file_path): """ Args: file_path R 8.46642 0.0287602 -3.04035 1477010443399637 8.6 0.25 -3.00029 0 (R) (rho) (phi) (drho) (timestamp) (real x) (real y) (real vx) (real vy) L 8.44818 0.251553 1477010443449633 8.45 0.25 -3.00027 0 (R) (x) (y) (timestamp) (real x) (real y) (real vx) (real vy) Returns: all_sensor_data, all_ground_truths - two lists of DataPoint() instances """ all_sensor_data = [] all_ground_truths = [] with open(file_path) as f: for line in f: data = line.split() if data[0] == 'L': sensor_data = DataPoint({ 'timestamp': int(data[3]), 'name': 'lidar', 'x': float(data[1]), 'y': float(data[2]) }) g = {'timestamp': int(data[3]), 'name': 'state', 'x': float(data[4]), 'y': float(data[5]), 'vx': float(data[6]), 'vy': float(data[7]) } ground_truth = DataPoint(g) elif data[0] == 'R': sensor_data = DataPoint({ 'timestamp': int(data[4]), 'name': 'radar', 'rho': float(data[1]), 'phi': float(data[2]), 'drho': float(data[3]) }) g = {'timestamp': int(data[4]), 'name': 'state', 'x': float(data[5]), 'y': float(data[6]), 'vx': float(data[7]), 'vy': float(data[8]) } ground_truth = DataPoint(g) all_sensor_data.append(sensor_data) all_ground_truths.append(ground_truth) return all_sensor_data, all_ground_truths # + deletable=true editable=true def parse_prediction_data(file_path): all_predictions = [] with open(file_path) as f: for line in f: data = line.split() p = {'timestamp': None, 'name': 'state', 'x': float(data[0]), 'y': float(data[1]), 'vx': float(data[2]), 'vy': float(data[3]) } all_predictions.append(DataPoint(p)) return all_predictions # + deletable=true editable=true all_sensor_data, all_ground_truths = parse_in_data("data/data-1.txt") all_state_estimations = parse_prediction_data("data/out-1-D.txt") # + deletable=true editable=true lidar_xs, lidar_ys = [], [] radar_xs, radar_ys, radar_angles = [], [], [] truth_xs, truth_ys, truth_angles = [], [], [] state_xs, state_ys, state_angles = [], [], [] for s, t, p in zip(all_sensor_data, all_ground_truths, all_state_estimations): if s.get_name() == "lidar": x, y = s.get_raw() lidar_xs.append(x) lidar_ys.append(y) else: x, y, vx, vy = s.get() angle = np.arctan2(vy, vx) radar_xs.append(x) radar_ys.append(y) radar_angles.append(angle) x, y, vx, vy = t.get() t_angle = np.arctan2(vy, vy) truth_xs.append(x) truth_ys.append(y) truth_angles.append(t_angle) x, y, vx, vy = p.get() p_angle = np.arctan2(vy, vx) state_xs.append(x) state_ys.append(y) state_angles.append(p_angle) # + deletable=true editable=true radar_source = ColumnDataSource(data = { 'x' : radar_xs, 'y' : radar_ys, 'angle': radar_angles, }) truth_source = ColumnDataSource(data = { 'x' : truth_xs, 'y' : truth_ys, 'angle': truth_angles, }) state_source = ColumnDataSource(data = { 'x' : state_xs, 'y' : state_ys, 'angle': truth_angles, }) lidar_source = ColumnDataSource(data = { 'x' : lidar_xs, 'y' : lidar_ys, }) # + deletable=true editable=true hover1 = HoverTool( tooltips = [ ("index", "$index"), ("x , y", "$x, $y"), ("angle radians", "@angle")]) p = figure(plot_width = 1000, plot_height = 700, tools = [hover1]) p.square( 'x', 'y', size = 5, fill_color = "orange", line_color = "orange", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "radar measurements", source = radar_source) p.circle( 'x', 'y', size = 15, fill_color = "green", line_color = "white", fill_alpha = 0.2, line_width = 1, legend = "lidar measurements", source = lidar_source) p.triangle( 'x', 'y', size = 7, fill_color = "violet", line_color = "violet", fill_alpha = 1, angle = 'angle', line_width = 0.5, legend = "ground truth", source = truth_source) p.triangle( 'x', 'y', size = 2, fill_color = "black", line_color = "black", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "state predictions", source = state_source) p.legend.location = "bottom_right" show(p) # + deletable=true editable=true hover2 = HoverTool( tooltips = [ ("index", "$index"), ("x , y", "$x, $y"), ("angle radians", "@angle")]) p = figure(plot_width = 1000, plot_height = 700, tools = [hover2]) p.square( 'x', 'y', size = 5, fill_color = "violet", line_color = "violet", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "radar measurements", source = radar_source) p.circle( 'x', 'y', size = 10, fill_color = "green", line_color = "white", fill_alpha = 0.4, line_width = 1, legend = "lidar measurements", source = lidar_source) p.line(state_xs, state_ys, line_width = 2, color='orange', legend = "state predictions") p.line(truth_xs, truth_ys, line_dash = "4 4", line_width = 1, color='navy', legend = "ground truth") p.legend.location = "bottom_right" show(p) # + deletable=true editable=true all_sensor_data, all_ground_truths = parse_in_data("data/data-2.txt") all_state_estimations = parse_prediction_data("data/out-2-D.txt") # + deletable=true editable=true lidar_xs, lidar_ys = [], [] radar_xs, radar_ys, radar_angles = [], [], [] truth_xs, truth_ys, truth_angles = [], [], [] state_xs, state_ys, state_angles = [], [], [] for s, t, p in zip(all_sensor_data, all_ground_truths, all_state_estimations): if s.get_name() == "lidar": x, y = s.get_raw() lidar_xs.append(x) lidar_ys.append(y) else: x, y, vx, vy = s.get() angle = np.arctan2(vy, vx) radar_xs.append(x) radar_ys.append(y) radar_angles.append(angle) x, y, vx, vy = t.get() t_angle = np.arctan2(vy, vy) truth_xs.append(x) truth_ys.append(y) truth_angles.append(t_angle) x, y, vx, vy = p.get() p_angle = np.arctan2(vy, vx) state_xs.append(x) state_ys.append(y) state_angles.append(p_angle) radar_source = ColumnDataSource(data = { 'x' : radar_xs, 'y' : radar_ys, 'angle': radar_angles, }) truth_source = ColumnDataSource(data = { 'x' : truth_xs, 'y' : truth_ys, 'angle': truth_angles, }) state_source = ColumnDataSource(data = { 'x' : state_xs, 'y' : state_ys, 'angle': truth_angles, }) lidar_source = ColumnDataSource(data = { 'x' : lidar_xs, 'y' : lidar_ys, }) # + deletable=true editable=true hover3 = HoverTool( tooltips = [ ("index", "$index"), ("x , y", "$x, $y"), ("angle radians", "@angle")]) p = figure(plot_width = 1000, plot_height = 700, tools = [hover3]) p.square( 'x', 'y', size = 5, fill_color = "orange", line_color = "orange", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "radar measurements", source = radar_source) p.circle( 'x', 'y', size = 15, fill_color = "green", line_color = "white", fill_alpha = 0.2, line_width = 1, legend = "lidar measurements", source = lidar_source) p.triangle( 'x', 'y', size = 7, fill_color = "violet", line_color = "violet", fill_alpha = 1, angle = 'angle', line_width = 0.5, legend = "ground truth", source = truth_source) p.triangle( 'x', 'y', size = 2, fill_color = "black", line_color = "black", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "state predictions", source = state_source) p.legend.location = "bottom_right" show(p) # + deletable=true editable=true hover4 = HoverTool( tooltips = [ ("index", "$index"), ("x , y", "$x, $y"), ("angle radians", "@angle")]) p = figure(plot_width = 1000, plot_height = 700, tools = [hover4]) p.square( 'x', 'y', size = 5, fill_color = "violet", line_color = "violet", fill_alpha = 1, angle = 'angle', line_width = 1, legend = "radar measurements", source = radar_source) p.circle( 'x', 'y', size = 10, fill_color = "green", line_color = "white", fill_alpha = 0.4, line_width = 1, legend = "lidar measurements", source = lidar_source) p.line(state_xs, state_ys, line_width = 2, color='orange', legend = "state predictions") p.line(truth_xs, truth_ys, line_dash = "4 4", line_width = 1, color='navy', legend = "ground truth") p.legend.location = "bottom_right" show(p) # + deletable=true editable=true
Fusion-EKF-Sample-Visualization-4-B.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="n9AqgHy2DN-a" # # **Imports** # + id="Z9CQei1bCXUc" # this code is based on https://github.com/pytorch/tutorials/blob/master/beginner_source/dcgan_faces_tutorial.py, which is released under the BSD-3-Clause License # imports import math import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as F import torchvision import matplotlib.pyplot as plt # hyperparameters batch_size = 64 image_size = 32 # (32 or 64) n_channels = 3 device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # + colab={"base_uri": "https://localhost:8080/"} id="foCnxV4gCiuj" outputId="2007ee0e-0b2d-45d7-87e1-4002f5b821f0" # optional Google drive integration - this will allow you to save and resume training, and may speed up redownloading the dataset from google.colab import drive drive.mount('/content/drive') # + [markdown] id="rHWUAZf8DKCP" # # **Loading Data** # We combine both CIFAR10 and STL10 into a single dataset of 32x32 images (or 64x64 images) containing only images of class horse and bird/airplane. # # # + colab={"base_uri": "https://localhost:8080/"} id="BxP8cBv4itLt" outputId="33fb1d22-7d33-4c3a-be42-0e2100704c12" # helper function to make getting another batch of data easier def cycle(iterable): while True: for x in iterable: yield x # Returns indexes of images belonging to class "label" def get_same_index(target, label): label_indices = [] for i in range(len(target)): if target[i] == label: label_indices.append(i) return label_indices cifar10 = torchvision.datasets.CIFAR10('drive/My Drive/training/cifar10', download=True, train=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Resize(image_size), torchvision.transforms.CenterCrop(image_size), torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ])) label_class = 7 # horse label_class2 = 2 # 0 airplane, 2 bird # Get indices of label_class train_indices = get_same_index(cifar10.targets, label_class) train_indices2 = get_same_index(cifar10.targets, label_class2) train_indices2 = train_indices2[:int(len(train_indices2)/3)] # give more weighting to horse class train_indices = train_indices + train_indices2 cifar10 = torch.utils.data.Subset(cifar10, train_indices) stl10 = torchvision.datasets.STL10('drive/My Drive/training/stl10', download=True, split='train', transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Resize(image_size), torchvision.transforms.CenterCrop(image_size), torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ])) label_class = 6 # horse label_class2 = 1 # 0 airplace, 1 bird # Get indicies of label_class train_indices = get_same_index(stl10.labels, label_class) train_indices2 = get_same_index(stl10.labels, label_class2) train_indices2 = train_indices2[:int(len(train_indices2)/3)] train_indices = train_indices + train_indices2 stl10 = torch.utils.data.Subset(stl10, train_indices) # Combine the two datasets into one to train on datasets = [cifar10, stl10] train_dataset = torch.utils.data.ConcatDataset(datasets) # Create a dataloader dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) # Our dataloader contains 86 batches of 64 images (5500 images in total) train_iterator = iter(cycle(dataloader)) # + [markdown] id="nTGwXrjhmfYU" # # **Viewing training data** # + colab={"base_uri": "https://localhost:8080/", "height": 514} id="mbfQVU9rlxH_" outputId="547a9489-0c11-47ac-e832-896e0226769d" # let's view some of the training data plt.rcParams['figure.dpi'] = 145 x,t = next(train_iterator) x,t = x.to(device), t.to(device) plt.grid(False) plt.axis("off") plt.title("Training Images") plt.imshow(torchvision.utils.make_grid(x, normalize=True).cpu().data.permute(0,2,1).contiguous().permute(2,1,0), cmap=plt.cm.binary) plt.show() # + [markdown] id="KgxgeyPhmzbU" # # **Defining our Generator and Discriminator for the GAN** # # This model architecture follows the original DCGAN papers (https://arxiv.org/abs/1511.06434) guidelines for stable Deep Convolutional GANs. The DCGAN paper hardcodes a model for use of 64x64. We remove a layer from both the generator and discriminator when using 32x32 data. # + colab={"base_uri": "https://localhost:8080/"} id="OYBLAwhQlRrj" outputId="cac53d67-3e0f-4251-c14b-03574754cb01" # features_d -> channels of discriminator that change z_dims = 100 # 100-dimensional noise vector g_features = 128 # 128 generator d_features = 128 # 128 discriminator n_channels = 3 # We want our output to be 32x32x3 (RGB 32x32 images) class Generator(nn.Module): def __init__(self, z_dims, g_features, n_channels): super(Generator, self).__init__() # The model follows the same architecture, with one less layer as our input is 32x32 self.gen = nn.Sequential( # for 64x64 images #nn.ConvTranspose2d(in_channels=z_dims, out_channels=(g_features * 8), kernel_size=4, stride=1, padding=0, bias=False), #nn.BatchNorm2d(num_features=(g_features * 8)), #nn.ReLU(True), # 100x1x1 -> 512x4x4 nn.ConvTranspose2d(in_channels=z_dims, out_channels=(g_features * 4), kernel_size=4, stride=1, padding=0, bias=False), # change z_dims to g_features*8 for 64x64 nn.BatchNorm2d(num_features=(g_features * 4)), nn.ReLU(True), # 512x4x4 -> 256x8x8 nn.ConvTranspose2d(in_channels=(g_features * 4), out_channels=(g_features * 2), kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(num_features=(g_features * 2)), nn.ReLU(True), # 256x8x8 -> 128x16x16 nn.ConvTranspose2d(in_channels=(g_features * 2), out_channels=(g_features), kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(num_features=(g_features)), nn.ReLU(True), # 128x16x16-> 3x32x32 nn.ConvTranspose2d(in_channels=g_features, out_channels=n_channels, kernel_size=4, stride=2, padding=1, bias=False), nn.Tanh(), ) def forward(self, x): return self.gen(x) class Discriminator(nn.Module): def __init__(self, d_features, n_channels): super(Discriminator, self).__init__() self.disc = nn.Sequential( # 3x32x32 -> 128x16x16 nn.Conv2d(in_channels=n_channels, out_channels=d_features, kernel_size=4, stride=2, padding=1, bias=False), nn.LeakyReLU(0.2, inplace=True), #nn.Dropout2d(0.25) # 128x16x16 -> 256x8x8 nn.Conv2d(in_channels=d_features, out_channels=(d_features * 2), kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(num_features=(d_features * 2)), nn.LeakyReLU(0.2, inplace=True), #nn.Dropout2d(0.25) Reduce mode collapse and increase train stability (https://www.kdd.org/kdd2018/files/deep-learning-day/DLDay18_paper_17.pdf) # 256x8x8 -> 512x4x4 nn.Conv2d(in_channels=(d_features * 2), out_channels=(d_features * 4), kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(num_features=(d_features * 4)), nn.LeakyReLU(0.2, inplace=True), #nn.Dropout2d(0.25) # for 64x64 images #nn.Conv2d(in_channels=(d_features * 4), out_channels=(d_features * 8), kernel_size=4, stride=2, padding=1, bias=False), #nn.BatchNorm2d(num_features=(d_features * 4)), #nn.LeakyReLU(0.2, inplace=True), #nn.Dropout2d(0.25) # 512x4x4 -> 1 (binary classification: real/fake) nn.Conv2d(in_channels=(d_features * 4), out_channels=1, kernel_size=4, stride=1, padding=0, bias=False), # change d_features * 8 for 64x64 nn.Sigmoid() ) def forward(self, x): return self.disc(x) # Initialize weights of model using a random distribution def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) G = Generator(z_dims=z_dims, g_features=g_features, n_channels=n_channels).to(device) G.apply(weights_init) D = Discriminator(d_features=d_features, n_channels=n_channels).to(device) D.apply(weights_init) # + id="yQaD2Xw2FUSX" lr= 0.0002 # (2e-4) beta1, beta2 = 0.5, 0.999 # Adam optimizers are known to perform the best for DCGAN G_opt = torch.optim.Adam(G.parameters(), lr=lr, betas=(beta1, beta2)) D_opt = torch.optim.Adam(D.parameters(), lr=lr, betas=(beta1, beta2)) bce_loss = nn.BCELoss() # + colab={"base_uri": "https://localhost:8080/"} id="gjuHEbU0G4DX" outputId="18cfa204-894c-46c1-936a-7ca12edd2f5b" # Making sure our generator and discriminator are working properly gen_noise = torch.randn(batch_size, 100, 1, 1) dis_noise = torch.randn(batch_size, 3, image_size, image_size) print((G(gen_noise)).shape) # Generator needs to be outputting batch_size * 3x32x32 (64 RGB image_size x image_size images) print((D(dis_noise)).shape) # Discriminator needs to be outputting batch_size * 1*1*1 (binary classification) # + [markdown] id="a2HTKgAhzq_j" # # **Main training loop** # # This training loop is based off the mini-batch stochastic gradient descent algorithm proposed in the original GAN paper (https://arxiv.org/abs/1406.2661) # + colab={"base_uri": "https://localhost:8080/", "height": 472} id="I_YcXV44lQ5m" outputId="65ca7d52-9f7f-4407-fbd6-b4860010ebfd" PATH = "drive/MyDrive/model-saves/generator.pth" # Path to save model every 10 epochs epoch = 1 max_epochs = 100 sample_noise = torch.randn(batch_size, 100, 1, 1) # define some sample noise to use when saving images saved_images = [] # a list containing example batch of generated images each epoch print("Starting training loop...") while epoch < max_epochs+1: gen_loss_arr = np.zeros(0) disc_loss_arr = np.zeros(0) # iterate over the train dataset for real_data, labels in dataloader: # labels wont be used as it's unsupervised real_data = real_data.to(device) # batch_size * image_size x image_size (real images) fake_data = G((torch.randn(batch_size, z_dims, 1, 1)).to(device)) # batch_size * image_size x image_size (fake images) # Train Discriminator # max logD(x) + log(1-D(G(Z))) d_real = D(real_data).reshape(-1) # D(x) d_fake = D(fake_data).reshape(-1) # D(G(z)) loss_d_real = bce_loss(d_real, torch.ones_like(d_real)) # max logD(x) (represented by min -logD(x) which is equivalent) loss_d_fake = bce_loss(d_fake, torch.zeros_like(d_fake)) # max log(1-D(G(Z))) (represented by min -log(1-D(G(Z))) which is equivalent) d_loss = (loss_d_real + loss_d_fake) / 2.0 D.zero_grad() d_loss.backward(retain_graph=True) # Don't have to detach fake data D_opt.step() # Train Generator # min log(1-D(G(Z))) # To avoid diminishing gradients, train to max logD(G(z)) x = D(fake_data).reshape(-1) # G(z) g_loss = bce_loss(x, torch.ones_like(x)) # logD(G(z)) G.zero_grad() g_loss.backward() G_opt.step() gen_loss_arr = np.append(gen_loss_arr, g_loss.item()) disc_loss_arr = np.append(disc_loss_arr, d_loss.item()) # Print some statistics each epoch print(f"[EPOCH : {epoch}/{max_epochs}]\tGenerator Loss: {gen_loss_arr.mean()}\tDiscriminator Loss: {disc_loss_arr.mean()}") if epoch % 10 == 0: # Save our model every 10 epochs torch.save(G.state_dict(), PATH) print("Saved model") # Save some examples each epoch (batch of 64 fake images) with torch.no_grad(): fake_examples = G(sample_noise) saved_images.append(torchvision.utils.make_grid(fake_examples, padding=2, normalize=True)) # Save and store into a folder on drive so we can view results img_name = str(time.gmtime()[3]) + ":" + str(time.gmtime()[4]) torchvision.utils.save_image(torchvision.utils.make_grid(fake_examples, padding=2, normalize=True), "drive/MyDrive/DCGAN-images/" + f"{img_name}.png") print(f"Saved {img_name}.png") epoch += 1 # + id="24TIAwHEVXIy" # Collect a batch of 64 fake images from the last epoch fake_images = img_list[-1] # View images generated from the last epoch plt.rcParams['figure.dpi'] = 145 plt.axis("off") plt.title("Fake Images") plt.imshow(np.transpose(fake_images, (1,2,0))) plt.show() # + id="vZ_FycHKXxug" # Save the model so we can reload it from memory PATH = "drive/MyDrive/model-saves/generator.pth" G_save = torch.save(G.save_dict(), PATH) # Load the model # G = Generator().to(device) # G.load_state_dict(torch.load(PATH)) # G.eval()
pegasus-code.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %run ../../../main.py # %matplotlib inline # + import pandas as pd from pyarc.algorithms import M1Algorithm, M2Algorithm, top_rules, createCARs from pyarc.data_structures import TransactionDB import pyarc.qcba as qcba from pyarc import CBA from pyarc.qcba.data_structures import * import matplotlib.pyplot as plt from pyarc.qcba import QCBA import pandas as pd from pyarc.qcba.data_structures import ( IntervalReader, Interval, QuantitativeDataFrame, QuantitativeCAR ) interval_reader = IntervalReader() interval_reader.closed_bracket = "", "NULL" interval_reader.open_bracket = "NULL", "" interval_reader.infinity_symbol = "inf", "inf" interval_reader.members_separator = "_to_" interval_reader.compile_reader() i = interval_reader.read("82.9815_to_inf") QuantitativeCAR.interval_reader = interval_reader # + # # # ========================= # Oveล™enรญ bฤ›hu v zรกvislosti na vloลพenรฝch pravidlech / instancรญch # ========================= # # # import time rule_count = 100 benchmark_data = { "input rows": [], "input rules": [], "output rules M1 pyARC": [], "output rules M1 pyARC unique": [], "output rules M2 pyARC": [], "output rules pyARC qCBA": [], "time M1 pyARC": [], "time M1 pyARC unique": [], "time M2 pyARC": [], "time pyARC qCBA": [] } stop_m2 = True number_of_iterations = 10 directory = "c:/code/python/machine_learning/assoc_rules" dataset_name_benchmark = "lymph0" pd_ds = pd.read_csv("c:/code/python/machine_learning/assoc_rules/train/{}.csv".format(dataset_name_benchmark)) pd_ds_quant = pd.read_csv("c:/code/python/machine_learning/assoc_rules/folds_undiscr/train/{}.csv".format(dataset_name_benchmark)) for i in range(5): dataset_name_benchmark = "lymph0" pd_ds = pd.concat([pd_ds, pd_ds]) pd_ds_quant = pd.concat([pd_ds_quant, pd_ds_quant]) quant_dataframe = QuantitativeDataFrame(pd_ds_quant) txns = TransactionDB.from_DataFrame(pd_ds, unique_transactions=True) txns_unique = TransactionDB.from_DataFrame(pd_ds, unique_transactions=False) rules = top_rules(txns.string_representation, appearance=txns.appeardict, target_rule_count=rule_count) cars = createCARs(rules) if len(cars) > rule_count: cars = cars[:rule_count] m1t1 = time.time() m1clf_len = [] for _ in range(number_of_iterations): m1 = M1Algorithm(cars, txns) clf = m1.build() m1clf_len.append(len(clf.rules) + 1) m1t2 = time.time() t1_qcba = time.time() qcba_clf_len = [] for _ in range(number_of_iterations): m1 = M1Algorithm(cars, txns) clf = m1.build() m1clf_len.append(len(clf.rules) + 1) rm_cba = CBA() rm_cba.clf = clf rm_qcba = QCBA(rm_cba, quant_dataframe) rm_qcba.fit() t2_qcba = time.time() m1t1_unique = time.time() m1clf_len_unique = [] for _ in range(number_of_iterations): m1 = M1Algorithm(cars, txns_unique) clf = m1.build() m1clf_len_unique.append(len(clf.rules) + 1) m1t2_unique = time.time() if not stop_m2: m2t1 = time.time() m2clf_len = [] for _ in range(number_of_iterations): m2 = M2Algorithm(cars, txns) clf = m2.build() m2clf_len.append(len(clf.rules) + 1) m2t2 = time.time() m1duration = (m1t2 - m1t1) / number_of_iterations m1duration_unique = (m1t2_unique - m1t1_unique) / number_of_iterations outputrules_m1 = sum(m1clf_len) / len(m1clf_len) outputrules_m1_unique = sum(m1clf_len_unique) / len(m1clf_len_unique) if not stop_m2: m2duration = (m2t2 - m2t1) / number_of_iterations outputrules_m2 = sum(m2clf_len) / len(m2clf_len) if m2duration > 0.5: stop_m2 = True benchmark_data["input rows"].append(len(txns)) benchmark_data["input rules"].append(rule_count) benchmark_data["output rules M1 pyARC"].append(outputrules_m1) benchmark_data["output rules M1 pyARC unique"].append(outputrules_m1_unique) benchmark_data["output rules M2 pyARC"].append(None if stop_m2 else outputrules_m2) benchmark_data["time M1 pyARC"].append(m1duration) benchmark_data["time M1 pyARC unique"].append(m1duration_unique) benchmark_data["time M2 pyARC"].append(None if stop_m2 else m2duration) print("data_count:", len(txns)) print("M1 duration:", m1duration) print("M1 unique duration", m1duration_unique) print("M1 output rules", outputrules_m1) if not stop_m2: print("M2 duration:", m2duration) print("M2 output rules", outputrules_m2) print("\n\n")
notebooks/qcba_extension/benchmarks/.ipynb_checkpoints/qcba_speed_benchmark_datacase_count-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # nuclio: ignore import nuclio # %nuclio config kind = "job" # %nuclio config spec.image = "mlrun/ml-models" # + # Copyright 2018 Iguazio # # 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. import numpy as np import pandas as pd from mlrun.execution import MLClientCtx def load_dataset( context: MLClientCtx, dataset: str, name: str = '', file_ext: str = 'parquet', params: dict = {} ) -> None: """Loads a scikit-learn toy dataset for classification or regression The following datasets are available ('name' : desription): 'boston' : boston house-prices dataset (regression) 'iris' : iris dataset (classification) 'diabetes' : diabetes dataset (regression) 'digits' : digits dataset (classification) 'linnerud' : linnerud dataset (multivariate regression) 'wine' : wine dataset (classification) 'breast_cancer' : breast cancer wisconsin dataset (classification) The scikit-learn functions return a data bunch including the following items: - data the features matrix - target the ground truth labels - DESCR a description of the dataset - feature_names header for data The features (and their names) are stored with the target labels in a DataFrame. For further details see https://scikit-learn.org/stable/datasets/index.html#toy-datasets :param context: function execution context :param dataset: name of the dataset to load :param name: artifact name (defaults to dataset) :param file_ext: output file_ext: parquet or csv :param params: params of the sklearn load_data method """ dataset = str(dataset) # reach into module and import the appropriate load_xxx function pkg_module = 'sklearn.datasets' fname = f'load_{dataset}' pkg_module = __import__(pkg_module, fromlist=[fname]) load_data_fn = getattr(pkg_module, fname) data = load_data_fn(**params) feature_names = data['feature_names'] # create the toy dataset xy = np.concatenate([data['data'], data['target'].reshape(-1, 1)], axis=1) if hasattr(feature_names, 'append'): # its a list feature_names.append('labels') else: # its an array feature_names = np.append(feature_names, 'labels') df = pd.DataFrame(data=xy, columns=feature_names) # log and upload the dataset context.log_dataset(name or dataset, df=df, format=file_ext, index=False) # + # nuclio: end-code # - # ### mlconfig # + from mlrun import mlconf import os mlconf.dbpath = mlconf.dbpath or 'http://mlrun-api:8080' mlconf.artifact_path = mlconf.artifact_path or f'{os.environ["HOME"]}/artifacts' # - # ### save # + from mlrun import code_to_function # create job function object from notebook code fn = code_to_function("load_dataset") # add metadata (for templates and reuse) fn.spec.default_handler = "load_dataset" fn.spec.description = "load a toy dataset from scikit-learn" fn.metadata.categories = ["data-source", "ml"] fn.metadata.labels = {"author": "yjb", "framework": "sklearn"} fn.export("function.yaml") # - # ## tests # + # load function from marketplacen from mlrun import import_function # vcs_branch = 'development' # base_vcs = f'https://raw.githubusercontent.com/mlrun/functions/{vcs_branch}/' # mlconf.hub_url = mlconf.hub_url or base_vcs + f'{name}/function.yaml' # fn = import_function("hub://load_dataset") # - if "V3IO_HOME" in list(os.environ): from mlrun import mount_v3io fn.apply(mount_v3io()) else: # is you set up mlrun using the instructions at https://github.com/mlrun/mlrun/blob/master/hack/local/README.md from mlrun.platforms import mount_pvc fn.apply(mount_pvc('nfsvol', 'nfsvol', '/home/joyan/data')) # + from mlrun import NewTask task_params = { "name" : "tasks load toy dataset", "params" : {"dataset" : "wine"}} # - # ### run remotely run = fn.run(NewTask(**task_params), artifact_path=mlconf.artifact_path) # ### or locally from mlrun import run_local for dataset in ["wine", "iris", "breast_cancer"]: run_local(handler=load_dataset, inputs={"dataset": dataset}, artifact_path=mlconf.artifact_path)
load_dataset/load_dataset.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Load dataset # + deletable=true editable=true import tools # + deletable=true editable=true edges, nodes, poss_set, neg_set = tools.sample_structural( '../datasets/directed/ego-twitter/train.in', N=10, directed=True) # - # # Make bipartite network # + deletable=true editable=true from graph_tool.all import * g = Graph(directed=False) g.add_vertex(2*max(nodes) + 2) # + deletable=true editable=true groups = g.new_vertex_property("int") for u in g.vertices(): groups[u] = int(u) % 2 for edge in edges: if edge not in poss_set: u, w = map(int, edge.split()) g.add_edge(g.vertex(2*u), g.vertex(2*w + 1)) # + deletable=true editable=true pos = sfdp_layout(g, max_iter=4) # - # # Scores # + deletable=true editable=true from sklearn.metrics import roc_auc_score # + deletable=true editable=true features = tools.TopologicalFeatures(g, pos, directed=True) X, Y = tools.make_dataset(poss_set, neg_set, [features.dist]) print 'di-SFDP:', roc_auc_score(Y, X) # + deletable=true editable=true from sklearn.decomposition import NMF model = NMF(n_components=10, init='random', random_state=0) matrix = tools.make_sparse_matrix(edges, nodes, poss_set, directed=True) features = tools.MFFeatures(model, matrix) X, Y = tools.make_dataset(poss_set, neg_set, [features.score]) print "NMF:", roc_auc_score(Y, X) # + deletable=true editable=true from scipy.sparse import linalg import numpy matrix = tools.make_sparse_matrix(edges, nodes, poss_set, directed=True) U, s, Vh = linalg.svds(matrix.asfptype(), k=30) def score(u, w): return numpy.dot(U[u] * s, Vh.T[w]) X, Y = tools.make_dataset(poss_set, neg_set, [score]) print "svds:", roc_auc_score(Y, X) # + [markdown] deletable=true editable=true # # Cross-validation # + deletable=true editable=true import cross_validation cross_validation.cross_validation( 'data/directed/ego-twitter/train.in', N=30, k=10, directed=True, max_iter=25)
notebooks/Directed_networks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # ะŸะฐั€ะฐะปะปะตะปัŒะฝะพะต ะฟั€ะพะณั€ะฐะผะผะธั€ะพะฒะฐะฝะธะต # # <NAME> https://www.youtube.com/watch?v=xYV_C4pg1LU # ะกะปะฐะนะดั‹ ะดะพัั‚ัƒะฟะฝั‹ ะฟะพ ะฐะดั€ะตััƒ: http://parallels.nsu.ru/~fat/Python/ # # ## ะŸะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพะต ะฒั‹ะฟะพะปะฝะตะฝะธะต print('Hello, World!') x = 1 y = 2 print(x + y) # ะŸะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝะพะต ะฒั‹ะฟะพะปะฝะตะฝะธะต ัั‚ะพ - ะŸะพะบะฐ ะพะดะฝะฐ ัั‚ั€ะพะบะฐ ะฝะต ะฒั‹ะฟะพะปะฝะธั‚ัั, ะดั€ัƒะณะฐั ะฝะต ะฝะฐั‡ะฝะตั‚ัั # # ### ะŸั€ะพะธะทะฒะพะดะธั‚ะตะปัŒะฝะพัั‚ัŒ # * ะŸั€ะพะธะทะฒะพะดะธั‚ะตะปัŒะฝะพัั‚ัŒ ~ ั‡ะฐัั‚ะพั‚ะฐ ะฟั€ะพั†ะตััะพั€ะฐ # * ะžะณั€ะฐะฝะธะตะฝะธะต ั€ะพัั‚ะฐ ั‡ะฐัั‚ะพั‚ั‹ # * ะ•ัั‚ัŒ ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะดะตะปะฐั‚ัŒ ะผะฝะพะณะพ ะฟั€ะพั†ะตััะพั€ะพะฒ # # ### ะ‘ะปะพะบะธั€ัƒัŽั‰ะธะต ะทะฐะดะฐั‡ะธ # # #### ะžะถะธะดะฐะฝะธะต ะดะตะนัั‚ะฒะธะน # * ะ˜ัะฟะพะปะฝะตะฝะธะต ะฟั€ะธะพัั‚ะฐะฝะฐะฒะปะธะฒะฐะตั‚ัั # * ะœะพะถะฝะพ ะฑั‹ะปะพ ะฑั‹ ั‡ั‚ะพ-ะฝะธะฑัƒะดัŒ ะดะตะปะฐั‚ัŒ # # #### ะŸั€ะธะผะตั€ั‹ # * ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะต ะธะฝั‚ะตั€ั„ะตะนัั‹ (ะพะถะธะดะฐะฝะธะต ะฒะฒะพะดะฐ) # * ะ ะฐะฑะพั‚ะฐ ั ัะตั‚ัŒัŽ # # ### ะŸะฐั€ะฐะปะปะตะปัŒะฝะพะต ะฒั‹ะฟะพะปะฝะตะฝะธะต # # #### ะŸั€ะตะธะผัƒั‰ะตัั‚ะฒะฐ: # * ะฃัะบะพั€ะตะฝะธะต ~ ั‡ะธัะปะพ ะฟั€ะพั†ะตััะพั€ะพะฒ (ะธะปะธ ัะดะตั€ ะฟั€ะพั†ะตััะพั€ะฐ) # # #### ะะตะดะพัั‚ะฐั‚ะบะธ: # * ะะตั‚ "ะฟะพั€ัะดะบะฐ" ะธัะฟะพะปะฝะตะฝะธั: # # ````python # text = 'Hello, World!' # # ะŸะพั‚ะพะบ โ„– 1: ะŸะพั‚ะพะบ โ„– 2: # for s in text: for s in text: # print(s) print(s) # # ะ ะตะทัƒะปัŒั‚ะฐั‚: # HHeelllol,o w,or ld!World! # ```` # # ## ะœะฝะพะณะพะฟะพั‚ะพั‡ะฝั‹ะต ะฟั€ะพะณั€ะฐะผะผั‹ # # ะะตัะบะพะปัŒะบะพ ะฟะพั‚ะพะบะพะฒ. # ะŸะพั‚ะพะบะธ ั…ะฐั€ะฐะบั‚ะตั€ะฝั‹ ั‚ะตะผ, ั‡ั‚ะพ ะฝะฐั…ะพะดัั‚ัั ะฒะฝัƒั‚ั€ะธ ะพะดะฝะพะณะพ ะฟั€ะพั†ะตััะฐ ะธ ั€ะฐะฑะพั‚ะฐัŽั‚ ั ะพะดะฝะพะน ะธ ั‚ะพะน ะถะต ะฟะฐะผัั‚ัŒัŽ, ะฝะพ ะฟั€ะธ ัั‚ะพะผ ะพะฝะธ ะผะพะณัƒั‚ ะธัะฟะพะปะฝัั‚ัั ะฝะฐ ั€ะฐะทะฝั‹ั… ะฟั€ะพั†ะตััะพั€ะฐั… (ะธะปะธ ัะดั€ะฐั… ะฟั€ะพั†ะตััะพั€ะฐ): # # ```` # ------------------------------------------------------------ # | Process | # | ------------------------------------------------------ | # | | Memory | | # | | | | # | ------------------------------------------------------ | # | ^ ^ ^ | # | | | | | # | ------------- ------------- ------------- | # | | Thread1 | | Thread2 | | Thread3 | | # | | | | | | | | # | ------------- ------------- ------------- | # | | # ------------------------------------------------------------ # ```` # # ะŸะพะดะณะพั‚ะพะฒะบะฐ: # + def test(part_index, inputs, outputs): print('ะ—ะฐะฟัƒั‰ะตะฝ ะฟะพั‚ะพะบ โ„– {}\n'.format(part_index), end='') output = inputs[part_index] ** 2 # ะญะผัƒะปัั†ะธั ะฝะตะบะพั‚ะพั€ะพะน ะทะฐะดะฐั‡ะธ outputs[part_index] = output # ะ—ะฐะฝะพัะธะผ ั€ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ั‡ะธัะปะตะฝะธั inputs = range(5) outputs = [ None for i in inputs ] # - # ะšะฐะบ ัะดะตะปะฐั‚ัŒ ั‚ะฐะบ, ั‡ั‚ะพะฑั‹ ะบะฐะถะดั‹ะน ะฟะพั‚ะพะบ ะทะฐะฟัƒัั‚ะธะป ั„ัƒะฝะบั†ะธัŽ `test`? ะ”ะปั ัั‚ะพะณะพ ะฝัƒะถะฝะพ ะฟะพะดะบะปัŽั‡ะธั‚ัŒ ะผะพะดัƒะปัŒ `threading`: # + from threading import Thread treads = [] # ะฅั€ะฐะฝะธะผ ััั‹ะปะบะธ ะฝะฐ ะฟะพั‚ะพะบะธ # ะกะพะทะดะฐะตะผ ะฟะพั‚ะพะบะธ ะธ ะบะปะฐะดะตะผ ะธั… ะฒ ัะฟะธัะพะบ treads for i in inputs: t = Thread(target=test, args=(i, inputs, outputs)) treads.append(t) # ะ—ะฐะฟัƒัะบะฐะตะผ ะฟะพั‚ะพะบะธ for i in treads: i.start() # ะ—ะฐะฟัƒัะบะฐะตั‚ัั ะฟะฐั€ะฐะปะปะตะปัŒะฝั‹ะน ะฟะพั‚ะพะบ. ะฆะธะบะป for ะพัั‚ะฐะปัั ะฒั‹ะฟะพะปะฝัั‚ัั ะฒ ะณะปะฐะฒะฝะพะผ (main) ะฟะพั‚ะพะบะต # ะงั‚ะพะฑั‹ ะณะปะฐะฒะฝั‹ะน ะฟะพั‚ะพะบ (main) ะฝะต ะทะฐะฒะตั€ัˆะธะปัั ะฑั‹ัั‚ั€ะตะต ะฟะฐั€ะฐะปะปะตะปัŒะฝะพ ะทะฐะฟัƒั‰ะตะฝะฝั‹ั… ะฟะพั‚ะพะบะพะฒ, # ะฒั‹ะฟะพะปะฝัะตะผ ะพะถะธะดะฐะฝะธะต ะฟะฐั€ะฐะปะปะตะปัŒะฝะพะณะพ ะฟะพั‚ะพะบะฐ ะณะปะฐะฒะฝั‹ะผ ะฟะพั‚ะพะบะพะผ: for i in treads: i.join() print('ะ ะตะทัƒะปัŒั‚ะฐั‚:', outputs) # - # ## ะะฐัะปะตะดะพะฒะฐะฝะธะต ะพั‚ Thread # + import time import random class TCalc(Thread): def __init__(self): super().__init__() self.sleeptime = random.randint(1,3) def run(self): self.status = 'started' time.sleep(self.sleeptime) self.status = 'done' def __repr__(self): if hasattr(self, 'status'): return '{}-{}'.format(self.name, self.status) return self.name + ' (id=' + str(id(self)) + ')' t = TCalc() t.start() # ะ—ะฐะฟัƒัะบะฐะตะผ ะฟะพั‚ะพะบ ะฝะฐ ะธัะฟะพะปะฝะตะฝะธะต # ะขะตะพั€ะตั‚ะธั‡ะตัะบะธ ะผะพะถะตั‚ ะฒะพะทะฝะธะบะฝัƒั‚ัŒ ั‚ะฐะบ, ั‡ั‚ะพ ะฟะพั‚ะพะบ ะผะพะถะตั‚ ะฟะธัะฐั‚ัŒ ั‡ั‚ะพ-ั‚ะพ ะฒ ะฟะตั€ะตะผะตะฝะฝัƒัŽ status, # ะฐ ะฒ ัั‚ะพ ะฒั€ะตะผั ะณะปะฐะฒะฝั‹ะน ะฟะพั‚ะพะบ ั ะธะฝัั‚ั€ัƒะบั†ะธะตะน print ะฑัƒะดะตั‚ ะฟั‹ั‚ะฐั‚ัŒัั ัั‡ะธั‚ะฐั‚ัŒ ะทะฝะฐั‡ะตะฝะธะต ัั‚ะพะน ะฟะตั€ะตะผะตะฝะฝะพะน, # ะญั‚ัƒ ัะธั‚ัƒะฐั†ะธัŽ Python ัƒัะฟะตัˆะฝะพ ั€ะฐะทั€ะตัˆะฐะตั‚, ะตัะปะธ ะฒั‹ ะฝะต ะฟะธัˆะธั‚ะต ะพะดะฝะพะฒั€ะตะผะตะฝะฝะพ ั ั€ะฐะทะฝั‹ั… ะผะตัั‚ ะฒ ัั‚ัƒ ะฟะตั€ะตะผะตะฝะฝัƒัŽ. print('status = {}, is_alive = {}'.format(t.status, t.is_alive())) print('ะŸะฐั€ะฐะปะปะตะปัŒะฝั‹ะน ะฟะพั‚ะพะบ ัƒะถะต ะฒั‹ะฟะพะปะฝัะตั‚ัั, ะฟั€ะธัะพะตะดะธะฝัะตะผัั ะธ ะดะพะถะธะดะฐะตะผัั ะตะณะพ ะทะฐะฒะตั€ัˆะตะฝะธั') t.join() # ะžะถะธะดะฐะฝะธะต ะฒั‹ะฟะพะปะฝะตะฝะธั ะฟะพั‚ะพะบะฐ. ะ’ ัั‚ะพะผ ะผะตัั‚ะต ะณะปะฐะฒะฝั‹ะน ะฟะพั‚ะพะบ ะฟั€ะธะพัั‚ะฐะฝะฐะฒะปะธะฒะฐะตั‚ัั print('status = {}, is_alive = {}'.format(t.status, t.is_alive())) # - # ## ะ•ั‰ะต ะฟั€ะธะผะตั€ ะฟะพั‚ะพะบะพะฒ ั ัั‚ะธะผ ะบะปะฐััะพะผ... # + treads = [] # ะกะพะทะดะฐะตะผ (ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒะตะผ) ะฟะพั‚ะพะบะธ for i in range(10): treads.append(TCalc()) print('ะŸะพั‚ะพะบะธ ัะพะทะดะฐะฝั‹:\n', treads, '\n') # ะ—ะฐะฟัƒัะบะฐะตะผ ะฟะพั‚ะพะบะธ for i in treads: i.start() print('ะ“ะปะฐะฒะฝั‹ะผ ะฟะพั‚ะพะบะพะผ ะฟะพะดะพะถะดะตะผ ะฝะตะผะฝะพะณะพ...\n') time.sleep(1.5) # ะ’ะฒะพะดะธะผ ะฒ ัะพะฝ ะณะปะฐะฒะฝั‹ะน ะฟะพั‚ะพะบ print('ะŸะพั‚ะพะบะธ ะฒั‹ะฟะพะปะฝััŽั‚ัั:\n', treads, '\n') # ะšะฐะบะธะต-ั‚ะพ ะฟะพั‚ะพะบะธ ัƒะถะต ะฒั‹ะฟะพะปะฝะธะปะธััŒ (ะฒ ัั‚ะฐั‚ัƒัะต done) # ะ”ะพะถะธะดะฐะตะผัั ะฒั‹ะฟะพะปะฝะตะฝะธะต ะฟะพั‚ะพะบะพะฒ for i in treads: i.join() print('ะŸะพั‚ะพะบะธ ะฒั‹ะฟะพะปะฝะตะฝั‹:\n', treads) # - # ## ะŸั€ะธะฝัƒะดะธั‚ะตะปัŒะฝะฐั ะพัั‚ะฐะฝะพะฒะบะฐ ะฟะพั‚ะพะบะฐ # # * ะŸะพั‚ะพะบ ะผะพะถะตั‚ ัะพะดะตั€ะถะฐั‚ัŒ ั€ะตััƒั€ัั‹, ะบะพั‚ะพั€ั‹ะต ะฝัƒะถะฝะพ ะพัะฒะพะฑะพะดะธั‚ัŒ. ะะฐะฟั€ะธะผะตั€, ั‡ั‚ะพ-ั‚ะพ ะดะพะปะณะพ ะฟั€ะพะธัั…ะพะดะธั‚ ะธ ะฝัƒะถะฝะพ ัั‚ะพ ะฟั€ะตั€ะฒะฐั‚ัŒ ะฟั€ะธะฝัƒะดะธั‚ะตะปัŒะฝะพ # * ะะตั‚ ัะฟะตั†ะธะฐะปัŒะฝะพะน ั„ัƒะฝะบั†ะธะธ ะดะปั ะพัั‚ะฐะฝะพะฒะบะธ. ะขะฐะบ ะบะฐะบ ัะบะพั€ะตะต ะฒัะตะณะพ ะฟะพัะปะต ัั‚ะพะณะพ ะฒั‹ะทะพะฒะฐ ะฟั€ะพะณั€ะฐะผะผะฐ ะฟะตั€ะตะนะดะตั‚ ะฒ ะฝะตะบะพั€ั€ะตะบั‚ะฝะพะต ัะพัั‚ะพัะฝะธะต # * ะœะพะถะฝะพ ัะฐะผะพัั‚ะพัั‚ะตะปัŒะฝะพ ั€ะตะฐะปะธะทะพะฒะฐั‚ัŒ ั‚ะฐะบัƒัŽ ะฒะพะทะผะพะถะฝะพัั‚ัŒ # + class KillableThread(Thread): def __init__(self): super().__init__() self.killing = False def run(self): self.status = 'started' for i in range(5,10): # ะญะผัƒะปัั†ะธั ะฝะตะบะพั‚ะพั€ั‹ั… ะดะตะนัั‚ะฒะธะน ะฟะพั‚ะพะบะฐ, ะฒะฝัƒั‚ั€ะธ ะบะพั‚ะพั€ั‹ั… ัƒัะปะพะฒะธะต ะพัั‚ะฐะฝะพะฒะบะธ ะฟะพั‚ะพะบะฐ if self.killing: self.status = 'killed i=' + str(i) return # break time.sleep(0.2) self.status = 'done' def kill(self): self.killing = True def __repr__(self): if hasattr(self, 'status'): return '{}-{}'.format(self.name, self.status) return self.name threads = [] for i in range(5): threads.append(KillableThread()) print('ะŸะพั‚ะพะบะธ ัะพะทะดะฐะฝั‹:\n', threads, '\n') for i in threads: i.start() print('ะŸะพั‚ะพะบะธ ะทะฐะฟัƒั‰ะตะฝั‹:\n', threads, '\n') kill_thread_id = random.randint(0, len(threads)-1) # ะ’ั‹ะฑะธั€ะฐะตะผ ัะปัƒั‡ะฐะนะฝั‹ะน ะฟะพั‚ะพะบ ะดะปั ะพัั‚ะฐะฝะพะฒะบะธ print('kill id =', kill_thread_id, '\n') threads[kill_thread_id].kill() # ะžัั‚ะฐะฝะฐะฒะปะธะฒะฐะตะผ ะฒั‹ะฑั€ะฐะฝะฝั‹ะน ะฟะพั‚ะพะบ # ะ”ะพะถะธะดะฐะตะผัั ะฒั‹ะฟะพะปะฝะตะฝะธะต ะฒัะตั… ะฟะพั‚ะพะบะพะฒ: for i in threads: i.join() print('ะŸะพั‚ะพะบะธ ะฒั‹ะฟะพะปะฝะตะฝั‹:\n', threads) # - # ## ะญะบัะฟะตั€ะธะผะตะฝั‚ ัะบะพั€ะพัั‚ะธ ะฟะพั‚ะพะบะพะฒ # # * CPU-intense ะฒั‹ั‡ะธัะปะตะฝะธั # * 4 ะฟั€ะพั†ะตััะพั€ะฐ # # ```` # | ะญะบัะฟะตั€ะธะผะตะฝั‚ | ะ’ั€ะตะผั | # | ะžะฑั‹ั‡ะฝั‹ะน ะทะฐะฟัƒัะบ | 42ั | # | 2 ะฟะพั‚ะพะบะฐ | 65ั | # | 4 ะฟะพั‚ะพะบะฐ | 80ั | # ```` # # ะงั‚ะพ ะฟั€ะพะธัั…ะพะดะธั‚? ะŸะพั‡ะตะผัƒ ั‚ะฐะบะพะต ะฒั€ะตะผั ะธัะฟะพะปะฝะตะฝะธั? # # ะŸั€ะธั‡ะธะฝะฐ: **GIL** (**G**lobal **I**nterpreter **L**ock) ะดะปั CPython # * ะšะพะด ัะดั€ะฐ CPython ะฝะตะบะพั€ั€ะตะบั‚ะตะฝ ะดะปั ะฝะตัะบะพะปัŒะบะธั… ะฟะพั‚ะพะบะพะฒ (ะทะฐั‚ะพ ะฑั‹ัั‚ั€ะพ ั€ะฐะฑะพั‚ะฐะตั‚ ะดะปั ะพะดะฝะพะณะพ!) # * GIL ะฝะต ะดะฐะตั‚ ะพะดะฝะพะฒั€ะตะผะตะฝะฝะพ ะธัะฟะพะปะฝัั‚ัŒัั ะฝะตัะบะพะปัŒะบะธะผ ะฟะพั‚ะพะบะฐะผ ัะดั€ะฐ # * ะ˜ัะฟะพะปะฝััŽั‰ะธะนัั ะฒ Python ะฟะพั‚ะพะบ "ะทะฐั…ะฒะฐั‚ั‹ะฒะฐะตั‚" ะธะฝั‚ะตั€ะฟั€ะตั‚ะฐั‚ะพั€ ะฝะฐ ะบะพั€ะพั‚ะบะพะต ะฒั€ะตะผั # * ะŸะพัะปะต ะพัะฒะพะฑะพะถะดะตะฝะธั ะฟะพั‚ะพะบะฐ ะธะฝั‚ะตั€ะฟั€ะตั‚ะฐั‚ะพั€ะพะผ ะฟั€ะพะดะพะปะถะธั‚ัŒ ะผะพะถะตั‚ ะดั€ัƒะณะพะน ะฟะพั‚ะพะบ # # ะ—ะฐั‡ะตะผ ะฝัƒะถะตะฝ GIL? # * ะกะบะพั€ะพัั‚ัŒ ะพะดะฝะพะฟะพั‚ะพั‡ะฝั‹ั… ะฟั€ะพะณั€ะฐะผะผ <--> GIL # # ะ—ะฐะดะฐั‡ะธ, ะบะพั‚ะพั€ั‹ะต ะฟั€ะพะฒะพะดัั‚ ะผะฐะปะพ ะฒั€ะตะผะตะฝะธ "ะฒะฝัƒั‚ั€ะธ ัะดั€ะฐ" Python: # * ะ˜ะฝั‚ะตั€ั„ะตะนัั‹ (GUI) # * ะ ะฐะฑะพั‚ะฐ ั ัะตั‚ัŒัŽ # * ะ’ะฒะพะด/ะ’ั‹ะฒะพะด # * ะ’ะฝะตัˆะฝะธะต ะฑะธะฑะปะธะพั‚ะตะบะธ. ะะฐะฟั€ะธะผะตั€ ะบะพั‚ะพั€ั‹ะต ั€ะตะฐะปะธะทะพะฒะฐะฝั‹ ะฝะฐ ะดั€ัƒะณะธั… ัะทั‹ะบะฐั… (NumPy) # # ## ะŸะฐั€ะฐะปะปะตะปัŒะฝั‹ะต ะฟั€ะพั†ะตััั‹ # # * ะ”ะปั ะบะฐะถะดะพะณะพ ะฟั€ะพั†ะตััะฐ ะฒั‹ะดะตะปัะตั‚ัั ัะฒะพะน ะฑะปะพะบ ะฟะฐะผัั‚ะธ # * GIL ะฐะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธ ะธัั‡ะตะทะฐะตั‚ # + from multiprocessing import Process def f(name): print('Hello,', name) p = Process(target=f, args=('World',)) p.start() p.join() # - # ะžะฑะผะตะฝ ะดะฐะฝะฝั‹ะผะธ ะผะตะถะดัƒ ะฟั€ะพั†ะตััะฐะผะธ ะฒะพะทะผะพะถะตะฝ ั‡ะตั€ะตะท: # * multiprocessing.Queue # * multiprocessing.Pipe # # ะะพ ะฑะพะปะตะต ะฟั€ะพัั‚ะพะน ัะฟะพัะพะฑ ะฒั‹ะณะปัะดะธั‚ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ `multiprocessing.Pool`: # + from multiprocessing import Pool def calc(value): return value ** 2 p = Pool(processes=4) results = p.map(calc, range(10)) # map - ะดะปั ะบะฐะถะดะพะณะพ ะธะท ะทะฝะฐั‡ะตะฝะธะน ะฒ range ะฒั‹ะฟะพะปะฝะธั‚ัั ั„ัƒะฝะบั†ะธั calc print(results) # - # ะžะณั€ะฐะฝะธั‡ะตะฝะธั `multiprocessing` - ะญั‚ะพั‚ ะบะพะด ะฝะต ะฑัƒะดะตั‚ ั€ะฐะฑะพั‚ะฐั‚ัŒ, ัƒะฟะฐะดะตั‚ ั ะพัˆะธะฑะบะพะน: # + from multiprocessing import Pool def calc_parallel(values): def calc(value): return value ** 2 p = Pool(processes=2) return p.map(calc, values) calc_parallel(range(10)) # - # ะŸะพั‡ะตะผัƒ? ะšะฐะบ ั€ะฐะฑะพั‚ะฐะตั‚ `multiprocessing`? # ะงั‚ะพะฑั‹ ะฟะตั€ะตะดะฐั‚ัŒ ะฒ ะดั€ัƒะณะพะน ะฟั€ะพั†ะตัั ั„ัƒะฝะบั†ะธัŽ ะบะพั‚ะพั€ัƒัŽ ะฝัƒะถะฝะพ ะฒั‹ะฟะพะปะฝะธั‚ัŒ ะธ ะทะฝะฐั‡ะตะฝะธั # 1. ะ—ะฐะฟัƒัะบะฐะตั‚ัั ะฒั‚ะพั€ะพะน ะธะฝั‚ะตั€ะฟั€ะตั‚ะฐั‚ะพั€ (ะฟั€ะพั†ะตัั ะžะก) # 2. ะ’ ะฝะตะณะพ ะธะผะฟะพั€ั‚ะธั€ัƒะตั‚ัั ะพะฟะตั€ะฐั‚ะพั€ะพะผ `import` ั„ัƒะฝะบั†ะธั `calc` ะธะท ั‚ะตะบัƒั‰ะตะณะพ ะผะพะดัƒะปั # # ะะพ ะฟั€ะพะฑะปะตะผะฐ ะทะดะตััŒ ะฒ ั‚ะพะผ, ั‡ั‚ะพ ั„ัƒะฝะบั†ะธั `calc` ะฝะฐั…ะพะดะธั‚ัั ะฒะฝัƒั‚ั€ะธ ั„ัƒะฝะบั†ะธะธ `calc_parallel` ะธ ะพะฝะฐ ะฝะต ะดะพัั‚ัƒะฟะฝะฐ ะพะฟะตั€ะฐั‚ะพั€ัƒ `import`! ะ˜ะผะฟะพั€ั‚ะธั€ะพะฒะฐั‚ัŒ ะฒะพะทะผะพะถะฝะพ ั‚ะพะปัŒะบะพ ั‚ะต ั„ัƒะฝะบั†ะธะธ, ะบะพั‚ะพั€ั‹ะต ะดะพัั‚ัƒะฟะฝั‹ ะฒ ะณะปะพะฑะฐะปัŒะฝะพะน ะพะฑะปะฐัั‚ะธ ะฒะธะดะธะผะพัั‚ะธ. ะะตะปัŒะทั ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ: # * ะ›ะพะบะฐะปัŒะฝั‹ะต ั„ัƒะฝะบั†ะธะธ # * `lambda` ั„ัƒะฝะบั†ะธะธ # * ะกะพัั‚ะฐะฒะฝั‹ะต ะฒั‹ั€ะฐะถะตะฝะธั ะธ ั‚.ะด. # # ะ”ะปั ะดะฐะฝะฝั‹ั…, `multiprocessing` ัะตั€ะธะฐะปะธะทะธั€ัƒะตั‚ ะพะฑัŠะตะบั‚ั‹ ะฒ ั„ะฐะนะป, ะฐ ะทะฐั‚ะตะผ ะธั… ะธะผะฟะพั€ั‚ะธั€ัƒะตั‚ ะฒ ะดั€ัƒะณะพะน ะฟั€ะพั†ะตัั. ะญั‚ะธ ะพะฑัŠะตะบั‚ั‹ ะดะพะปะถะฝั‹ ะฑั‹ั‚ัŒ "pickable". # # ## ะ’ะฝะตัˆะฝะธะต ะฟั€ะพั†ะตััั‹ # + import os # ะ’ั‹ะฒะพะดะธั‚ ั€ะตะทัƒะปัŒั‚ะฐั‚ ั€ะฐะฑะพั‚ั‹ ะธ ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ ะบะพะด ะฒะพะทะฒั€ะฐั‚ะฐ os.system('ls') # - os.system('echo "Hello, World!"') # ## ะœะพะดัƒะปัŒ subprocess # + import subprocess # ะ’ะผะตัั‚ะพ os.system('echo "Hello, World!"'): subprocess.check_output(['echo', '"Hello, World!"']) # - # ะ’ะพะทะผะพะถะฝะพ ะฒะพะทะฒั€ะฐั‰ะฐั‚ัŒ `Exception`, ะตัะปะธ `shell` ะฟั€ะพะณั€ะฐะผะผะฐ ะทะฐะฒะตั€ัˆะธะปะฐััŒ ะฝะตัƒะดะฐั‡ะฝะพ: try: subprocess.check_output('exit 1', shell=True) except subprocess.CalledProcessError as e: print('ะŸั€ะพะธะทะพัˆะปะพ ะธัะบะปัŽั‡ะตะฝะธะต:', e) # ะ‘ะพะปะตะต ัะปะพะถะฝั‹ะน ัะฟะพัะพะฑ ั€ะฐะฑะพั‚ั‹ ั ะฟั€ะพั†ะตััะฐะผะธ, ะฟะพะดะฟั€ะพั†ะตััะฐะผะธ: p = subprocess.Popen(['echo', 'hi']) # ะ”ะพะถะธะดะฐะตั‚ัั ะพั‚ะฒะตั‚ ะพั‚ ะฟั€ะพั†ะตััะฐ ะธ ะฒะพะทะฒั€ะฐั‰ะฐะตั‚ stdout ะบะพั‚ะพั€ั‹ะน ะฟะพะปัƒั‡ะธะปะฐ print(p.communicate()) # PIPE - ะพะทะฝะฐั‡ะฐะตั‚ ะฟั€ะธะณะพั‚ะพะฒะธั‚ัŒ `stdout` ะดะปั ะดั€ัƒะณะพะณะพ ะฟั€ะพั†ะตััะฐ: p = subprocess.Popen(['echo', 'hi'], stdout=subprocess.PIPE) print(p.communicate()) # ะŸะตั€ะตะดะฐะตั‚ัั ะฝะฐ `stdin` ะฟะพะดะฟั€ะพั†ะตััะฐ: p = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) print(p.communicate('sample text'.encode('utf8'))) # Pipeline: p1 = subprocess.Popen(['echo', 'qwerty'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['tr', 'q', 'z'], stdin=p1.stdout, stdout=subprocess.PIPE) # ะงั‚ะพะฑั‹ ัั‚ะพ ะฝะต ะฟะฐะดะฐะปะพ ะฒ ะพัˆะธะฑะบัƒ, ะฟะตั€ะตะด ั‚ะตะผ ะบะฐะบ ะฒั‹ะทะฒะฐั‚ัŒ `communicate()` ัƒ ะฒั‚ะพั€ะพะณะพ ะฟั€ะพั†ะตััะฐ, ะฝัƒะถะฝะพ ัƒ ะฟะตั€ะฒะพะณะพ ะฟั€ะพั†ะตััะฐ ะทะฐะบั€ั‹ั‚ัŒ `stdout`: p1.stdout.close() print(p2.communicate())
lesson-12.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Lecture-02 Snell's Law # * author : <NAME> # * Data : 2019/12/03 # %matplotlib inline import matplotlib.pyplot as plt import numpy as np # ## Snell's Law # Snell's Law is an equation describing the relation between the angle of the incident ray and the angle of the refracted ray. $n_i$ and $n_t$ is the refractive index of the incident material and the transmissive material, respectively. Besides, $\theta_i$ is the incident angle and $\theta_t$ is the transmissive angle as in **Fig. 1**. # # # <img src="Lecture-2-Material/Fig-1 Snells Law.jpg" width="600" /> # # $$Fig. 1. (a) n_t<n_i (b) n_t>n_i $$ # # # <font size="4">Snell's Law:</font> # # <font size="4">$$n_isin\theta_i = n_tsin\theta_t$$</font> # # From Snell's Law, it is obvious that if $n_t<n_i$, $\theta_t$ would be larger than $\theta_i$ as in **Fig. 1(a)**. On the other hand, if $n_t>n_i$, $\theta_t$ would be smaller than $\theta_i$ as in **Fig. 1(b)**. def SnellLaw(theta_i, ni, nt=1.0): # theta_i : incident angle # ni : the refractive index of the incident material # nt : the refractive index of the transmissive material theta_i = np.array( theta_i, dtype=np.complex_ ) # theta_t : refractive angle theta_t = np.arcsin( (ni/nt) * np.sin(theta_i) ) return theta_t # + theta_i = np.linspace(0, np.pi/2, 10000) theta_t = SnellLaw( theta_i, ni = 1.5, nt = 1.0) ## plot data fig, axes = plt.subplots(1,1) axes.plot( theta_i*180/np.pi, theta_t*180/np.pi, 'r-', linewidth=2.0) axes.set_xlabel(r'$\theta_i$ (deg.)', fontsize=20) axes.set_ylabel(r'$\theta_t$ (deg.)', fontsize=20) plt.xlim( 0, 90); plt.ylim( 0, 90); # + theta_i = np.linspace(0, np.pi/2, 1000) theta_t = SnellLaw( theta_i, ni = 1.0, nt = 1.5) ## plot data fig, axes = plt.subplots(1,1) axes.plot( theta_i*180/np.pi, theta_t*180/np.pi, 'r-', linewidth=2.0) axes.set_xlabel(r'$\theta_i$ (deg.)', fontsize=20) axes.set_ylabel(r'$\theta_t$ (deg.)', fontsize=20) plt.xlim( 0, 90); plt.ylim( 0, 90); # - # * From Snell's Law, critical angle, $\theta_c$, can be defined as # $$\theta_c=sin^{-1}(\frac{n_t}{n_i})$$ def CriticalAngle( ni, nt): return np.arcsin( nt/ni ) if nt<=ni else np.pi/2 print( 'From ni=1.0 into nt=1.5, critical angle is {0:>.2f} degree'.format( CriticalAngle( 1.0, 1.5) * 180/np.pi ) ) print( 'From ni=1.5 into nt=1.0, critical angle is {0:>.2f} degree'.format( CriticalAngle( 1.5, 1.0) * 180/np.pi ) ) # + ni = 1.5; nt_list = np.linspace(1.0, 2.5, 150) ## find critical angles CA_List = np.zeros( nt_list.size, dtype=np.float64 ) for ii in range( len( nt_list ) ): CA_List[ii] = CriticalAngle( ni, nt_list[ii] ) ## plot data fig, axes = plt.subplots(1,1) axes.plot(nt_list, CA_List*180/np.pi, 'r-', linewidth=2.0) axes.set_xlabel(r'$n_t$', fontsize=20) axes.set_ylabel(r'$\theta_c$ (deg.)', fontsize=20) plt.xlim( np.min(nt_list), np.max(nt_list)); plt.ylim( 0, 90); # - # ## But how does Snell's Law come from? # In the physics of senior high school, the teacher would tell us that the light is in wave nature. Here, we'll going to use wave property to prove the Snell's Law. # # As in **Fig.2.**, the wave front should be normal to the propagation direction and besides, the propagation vector is parallel to the wave vector $\textbf{k}=(k_x,k_y,k_z)$ and the relation between $k_x,k_y,k_z$, refractive index (n), and the angular frequency, $\omega$, is # # <font size="4">$$(nk_0)^2 = k^2 = k_x^2 + k_y^2 + k_z^2$$</font> # <font size="4">$$k_o = \omega/c = 2\pi/\lambda$$</font> # # where c is the speed of light in vacuum and $k_o$ is the wave number in vacuum. # # # Besides, as shown in **Fig. 2.**, according to the boundary condition, the wavelength along the surface should be continuous in both the incident material and the transmissive material. (i.e. $\lambda_{x,i}=\lambda_{x,t}$ and $\lambda_{y,i}=\lambda_{y,t}$ ). Besides, as discussed in **Lecture 1**, the components of the wave vector can be quitely write down by the wavelength along the arbitraty direction (i.e. $k_x = 2\pi/\lambda_x$). So the tangential wave number should also be continuous on the boundary. Then, # # <font size="4">$$k_{x,i}=k_{x,t}$$</font> # <font size="4">$$k_{y,i}=k_{y,t}$$</font> # # As a result, the z component of the wave vector in material 1 and material 2 can be calculated as the following blocks. # <img src="Lecture-2-Material/Fig-2 Snells Law.jpg" width="400" > # $$Fig. 2. $$ # # def cal_kz(k, kx, ky): # n : refractive index # ko : wave number in vacuum # kx : wave number along x-axis # ky : wave number along y-axis kz = np.sqrt( k**2 - kx**2 - ky**2, dtype=np.complex_ ) # process floating mask = np.abs( np.real(kz) )<1e-15 kz[mask] = 1j * np.imag( kz[mask] ) mask = (np.real(kz)==0) & (np.imag( kz )<0) kz[mask] = -kz[mask] return kz wavelength = 550 # incident wavelength (nm) ko = 2 * np.pi/wavelength # wave number in vacuum ni = 1.5 # refractive index of incident material nt = 1.0 # refractive index of transmissive material # <font size="4">$$k_x = ksin\theta cos\phi$$</font> # <font size="4">$$k_y = ksin\theta sin\phi$$</font> # <font size="4">$$k_z = kcos\theta$$</font> # + k_i = ni * ko theta_i = np.linspace(0, np.pi/2, 1000, dtype=np.complex_) phi_i = np.zeros( theta_i.size, dtype=np.complex_) kx_i = k_i * np.sin(theta_i) * np.cos(phi_i) ky_i = k_i * np.sin(theta_i) * np.sin(phi_i) kz_i = cal_kz(k_i, kx_i, ky_i) ## plot data fig, axes = plt.subplots(1,1) axes.plot(theta_i*180/np.pi, kx_i, 'r-', linewidth=2.0) axes.plot(theta_i*180/np.pi, kz_i, 'k-', linewidth=2.0) axes.set_xlabel(r'$\theta_i$ (deg.)', fontsize=20) axes.legend([r'$k_{x,i}$', r'$k_{z,i}$'], fontsize=20) plt.xlim( 0, 90); # + k_t = nt * ko kx_t, ky_t = kx_i, ky_i # continuity in tangential components of the wave vector kz_t = cal_kz(k_t, kx_t, ky_t) ## plot data fig, axes = plt.subplots(1,1) axes.plot(theta_i*180/np.pi, kx_i, 'r-', linewidth=2.0) axes.plot(theta_i*180/np.pi, kz_i, 'k-', linewidth=2.0) axes.plot(theta_i*180/np.pi, kz_t, 'b-', linewidth=2.0) axes.set_xlabel(r'$\theta_i$ (deg.)', fontsize=20) axes.legend([r'$k_{x,i}$', r'$k_{z,i}$', r'$k_{z,t}$'], fontsize=10) plt.xlim( 0, 90); # - # Up to now, we have calculated the wave vector of the refracted light, hence the refracted angle can be calculated as: # # <font size="4">$$\theta = cos^{-1}(\frac{k_z}{k})$$</font> def cal_theta_from_vector(vx, vy, vz): v_len = np.sqrt( vx**2 + vy**2 + vz**2) theta = np.arccos( vz/v_len ) return theta # + theta_t = cal_theta_from_vector(kx_t, ky_t, kz_t) theta_t_SL = SnellLaw(theta_i, ni, nt) ## plot data fig, axes = plt.subplots(1,1) axes.plot( theta_i*180/np.pi, theta_t_SL*180/np.pi, 'k-', linewidth=2.0) axes.plot( theta_i*180/np.pi, theta_t*180/np.pi, 'r-', linewidth=2.0) axes.set_xlabel(r'$\theta_i$ (deg.)', fontsize=20) axes.set_ylabel(r'$\theta_t$ (deg.)', fontsize=20) axes.legend(["calculate from Snell's Law", "calculate from wave front"], fontsize=15) plt.xlim( 0, 90); plt.ylim( 0, 90); # - # From the calculation in the previous steps, the tangential components of the wave vectors are continuous on the boundary. However, the normal components of the wave vectors are not continuous and they should depend on the refractive index of the material and the tangential wave vector components. Because the value of the z component would be changed in the different material, the angle of the ray should be followingly adjusted, which would correspond to the Snell's Law and it was also proved by the previous simulation. As a result, Snell's Law is one of the phenomenon of the wave nature of light.
Lecture-02 Snell's Law.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Timing your code # Sometimes it's important to know how long your code is taking to run, or at least know if a particular line of code is slowing down your entire project. Python has a built-in timing module to do this. # # This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times. # # Let's learn about timeit! import timeit # Let's use timeit to time various methods of creating the string '0-1-2-3-.....-99' # # We'll pass two arguments: the actual line we want to test encapsulated as a string and the number of times we wish to run it. Here we'll choose 10,000 runs to get some high enough numbers to compare various methods. # For loop timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) # List comprehension timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) # Map() timeit.timeit('"-".join(map(str, range(100)))', number=10000) # Great! We see a significant time difference by using map()! This is good to know and we should keep this in mind. # # Now let's introduce iPython's magic function **%timeit**<br> # *NOTE: This method is specific to jupyter notebooks!* # # iPython's %timeit will perform the same lines of code a certain number of times (loops) and will give you the fastest performance time (best of 3). # # Let's repeat the above examinations using iPython magic! # %timeit "-".join(str(n) for n in range(100)) # %timeit "-".join([str(n) for n in range(100)]) # %timeit "-".join(map(str, range(100))) # Great! We arrive at the same conclusion. It's also important to note that iPython will limit the amount of *real time* it will spend on its timeit procedure. For instance if running 100000 loops took 10 minutes, iPython would automatically reduce the number of loops to something more reasonable like 100 or 1000. # # Great! You should now feel comfortable timing lines of your code, both in and out of iPython. Check out the documentation for more information: # https://docs.python.org/3/library/timeit.html
13-Advanced Python Modules/04-Timing your code - timeit.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Bucles # # Asรญ como podemos necesitar que uno u otro fragmento de cรณdigo dependiendo de ciertas condiciones, tambiรฉn podemos necesitar que un fragmento de cรณdigo se repita tantas veces como se cumpla una condiciรณn. Para ello utilizamos los **Bucles**. # # De **Python para todos** de _<NAME>_: # # > Mientras que los condicionales nos permiten ejecutar distintos fragmentos de cรณdigo dependiendo de ciertas condiciones, los bucles nos permiten ejecutar un mismo fragmento de cรณdigo un cierto nรบmero de veces, mientras se cumpla una determinada condiciรณn. # # En Python encontraremos dos tipos de bucles: `for` y `while`. # # ### `while` # # `While` (_mientras_ en inglรฉs) nos permite ejecutar fragmento un cรณdigo, **mientras** vez que se cumpla una condiciรณn. # # Veamos un ejemplo: # + n = 1 while n <= 10: print(n) n = n+1 # - # Si representaramos el fragmento de cรณdigo con un flujograma tendrรญamos: # # ![Bucle while](./Diagramas/Ejemplo-while.png) # # Para definir entonces un bucle utilizando `while` debemos comenzar la linea con `while`, seguido de la condiciรณn que queremos (aquรญ `n <= 10`) y finalizamos la linea con `:`. # # Despuรฉs escribimos el bloque de cรณdigo que queremos que se ejecute indendado a 4 espacios. # # Para el caso de este bucle, tenemos que agregar al final una linea que incremente la variable (`n = n+1`), para que el bucle pueda finalizar en algรบn momento. Si no el bucle se repeterรญa una y otra vez sin nunca lograr terminar (lo que se llama un _bucle infinito_). # # Como este tipo de operaciones son muy comunes, en python se puede ocupar el operador `+=`: # + n = 1 while n <= 10: print(n) n += 1 # - # Tambiรฉn existen los operadores `*=`, `-=`, etc. # # Muchas veces los bucles infinitos pueden llegar a ser รบtiles en un programa, por ejemplo: # + numero = int(input("Ingrese un nรบmero positivo: ")) while numero <= 0: numero = int(input("Error. Por favor ingrese un nรบmero positivo: ")) # - # En este caso el bucle se repite hasta que el usuario ingrese un nรบmero correcto. # # Tambiรฉn se pueden utilizar `else` en los bucles (tanto `while` como `for`) que son fragmentos de cรณdigo que se ejecutan al finalizar el bucle: # + n = 1 while n <= 10: print(n) n += 1 else: print("Fin") # - # ## `for` # # La secuencia`for` (_para_ en inglรฉs) nos permite iterar sobre los elementos de una secuencia. Asรญ se ejecutarรก el mismo bloque de cรณdigo, **para todos los elementos** de la secuencia. Por ejemplo: # + numeros = 1, 2, 3, 4, 5, 6, 7, 8 for elemento in numeros: print(elemento) # - # Vemos entonces que para crear un bucle debemos comenzar la linea con `for`, luego poner el nombre de la variable que almacenarรก los valores del la secuencia dentro del bucle (en nuestro caso `elemento`), la palabra `in`(_en_ en inglรฉs), y la secuencia sobre la que queremos iterar. # ### `range` # # A medida que las secuencias con elementos a iterar crece, se vuelve tedioso escribir todos los valores a mano. Para evitarnos este trabajo python tiene la funciรณn `range()`: # Sin embargo, a medida que la lista con elementos a iterar crece, se vuelve tedioso escribir una lista con todos los valores. Para evitarnos este trabajo python tiene la funciรณn `range()`: for i in range(10): print("El cubo de", i, "es", i**3) # Vemos que `range()` genera una secuencia que va desde el 0 hasta el nรบmero que especificamos, **sin incluirlo**. Si queremos, entonces, crear una lista que vaya del uno al nรบmero que queremos, tenemos dos opciones: for i in range(11): print("El cubo de", i, "es", i**3) for i in range(10+1): print("El cubo de", i, "es", i**3) # La segunda nos puede llegar a ser รบtil en alguno de los casos que el nรบmero final lo ingrese el usuario. # # Tambiรฉn podemos ingresar el nรบmero en el que queremos que empiece la funciรณn `range`: # + print("Los nรบmeros pares entre 1 y 10 son:") for x in range(1, 11): if x%2 == 0: print(x) # - # Asรญ tambiรฉn podemos especificar el incremento de la funciรณn: # + print("Los nรบmeros mรบltiplos de 3 entre 1 y 20 son:") for x in range(3, 21, 3): print(x) # - # Veamos ahora un ejemplo del uso de un bucle for con funciones. # # ##### Ejemplo 1 def masa_alcano(cant_carbonos): """Calcula la masa de un alcano linea, ingresando la cantidad de carbonos de la cadena """ cant_hidrogenos = 2*cant_carbonos + 2 masa_molecular = 12*cant_carbonos + 1*cant_hidrogenos return masa_molecular # En ese caso podemos calcular la masa de los distintos compuestos de la cadena de alcanos llamando a la funciรณn `masa_alcano` masa_alcano(1), masa_alcano(2) # Si queremos calcular la masa molecular de los primeros 10 alcanos de la serie, podrรญamos hacer lo siguiente: for cantidad in range(1, 11): print("La masa del alcano con", cantidad, "carbonos es", masa_alcano(cantidad)) # ### Acumuladores y contadores # # En muchos programas necesitaremos incluir distintas variables dentro de los bucles, de modo tal de que estas se modifiquen a medida de que se ejecute el cรณdigo. Para distintos casos necesitaremos entonces **Acumuladores** y **Contadores**. # # #### Acumuladores # # Los contadores son un tipo de variable que se incrementa (o decrementa) en un cierto valor a medida que se ejecuta un fragmento de cรณdigo. Veamos un ejemplo: # # ##### Ejemplo 2 # Cree un programa que calcule la suma desde 1 hasta el nรบmero ingresado por el usuario # + final = int(input("Ingrese un nรบmero: ")) sumatoria = 0 for numero in range(1, final+1): sumatoria += numero print(sumatoria) # - # En este ejemplo, la variable `sumatoria` es un _acumulador_. # # Lo primero que obsevamos es que esta variable estรก definida _fuera del bucle_ con el valor 0. A esto se denomina _"inicializar el acumulador"_ y siempre tiene que hacerse, ya que si no python no va a saber a que valor sumarle la variable `i` dentro del bucle. # # Ademรกs **nunca** debe hacerse `acumulador = 0` dentro del bucle, ya que esto resetearรญa el valor a cero en cada iteraciรณn. # Pensemos ahora en quรฉ hace la siguiente lรญnea: # # ```python # sumatoria += numero # ``` # # Como ya lo vimos arriba, este fragmento es igual a escribir: # # ```python # sumatoria = sumatoria + numero # ``` # # Allรญ al valor de `sumatoria` se le suma el valor de `numero`, y se lo guarda en `sumatoria` nuevamente (de allรญ el nombre **acumulador**). # # Veamos ahora un ejemplo de acumulador dentro de una funciรณn: # ##### Ejemplo 2 # # Defina una funciรณn que calcule el factorial de un nรบmero dado def factorial(nro): """Calcula el factorial del nรบmero ingresado """ factorial=1 for i in range(1, nro+1): factorial *= i return factorial factorial(6) # #### Contadores # # Los contadores son un tipo de variable que tienen una funciรณn especial, incrementarse cada vez que se cumpla una determinada condiciรณn. Por ejemplo, cuando vimos el ejemplo con `while` tenรญamos una variable `n` que se incrementaba en uno en cada ciclo del bucle (`n += 1`). # Para aprender mรกs de acumuladores y contadores puedes consultar el libro, asรญ como tambiรฉn ver esta publicaciรณn en el blog [10 goto 10](https://medium.com/10-goto-10/algoritmos-variables-contadores-y-acumuladores-6d8f7d1bfbc7)
Clase 3 - Bucles.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/abhishekworkspace/SmartEnergy/blob/master/pre.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="M-sbs733zUYR" colab_type="code" colab={} # + id="ZbblcmQhy2IQ" colab_type="code" outputId="51c5a814-cd80-450e-969c-8c68959a80db" colab={"base_uri": "https://localhost:8080/", "height": 35} from google.colab import drive drive.mount('/content/gdrive/') # + id="6WJbKYliGSlB" colab_type="code" colab={} import pandas as pd import numpy as np import time import datetime as dt from sklearn.cluster import KMeans import random from math import sqrt import matplotlib.pylab as plt import seaborn as sns # + id="KbDyJ5y-GSlF" colab_type="code" colab={} def toTimeStamp(date): for fmt in ('%d-%m-%Y %H:%M:%S', '%d-%m-%Y %H:%M', '%d/%m/%Y %H:%M'): try: return int(time.mktime(dt.datetime.strptime(date, fmt).timetuple())) except ValueError: pass # + id="HLfomelcGSlI" colab_type="code" colab={} def toStrTime(timestamp): return time.strftime("%d/%m/%Y %H:%M", dt.datetime.fromtimestamp(timestamp).timetuple()) # + id="iuH3HHfzGSlK" colab_type="code" colab={} def toDateTime(timestamp): return pd.to_datetime(timestamp, unit='s') + pd.Timedelta('05:30:00') # + id="i-86ZhaIGSlM" colab_type="code" outputId="dcf990f2-98fa-454a-e665-301a3d875b47" colab={"base_uri": "https://localhost:8080/", "height": 467} df = pd.read_csv("Energy.csv") df["Time"] = df["Time"].apply(toTimeStamp) initialValue = toTimeStamp("31/12/2017 11:15") finalValue = toTimeStamp("1/1/2019 00:00") df2018 = df[df.apply(lambda x: initialValue <= x[0] < finalValue, axis = 1)] newIndex = pd.Index( np.arange(initialValue, finalValue, 15*60), name= "Time") finalDf = df2018.set_index("Time").reindex(newIndex).reset_index() # + id="U9HqPmz5GSlO" colab_type="code" colab={} ## Missing Value Interpretation for i in range(2, finalDf.shape[0]): if(pd.isna(finalDf.loc[i, "Energy"])): if(pd.isna(finalDf.loc[i+1, "Energy"])): finalDf.loc[i, "Energy"] = np.average([finalDf.loc[i-1, "Energy"], finalDf.loc[i-2, "Energy"]]) else: finalDf.loc[i, "Energy"] = np.average([finalDf.loc[i-1, "Energy"], finalDf.loc[i+1, "Energy"]]) finalDf = finalDf[finalDf.Time.apply(lambda x: x >= toTimeStamp("1/1/2018 00:00"))] finalDf.head() # + id="f5A4pbG4GSlS" colab_type="code" colab={} finalDf['Time'] = pd.to_datetime(finalDf['Time'], unit='s') finalDf.head() # + id="CJw780-NGSlW" colab_type="code" colab={} finalDf.set_index('Time',inplace=True) # + id="I9-V6s_dGSlZ" colab_type="code" colab={} ## Normalization finalDf.Time = finalDf.Time.apply(toDateTime) dfMin = finalDf.Energy.min() dfMax = finalDf.Energy.max() finalDf.Energy = finalDf.Energy.apply(lambda x: (x - dfMin)/(dfMax - dfMin)) finalDf.Energy.head() # + id="Sap56wwZGSlc" colab_type="code" colab={} #### Outlier Detection outlierValue = finalDf["Energy"].mean() + 2*finalDf["Energy"].std() def replace(value): return outlierValue if(value > outlierValue) else value finalDf.Energy = finalDf.Energy.apply(lambda x: outlierValue if(x > outlierValue) else x) finalDf.Energy.head() # + id="NzuqOeADGSlg" colab_type="code" colab={} finalDf['dayofyear'] = finalDf.index.dayofyear finalDf['month'] = finalDf.index.month finalDf['date'] = finalDf.index.date finalDf['dayofweek'] = finalDf.index.dayofweek + 1 finalDf['hourofday'] = finalDf.index.hour finalDf['minuteofday'] = finalDf.index.minute finalDf['daytype'] = ((pd.DatetimeIndex(finalDf.index).dayofweek) // 5 == 1).astype(int) # + id="xr8tw9sjGSlj" colab_type="code" colab={} def assign_season(temp_df): if temp_df['month'] in [10,11,12,1,2]: return 1 elif temp_df['month'] in [3,4,5,6]: return 2 elif temp_df['month'] in [7,8,9]: return 3 # + id="hx7upzfWGSlm" colab_type="code" colab={} finalDf['season'] = finalDf.apply(assign_season, axis=1) finalDf.head() # + id="m6tRaEsSGSlo" colab_type="code" colab={} finalDf.to_csv('Normalized 2018.csv') # + id="URcGcbCsGSlr" colab_type="code" colab={} ## Normalization finalDf.Time = finalDf.Time.apply(toDateTime) dfMin = finalDf.Energy.min() dfMax = finalDf.Energy.max() finalDf.Energy = finalDf.Energy.apply(lambda x: (x - dfMin)/(dfMax - dfMin)) finalDf.Energy.head() # + id="tEWrjqgvGSlu" colab_type="code" colab={} cl = pd.read_csv("Cluster 2\\Cluster2n.csv") cl.head() # + id="wONqVOW-GSlw" colab_type="code" colab={} clu = cl.loc[cl['month'].isin(['3', '5'])] clu.to_csv('Cluster3n.csv') # + id="K7HXh4ObGSlz" colab_type="code" colab={} clu = cl.loc[cl['dayofweek'].isin(['1'])] clu.to_csv('Cluster2Mondayn.csv') # + id="zhSaFCFuGSl1" colab_type="code" colab={}
pre.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Self-Driving Car Engineer Nanodegree # # ## Deep Learning # # ## Project: Build a Traffic Sign Recognition Classifier # # In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. # # > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", # "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. # # In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project. # # The [rubric](https://review.udacity.com/#!/rubrics/481/view) contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file. # # # >**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. # --- # ## Step 0: Load The Data # + # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data training_file = './traffic-signs-data/train.p' validation_file='./traffic-signs-data//valid.p' testing_file = './traffic-signs-data/test.p' signnames_file = './signnames.csv' with open(training_file, mode='rb') as f: train = pickle.load(f) with open(validation_file, mode='rb') as f: valid = pickle.load(f) with open(testing_file, mode='rb') as f: test = pickle.load(f) X_train, y_train = train['features'], train['labels'] X_valid, y_valid = valid['features'], valid['labels'] X_test, y_test = test['features'], test['labels'] # - # --- # # ## Step 1: Dataset Summary & Exploration # # The pickled data is a dictionary with 4 key/value pairs: # # - `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels). # - `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id. # - `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image. # - `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES** # # Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. # ### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas # + ### Replace each question mark with the appropriate value. ### Use python, pandas or numpy methods rather than hard coding the results # TODO: Number of training examples n_train = X_train.shape[0] # TODO: Number of validation examples n_validation = X_valid.shape[0] # TODO: Number of testing examples. n_test = X_test.shape[0] # TODO: What's the shape of an traffic sign image? image_shape = X_test.shape[1:] # TODO: How many unique classes/labels there are in the dataset. n_classes = len(set(y_train)) print("Number of training examples =", n_train) print("Number of Validation examples", n_validation) print("Number of testing examples =", n_test) print("Image data shape =", image_shape) print("Number of classes =", n_classes) # - # ### Include an exploratory visualization of the dataset # Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. # # The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python. # # **NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others? # + ### Data exploration visualization code goes here. ### Feel free to use as many code cells as needed. import matplotlib.pyplot as plt import numpy as np import pandas as pd # Visualizations will be shown in the notebook. # %matplotlib inline import collections a = collections.Counter(y_train) x = [] y = [] for i in range(n_classes): x.append(i) y.append(a[i]) def plotbarh(x,y,labels,title): width = 1/1.5 flg, ax = plt.subplots(figsize = (20,20)) y_pos = np.arange(n_classes) ax.barh(x, y, width, color="blue") ax.set_yticks(y_pos) ax.set_yticklabels(labels, fontsize=16) ax.invert_yaxis() ax.grid() ax.set_title(title, fontsize = 26) for i in range(len(x)): ax.text(y[i]+10,i,y[i], fontsize = 12) plt.show() signnames = pd.read_csv(signnames_file)['SignName'] plotbarh(x,y,signnames,'Class Distribution in the Training Set') a = collections.Counter(y_valid) x = [] y = [] for i in range(n_classes): x.append(i) y.append(a[i]) plotbarh(x,y,signnames,'Class Distribution in the Validation Set') # - import scipy.misc img = scipy.misc.toimage(X_train[3000]) plt.imshow(img) # ---- # # ## Step 2: Design and Test a Model Architecture # # Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset). # # The LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! # # With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. # # There are various aspects to consider when thinking about this problem: # # - Neural network architecture (is the network over or underfitting?) # - Play around preprocessing techniques (normalization, rgb to grayscale, etc) # - Number of examples per label (some have more than others). # - Generate fake data. # # Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these. # ### Pre-process the Data Set (normalization, grayscale, etc.) # Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. # # Other pre-processing steps are optional. You can try different techniques to see if it improves performance. # # Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. # + ### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include ### converting to grayscale, etc. ### Feel free to use as many code cells as needed. #first, change range of the image pixel from 0-255 to 0-1. #first convert color to grayscale using the equation grayscale = 0.2989 * r + 0.5870 * g + 0.1140 * b def Preprocessimage(images): image_shape = (images.shape[1],images.shape[2]) result = 0.2989 *images[:,:,:,0]+ 0.5870 *images[:,:,:,1]+ 0.1140 *images[:,:,:,2] result = result/255.0 result = result.reshape([-1,image_shape[0], image_shape[1], 1]) return result X_traingray = Preprocessimage(X_train) X_validgray = Preprocessimage(X_valid) X_testgray = Preprocessimage(X_test) plt.imshow(X_train[1000]) plt.show() plt.imshow(X_traingray[1000].reshape(32,32),'gray') plt.show() # - # ### Model Architecture # + ### Define your architecture here. ### Feel free to use as many code cells as needed. import tensorflow as tf import imutils from tensorflow.contrib.layers import flatten EPOCHS = 100 BATCH_SIZE = 128 rate = 0.0005 keepprop = .5 def getbatch(x,y,amount,i=-1, change=False): if (i==-1): batchindexes = np.random.randint(len(x),size=amount) xbatch= np.copy(x[batchindexes]) ybatch= np.copy(y[batchindexes]) else: maxi = min(x.shape[0],i+amount) xbatch= np.copy(x[i:maxi]) ybatch= np.copy(y[i:maxi]) if (change==True): for i in range(xbatch.shape[0]): angle = np.random.randint(-180,180) rotated = scipy.ndimage.interpolation.rotate(xbatch[i], angle,reshape=False) xbatch[i] = rotated return xbatch,ybatch def conv2d(dx, kernel, outputdepth, strides,mu,sigma): inputdepth = int(dx.shape[3]) shape = (kernel,kernel,inputdepth,outputdepth) filter_weights = tf.Variable(tf.truncated_normal(shape,mean=mu,stddev=sigma)) # (height, width, input_depth, output_depth) filter_bias = tf.Variable(tf.zeros(outputdepth)) padding = 'VALID' stridessize = [1,strides,strides,1] conv = tf.nn.conv2d(dx, filter_weights, stridessize, padding) + filter_bias return conv def fullyconnected(dx,outputsize,mu,sigma): inputsize = int(dx.shape[1]) weights = tf.Variable(tf.truncated_normal((inputsize,outputsize),mean=mu,stddev=sigma)) filter_bias = tf.Variable(tf.zeros(outputsize)) fc = tf.matmul(dx,weights)+filter_bias return fc def LeNet(inputdata, keepprop): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0.0 sigma = 0.1 a=0.001 net = conv2d(inputdata,5,6,1,mu,sigma) net = tf.maximum(a*net,net) net = tf.nn.max_pool(net,[1,2,2,1],[1,2,2,1],padding='VALID') net = conv2d(net,5,16,1,mu,sigma) net = tf.maximum(a*net,net) net = tf.nn.max_pool(net,[1,2,2,1],[1,2,2,1],padding='VALID') net = flatten(net) net = fullyconnected(net,120,mu,sigma) net = tf.maximum(a*net,net) net = tf.nn.dropout(net,keepprop) net = fullyconnected(net,84,mu,sigma) net = tf.maximum(a*net,net) net = tf.nn.dropout(net,keepprop) logits = fullyconnected(net,n_classes,mu,sigma) return logits def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] accuracy = sess.run(accuracy_operation, feed_dict={inputx: batch_x, labels: batch_y,keepprop:1.0}) total_accuracy += (accuracy * len(batch_x)) return total_accuracy / num_examples # - def printtop5prob(image,groundtruth,labels): sess = tf.get_default_session() allprob = sess.run(probability_prediction, feed_dict={inputx: image, keepprop:1.0})[0] allprodict = dict() for i in range(len(allprob)): allprodict[i]=allprob[i] allprodictsorted = sorted(allprodict, key=allprodict.get, reverse=True) top5 = allprodictsorted[:5] label = [] proboflabel = [] labelname = [] for item in top5: label.append(item) proboflabel.append(allprodict[item]) labelname.append(labels[item]) fig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2, sharex=False, sharey=False, figsize = (30,10)) ax1.imshow(image.reshape(32,32),'gray') y_pos = np.arange(len(labelname)) result = 0 if (label[0]!=groundtruth): ax2.barh(range(5), proboflabel, color="red", align='edge') else: ax2.barh(range(5), proboflabel, color="blue", align='edge') result = 1 ax2.set_yticks(y_pos) ax2.set_yticklabels(labelname, fontsize=16) ax2.invert_yaxis() ax2.grid() ax2.set_title("Top 5 Probabilities") fig.tight_layout() for i in range(len(labelname)): ax2.text(1,i,proboflabel[i], fontsize = 12) plt.show() print (labels[groundtruth]) return result def predict(image): sess = tf.get_default_session() allprob = sess.run(probability_prediction, feed_dict={inputx: image, keepprop:1.0})[0] allprodict = dict() for i in range(len(allprob)): allprodict[i]=allprob[i] allprodictsorted = sorted(allprodict, key=allprodict.get, reverse=True) result = allprodictsorted[0] return result # + image_shape = X_traingray.shape inputshape = (None,image_shape[1],image_shape[2],image_shape[3]) inputx = tf.placeholder(tf.float32,shape=inputshape) labels = tf.placeholder(tf.int32, shape=(None)) one_hot_y = tf.one_hot(labels, int(n_classes)) keepprop = tf.placeholder(tf.float32) logits = LeNet(inputx,keepprop) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)) training_operation = tf.train.AdamOptimizer(learning_rate = rate).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) probability_prediction = tf.nn.softmax(logits) # + import scipy.misc np_array=getbatch(X_traingray,y_train,1,-1,change=True)[0] np_array = np_array.reshape((32,32)) plt.imshow(np_array,cmap='gray') # - # ### Train, Validate and Test the Model # A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation # sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting. # + from sklearn.utils import shuffle saver = tf.train.Saver() config = tf.ConfigProto() config.gpu_options.allow_growth=True with tf.Session(config = config) as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for step in range(EPOCHS): X_traingray, y_train = shuffle(X_traingray, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH_SIZE batch_x, batch_y = X_traingray[offset:end], y_train[offset:end] sess.run(training_operation, feed_dict={inputx: batch_x, labels: batch_y,keepprop:0.5}) train_accuracy = evaluate(X_traingray, y_train) validation_accuracy = evaluate(X_validgray, y_valid) print("EPOCH {} ...".format(step+1)) print("Train Accuracy = {:.3f}".format(train_accuracy)) print("Validation Accuracy = {:.3f}".format(validation_accuracy)) print() saver.save(sess, './lenet') print("Model saved") # - saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_testgray, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy)) # --- # # ## Step 3: Test a Model on New Images # # To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type. # # You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name. # ### Load and Output the Images # + ### Load the images and plot them here. ### Feel free to use as many code cells as needed. import os import cv2 web_imagefolder = './Webdownloadimages/' webimages=[] webimagesclasses = [] for file in os.listdir(web_imagefolder): print (file) webimages.append(cv2.imread(web_imagefolder+file)) webimagesclasses.append(int(file.split('.')[0])) webimages =np.array(webimages) for image in webimages: plt.imshow(image) plt.show() # - # ### Predict the Sign Type for Each Image # + ### Run the predictions here and use the model to output the prediction for each image. ### Make sure to pre-process the images with the same pre-processing pipeline used earlier. ### Feel free to use as many code cells as needed. saver = tf.train.Saver() webimagesgray = Preprocessimage(webimages) total = 0 right = 0 with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) for classnum, image in zip (webimagesclasses,webimagesgray): total+=1 right+=printtop5prob(image.reshape(1,32,32,1),classnum,signnames) # - # ### Analyze Performance # + ### Calculate the accuracy for these 5 new images. ### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images. Accuracy = right/total*100 print ("Accurancy = {0}%".format(Accuracy)) # - # ### Output Top 5 Softmax Probabilities For Each Image Found on the Web # For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#top_k) could prove helpful here. # # The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image. # # `tf.nn.top_k` will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids. # # Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. `tf.nn.top_k` is used to choose the three classes with the highest probability: # # ``` # # (5, 6) array # a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497, # 0.12789202], # [ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401, # 0.15899337], # [ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 , # 0.23892179], # [ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 , # 0.16505091], # [ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137, # 0.09155967]]) # ``` # # Running it through `sess.run(tf.nn.top_k(tf.constant(a), k=3))` produces: # # ``` # TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202], # [ 0.28086119, 0.27569815, 0.18063401], # [ 0.26076848, 0.23892179, 0.23664738], # [ 0.29198961, 0.26234032, 0.16505091], # [ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5], # [0, 1, 4], # [0, 5, 1], # [1, 3, 5], # [1, 4, 3]], dtype=int32)) # ``` # # Looking just at the first row we get `[ 0.34763842, 0.24879643, 0.12789202]`, you can confirm these are the 3 largest probabilities in `a`. You'll also notice `[3, 0, 5]` are the corresponding indices. # + saver = tf.train.Saver() webimagesgray = Preprocessimage(webimages) total = 0 right = 0 with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) for classnum, image in zip (webimagesclasses,webimagesgray): total+=1 right+=printtop5prob(image.reshape(1,32,32,1),classnum,signnames) # - def precisionandrecall(X_data,y_data,classnum): falsenegatives = 0 truepostives = 0 falsepostive = 0 for x, y in zip(X_data,y_data): pred = predict(x.reshape(1,32,32,1)) if (pred==y and y == classnum): truepostives+=1 elif (pred!=y and pred==classnum): falsepostive+=1 elif (pred!=y and y==classnum): falsenegatives+=1 precision = truepostives/(truepostives+falsepostive) recall = truepostives/(truepostives+falsenegatives) return precision,recall # + with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) for i in range (classnum): prec, rec = precisionandrecall(X_testgray,y_test,i) print (signnames[i] + " Recall: {0:.2f} | Precision: {1:.2f}".format(rec,prec)) # - # # # # ### Project Writeup # # Once you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. # > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", # "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. # --- # # ## Step 4 (Optional): Visualize the Neural Network's State with Test Images # # This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol. # # Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable. # # For an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image. # # <figure> # <img src="visualize_cnn.png" width="380" alt="Combined Image" /> # <figcaption> # <p></p> # <p style="text-align: center;"> Your output should look something like this (above)</p> # </figcaption> # </figure> # <p></p> # # + ### Visualize your network's feature maps here. ### Feel free to use as many code cells as needed. # image_input: the test image being fed into the network to produce the feature maps # tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer # activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output # plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1): # Here make sure to preprocess your image_input in a way your network expects # with size, normalization, ect if needed # image_input = # Note: x should be the same name as your network's tensorflow data placeholder variable # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function activation = tf_activation.eval(session=sess,feed_dict={x : image_input}) featuremaps = activation.shape[3] plt.figure(plt_num, figsize=(15,15)) for featuremap in range(featuremaps): plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number if activation_min != -1 & activation_max != -1: plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray") elif activation_max != -1: plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray") elif activation_min !=-1: plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray") else: plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
Traffic_Sign_Classifier LeNet-97val.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import bokeh import re import requests import subprocess import os import pandas as pd RAW_FIXTURES_DIR = "./fixtures/raw" CI_pattern = '95%(.)*' Z_pattern = 'Z-(.)*' urls = {'2017':"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2017%20County%20Health%20Rankings%20Indiana%20Data%20-%20v1.xls", '2016':"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2016%20County%20Health%20Rankings%20Indiana%20Data%20-%20v3.xls", '2015':"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2015%20County%20Health%20Rankings%20Indiana%20Data%20-%20v3.xls", '2014':"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2014%20County%20Health%20Rankings%20Indiana%20Data%20-%20v6.xls", '2013':"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2013%20County%20Health%20Ranking%20Indiana%20Data%20-%20v1_0.xls", "2012":"http://www.countyhealthrankings.org/sites/default/files/state/downloads/2012%20County%20Health%20Ranking%20Indiana%20Data%20-%20v2.xls", "2011": "http://www.countyhealthrankings.org/sites/default/files/state/downloads/2011%20County%20Health%20Ranking%20Indiana%20Data%20-%20v2.xls"} CI_re = re.compile(CI_pattern) Z_re = re.compile(Z_pattern) regex_list = [CI_re, Z_re] cols_to_keep=['County', 'Teen Births', 'Teen Birth Rate'] def get_file(url, filename): try: subprocess.call(['wget', url, '-O', filename]) except Exception as e: print(filename, "failed.") else: return filename def drop_bad_cols(df, regex_patterns=[]): bad_cols_ci = [] for idx, col in enumerate(df.columns): for each_regex in regex_patterns: if re.search(each_regex, col): bad_cols_ci.append(idx) for bad_col in sorted(bad_cols_ci, reverse=True): df = df.drop(df.columns[bad_col], axis=1, inplace=False) return df def keep_good_cols(df, cols_to_keep=[]): return df[cols_to_keep] def load_dataset(year, url, sheetname="Ranked Measure Data", skiprows=1, bad_col_regex=list(), good_cols=list(), **kwargs): try: file_path = "{path}/teenbirth_{year}.xls".format(path = RAW_FIXTURES_DIR, year = year) url = url path_to_file = get_file(url = url, filename = file_path) df = pd.read_excel(path_to_file, sheetname=sheetname, skiprows=skiprows, **kwargs) df.columns = [col.strip() for col in df.columns] df = drop_bad_cols(df, regex_patterns=bad_col_regex) df = keep_good_cols(df, cols_to_keep = good_cols) df['year'] = year except KeyError as ke: print(year) print(df.columns) raise else: return df dfs = {} for year, url in urls.items(): dfs[year] = load_dataset(year, url, bad_col_regex=regex_list, good_cols = cols_to_keep) master_df = pd.concat([df for df in dfs.values()]) master_df.to_csv("./fixtures/clean/teen_births.csv", sep = ',') master_df.head
.ipynb_checkpoints/Untitled-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="Tx35TmvXASDM" # # #Olรก! # # Seja bem-vinda ou bem-vindo ao notebook da aula 01, nesta aula vamos realizar nossa primeira anรกlise de dados e no final jรก seremos capazes de tirar algumas conclusรตes. # # Nรณs desenvolveremos nosso projeto aqui no google colaboratory, assim podemos mesclar cรฉlulas contendo textos em formato markdown e cรฉlulas de cรณdigo, alรฉm disso vocรช nรฃo precisa instalar nada na sua mรกquina. Entรฃo, que tal comeรงar testando algumas linhas de cรณdigo? # # No campo abaixo temos o que chamamos de cรฉlula. Na cรฉlula nรณs podemos digitar textos, cรกlculos e cรณdigos. # # Apรณs eu introduzir o que eu quero na cรฉlula eu vou rodar esse conteรบdo. Para isso podemos usar o atalho SHIFT + ENTER, ou atรฉ mesmo clicar no sรญmbolo de play no canto esquerdo da cรฉlula. Na primeira vez que rodamos algo no nosso notebook ele vai demorar um pouco mais de tempo, e isso ocorre porque o google estรก alocando uma mรกquina virtual para nรณs utilizarmos. # # Vamos entรฃo fazer alguns testes, como os exemplos abaixo: # # + id="OcBN_0IyCPi2" colab={"base_uri": "https://localhost:8080/"} outputId="03c8d899-e92e-4006-db15-7901f857b173" 10 + 10 # + id="JwlLIq4sC_0_" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="c3ea6900-2f75-4ea2-eb8e-0b50c8262e1c" 'Thiago' # + [markdown] id="5PGNQ2pACcmg" # # Importando os dados # # Nessa imersรฃo nรณs vamos mergulhar no universo da biologia e da biotecnologia e explorar uma base de dados da รกrea. # # Para a nossa anรกlise, estรก faltando entรฃo os dados. Para conseguirmos esses dados vamos acessar o Github, nesse link: # # https://github.com/alura-cursos/imersaodados3/tree/main/dados # # Entรฃo, agora vamos importar essa base de dados para dentro do nosso notebook. Para juntar essas informaรงรตes vamos utilizar nossa famosa biblioteca do "Pandas". # Vamos importar essa biblioteca atravรฉs do seguinte cรณdigo: # + colab={"base_uri": "https://localhost:8080/", "height": 422} id="n4nsCvloshsm" outputId="466dee5f-0d8b-4ebf-b552-6b8a966514d4" import pandas as pd url_dados = 'https://github.com/alura-cursos/imersaodados3/blob/main/dados/dados_experimentos.zip?raw=true' dados = pd.read_csv(url_dados, compression = 'zip') dados # + [markdown] id="8xT1NuIIOo8o" # # Analisando os Dados # + [markdown] id="0p7WSVbJewNd" # Observe que imprimimos agora todas as nossas linhas e colunas da nossa tabela. # # Aqui observamos que temos dados referentes a ID, tratamento, tempo, dose, entre outras. # # Para nos auxiliar na visualizaรงรฃo e na identificaรงรฃo das colunas dos dados que vamos trabalhar, faremos um recorte, uma espรฉcie de cabeรงalho, com 5 linhas, e para isso usamos o seguinte comando: # + colab={"base_uri": "https://localhost:8080/", "height": 244} id="ongQ8MkFsnWY" outputId="4d52ad9a-e06e-4e65-9e99-010e64ca2ccd" dados.head() # + [markdown] id="PR-2eTPghNeM" # Quando estรกvamos trabalhando com o conjunto total de dados nรณs tรญnhamos a informaรงรฃo do nรบmero total de linhas e colunas. Porรฉm, agora com o head, nรณs perdemos essa informaรงรฃo. Entรฃo, caso vocรช queira recuperar a informaรงรฃo do total de linhas e colunas basta utilizar: # + colab={"base_uri": "https://localhost:8080/"} id="Q_5RP0HKs1Sy" outputId="56ee85c9-82bc-4bce-f968-931ed94dbed8" dados.shape # + [markdown] id="mrB8egkqhuqu" # Entรฃo, agora vamos voltar para o nosso problema. # # Nรณs queremos iniciar fazendo uma anรกlise dos dados que estamos tratando. Vamos comeรงar selecionando sรณ uma coluna, para entendermos do que ela estรก tratando. # # Vamos iniciar com a coluna tratamento. Para isso vamos digitar: # + colab={"base_uri": "https://localhost:8080/"} id="a8Og_8PIwdAS" outputId="cc09d464-df20-4a38-ae10-e5e447d57d8e" dados['tratamento'] # + [markdown] id="2r9MV9uDijPI" # Esse tipo de informaรงรฃo, da coluna, รฉ o que chamamos de 'sรฉrie'. Jรก a tabela inteira nรณs chamos de 'dataframe'. # # Agora para vermos os tipos especรญficos de informaรงรฃo que temos dentro dessa coluna vamos digitar: # + colab={"base_uri": "https://localhost:8080/"} id="_RkLWqqrwtJG" outputId="29889f00-f56f-4ee5-dd6b-f2e2f1e04b3e" dados['tratamento'].unique() # + [markdown] id="T1ZunAY_jBGM" # A resposta foi dada no formato de array, que nada mais รฉ do que um vetor, ou seja, um tipo de estrutura de dados. # # Observe que encontramos dois tipos: 'com droga' e 'com controle'. # # Com droga, como o prรณprio nome nos diz, รฉ quando estamos aplicando algum tipo de droga para a amostra. Jรก com o controle รฉ uma tรฉcnica estatรญstica em que isolamos as outras varรญaveis e observamos apenas a variรกvel de interesse. # # + [markdown] id="uceNBUhKkkUt" # Agora vamos analisar a coluna do tempo: # + colab={"base_uri": "https://localhost:8080/"} id="IOPFkJW5w5i-" outputId="66c3a625-1429-4e7d-8d69-77683ddee784" dados['tempo'].unique() # + [markdown] id="40HmKHUikxpD" # Encontramos 3 tipos de informaรงรฃo nessa coluna: 24, 72 e 48. O que pode nos indicar o tempo, provavelmente em horas, de intervalo que foi administrada a dose de medicamentos ou drogas. # # ร‰ interessante que observamos o comportamento das cรฉlulas com essa diferenรงa de tempo, jรก que se analisรกssemos num perรญodo diferente poderia nรฃo dar tempo suficiente pra cรฉlula manifestar o determinado comportamento. # + [markdown] id="e1ObXppVlkS2" # Alรฉm do tempo, podemos analisar tambรฉm a coluna de dose: # + colab={"base_uri": "https://localhost:8080/"} id="2UWEVupCx9M7" outputId="5c8d1493-f14f-4e19-e41e-ea05908d678d" dados['dose'].unique() # + [markdown] id="Gd3tqT3NmHy2" # Aqui obtemos dois tipos de doses diferentes, d1 e d2, mas nรฃo conseguimos afirmar nada categoricamente de antemรฃo. # + [markdown] id="TplxQpeJmO88" # Vamos entรฃo analisar a categoria droga: # + colab={"base_uri": "https://localhost:8080/"} id="p1NaXGzCySfP" outputId="fac29137-5d90-44a7-dabd-723824b1a177" dados['droga'].unique() # + [markdown] id="Htm4SDCO-AZS" # Agora com a resposta de ```dados['droga'].unique()``` obtivemos essa sรฉrie de cรณdigos como resposta. Talvez esses nรบmeros foram codificados na tentativa de anonimizar os tipos de drogas usadas, para tentar evitar qualquer tipo de viรฉs na anรกlise dos resultados. # # Hรก uma sรฉrie de regras quando alguns experimentos sรฃo feitos, evitando mostrar dados como nome, sexo, e outros fatores, dependendo da anรกlise a ser feita, para que sejam evitados vieses. # + [markdown] id="Dq3VdLCAAKdt" # Vamos analisar a coluna nomeada como g-0 agora: # + colab={"base_uri": "https://localhost:8080/"} id="CgHdbkO9ye6g" outputId="10c758c6-10aa-468d-aa95-bd1235df9494" dados['g-0'].unique() # + [markdown] id="BqL9s6hrBPRT" # Sรณ olhando fica difรญcil tentar deduzir o que esses nรบmeros representam. Entรฃo, nesse ponto, com o auxรญlio da Vanessa, especialista, conseguimos a informaรงรฃo que essa letra 'g' da coluna remete ร  palavra gene. Ou seja, esses nรบmeros nos dizem a expressรฃo de cada gene frente as drogas ou a exposiรงรฃo. # # Quando subimos de volta na tabela, percebemos que hรก diversos valores, inclusive com vรกrias casas decimais. Aparentemente esses nรบmeros foram "arredondados", normalizados, para podermos comparรก-los de alguma forma. # # Entรฃo, atรฉ agora na nossa anรกlise, jรก conseguimos identificar e entender as informaรงรตes de diferentes colunas; as colunas que nos indicam os tratamentos, as drogas, o tempo, e depois as respostas genรฉticas, que tem a letra g no รญnicio do seu nome. # # Outro tipo de anรกlise que podemos fazer agora รฉ entender a distribuiรงรฃo dessas informaรงรตes. Por exemplo, podemos saber quantos experimentos temos utilizando droga e quantos nรฃo utilizam; quantos usam o d1, e quantos utilizam o d2, e assim por diante. # # Como podemos fazer isso? Vamos utilizar esse cรณdigo: # + colab={"base_uri": "https://localhost:8080/"} id="pvSIUn9_zTWH" outputId="34ab4c25-cb0b-4002-dfa0-641990df1b6e" dados['tratamento'].value_counts() # + [markdown] id="WKEZrPM3R6sn" # Agora, em vez de usarmos o ```.unique``` no cรณdigo, nรณs utilizamos o ```.value_counts``` jรก que nosso objetivo era contar a quantidade de valores que apareciam nas colunas, nesse caso, na coluna ```tratamento```. # # No resultado ele retornou 2 linhas: uma com a quantidade de elementos que temos, ou seja, com a minha frequรชncia, na categoria ```com_droga``` e a outra com a quantidade que temos na categoria ```com_controle```. # # # + [markdown] id="faqZ_zpwXGPf" # ##Desafio 01: Investigar por que a classe tratamento รฉ tรฃo desbalanceada. # + colab={"base_uri": "https://localhost:8080/"} id="swWCKQ-wf6Hq" outputId="b84957a5-d0e7-4bd2-d1ec-d711a81358fd" dados['tratamento'].describe() # + colab={"base_uri": "https://localhost:8080/", "height": 185} id="eDi-tmL-_tbS" outputId="86e02b9e-752a-4cbd-f196-a5785338e992" print(f"Quantidade de drogas {len(dados.groupby(['droga', 'tratamento']).count()['id'])}\n") display(dados.query('tratamento == "com_controle"').value_counts('droga')) print() display(dados.query('droga == "cacb2b860"').value_counts('tratamento')) print() # + [markdown] id="KjLbA9JhPkwe" # # ##Desafio 02: Plotar as 5 รบltimas linhas da tabela # + colab={"base_uri": "https://localhost:8080/", "height": 244} id="UblZtgIpXYzK" outputId="82fe2204-b013-4adc-ab9e-de5d21256ee9" dados.tail() # + [markdown] id="n2E1OtP7PklZ" # ##Desafio 03: Proporรงรฃo das classes tratamento. # + colab={"base_uri": "https://localhost:8080/"} id="LVg0Qk_OYZFz" outputId="868956ba-640f-40d0-ead2-13c713e350f9" dados['tratamento'].value_counts(normalize = True) # + [markdown] id="__3HwwQePkai" # ##Desafio 04: Quantos tipos de drogas foram investigados? # + colab={"base_uri": "https://localhost:8080/"} id="T0ADgnLkZVWk" outputId="a6f6c777-83bf-4dd0-d69e-84056d5c270c" dados['droga'].nunique() # + [markdown] id="p0VTIhAYP3JI" # ## Continuando... # + [markdown] id="SlyZ2RiGeU80" # Serรก que essa diferenรงa entre os valores dentro das categorias continuam tรฃo desproporcionais? Vamos investigar a categoria ```dose```: # + colab={"base_uri": "https://localhost:8080/"} id="8F1qPq6h2WBl" outputId="40267531-cffa-4fd9-c4d2-ab6ff8871030" dados['dose'].value_counts() # + [markdown] id="TFa5qpVfepQE" # Nesse ponto parece que as coisas jรก estรฃo mais equilibradas. Mas somente com o nรบmero รฉ difรญcil fazermos uma leitura mais aprofundada. Entรฃo, nesse momento, vamos resolver um dos desafios deixados. Entรฃo, se atรฉ aqui vocรช ainda nao resolveu os desafios do vรญdeo e nao quer receber um spoiler, pare aqui e tente resolvรช-los primeiro. # + [markdown] id="l7KpuFzEfPvu" # Para entendermos melhor e fazer um comparativo รฉ legal traรงarmos a proporรงรฃo entre os dados. Vamos escrever o cรณdigo agora, setando como parรขmetro, dentro dos parรชnteses o ```normalize = True``` : # + colab={"base_uri": "https://localhost:8080/"} id="1sX66gG249OZ" outputId="4a592525-9e96-45ae-a657-f0cd9784a2b9" dados['tratamento'].value_counts(normalize = True) # + [markdown] id="hqvUYNmCfy4k" # Temos agora os dados "normalizados". Podemos interpretar utilizando a porcentagem (multiplicando por 100), o que nos daria algo em torno de 92% versus 8% (aproximadamente), mostrando o tamanho da desproporรงรฃo. # + [markdown] id="6pt69FpPgJes" # Vamos fazer o mesmo agora com a coluna ```dose```: # + colab={"base_uri": "https://localhost:8080/"} id="wrLfRXx65NPP" outputId="b8f5c5f0-af01-4cef-bf25-66816d9de065" dados['dose'].value_counts(normalize = True) # + [markdown] id="jfzmJDZMglnC" # Temos aqui o resultado. Inclusive, como mini-desafio, vocรช pode fazer o mesmo processo com as outras colunas. # # Certo, mas geralmente, quando hรก a trasmissรฃo dessas informaรงรตes, vemos uma sรฉrie de grรกficos. E, geralmente, รฉ usado aquele grรกfico que parece uma torta, ou uma pizza. # # Vamos entรฃo plotar um grรกfico dessa tipo, com o seguinte cรณdigo: # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="LYiMo76m5bnS" outputId="009e58ac-bc18-4eb9-8662-a6dc95354443" dados['tratamento'].value_counts().plot.pie() # + [markdown] id="3TSXa6pLhM79" # Aqui, em azul, nรณs temos a quantidade de tratamento com drogas(que รฉ muito maior, em proporรงรฃo), e em laranja temos o tratamento "com controle". Ficou atรฉ parecendo um pacman, hehe. # # Vamos aproveitar e analisar as outras informaรงรตes com os grรกficos tambรฉm, para vermos o que acontece. Vamos analisar a coluna tempo: # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="qmBQF9kx5uIc" outputId="076f1c29-d39a-4f57-9033-bc8b14af8dba" dados['tempo'].value_counts().plot.pie() # + [markdown] id="fMiT70FVhtsj" # Repare como ficou difรญcil a olho nรบ identificarmos qual observaรงรฃo รฉ maior atravรฉs do grรกfico. Esse tipo de grรกfico pode acabar dificultando um pouco a anรกlise, especialmente quando as informaรงรตes estรฃo melhor balanceadas. # # Alรฉm de identificar a quantidade de horas observadas, nรณs nรฃo conseguimos extrair mais nenhuma informaรงรฃo desse grรกfico. Inclusive, nรณs temos uma espรฉcie de regrinha, que diz que quando formos fazer algum tipo de anรกlise, procurarmos evitar o uso de grรกficos que nos remetem a comida, como por exemplo: rosca, pizza, torta, e assim por diante. # # Entรฃo qual tipo de grรกfico poderรญamos utlizar para melhorarmos nossa visualizaรงรฃo? Vamos utilizar o grรกfico de barras, atravรฉs deste cรณdigo: # + colab={"base_uri": "https://localhost:8080/", "height": 285} id="TJ0MjBYZ6LOI" outputId="76518c93-4c86-4077-f25c-02f8a5286566" dados['tempo'].value_counts().plot.bar() # + [markdown] id="htMQ_11Vpjsv" # Agora sim conseguimos identificar com mais facilidade qual observaรงรฃo tem a sua maior frequรชncia. Na verdade a quantidade de horas com o maior nรบmero de observaรงรตes foi a de 48. # # No eixo y temos o nรบmero que nos remete ao nรบmero de observaรงรตes. Entรฃo podemos observar que tivemos pouco mais de 8000 observaรงรตes relativas ร s 48 horas. # # Entรฃo, o grรกfico de barras acabou sendo muit mais รบtil, nesse caso, do que o grรกfico de pizza. # + [markdown] id="qnvEJWZgqw7K" # Ao longo da aula nรณs falamos sobre a expressรฃo gรชnica. Se nรณs voltarmos ร  tabela, na coluna g-0, nรณs temos alguns valores dentro de um intervalo definido. Para nรฃo termos valores muito distantes entre si, รฉ bastante comum no meio cientรญfico que haja uma normalizaรงรฃo dos resultados, para criamos um intervalo que nรฃo seja tรฃo grande, em que o meio dessa distribuiรงรฃo seja o 0. # # Como nรณs podemos saber em quais linhas dessa coluna, o meu valor estรก acima de 0? # # Vamos fazer uma consulta nos nossos dados, da seguinte maneira: # + colab={"base_uri": "https://localhost:8080/", "height": 244} id="_igXHK3A8wQr" outputId="a3f094ba-0181-41cf-e41d-266f9c1f6aed" dados_filtrados = dados[dados['g-0'] > 0] dados_filtrados.head() # + [markdown] id="7Bbn_WyZuSSD" # Dessa maneira, temos somente as 5 primeiras linhas com o valores maiores do que 0 na coluna g-0, com a ajuda dessa mรกscara com o cรณdigo ```[dados['g-0']>0]```. # # Dessa mesma forma que aplicamos essa mรกscara, podemos utilizar o mesmo caminho, ou outras 'querys', para responder vรกrias outras perguntas. # # + [markdown] id="KMurn5YrQxLT" # ## Desafio 05: Procurar na documentaรงรฃo o mรฉtodo query(pandas). # # https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html # # https://medium.com/horadecodar/como-usar-o-query-do-pandas-fdf4a00727dc # # + [markdown] id="dY-H-yG_ciXk" # Vamos tentar um exemplo no dataset # + colab={"base_uri": "https://localhost:8080/", "height": 422} id="DNabPibkcWtM" outputId="874ba8ea-2329-44f8-920a-0c4af62ec4b7" dados.query('tempo > 24') # + [markdown] id="TUzPJEGVPP7U" # ##Desafio 06: Renomear as colunas tirando o hรญfen. # # https://www.ti-enxame.com/pt/python/renomeando-colunas-em-pandas/1068622211/ # + colab={"base_uri": "https://localhost:8080/"} id="6w8P73O9dkpl" outputId="3973d246-5640-4f36-b47f-a3661011db36" dados.columns = dados.columns.str.replace('-', '') dados.columns # + colab={"base_uri": "https://localhost:8080/", "height": 244} id="BnarsEAad72o" outputId="dceb693c-e746-45d1-da28-1cd17d9f1249" dados_renomeados_filtrados = dados.query('g0 > 0') dados_renomeados_filtrados.head() # + [markdown] id="igPYFjulBWMW" # Segunda forma de se fazer isso # + colab={"base_uri": "https://localhost:8080/", "height": 244} id="5KUcYSqMBY6L" outputId="633f826a-22f4-4aa0-bb70-298eb0364a34" nome_das_colunas = dados.columns novo_nome_coluna = [] for coluna in nome_das_colunas: coluna = coluna.replace('-', '_') novo_nome_coluna.append(coluna) dados.columns = novo_nome_coluna dados.head() # + [markdown] id="wICe8HYKPQqm" # ##Desafio 07: Deixar os grรกficos bonitรตes. (Matplotlib.pyplot) # + id="2NokfRrYhbl2" import matplotlib.pyplot as plt # + colab={"base_uri": "https://localhost:8080/"} id="iy6H7uHfAbv4" outputId="a024bb50-b468-406d-e27e-0b5b11d02d7b" valore_tempo = dados['tempo'].value_counts(ascending=True) valore_tempo.sort_index() # + colab={"base_uri": "https://localhost:8080/", "height": 639} id="5jvPcffFhfKf" outputId="f19f45e6-2532-43ba-f5d7-b436b1bbbcd6" plt.figure(figsize=(15, 10)) valore_tempo = dados['tempo'].value_counts(ascending=True) ax = valore_tempo.sort_index().plot.bar() ax.set_title('Janelas de tempo', fontsize=20) ax.set_xlabel('Tempo', fontsize=18) ax.set_ylabel('Quantidade', fontsize=18) plt.xticks(rotation = 0, fontsize=16) plt.yticks(fontsize=16) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 264} id="kzHyiJIWoDG4" outputId="b99f299f-ce24-4870-80f5-8f5f5c667559" labels = dados['tratamento'].unique() values = dados['tratamento'].value_counts() plt.pie(values, labels= labels, shadow= True, autopct='%1.1f%%', textprops=dict(color="b")) plt.title('Tratamentos') plt.show() # + [markdown] id="xtaaFSiHPREN" # ##Desafio 08: Resumo do que vocรช aprendeu com os dados # + [markdown] id="c8PzxJUCS6Q9" # - A base consiste em alguns tipos de experimentos realizados com drogas em cรฉlulas; # - A classe tratamento รฉ bem desbalanceada; # - Os experimentos sรฃo deixados para anรกlise por atรฉ 3 dias (24, 48 ou 72 horas); # - Varios tipos diferentes de drogas foram testadas nas cรฉlulas; # + [markdown] id="jeyUzd9KA4DA" # Se quiser mais informaรงรตes a base dados estudada na imersรฃo รฉ uma versรฃo simplificada [deste desafio](https://www.kaggle.com/c/lish-moa/overview/description) do Kaggle (em inglรชs). # # # Tambรฉm recomendamos que vocรช acesse o # [Connectopedia](https://clue.io/connectopedia/). O Connectopedia รฉ um dicionรกrio gratuito de termos e conceitos que incluem definiรงรตes de viabilidade de cรฉlulas e expressรฃo de genes. # # # O desafio do Kaggle tambรฉm estรก relacionado a estes artigos cientรญficos: # # Corsello et al. โ€œDiscovering the anticancer potential of non-oncology drugs by systematic viability profiling,โ€ Nature Cancer, 2020, https://doi.org/10.1038/s43018-019-0018-6 # # Subramanian et al. โ€œA Next Generation Connectivity Map: L1000 Platform and the First 1,000,000 Profiles,โ€ Cell, 2017, https://doi.org/10.1016/j.cell.2017.10.049
Aulas/Aula_01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Benchmarking doubelt detection methods with Demuxlet data sets # + import os import numpy as np import pandas as pd import matplotlib.pyplot as plt dat_dir = "../data/" os.chdir(dat_dir) # - # ### Load data # #### Demuxlet # + demux_ctrl = pd.read_csv(dat_dir + "/demux_ctrl/demux_table.tsv.gz", sep = "\t") demux_stim = pd.read_csv(dat_dir + "/demux_stim/demux_table.tsv.gz", sep = "\t") demux_ctrl['doublet'] = demux_ctrl['multiplets'] == 'doublet' demux_stim['doublet'] = demux_stim['multiplets'] == 'doublet' # - demux_ctrl[:5] # #### DoubletFinder # + dbfinder_ctrl = pd.read_csv(dat_dir + "/demux_ctrl/doubletFinder_table.tsv", header=0, sep="\t") dbfinder_stim = pd.read_csv(dat_dir + "/demux_stim/doubletFinder_table.tsv", header=0, sep="\t") dbfinder_stim.cellID = [x + "-1" for x in dbfinder_stim.cellID] dbfinder_ctrl.cellID = [x + "-1" for x in dbfinder_ctrl.cellID] dbfinder_ctrl[:5] # + print(np.mean(dbfinder_stim.cellID == demux_stim.cellID)) print(np.mean(dbfinder_ctrl.cellID == demux_ctrl.cellID)) print(np.mean(dbfinder_stim.label_fix == "Doublet")) print(np.mean(dbfinder_ctrl.label_fix == "Doublet")) # + fig = plt.figure(figsize = (8, 3)) plt.subplot(1, 2, 1) plt.hist(dbfinder_ctrl.pANN_fix, bins=30) plt.title("ctrl sample") plt.subplot(1, 2, 2) plt.hist(dbfinder_stim.pANN_fix, bins=30) plt.title("stim sample") plt.tight_layout() plt.show() # - # #### scrublet # + scrublet_ctrl = pd.read_csv(dat_dir + "/demux_ctrl/scrublet_table.tsv", header=0, sep="\t") scrublet_stim = pd.read_csv(dat_dir + "/demux_stim/scrublet_table.tsv", header=0, sep="\t") scrublet_stim[:5] # + print(np.mean(scrublet_ctrl.cellID == demux_ctrl.cellID)) print(np.mean(scrublet_stim.cellID == demux_stim.cellID)) print(np.mean(scrublet_ctrl['label_frac'])) print(np.mean(scrublet_stim['label_frac'])) # + fig = plt.figure(figsize = (8, 3)) plt.subplot(1, 2, 1) plt.hist(scrublet_ctrl.score, bins=50) plt.title("ctrl sample") plt.subplot(1, 2, 2) plt.hist(scrublet_stim.score, bins=50) plt.title("stim sample") plt.tight_layout() plt.show() # - # ## Comparison def average_score(x1, x2, x3, W=np.array([0.25, 0.25, 0.5])): """ """ X = np.zeros((len(x1), 3)) X[:, 0] = x1 X[:, 1] = x2 X[:, 2] = x3 if W is None: W = np.ones((X.shape[1], 1)) / X.shape[1] _X = ((X - np.min(X, axis=0, keepdims=True)) / (np.max(X, axis=0, keepdims=True) - np.min(X, axis=0, keepdims=True))) # _X = ((X - np.mean(X, axis=0, keepdims=True)) / # np.var(X, axis=0, keepdims=True)) return np.dot(_X, W), X def scatter_with_label(x, y, label1, label2, title="", names=['Singlet', 'SNP only', 'GEX only', 'Both']): label1 = np.array(label1) label2 = np.array(label2) idx0 = (label1 == False) * (label2 == False) idx1 = (label1 == True) * (label2 == False) idx2 = (label1 == False) * (label2 == True) idx3 = (label1 == True) * (label2 == True) plt.scatter(x[idx0], y[idx0], s=1, label=names[0], color="lightgray") plt.scatter(x[idx1], y[idx1], s=1, label="%s: %d" %(names[1], sum(idx1)), color='#4796d7') plt.scatter(x[idx2], y[idx2], s=1, label="%s: %d" %(names[2], sum(idx2)), color='#79a702') plt.scatter(x[idx3], y[idx3], s=1, label="%s: %d" %(names[3], sum(idx3)), color='#df5858') plt.xlabel("t-SNE 1") plt.ylabel("t-SNE 2") plt.title("%s: %d cells" %(title, len(x))) plt.legend(loc="best", markerscale=5) def multi_plot(demux_dat, dbfinder_dat, scrublet_dat, _sample, fig_file=None): fig = plt.figure(figsize=(10, 8), dpi=100) ### doubletFinder with pK according to n_cell plt.subplot(2, 2, 1) scatter_with_label(demux_dat['tsne1'], demux_dat['tsne2'], demux_dat['doublet'], dbfinder_dat['label_fix'] == 'Doublet', title='dbfinder fix, %s' %(_sample)) ### doubletFinder with sweeped pK plt.subplot(2, 2, 2) scatter_with_label(demux_dat['tsne1'], demux_dat['tsne2'], demux_dat['doublet'], dbfinder_dat['label_sweep'] == 'Doublet', title='dbfinder sweep, %s' %(_sample)) ### scrublet plt.subplot(2, 2, 3) _doublet_rate = np.mean(dbfinder_dat['label_fix'] == 'Doublet') _cut = np.quantile(scrublet_dat['score'], 1 - _doublet_rate) scatter_with_label(demux_dat['tsne1'], demux_dat['tsne2'], demux_dat['doublet'], scrublet_dat['score'] >= _cut, title='scrublet, %s' %(_sample)) ### Combine three values (averaged) plt.subplot(2, 2, 4) _avg_score, _X = average_score(dbfinder_dat['pANN_fix'], dbfinder_dat['pANN_sweep'], scrublet_dat['score']) _doublet_rate = np.mean(dbfinder_dat['label_fix'] == 'Doublet') _cut = np.quantile(_avg_score, 1 - _doublet_rate) scatter_with_label(demux_dat['tsne1'], demux_dat['tsne2'], demux_dat['doublet'], _avg_score > _cut, title='combined-results, %s' %(_sample)) plt.tight_layout() if fig_file is not None: plt.savefig(fig_file, dpi=200) plt.show() # ### Stimulated sample _sample = "demux_stim" multi_plot(demux_stim, dbfinder_stim, scrublet_stim, _sample, fig_file=dat_dir + "../examples/images/%s.doublet.png" %(_sample)) # ### Control sample _sample = "demux_ctrl" multi_plot(demux_ctrl, dbfinder_ctrl, scrublet_ctrl, _sample, fig_file=dat_dir + "../examples/images/%s.doublet.png" %(_sample)) # ### Using combined file combined_ctrl = pd.read_csv(dat_dir + "/demux_ctrl/combined_table.tsv", header=0, sep="\t") combined_ctrl[:5] np.mean(demux_ctrl['cellID'] == combined_ctrl['cellID']) np.unique(demux_ctrl.loc[combined_ctrl['combined_label']]['cell'], return_counts=True) np.unique(list(demux_ctrl['cell']), return_counts=True) frac_GEX_ctrl=(np.unique(demux_ctrl.loc[combined_ctrl['combined_label']]['cell'], return_counts=True)[1] / np.unique(list(demux_ctrl['cell']), return_counts=True)[1][:8]) frac_SNP_stim=(np.unique(demux_ctrl.loc[demux_ctrl['doublet']]['cell'], return_counts=True)[1] / np.unique(list(demux_ctrl['cell']), return_counts=True)[1][:8]) cell_types = np.unique(demux_stim.loc[combined_stim['combined_label']]['cell']) for i in range(len(cell_types)): print(cell_types[i] + ",%.2f,%.2f" %(frac_GEX_ctrl[i], frac_SNP_stim[i])) # ### stimulated sample combined_stim = pd.read_csv(dat_dir + "/demux_stim/combined_table.tsv", header=0, sep="\t") np.mean(demux_stim['cellID'] == combined_stim['cellID']) frac_GEX_stim = (np.unique(demux_stim.loc[combined_stim['combined_label']]['cell'], return_counts=True)[1] / np.unique(list(demux_stim['cell']), return_counts=True)[1][:8]) frac_SNP_stim = (np.unique(demux_stim.loc[demux_stim['doublet']]['cell'], return_counts=True)[1] / np.unique(list(demux_stim['cell']), return_counts=True)[1][:8]) cell_types = np.unique(demux_stim.loc[combined_stim['combined_label']]['cell']) for i in range(len(cell_types)): print(cell_types[i] + ",%.2f,%.2f" %(frac_GEX_stim[i], frac_SNP_stim[i])) np.unique(demux_stim.loc[combined_stim['combined_label']]['cell']) == np.unique(demux_stim.loc[demux_stim['doublet']]['cell'])
examples/demuxlet_data_celltype.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:coursera_capstone] # language: python # name: conda-env-coursera_capstone-py # --- # # Third week notebook-part three # # This notebook get the Postcode, Borough and Neighbourhood from Toronto and adds the longitude and latitude. Finally we do clustering and visualization. # # # First modules are imported # # # # *Warning: This document uses both neighbo**u**rhood and neighborhood. This should be avoided* from bs4 import BeautifulSoup import requests import csv print('Modules imported :)') # # # Then the URI is defined uri = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M' print('The URI is: {} '.format(uri) ) # Scarping the data and making the data frame import pandas as pd dfs = pd.read_html(uri, header=0) df = dfs[0] # Using method chaining operations are carried out. # - First, the rows where Borough are assigned the value 'Not assigned' is removed # - Then, for each postcode the name of the first borough and a comma separated list of the neighourhoods are compiled. If the boroughs have the same postcode this will only keep the name of the first borough # - Finaly, reset index is used to make the postcode a colum and not an index df1 = (df[df.Borough != 'Not assigned'] .groupby('Postcode') .agg({'Borough': lambda x: x.iloc[0], 'Neighbourhood': lambda x: "%s" % ', '.join(x)}) .reset_index() ) # Making a copy to aviod mutating a data frame. Then, the values for the Neighbourhood which are not assigend are replaced with the name of the Borough. This assumes that no Borough have the value Not assigned. df2 = df1.copy(deep=True) df2.loc[df2.Neighbourhood == 'Not assigned', 'Neighbourhood'] = df1.loc[df1.Neighbourhood == 'Not assigned', 'Borough'] import os project_path = os.path.dirname(os.getcwd()) file_path = project_path + '/data/raw/Geospatial_Coordinates.csv' file_path postal_code_ll_df = (pd.read_csv(file_path) .rename(columns={'Postal Code': 'Postcode'}) ) df3 = pd.merge(df2, postal_code_ll_df, how='left', on='Postcode') # ## This is where the third week start # # Import libraries used in the klustering # + import numpy as np import json # Hard code the latitude and longitude instead # from geopy.geocoders import Nominatim, import requests from pandas.io.json import json_normalize # Matplotlib and associated plotting modules import matplotlib.cm as cm import matplotlib.colors as colors # import k-means from clustering stage from sklearn.cluster import KMeans import folium # map rendering library print('Libraries imported.') # - # From the web i found that the latitude of North York, Toronto, ON, Canada is 43.761539, and the longitude is -79.411079 # This method is preferd to avoid the use of Nominatim latitude = 43.761539 longitude = -79.411079 df3.head() # Use folium to create a map # + # create map of New York using latitude and longitude values map_toronto = folium.Map(location=[latitude, longitude], zoom_start=11) # Rename instead of refactor neighborhoods = df3.copy() for lat, lng, borough, neighborhood in zip(neighborhoods['Latitude'], neighborhoods['Longitude'], neighborhoods['Borough'], neighborhoods['Neighbourhood']): label = '{}, {}'.format(neighborhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, color='blue', fill=True, fill_color='#3186cc', fill_opacity=0.7, popup=label).add_to(map_toronto) map_toronto # - # The API secrets are not pushed to github. This is handled by placing them in a file named secrets and removing version control from that file. # Since the file is not in the same directory as the notebooks extra code is needed to add the path to the sys search path import os secrets_folder_path = os.path.dirname(os.getcwd()) secrets_folder_path import sys sys.path.insert(0, secrets_folder_path) # The secrets file containts two variables CLIENT_ID and CLIENT_SECRET import secrets CLIENT_ID = secrets.CLIENT_ID # your Foursquare ID CLIENT_SECRET = secrets.CLIENT_SECRET # your Foursquare Secret VERSION = '20180604' LIMIT = 30 def getNearbyVenues(names, latitudes, longitudes, radius=500): venues_list=[] number = 0 print('The number of names in the list is {}'.format(len(names))) for name, lat, lng in zip(names, latitudes, longitudes): number += 1 print('Nr.: {}, name: {}'.format(number, name)) # create the API request URL url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT) # make the GET request results = requests.get(url).json()["response"]['groups'][0]['items'] # return only relevant information for each nearby venue venues_list.append([( name, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results]) nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list]) nearby_venues.columns = ['Neighborhood', 'Neighborhood Latitude', 'Neighborhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category'] return(nearby_venues) neighborhood_latitude_list = neighborhoods['Latitude'] # neighborhood latitude value neighborhood_longitude_list = neighborhoods['Longitude'] # neighborhood longitude value neighborhood_name_list = neighborhoods['Neighbourhood'] # neighborhood name toronto_venues = getNearbyVenues(neighborhood_name_list, neighborhood_latitude_list, neighborhood_longitude_list) print(toronto_venues.shape) toronto_venues.head() print('There are {} uniques categories.'.format(len(toronto_venues['Venue Category'].unique()))) print('There are {} uniques Neighborhoods.'.format(len(toronto_venues['Neighborhood'].unique()))) print('The length of the neighborhood_name_list is {}'.format(len(neighborhood_name_list))) print('The length of uniqe values in the neighborhood_name_list is {}'.format(len(neighborhood_name_list.unique()))) # It is likely that thee of the neighbourhoods does not have any venues. **I'm taking out the neighbourhoods that does not have any venues** # ## Identify the naming problem # # Is there a category for venues called Neighborhood? sum(toronto_venues['Venue Category'] == 'Neighborhood') toronto_venues[toronto_venues['Venue Category'] == 'Neighborhood'] # The solution is to rename Neighborhood to Neighbourhood # # ## Prepare the data for machine learning # + # one hot encoding toronto_onehot = pd.get_dummies(toronto_venues[['Venue Category']], prefix="", prefix_sep="") # add neighborhood column back to dataframe, look at name ... toronto_onehot['Neighbourhood'] = toronto_venues['Neighborhood'] # move neighborhood column to the first column fixed_columns = [toronto_onehot.columns[-1]] + list(toronto_onehot.columns[:-1]) toronto_onehot_fixed = toronto_onehot[fixed_columns] print(toronto_onehot_fixed.shape) toronto_onehot_fixed.head() # - # ## Time for some machine learning # # The suggested methods might not be the best. I'm going to try using the sum instead of the mean. This will classify neighborhoods with apox the same numbers of venues of the same type together. Larger areas will usually have higher number of venues. The best would be to divide by the area of the neighborhood. toronto_sum_df = toronto_onehot_fixed.groupby('Neighbourhood').sum().reset_index() print(toronto_sum_df.shape) # + # set number of clusters kclusters = 5 # Sum the number of venues in each venue category toronto_grouped_clustering = toronto_sum_df.drop('Neighbourhood', 1) # run k-means clustering kmeans = KMeans(n_clusters=kclusters, random_state=0).fit(toronto_grouped_clustering) # - # Merge labels with the labels merged_df_tmp = pd.DataFrame({"Neighbourhood" : toronto_sum_df.loc[:,'Neighbourhood'], "Cluster Labels" : kmeans.labels_}) toronto_data = neighborhoods.loc[:, ['Neighbourhood', 'Latitude', 'Longitude']] merged_df = pd.merge(merged_df_tmp, toronto_data, how = 'left', on = 'Neighbourhood') # + # create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i+x+(i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, poi, cluster in zip(merged_df['Latitude'], merged_df['Longitude'], merged_df['Neighbourhood'], merged_df['Cluster Labels']): label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( [lat, lon], radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(map_clusters) map_clusters
notebooks/08-third-week-part-three.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Note # * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. # + # Dependencies and Setup import pandas as pd import numpy as np # File to Load (Remember to Change These) P_D = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_data1 = pd.read_csv(P_D) purchase_data = pd.DataFrame(purchase_data1, columns=['SN', 'Age', 'Gender', 'Item ID', 'Item Name', 'Price']) purchase_data.head() # - # ## Player Count # * Display the total number of players # # + # Use the value counts method to find the value of unique names in the SN column. # Factoring in that accounts can make multiple purchases. # Able to ge the total players value to appear in the length with this first method. # PLayer count should be 576 unique players. player_count = purchase_data.SN.value_counts() total_play = player_count.count() total_play # - # ## Purchasing Analysis (Total) # * Run basic calculations to obtain number of unique items, average price, etc. # # # * Create a summary data frame to hold the results # # # * Optional: give the displayed data cleaner formatting # # # * Display the summary data frame # # + # Use the Value counts function again to get the number of unique items in the game. # This should return 179 in game items. unique_items = len(purchase_data["Item Name"].value_counts()) # Use the mean function to find the average price of a purchase. # This should return an average transaction price of $3.05. avg_rev = purchase_data["Price"].mean() # Use the unique function to return the number of items in the data set. # This gives the value for the number of purchases, and should return 780 purchases. purchases = purchase_data["Item Name"].count() # Use the sum function to find the total revenue # This should return $2,379.77 total_rev = purchase_data["Price"].sum() # Create a data frame to hold the results pur_analysis = pd.DataFrame({"Number of Unique Items": [unique_items], "Average Revenue": [avg_rev], "Total Purchases": [purchases], "Total Revenue": [total_rev], }) # Give the displayed data cleaner formatting pur_analysis = pur_analysis[["Total Purchases", "Total Revenue", "Average Revenue", "Number of Unique Items"]] # Display the summary data frame pur_analysis # - # ## Gender Demographics # * Percentage and Count of Male Players # # # * Percentage and Count of Female Players # # # * Percentage and Count of Other / Non-Disclosed # # # # + # Use the value counts function to get the counts for all genders # Should be returning lower values than what has been output (Was adding up every transaction even duplicates) # Male: 484 / 84.03% Female: 81 / 14.06% Other/Non-Disclosed: 11 / 1.91% # Group by gender to get rid of duplicates and return correct values players = purchase_data.groupby(["Gender"]) count = players.nunique(["SN"]) # Count of players and percentage of players total_count = count["SN"] percentage = (total_count/total_play) *100 # Create a data frame to hold our answers gender = pd.DataFrame({"Count":total_count, "Percentage": percentage }) # Display the data frame gender # - # # ## Purchasing Analysis (Gender) # * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender # # # # # * Create a summary data frame to hold the results # # # * Optional: give the displayed data cleaner formatting # # # * Display the summary data frame # + # Use the players data frame to start being that its already separated by gender # Sum, purchase count per gender. # Sum purchase count per divided by total purchases, average purchase price per gender. # Sum purchase count per divided by people per gender, average total purchase per person per gender. gen = purchase_data.groupby('Gender') # # Create a data frame to store the data. gender_pur = pd.DataFrame({"Total purchases per gender": gen.Price.count(), "Average purchase per gender": gen.Price.mean(), "Average total per gender": gen.Price.sum()/gen.Price.count(), "Avg Total Purchase per Person": gen.Price.sum()/percentage.mean() }) # Convert to USD gender_pur['Average purchase per gender'] = gender_pur['Average purchase per gender'].map('${:.2f}'.format) gender_pur['Average total per gender'] = gender_pur['Average total per gender'].map('${:.2f}'.format) gender_pur['Avg Total Purchase per Person'] = gender_pur['Avg Total Purchase per Person'].map('${:.2f}'.format) # Display the data frame. gender_pur # - # ## Age Demographics # * Establish bins for ages # # # * Categorize the existing players using the age bins. Hint: use pd.cut() # # # * Calculate the numbers and percentages by age group # # # * Create a summary data frame to hold the results # # # * Optional: round the percentage column to two decimal points # # # * Display Age Demographics Table # # + # Establish bins for ages age_bins = [0, 9.90, 14.90, 19.90, 24.90, 29.90, 34.90, 39.90, 99999] group_names = ["<10", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40+"] # Segment and sort age values into bins established above purchase_data["Age Group"] = pd.cut(purchase_data["Age"],age_bins, labels=group_names) purchase_data # Create new data frame with the added "Age Group" and group it age_grouped = purchase_data.groupby("Age Group") # Count total players by age category total_count_age = age_grouped["Age"].count() # Calculate percentages by age category percentage_by_age = (total_count_age/total_play) * 100 # Create data frame with obtained values age_demo = pd.DataFrame({"Percentage of Players": percentage_by_age, "Total Count": total_count_age}) age_demo # - # ## Purchasing Analysis (Age) # * Bin the purchase_data data frame by age # # # * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below # # # * Create a summary data frame to hold the results # # # * Optional: give the displayed data cleaner formatting # # # * Display the summary data frame # + # Purchases per age group purchase_age = age_grouped["SN"].count() # Average purchase price avg_price_age = age_grouped["Price"].mean() # Total purchased by age group total_value = age_grouped["Price"].sum() # Total average purchased by age group avg_per_age = total_value/percentage_by_age # Create data frame with obtained values age_pur = pd.DataFrame({"Purchase Count": purchase_age, "Average Purchase Price": avg_price_age, "Total Purchase Value":total_value, "Average Purchase Total per Person": avg_per_age}) # Display the summary Data Frame age_pur # - # ## Top Spenders # * Run basic calculations to obtain the results in the table below # # # * Create a summary data frame to hold the results # # # * Sort the total purchase value column in descending order # # # * Optional: give the displayed data cleaner formatting # # # * Display a preview of the summary data frame # # # + # Identify the top five spenders in the game by total purchases. # Group purchase data by screen names spenders = purchase_data.groupby("SN") # Count the total purchases by name pur_count_5 = spenders["Item ID"].count() # Average purchase avg_pur_5 = spenders["Price"].mean() # Purchasing total tot_pur_5 = spenders["Price"].sum() # Create a data frame to hold the results, sorted by the purchase value column in decending order. top_spenders = pd.DataFrame({"Purchase Count": pur_count_5, "Average Purchase Price": avg_pur_5, "Total Purchase Value":tot_pur_5}) spenders_top5 = top_spenders.sort_values(["Total Purchase Value"]).tail() # Display the data frame. spenders_top5 # - # ## Most Popular Items # * Retrieve the Item ID, Item Name, and Item Price columns # # # * Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value # # # * Create a summary data frame to hold the results # # # * Sort the purchase count column in descending order # # # * Optional: give the displayed data cleaner formatting # # # * Display a preview of the summary data frame # # # + # Create a new data frame containing only the id, item name, and price columns. items = purchase_data[["Item ID", "Item Name", "Price"]] # Group by the item id and name. item_stats = items.groupby(["Item ID","Item Name"]) # New column sum of total purchases per item. item_count = item_stats["Price"].count() # New column sum of total value of total purchases per item. item_purchases = (item_stats["Price"].sum()) # Find individual item price item_price = item_purchases/item_count # Create data frame with obtained values most_pop = pd.DataFrame({"Purchase Count": item_count, "Item Price": item_price, "Total Purchase Value":item_purchases}) most_pop5 = most_pop.sort_values(["Total Purchase Value"]).tail() # Show the new data frame with added columns, sorted by the purchase count column in decending order. most_pop5 # - # ## Most Profitable Items # * Sort the above table by total purchase value in descending order # # # * Optional: give the displayed data cleaner formatting # # # * Display a preview of the data frame # # # + # Use the data frame created in the most popular items step and re-sort it by the total purchase value. most_prof5 = most_pop5.sort_values(["Total Purchase Value"], ascending=False).head # Display the new reorganized data frame. most_prof5 # + # Three observeable trends in the data summary # 1. Males account for most of the games player base at slightly over 84%, where as women and other/not specified only # account for 14% and 2% respectively. However when speaking about average spending it would appear that males are more # likely to spend 6x more than females. With their average spent being almost $60 compared to females only spending # about $10. # # 2. The age group 20-24, our largest category in the bins for players, had the largest number of purchases and largest # revinue from purchases, the groups immedately above and below are also two of the strongest age demographics for total # gross revenue as well. However they are all beaten by the 35-39 bracket in both averages, average purchase price and # average total purchase per person. # # 3. The final critic is the most popular item by sales numbers, and total sales gross. Lisosia93 is the biggest spender # in game with alomst $20 total spent. # # Conclusion: This game is mostly popular with male players in the age 20-24 demographic.
HeroesOfPymoli/HeroesOfPymoli_starter.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/projects/ComputerVision/em_synapses.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> &nbsp; <a href="https://kaggle.com/kernels/welcome?src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/projects/ComputerVision/em_synapses.ipynb" target="_parent"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open in Kaggle"/></a> # - # # Knowledge Extraction from a Convolutional Neural Network # # **By Neuromatch Academy** # # __Content creators:__ <NAME> # # __Production editors:__ <NAME> # **Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs** # # <p align='center'><img src='https://github.com/NeuromatchAcademy/widgets/blob/master/sponsors.png?raw=True'/></p> # --- # # Objective # # Train a convolutional neural network to classify images and a CycleGAN to translate between images of different types. # # This notebook contains everything to train a VGG network on labelled images and to train a CycleGAN to translate between images. # # We will use electron microscopy images of Drosophila synapses for this project. Those images can be classified according to the neurotransmitter type they release. # --- # # Setup # + cellView="form" # @title Install dependencies # !pip install scikit-image --quiet # !pip install pillow --quiet # !pip install scikit-image --quiet # + import glob import json import torch import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from skimage.io import imread from torchvision.datasets import ImageFolder from torch.utils.data import DataLoader, random_split from torch.utils.data.sampler import WeightedRandomSampler # %matplotlib inline # - # --- # # Project Ideas # # 1. Improve the classifier. This code uses a VGG network for the classification. On the synapse dataset, we will get a validation accuracy of around 80%. Try to see if you can improve the classifier accuracy. # * (easy) Data augmentation: The training code for the classifier is quite simple in this example. Enlarge the amount of available training data by adding augmentations (transpose and mirror the images, add noise, change the intensity, etc.). # * (easy) Network architecture: The VGG network has a few parameters that one can tune. Try a few to see what difference it makes. # * (easy) Inspect the classifier predictions: Take random samples from the test dataset and classify them. Show the images together with their predicted and actual labels. # * (medium) Other networks: Try different architectures (e.g., a ResNet) and see if the accuracy can be improved. # * (medium) Inspect errors made by the classifier. Which classes are most accurately predicted? Which classes are confused with each other? # # # 2. Explore the CycleGAN. # * (easy) The example code below shows how to translate between GABA and glutamate. Try different combinations, and also in the reverse direction. Can you start to see differences between some pairs of classes? Which are the ones where the differences are the most or the least obvious? # * (hard) Watching the CycleGAN train can be a bit boring. Find a way to show (periodically) the current image and its translation to see how the network is improving over time. Hint: The `cycle_gan` module has a `Visualizer`, which might be helpful. # # # 3. Try on your own data! # * Have a look at how the synapse images are organized in `data/raw/synapses`. Copy the directory structure and use your own images. Depending on your data, you might have to adjust the image size (128x128 for the synapses) and number of channels in the VGG network and CycleGAN code. # # ### Acknowledgments # # This notebook was written by <NAME>, using code from <NAME> and a modified version of the [CycleGAN](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) implementation. # # --- # # Train an Image Classifier # # In this section, we will implement and train a VGG classifier to classify images of synapses into one of six classes, corresponding to the neurotransmitter type that is released at the synapse: GABA, acethylcholine, glutamate, octopamine, serotonin, and dopamine. # ## Data Preparation # + cellView="form" # @title Download the data import requests, os from zipfile import ZipFile # @markdown Download the resources for this tutorial (one zip file) fname = 'resources.zip' url = 'https://www.dropbox.com/sh/ucpjfd3omjieu80/AAAvZynLtzvhyFx7_jwVhUK2a?dl=1' if not os.path.exists('data/'): print('Data downlading...') r = requests.get(url, allow_redirects=True, stream=True) with open(fname, 'wb') as fh: fh.write(r.content) print('Download is cmpleted.') # @markdown Unzip the file fname = 'resources.zip' # specifying the zip file name fnames = ['data.zip', 'checkpoints.zip'] # opening the zip file in READ mode with ZipFile(fname, 'r') as zf: # extracting all the files print('Extracting all the files now...') zf.extractall(path='.') print('Done!') # @markdown Extract the data fnames = ['data.zip', 'checkpoints.zip'] for fname in fnames: # opening the zip file in READ mode with ZipFile(fname, 'r') as zh: # extracting all the files print(f"\nArchive: {fname}") print(f"\tExtracting data...") zh.extractall(path='.') print('Done!') # @markdown Make sure the order of classes matches the pretrained model os.rename('data/raw/synapses/gaba', 'data/raw/synapses/0_gaba') os.rename('data/raw/synapses/acetylcholine', 'data/raw/synapses/1_acetylcholine') os.rename('data/raw/synapses/glutamate', 'data/raw/synapses/2_glutamate') os.rename('data/raw/synapses/serotonin', 'data/raw/synapses/3_serotonin') os.rename('data/raw/synapses/octopamine', 'data/raw/synapses/4_octopamine') os.rename('data/raw/synapses/dopamine', 'data/raw/synapses/5_dopamine') else: print('Data are downloaded.') # @markdown Remove the archives for i in ['checkpoints.zip', 'experiments.zip', 'data.zip', 'resources.zip']: if os.path.exists(i): os.remove(i) # - # ## Classifier Training # ### Create and Inspect Datasets # # First, we create a `torch` data loaders for training, validation, and testing. We will use weighted sampling to account for the class imbalance during training. # + def load_image(filename): image = imread(filename) # images are grescale, we only need one of the RGB channels image = image[:, :, 0] # img is uint8 in [0, 255], but we want float32 in [-1, 1] image = image.astype(np.float32)/255.0 image = (image - 0.5)/0.5 return image # create a dataset for all images of all classes full_dataset = ImageFolder(root='data/raw/synapses', loader=load_image) # randomly split the dataset into train, validation, and test num_images = len(full_dataset) # ~70% for training num_training = int(0.7 * num_images) # ~15% for validation num_validation = int(0.15 * num_images) # ~15% for testing num_test = num_images - (num_training + num_validation) # split the data randomly (but with a fixed random seed) train_dataset, validation_dataset, test_dataset = random_split( full_dataset, [num_training, num_validation, num_test], generator=torch.Generator().manual_seed(23061912)) # compute class weights in training dataset for uniform sampling ys = np.array([y for _, y in train_dataset]) counts = np.bincount(ys) label_weights = 1.0 / counts weights = label_weights[ys] print("Number of images per class:") for c, n, w in zip(full_dataset.classes, counts, label_weights): print(f"\t{c}:\tn={n}\tweight={w}") # create a data loader with uniform sampling sampler = WeightedRandomSampler(weights, len(weights)) # this data loader will serve 8 images in a "mini-batch" at a time dataloader = DataLoader(train_dataset, batch_size=8, drop_last=True, sampler=sampler) # - # The cell below visualizes a single, randomly chosen batch from the training data loader. Feel free to execute this cell multiple times to get a feeling for the dataset. See if you can tell the difference between synapses of different types! # + def show_batch(x, y): fig, axs = plt.subplots(1, x.shape[0], figsize=(14, 14), sharey=True) for i in range(x.shape[0]): axs[i].imshow(np.squeeze(x[i]), cmap='gray') axs[i].set_title(train_dataset.dataset.classes[y[i].item()]) plt.show() # show a random batch from the data loader # (run this cell repeatedly to see different batches) for x, y in dataloader: show_batch(x, y) break # - # ### Create a Model, Loss, and Optimizer class Vgg2D(torch.nn.Module): def __init__( self, input_size, fmaps=12, downsample_factors=[(2, 2), (2, 2), (2, 2), (2, 2)], output_classes=6): super(Vgg2D, self).__init__() self.input_size = input_size current_fmaps = 1 current_size = tuple(input_size) features = [] for i in range(len(downsample_factors)): features += [ torch.nn.Conv2d( current_fmaps, fmaps, kernel_size=3, padding=1), torch.nn.BatchNorm2d(fmaps), torch.nn.ReLU(inplace=True), torch.nn.Conv2d( fmaps, fmaps, kernel_size=3, padding=1), torch.nn.BatchNorm2d(fmaps), torch.nn.ReLU(inplace=True), torch.nn.MaxPool2d(downsample_factors[i]) ] current_fmaps = fmaps fmaps *= 2 size = tuple( int(c/d) for c, d in zip(current_size, downsample_factors[i])) check = ( s*d == c for s, d, c in zip(size, downsample_factors[i], current_size)) assert all(check), \ "Can not downsample %s by chosen downsample factor" % \ (current_size,) current_size = size self.features = torch.nn.Sequential(*features) classifier = [ torch.nn.Linear( current_size[0] * current_size[1] * current_fmaps, 4096), torch.nn.ReLU(inplace=True), torch.nn.Dropout(), torch.nn.Linear( 4096, 4096), torch.nn.ReLU(inplace=True), torch.nn.Dropout(), torch.nn.Linear( 4096, output_classes) ] self.classifier = torch.nn.Sequential(*classifier) def forward(self, raw): # add a channel dimension to raw shape = tuple(raw.shape) raw = raw.reshape(shape[0], 1, shape[1], shape[2]) # compute features f = self.features(raw) f = f.view(f.size(0), -1) # classify y = self.classifier(f) return y # + # get the size of our images for x, y in train_dataset: input_size = x.shape break # create the model to train model = Vgg2D(input_size) # create a loss loss = torch.nn.CrossEntropyLoss() # create an optimzer optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) # - # ### Train the Model # use a GPU, if it is available device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) print(f"Will use device {device} for training") # The next cell merely defines some convenience functions for training, validation, and testing: # + def train(dataloader, optimizer, loss, device): '''Train the model for one epoch.''' # set the model into train mode model.train() epoch_loss, num_batches = 0, 0 for x, y in tqdm(dataloader, 'train'): x, y = x.to(device), y.to(device) optimizer.zero_grad() y_pred = model(x) l = loss(y_pred, y) l.backward() optimizer.step() epoch_loss += l num_batches += 1 return epoch_loss/num_batches def evaluate(dataloader, name, device): correct = 0 total = 0 for x, y in tqdm(dataloader, name): x, y = x.to(device), y.to(device) logits = model(x) probs = torch.nn.Softmax(dim=1)(logits) predictions = torch.argmax(probs, dim=1) correct += int(torch.sum(predictions == y).cpu().detach().numpy()) total += len(y) accuracy = correct/total return accuracy def validate(validation_dataset, device): '''Evaluate prediction accuracy on the validation dataset.''' model.eval() dataloader = DataLoader(validation_dataset, batch_size=32) return evaluate(dataloader, 'validate', device) def test(test_dataset, device): '''Evaluate prediction accuracy on the test dataset.''' model.eval() dataloader = DataLoader(test_dataset, batch_size=32) return evaluate(dataloader, 'test', device) # - # We are ready to train. After each epoch (roughly going through each training image once), we report the training loss and the validation accuracy. def train_from_scratch(dataloader, validation_dataset, optimizer, loss, num_epochs=100, device=device): for epoch in range(num_epochs): epoch_loss = train(dataloader, optimizer, loss, device=device) print(f"epoch {epoch}, training loss={epoch_loss}") accuracy = validate(validation_dataset, device=device) print(f"epoch {epoch}, validation accuracy={accuracy}") # `yes_I_want_the_pretrained_model = True` will load a checkpoint that we already prepared, whereas setting it to `False` will train the model from scratch. # # Unceck the box below and run the cell to train a model. # + cellView="form" # @markdown yes_I_want_the_pretrained_model = True # @param {type:"boolean"} # + # Load a pretrained model or train the model from scratch # set this to True and run this cell if you want a shortcut if yes_I_want_the_pretrained_model: checkpoint = torch.load('checkpoints/synapses/classifier/vgg_checkpoint', map_location=device) model.load_state_dict(checkpoint['model_state_dict']) else: train_from_scratch(dataloader, validation_dataset, optimizer, loss, num_epochs=100, device=device) # - accuracy = test(test_dataset, device=device) print(f"final test accuracy: {accuracy}") # This concludes the first section. We now have a classifier that can discriminate between images of different types. # # If you used the images we provided, the classifier is not perfect (you should get an accuracy of around 80%), but pretty good considering that there are six different types of images. Furthermore, it is not so clear for humans how the classifier does it. Feel free to explore the data a bit more and see for yourself if you can tell the difference betwee, say, GABAergic and glutamatergic synapses. # # So this is an interesting situation: The VGG network knows something we don't quite know. In the next section, we will see how we can visualize the relevant differences between images of different types. # --- # # Train a GAN to Translate Images # # We will train a so-called CycleGAN to translate images from one class to another. # + cellView="form" # @title Get the CycleGAN code and dependencies # @markdown GitHub repo: https://github.com/funkey/neuromatch_xai import requests, zipfile, io url = 'https://osf.io/vutn5/download' r = requests.get(url) z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall() # !pip install dominate --quiet # - # In this example, we will translate between GABAergic and glutamatergic synapses. # # First, we have to copy images of either type into a format that the CycleGAN library is happy with. Afterwards, we can start training on those images. # + import cycle_gan cycle_gan.prepare_dataset('data/raw/synapses/', ['0_gaba', '2_glutamate']) ## Uncomment if you want to enable the training procedure # cycle_gan.train('data/raw/synapses/', '0_gaba', '2_glutamate', 128) # - # Training the CycleGAN takes a lot longer than the VGG we trained above (on the synapse dataset, this will be around 7 days...). # # To continue, interrupt the kernel and continue with the next one, which will just use one of the pretrained CycleGAN models for the synapse dataset. # translate images from class A to B, and classify each with the VGG network trained above cycle_gan.test( data_dir='data/raw/synapses/', class_A='0_gaba', class_B='2_glutamate', img_size=128, checkpoints_dir='checkpoints/synapses/cycle_gan/gaba_glutamate/', vgg_checkpoint='checkpoints/synapses/classifier/vgg_checkpoint' ) # Read all translated images and sort them by how much the translation "fools" the VGG classifier trained above: # + class_A_index = 0 class_B_index = 2 result_dir = 'data/raw/synapses/cycle_gan/0_gaba_2_glutamate/results/test_latest/images/' classification_results = [] for f in glob.glob(result_dir + '/*.json'): result = json.load(open(f)) result['basename'] = f.replace('_aux.json', '') classification_results.append(result) classification_results.sort( key=lambda c: c['aux_real'][class_A_index] * c['aux_fake'][class_B_index], reverse=True) # - # Show the top real and fake images that make the classifier change its mind: # + def show_pair(a, b, score_a, score_b, class_a, class_b): fig, axs = plt.subplots(1, 2, figsize=(20, 20), sharey=True) axs[0].imshow(a, cmap='gray') axs[0].set_title(f"p({class_a}) = " + str(score_a)) axs[1].imshow(b, cmap='gray') axs[1].set_title(f"p({class_b}) = " + str(score_b)) plt.show() # show the top successful translations (according to our VGG classifier) for i in range(10): basename = classification_results[i]['basename'] score_A = classification_results[i]['aux_real'][class_A_index] score_B = classification_results[i]['aux_fake'][class_B_index] real_A = imread(basename + '_real.png') fake_B = imread(basename + '_fake.png') show_pair(real_A, fake_B, score_A, score_B, 'gaba', 'glutamate')
projects/ComputerVision/em_synapses.ipynb
# Copyright 2018 Google LLC # # 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. # Only for when running on Colab: import sys if 'google.colab' in sys.modules: # Get the dependency .py files, if any. # ! git clone https://github.com/GoogleCloudPlatform/cloudml-samples.git # ! cp cloudml-samples/tpu/templates/tpu_rewrite/* . # Authenticate the user for better GCS access. # Copy verification code into the text field to continue. from google.colab import auth auth.authenticate_user() import argparse import numpy as np import os import tensorflow as tf from tensorflow.contrib.cluster_resolver import TPUClusterResolver def tpu_computation(features, labels): # Similar to the role of model_fn, the TPU function builds the part of the graph to be run on TPUs # build model hidden = tf.layers.dense(features, 10, activation=tf.nn.relu) outputs = tf.layers.dense(hidden, 1) loss = tf.nn.l2_loss(outputs - labels) optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05) # Wrap the optimizer optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) global_step = tf.train.get_or_create_global_step() train_op = optimizer.minimize(loss, global_step=global_step) # TPU functions must return zero-or more Tensor values followed by zero or more Operations. return global_step, loss, train_op def train_input_fn(): # data input function runs on the CPU, not TPU # make some fake regression data x = np.random.rand(100, 5) w = np.random.rand(5) y = np.sum(x * w, axis=1) # TPUs currently do not support float64 x_tensor = tf.constant(x, dtype=tf.float32) y_tensor = tf.constant(y, dtype=tf.float32) # create tf.data.Dataset dataset = tf.data.Dataset.from_tensor_slices((x_tensor, y_tensor)) # TPUs need to know all dimensions including batch size batch_size = 16 dataset = dataset.repeat().shuffle(32).batch(batch_size)#, drop_remainder=True) # TPUs need to know all dimensions when the graph is built # Datasets know the batch size only when the graph is run def set_shapes(features, labels): features_shape = features.get_shape().merge_with([batch_size, None]) labels_shape = labels.get_shape().merge_with([batch_size]) features.set_shape(features_shape) labels.set_shape(labels_shape) return features, labels dataset = dataset.map(set_shapes) dataset = dataset.prefetch(tf.contrib.data.AUTOTUNE) return dataset def main(args): # unpack the tensor batch to be used as the list of inputs of the TPU function dataset = train_input_fn() iterator = dataset.make_one_shot_iterator() features, labels = iterator.get_next() # mark part of the graph to be run on the TPUs global_step_tensor, loss_tensor = tf.contrib.tpu.rewrite(tpu_computation, [features, labels]) # utility ops tpu_init = tf.contrib.tpu.initialize_system() tpu_shutdown = tf.contrib.tpu.shutdown_system() variables_init = tf.global_variables_initializer() saver = tf.train.Saver() # get the TPU resource's grpc url # Note: when running on CMLE, args.tpu should be left as None tpu_grpc_url = TPUClusterResolver(tpu=args.tpu).get_master() sess = tf.Session(tpu_grpc_url) sess.run(tpu_init) sess.run(variables_init) for i in range(args.max_steps): # the tensor values in the TPU function are returned in a list, and the operations in the TPU function are called with no return value global_step, loss = sess.run([global_step_tensor, loss_tensor]) if i % args.save_checkpoints_steps == 0: saver.save(sess, os.path.join(args.model_dir, 'model.ckpt'), global_step=global_step) tf.logging.info('global_step: {}, loss: {}'.format(global_step, loss)) sess.run(tpu_shutdown) # + parser = argparse.ArgumentParser() parser.add_argument( '--model-dir', type=str, default='/tmp/tpu-template', help='Location to write checkpoints and summaries to. Must be a GCS URI when using Cloud TPU.') parser.add_argument( '--max-steps', type=int, default=1000, help='The total number of steps to train the model.') parser.add_argument( '--save-checkpoints-steps', type=int, default=100, help='The number of training steps before saving each checkpoint.') parser.add_argument( '--tpu', default=None, help='The name or GRPC URL of the TPU node. Leave it as `None` when training on CMLE.') args, _ = parser.parse_known_args() # - # colab.research.google.com specific if 'google.colab' in sys.modules: import json import os # TODO(user): change this args.model_dir = 'gs://your-gcs-bucket' # When connected to the TPU runtime if 'COLAB_TPU_ADDR' in os.environ: tpu_grpc = 'grpc://{}'.format(os.environ['COLAB_TPU_ADDR']) args.tpu = tpu_grpc args.use_tpu = True # Upload credentials to the TPU with tf.Session(tpu_grpc) as sess: data = json.load(open('/content/adc.json')) tf.contrib.cloud.configure_gcs(sess, credentials=data) main(args)
tpu/templates/tpu_rewrite/trainer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + colab={"base_uri": "https://localhost:8080/"} id="awCwVH9dlfsy" executionInfo={"status": "ok", "timestamp": 1620051765584, "user_tz": -120, "elapsed": 565, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07097771029035828065"}} outputId="f5762fda-3658-4863-9e82-8304305e0e0d" import torch a = torch.tensor([[1,2], [3,4], [5,6]]) a[2,1] # + colab={"base_uri": "https://localhost:8080/"} id="bCAdk1JEoo2p" executionInfo={"status": "ok", "timestamp": 1620052887129, "user_tz": -120, "elapsed": 472, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07097771029035828065"}} outputId="fd250fa5-a78c-47f9-e982-b731ce40a57d" img_t = torch.randn(3, 5, 5) weights = torch.tensor([0.2126, 0.7152, 0.0722]) batch_t = torch.randn(2, 3, 5, 5) img_gray_naive = img_t.mean(-3) batch_t_naive = batch_t.mean(-3) weights.unsqueeze(-1).unsqueeze_(-1).shape # + colab={"base_uri": "https://localhost:8080/"} id="V8yW1pqowTkl" executionInfo={"status": "ok", "timestamp": 1620054246212, "user_tz": -120, "elapsed": 505, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07097771029035828065"}} outputId="0a961375-9320-445b-8b9a-c910e07c0fd1" points = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]]) print(points.storage()) points2 = points
notebooks/tensors.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import unittest import mlm class Testmlm(unittest.TestCase): # Each test class should have at least two test cases and each test case should contain at least four assertion statements. def test_summarylin(self): A = [1, 2, 3, 4, 5, 6, 7, 8 , 9 , 10] B = [5, 6, 8, 9, 16, 29, 14, 16, 19, 25] C = ["1","1","1","1","1","1","2","2","2","2"] self.assertEqual(str( type(mlm.linearmixedeffects(A,B,C)) ), "<class 'mlm.linearmixedeffects'>") self.assertEqual(str( type(mlm.linearmixedeffects(A,B,C).summarymlm()) ), "<class 'statsmodels.iolib.summary2.Summary'>") self.assertEqual(mlm.linearmixedeffects(A,B,C).fitmlm().fe_params[0], 0.2) self.assertEqual(str( type(mlm.linearmixedeffects(A,B,C).fitmlm().model) ), "<class 'statsmodels.regression.mixed_linear_model.MixedLM'>") unittest.main(argv=[''], verbosity=2, exit=False) # + import unittest import mlm import pandas as pd class Testmlm(unittest.TestCase): # Each test class should have at least two test cases and each test case should contain at least four assertion statements. def test_summarylin(self): A = [1, 2, 3, 4, 5, 6, 7, 8 , 9 , 10] B = [5, 6, 8, 9, 16, 29, 14, 16, 19, 25] C = ["1","1","1","1","1","1","2","2","2","2"] self.assertTrue(mlm.linearmixedeffects(A,B,C).fitmlm().cov_re["Group Var"][0] == 0) self.assertTrue(pd.isnull(mlm.linearmixedeffects(A,B,C).fitmlm().normalized_cov_params[0][0])) self.assertTrue(pd.isnull(mlm.linearmixedeffects(A,B,C).fitmlm().bse_fe[0])) self.assertTrue(pd.isnull(mlm.linearmixedeffects(A,B,C).fitmlm().bse_re[0])) unittest.main(argv=[''], verbosity=2, exit=False)
lr_for_the_masses/rr_mlm/notebook test_mlm.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Classification avec `scikit-learn` # # [scikit-learn](https://scikit-learn.org/stable/index.html) est une bibliothรจque Python dรฉdiรฉe ร  l'apprentissage automatique (*machine learning*). Ce package est dรฉveloppรฉ sur licence libre. Il y a une forte proportion de franรงais parmi les dรฉveloppeurs, le projet est soutenu par l'INRIAย notamment. # [scikit-learn](https://scikit-learn.org/stable/index.html) repose sur `NumPy` et `SciPy`. Il est รฉcrit en Python et Cython. Il s'interface trรจs bien avec `matplotlib`, `plotly` ou `pandas`. C'est devenu un incontournable du *machine learning* et de la *datascience* en Python. # # Dans ce notebook nous nous limiterons ร  la classification, une partie seulement du package [scikit-learn](https://scikit-learn.org/stable/index.html). # La classification est souvent utilisรฉe en TAL, par exemple dans les tรขches d'analyse de sentiment, de dรฉtection d'รฉmotion ou l'identification de la langue. L'idรฉe est d'apprendre un modรจle ร  partir de donnรฉes รฉtiquetรฉes et de prรฉdire la bonne รฉtiquette pour une donnรฉe inconnue du modรจle. # # On a un รฉchantillon d'entraรฎnement composรฉ de $n$ couples $Z_{i}=(X_{i}, Y_{i}), i=1...n$ oรน les $X_{i}$ sont les inputs avec plusieurs traits et les $Y_{i}$ seront les outputs, les catรฉgories ร  prรฉdire. # L'objectif du problรจme d'apprentissage est de trouver une fonction $g:Xโ†’Y$ de prรฉdiction, qui minimise les erreurs de prรฉdiction. # - # `scikitlearn` offre beaucoup d'algorithmes d'apprentissage. Vous en trouverez un aperรงu sur [https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html](cette carte) et sur ces listes : [supervisรฉ](https://scikit-learn.org/stable/supervised_learning.html) / [non supervisรฉ](https://scikit-learn.org/stable/unsupervised_learning.html). # # Mais `scikitlearn` offre รฉgalement les outils pour mener ร  bien les รฉtapes d'une tรขche de *machine learning* : # - Manipuler les donneรฉs, constituter un jeu de donnรฉes d'entraรฎnement et de test # - Entraรฎnement du modรจle # - ร‰valuation # - Optimisation des hyperparamรจtres # ## Un premier exemple # # ### Les donnรฉes # # C'est la clรฉ de voute du *machine learning*, vous le savez n'est-ce pas ? Nous allons travailler avec un des jeux de donnรฉes fourni par scikitlearn :ย https://scikit-learn.org/stable/datasets/index.html#wine-recognition-dataset # C'est un peu facile parce que les donnรฉes sont dรฉjร  nettoyรฉes et organisรฉes. from sklearn import datasets wine = datasets.load_wine() type(wine) # Ces jeux de donnรฉes sont des objets `sklearn.utils.Bunch`. Organisรฉs un peu comme des dictionnaires Python, ces objets contiennent : # - `data` :ย array numpy ร  deux dimensions d'รฉchantillons de donnรฉes (n_samples * n_features), les inputs, les X # - `target` :ย les variables ร  prรฉdire, les catรฉgories des รฉchantillons si vous voulez, les outputs, les y # - `feature_names` # - `target_names` print(wine.DESCR) wine.feature_names # On peut convertir ces donnรฉes en Dataframe pandas si on veut. # + import pandas as pd df = pd.DataFrame(data=wine.data,columns=wine.feature_names) df['target']=wine.target df.head() # - # Mais l'essentiel est de retrouver nos inputs X et outputs y nรฉcessaires ร  l'apprentissage. X_wine, y_wine = wine.data, wine.target # Vous pouvez sรฉparer les donnรฉes en train et test facilement ร  l'aide de `sklearn.model_selection.train_test_split` ( voir la [doc](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html#sklearn.model_selection.train_test_split)) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_wine, y_wine, test_size=0.3) y_train # + import matplotlib.pyplot as plt # %matplotlib inline plt.hist(y_train, align="right", label="train") plt.hist(y_test, align="left", label="test") plt.title("rรฉpartition des classes") plt.show() # - # Il ne faut pas hรฉsiter ร  recourir ร  des reprรฉsentations graphiques quand vous manipulez les donnรฉes. Ici on voit que la rรฉpartition des classes ร  prรฉdire n'est pas homogรจne pour les donnรฉes de test. # On peut y remรฉdier en utilisant le paramรจtre `stratify` X_train, X_test, y_train, y_test = train_test_split(X_wine, y_wine, test_size=0.25, stratify=y_wine) plt.hist(y_train, align="right", label="train") plt.hist(y_test, align="left", label="test") plt.title("rรฉpartition des classes") plt.show() # ## Entraรฎnement # # L'รฉtape suivante est de choisir un algorithme (un *estimator*), de l'entraรฎner sur nos donnรฉes train (avec la fonction `fit()`) puis de faire la prรฉdiction (avec la fonction `predict`). # Quelque soit l'algo choisi vous allez retrouver les fonctions `fit` et `predict`. Ce qui changera ce seront les paramรจtres ร  passer au constructeur de la classe de l'algo. Votre travail portera sur le choix de ces paramรจtres. # Exemple un peu bateau avec une mรฉthode de type SVM. from sklearn.svm import SVC clf = SVC(C=1, kernel="linear") clf.fit(X_train, y_train) clf.predict(X_test) # ## ร‰valuation # # On fait l'รฉvaluation en confrontant les prรฉdictions sur les X_test et les y_test. La fonction `score` nous donne l'*accuracy* moyenne du modรจle. clf.score(X_test, y_test) # Pour la classification il existe une classe bien pratique :ย `sklearn.metrics.classification_report` # + from sklearn.metrics import classification_report y_pred = clf.predict(X_test) print(classification_report(y_test, y_pred)) # - # ### โœ๏ธ Exo โœ๏ธ # 1. Essayez un autre algo de classification (linear SVM par exemple) et comparez les rรฉsultats. # 2. Sur ce mรชme algo, refaites une partition train/test et comparez l'รฉvaluation avec les rรฉsultats prรฉcรฉdents. # Pour amรฉliorer la robustesse de l'รฉvaluation on va utiliser la cross validation. `scikit-learn` a des classes pour รงa. from sklearn.model_selection import cross_validate, cross_val_score print(cross_validate(SVC(C=1, kernel="linear"), X_wine, y_wine)) # infos d'accuracy mais aussi de temps print(cross_val_score(SVC(C=1, kernel="linear"), X_wine, y_wine)) # uniquement accuracy # ## Optimisation des hyperparamรจtres # L'optimisation des hyperparamรจtres est la derniรจre รฉtape. Ici encore `scikitlearn` nous permet de le faire de maniรจre simple et efficace.ย Nous utiliserons `sklearn.model_selection.GridSearchCV` qui fait une recherche exhaustive sur tous les paramรจtres donnรฉs au constructeur. Cette classe utilise aussi la cross validation. # + from sklearn.model_selection import GridSearchCV param_grid = {'C': [0.1, 0.5, 1, 10, 100, 1000], 'kernel':['rbf','linear']} grid = GridSearchCV(SVC(), param_grid, cv = 5, scoring = 'accuracy') estimator = grid.fit(X_wine, y_wine) estimator.cv_results_ # - df = pd.DataFrame(estimator.cv_results_) df.sort_values('rank_test_score') # # Classification de textes # Vous trouverez un exemple de classification proposรฉ par `scikitlearn` ici :ย https://scikit-learn.org/stable/auto_examples/text/plot_document_classification_20newsgroups.html et de la doc sur les features des documents textuels ici :ย https://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction # La classification avec des techniques non neuronales repose en grande partie sur les features utilisรฉes pour reprรฉsenter les textes. # + from sklearn.datasets import fetch_20newsgroups categories = [ 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space'] data_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True) data_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True) # - print(len(data_train.data)) print(len(data_test.data)) # Ici on a un jeu de 2373 textes catรฉgorisรฉs pour train. ร€ nous d'en extraire les features dรฉsirรฉes. # tfidf est un grand classique. Vous pouvez rรฉutiliser votre propre scritp ou la classe de `scikitlearn` # # Attention aux valeurs par dรฉfaut des paramรจtres. Ici par exemple on passe tout en minuscule et la tokenisation est rudimentaire. ร‡a fonctionnera mal pour d'autres langues que l'anglais. # + from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english') X_train = vectorizer.fit_transform(data_train.data) # donnรฉes de train vectorisรฉes y_train = data_train.target # - X_test = vectorizer.transform(data_test.data) y_test = data_test.target # + # Pour l'entraรฎnement et l'รฉval on reprend le code vu auparavant clf = SVC(C=1, kernel="linear") clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(classification_report(y_test, y_pred)) # - # Essayez avec d'autres features. La longueur moyennes des mots, le nombre d'adjectifs, la prรฉsence d'entitรฉs nommรฉes, โ€ฆ # ## Et les rรฉseaux de neurones ? # # `scikitlearn` permet d'utiliser un Multi-layer Perceptron (MLP). Et comme la bibliothรจque ne permet pas d'utiliser un GPU pour les calculs, son utilisation est limitรฉe ร  des jeux de donnรฉes de taille moyenne. # `scikitlearn` n'est pas fait pour le deep learning. Il existe des bib associรฉes qui permettent de combiner Keras ou pytorch avec `scikitlearn` nรฉanmoins. # Essayons ensemble en suivant la doc de https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html
9-classification-scikitlearn.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/saritmaitra/Momentum_Trading/blob/main/RSI_Momentum_strategy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="ST_TfLnBl6az" # A momentum strategy basically bets on the continuation of an existing market trend. For example, if the market is or starts going up, we will bet that the trend will continue for a while and we will try to make our trading strategy based on this. # # Momentum indicators can help us locate the entry and exit points to follow momentum strategies. One of this type of indicators is the Relative Strength Index (RSI). This indicator is the one that we will use in order to define our backtesting strategy with Python. # # ## Relative Strength Index (RSI) # The Relative Strength Index (RSI) is a technical indicator that measures the speed and change of price movements. It was developed by <NAME>. # + id="TJ3Q1CnOdVTo" # !pip install yfinance import yfinance as yf import datetime as dt import matplotlib.pyplot as plt import matplotlib.transforms as transform import matplotlib.gridspec as gridspec import pandas as pd from pandas.tseries.offsets import MonthEnd pd.options.mode.chained_assignment = None pd.set_option('use_inf_as_na', True) from pandas import DataFrame, concat # + colab={"base_uri": "https://localhost:8080/"} id="BecBcyseddDm" outputId="9923b44d-6fc5-4018-efe4-75b1368e2f56" ticker = "CL=F" start_date = dt.datetime(2018,1,1) end_date = dt.datetime(2020,12,31) class DataBase(): def __init__(self, ticker, days): self.ticker = ticker data = yf.download(ticker, start = start_date, end =end_date ) self.df = DataFrame(data) pd.set_option("display.max_columns", None) self.df[self.df.index.dayofweek < 4] self.df= self.df[-days:] def quote(self): return self.df db = DataBase(ticker, 1000) df = db.quote() print(df.tail(10)) df['MA_14'] = df['Adj Close'].rolling(window=14).mean() df.dropna(inplace=True) # plt.rcParams.update({'font.size': 10}) # fig, ax1 = plt.subplots(figsize = (15,6)) # ax1.set_ylabel("Price in US$") # ax1.set_xlabel("Timestamp") # ax1.plot('Adj Close', data=df, label = "Adj Close Price") # ax1.plot('MA_15', data=df, label = "3 weeks MA"); plt.grid(True) # ax1.set_title('Crude Oil price & 15 days rolling average') # plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 350} id="_D8d6IZ2FxFc" outputId="cd262805-f186-4532-90c1-09e9719996c6" df['MA_14'] = df['Adj Close'].rolling(window=14).mean() df.dropna(inplace=True) plt.rcParams.update({'font.size': 10}) fig, ax1 = plt.subplots(figsize = (10,5)) ax1.set_ylabel("Price in US$") ax1.set_xlabel("Timestamp") ax1.plot('Adj Close', data=df, label = "Adj Close Price") ax1.plot('MA_14', data=df, label = "14 days MA"); plt.grid(True) ax1.set_title('Crude Oil price & 14 days rolling average') plt.show() # + [markdown] id="7eKXOJzseVOF" # It measures the relative strength of upside and downside moves in security prices. # # ## Formula: # # - RSI = 100 โ€“ 100 / ( 1 + RS ) # - RS = Relative Strength = AvgU / AvgD # - AvgU = average of all up moves in the last N price bars # - AvgD = average of all down moves in the last N price bars # - N = the period of RSI # # ## RSI values # The Relative Strenght Index can reach values from 0 to 100. # - Values close to zero are a sign of declining (bearish) market; # - values close to 100 occur when prices are rising and the rises are greater than the declines. # # High RSI means that the second part of the RSI formula (behind the minus sign) is very small and RS is very large, which means that recent up moves have been much greater than recent down moves. In other words, high RSI values are a sign of bullish market (which may be overbought โ€“ depending on your particular view and trading style). # # Conversely, low RSI means that RS is also low and recent down moves have been much greater than recent up moves โ€“ in other words, bearish (and possibly oversold) market. # # When there are no down moves and AvgD is zero, RS canโ€™t be calculated (you would be dividing by zero). In such case, we can consider RS close to infinite and RSI is 100. # # ## RSI overbought and oversold # - RSI value over 80 or 90 is considered overbought. # - RSI value under 20 or 10 is considered oversold. # # The tighter condition we choose (higher RSI value for overbought condition, lower RSI value for oversold condition), the fewer times RSI will get to the overbought or oversold territory and the fewer signals or trading situations we get. # + colab={"base_uri": "https://localhost:8080/", "height": 447} id="Tbohj0CmeEz1" outputId="a0770ba8-870b-4cd6-cb66-1b1dd970c2d5" df['price_change'] = df['Adj Close'].pct_change() df = df.dropna() # https://www.macroption.com/rsi/ df['up_move'] = df['price_change'].apply(lambda x: x if x > 0 else 0) df['down_move'] = df['price_change'].apply(lambda x: abs(x) if x < 0 else 0) df['avg_up'] = df['up_move'].ewm(span=15).mean() df['avg_down'] = df['down_move'].ewm(span=15).mean() df = df.dropna() df['RS'] = df['avg_up'] / df['avg_down'] df = df.dropna() df['RSI'] = df['RS'].apply(lambda x: 100 - (100/(x+1))) df.loc[(df['Adj Close'] > df['MA_14']) & (df['RSI'] > 30), "BUY"] = 'YES' df.loc[(df['Adj Close'] < df['MA_14']) | (df['RSI'] < 30), "BUY"] = 'NO' df # + colab={"base_uri": "https://localhost:8080/", "height": 375} id="obr5Fd_p3K7n" outputId="e0028d4c-5cb3-47a3-e764-0dab3441db22" plt.figure(figsize=(15,6)) df['RSI'].plot(legend=True).axhline(y=50, color="black", lw=2) df['Adj Close'].plot(legend=True) plt.grid(True) # + colab={"base_uri": "https://localhost:8080/"} id="-MfEpCQLfXOu" outputId="9b9399dd-ad19-48a5-d869-1aca20a8c6c4" pd.value_counts(df.BUY) # + colab={"base_uri": "https://localhost:8080/", "height": 417} id="fHAEVyULfbx1" outputId="e4135a4d-6c44-47bb-885d-da7634ea810d" PnL = [] for i in range(len(df) - 12): if "YES" in df['BUY'].iloc[i]: for j in range(1,11): if df['RSI'].iloc[i+j] > 70: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) break if df['RSI'].iloc[i+j] < 30: PnL.append(df['Open'].iloc[i+12] - df['Open'].iloc[i+1]) break pd.DataFrame(PnL) # + colab={"base_uri": "https://localhost:8080/"} id="v1CMTR7SfinF" outputId="f1465730-a6a7-42d2-9743-d0637124fcaa" len([i for i in PnL if i > 0]) len(PnL) # winning rate print(len([i for i in PnL if i > 0]) / len(PnL)) # + colab={"base_uri": "https://localhost:8080/"} id="Jf2jOphif0UM" outputId="940b0411-b99d-4131-f205-bd03e8e6b6d5" tickers=["CL=F"] start_date = dt.datetime(2018,1,1) end_date = dt.datetime(2020,12,31) def RSI_calculation(symbol): data = yf.download(tickers, start = start_date, end=end_date) data['MA_14'] = data['Adj Close'].rolling(window=14).mean() data['price_change'] = data['Adj Close'].pct_change() data['up_move'] = data['price_change'].apply(lambda x: x if x > 0 else 0) data['down_move'] = data['price_change'].apply(lambda x: abs(x) if x < 0 else 0) data['avg_up'] = data['up_move'].ewm(span=14).mean() data['avg_down'] = data['down_move'].ewm(span=14).mean() data = data.dropna() data['RS'] = data['avg_up'] / data['avg_down'] data['RSI'] = data['RS'].apply(lambda x: 100 - (100/(x+1))) data.loc[(data['Adj Close'] > data['MA_14']) & (data['RSI'] > 30), "BUY"] = 'YES' data.loc[(data['Adj Close'] < data['MA_14']) | (data['RSI'] < 30), "BUY"] = 'NO' return (data) def get_signals(data): buy_date = [] sell_date = [] for i in range(len(data) - 11): if "YES" in data['BUY'].iloc[i]: buy_date.append(data.iloc[i+1].name) for j in range(1,11): if data['RSI'].iloc[i+j] > 70: sell_date.append(data.iloc[i+j+1].name) break elif j == 10: sell_date.append(data.iloc[i+j+1].name) return (buy_date, sell_date) dataframe = RSI_calculation(tickers[0]) buy, sell = get_signals(dataframe) # + colab={"base_uri": "https://localhost:8080/", "height": 374} id="uQvtl6r5gBls" outputId="55bd9f09-f667-493b-bc44-4da7c601aa2a" plt.figure(figsize = (15,6)) plt.scatter(dataframe.loc[buy].index, dataframe.loc[buy]['Adj Close'], marker = '^', c = 'k') plt.plot(dataframe['Adj Close']) plt.grid(True); plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="EPqEWWQHgmr0" outputId="2859fff2-365c-4dc8-e4cc-f895fa674928" profits = (dataframe.loc[sell].Open.values - dataframe.loc[buy].Open.values) / dataframe.loc[sell].Open.values len([i for i in profits if i > 0]) / len(profits) # + colab={"base_uri": "https://localhost:8080/"} id="oD7G3RrDgwf8" outputId="676706c6-a40a-4b3c-b36c-3b1a9bf96f0b" len(profits) # + colab={"base_uri": "https://localhost:8080/"} id="6Y77_H5hgzIM" outputId="f3bf3559-9399-4d9f-eef0-a6f49a7a5d38" matrix_signals = [] matrix_profit = [] for i in range(len(tickers)): dataframe = RSI_calculation(tickers[i]) buy, sell = get_signals(dataframe) profits = (dataframe.loc[sell].Open.values - dataframe.loc[buy].Open.values) / dataframe.loc[sell].Open.values matrix_signals.append(buy) matrix_profit.append(profits) # + colab={"base_uri": "https://localhost:8080/", "height": 417} id="PTi5onKrg3QM" outputId="e7e7649d-b017-48cc-ff2a-bce7e22ebd68" final_profit = [] for i in matrix_profit: for e in i: final_profit.append(e) DataFrame(final_profit) # + colab={"base_uri": "https://localhost:8080/"} id="URHLqLcXhAKl" outputId="ca252b77-8483-4d7f-e8ce-0de98b45a36b" wins = [i for i in final_profit if i > 0] len(wins) / len(final_profit) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="hnVVyys0hCpt" outputId="e43da0e1-f472-4954-8d0c-ba6c6ac814d1" plt.hist(final_profit, bins=100) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="WI_ffdHjhHjt" outputId="0a174bc3-b1d7-48e5-f19b-787c72daf3da" for i in matrix_signals: for e in i: if e.year == 2020: print(e) # + colab={"base_uri": "https://localhost:8080/"} id="kKH6Zlp_nCWs" outputId="f364ca36-8809-4c6a-f50b-f8e31252fe96" import numpy as np import warnings warnings.simplefilter(action = "ignore", category = RuntimeWarning) ticker = "CL=F" start_date = dt.datetime(2018,1,1) end_date = dt.datetime(2020,12,31) class DataBase(): def __init__(self, ticker, days): self.ticker = ticker data = yf.download(ticker, start = start_date, end =end_date ) self.df = DataFrame(data) pd.set_option("display.max_columns", None) self.df[self.df.index.dayofweek < 5] self.df= self.df[-days:] def quote(self): return self.df db = DataBase(ticker, 1000) df = db.quote() # print(df.tail()) # calculate the return of the day and add as new column df['price_change'] = np.log(df['Adj Close'] / df['Adj Close'].shift(1) ) df.dropna(inplace=True) # calculate the movement on the price compared to the previous day closing price df['movement'] = df['Adj Close'] - df['Adj Close'].shift(1) df['up'] = np.where((df['movement'] > 0), df['movement'],0) df['down'] = np.where((df['movement'] < 0), df['movement'],0) window_size = 14 # calculate moving average of the last 14 days gains up = df['up'].rolling(window_size).mean() # calculate moving average of the last 14 days losses down = df['down'].abs().rolling(window_size).mean() RS = up / down RSI = 100.0 - (100.0 / (1.0 + RS)) RSI = RSI.rename("RSI") print(RSI) # + [markdown] id="8CzUAwy9o8Ec" # We need three lines of code to ensure that our strategy is defined appropriately. E.g. 1 when we need to be long: # # The first line of code on the long column, ensures that we will have a 1, if RSI is below 30. # The second line of code, ensures that we will have 0 if the RSI is above 70. # Then, finally, the third line of code, will โ€˜forward fillโ€™ and propagate the last valid observation forward to get rid of the nan. # Above three lines will ensure that we only go long when we cross the line from below 30. # # Finally, we calculate the gain and loss for each of the day and the accumulative return. Below screenshot shows that with this strategy, we would get an accumulative return of 50% if we followed the strategy during the last 5 years. # + colab={"base_uri": "https://localhost:8080/", "height": 447} id="ESsCc6GHpA7z" outputId="1c0852dd-8cbc-4350-dd25-4f815808c461" new_df = pd.merge(df, RSI, left_index=True, right_index=True) #If the indicatorโ€™s line crosses the level 30 from below, a long position (Buy) is opened. new_df['long'] = np.where((new_df['RSI'] < 20),1,np.nan) new_df['long'] = np.where((new_df['RSI'] > 80),0, new_df['long']) new_df['long'].ffill(inplace=True) new_df['gain_loss'] = new_df['long'].shift(1) * new_df['price_change'] new_df['total'] = new_df['gain_loss'].cumsum() new_df[['Adj Close', 'price_change', 'movement', 'up','down', 'RSI','long','gain_loss', 'total']].tail(500) # + colab={"base_uri": "https://localhost:8080/"} id="4y6WVOHhqGz7" outputId="8c76665e-2355-4fd9-f2d1-37c117c81e4c" #alternative strategy of buying and hold stock: buy_hold_strat = (new_df['Adj Close'][-1] - new_df['Adj Close'][1]) / new_df['Adj Close'][1] print(buy_hold_strat)
RSI_Momentum_strategy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # CPW Launch Pad # ### Preparations # The next cell enables [module automatic reload](https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html?highlight=autoreload). Your notebook will be able to pick up code updates made to the qiskit-metal (or other) module code. # %reload_ext autoreload # %autoreload 2 # Import key libraries and open the Metal GUI. Also we configure the notebook to enable overwriting of existing components # + from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, Headings design = designs.DesignPlanar() gui = MetalGUI(design) # if you disable the next line, then you will need to delete a component [<component>.delete()] before recreating it design.overwrite_enabled = True # - from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled # + #Explore the options of the LaunchpadWirebondCoupled LaunchpadWirebondCoupled.get_template_options(design) # + #Setup the launchpad location and orientation launch_options = dict(pos_x='990um', pos_y='2812um', orientation='270', lead_length='30um') lp = LaunchpadWirebondCoupled(design, 'P4_Q', options = launch_options) gui.rebuild() gui.autoscale() # + # Get a list of all the qcomponents in QDesign and then zoom on them. all_component_names = design.components.keys() gui.zoom_on_components(all_component_names) # - # Look at the options of the launch pad in QDesign. lp.options #Save screenshot as a .png formatted file. gui.screenshot() # + tags=["nbsphinx-thumbnail"] # Screenshot the canvas only as a .png formatted file. gui.figure.savefig('shot.png') from IPython.display import Image, display _disp_ops = dict(width=500) display(Image('shot.png', **_disp_ops)) # - # Closing the Qiskit Metal GUI gui.main_window.close()
tutorials/Appendix C Circuit examples/E. Input-output-coupling/41-LaunchPad.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Computer Vision Learner # [`vision.learner`](/vision.learner.html#vision.learner) is the module that defines the [`create_cnn`](/vision.learner.html#create_cnn) method, to easily get a model suitable for transfer learning. # + hide_input=true from fastai.gen_doc.nbdoc import * from fastai.vision import * # - # ## Transfer learning # Transfer learning is a technique where you use a model trained on a very large dataset (usually [ImageNet](http://image-net.org/) in computer vision) and then adapt it to your own dataset. The idea is that it has learned to recognize many features on all of this data, and that you will benefit from this knowledge, especially if your dataset is small, compared to starting from a randomly initialized model. It has been proved in [this article](https://arxiv.org/abs/1805.08974) on a wide range of tasks that transfer learning nearly always give better results. # # In practice, you need to change the last part of your model to be adapted to your own number of classes. Most convolutional models end with a few linear layers (a part will call head). The last convolutional layer will have analyzed features in the image that went through the model, and the job of the head is to convert those in predictions for each of our classes. In transfer learning we will keep all the convolutional layers (called the body or the backbone of the model) with their weights pretrained on ImageNet but will define a new head initialized randomly. # # Then we will train the model we obtain in two phases: first we freeze the body weights and only train the head (to convert those analyzed features into predictions for our own data), then we unfreeze the layers of the backbone (gradually if necessary) and fine-tune the whole model (possibly using differential learning rates). # # The [`create_cnn`](/vision.learner.html#create_cnn) factory method helps you to automatically get a pretrained model from a given architecture with a custom head that is suitable for your data. # + hide_input=true show_doc(create_cnn) # - # This method creates a [`Learner`](/basic_train.html#Learner) object from the [`data`](/vision.data.html#vision.data) object and model inferred from it with the backbone given in `arch`. Specifically, it will cut the model defined by `arch` (randomly initialized if `pretrained` is False) at the last convolutional layer by default (or as defined in `cut`, see below) and add: # - an [`AdaptiveConcatPool2d`](/layers.html#AdaptiveConcatPool2d) layer, # - a [`Flatten`](/layers.html#Flatten) layer, # - blocks of \[[`nn.BatchNorm1d`](https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d), [`nn.Dropout`](https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout), [`nn.Linear`](https://pytorch.org/docs/stable/nn.html#torch.nn.Linear), [`nn.ReLU`](https://pytorch.org/docs/stable/nn.html#torch.nn.ReLU)\] layers. # # The blocks are defined by the `lin_ftrs` and `ps` arguments. Specifically, the first block will have a number of inputs inferred from the backbone `arch` and the last one will have a number of outputs equal to `data.c` (which contains the number of classes of the data) and the intermediate blocks have a number of inputs/outputs determined by `lin_frts` (of course a block has a number of inputs equal to the number of outputs of the previous block). The default is to have an intermediate hidden size of 512 (which makes two blocks `model_activation` -> 512 -> `n_classes`). If you pass a float then the final dropout layer will have the value `ps`, and the remaining will be `ps/2`. If you pass a list then the values are used for dropout probabilities directly. # # Note that the very last block doesn't have a [`nn.ReLU`](https://pytorch.org/docs/stable/nn.html#torch.nn.ReLU) activation, to allow you to use any final activation you want (generally included in the loss function in pytorch). Also, the backbone will be frozen if you choose `pretrained=True` (so only the head will train if you call [`fit`](/basic_train.html#fit)) so that you can immediately start phase one of training as described above. # # Alternatively, you can define your own `custom_head` to put on top of the backbone. If you want to specify where to split `arch` you should so in the argument `cut` which can either be the index of a specific layer (the result will not include that layer) or a function that, when passed the model, will return the backbone you want. # # The final model obtained by stacking the backbone and the head (custom or defined as we saw) is then separated in groups for gradual unfreezing or differential learning rates. You can specify how to split the backbone in groups with the optional argument `split_on` (should be a function that returns those groups when given the backbone). # # The `kwargs` will be passed on to [`Learner`](/basic_train.html#Learner), so you can put here anything that [`Learner`](/basic_train.html#Learner) will accept ([`metrics`](/metrics.html#metrics), `loss_func`, `opt_func`...) path = untar_data(URLs.MNIST_SAMPLE) data = ImageDataBunch.from_folder(path) learner = create_cnn(data, models.resnet18, metrics=[accuracy]) learner.fit_one_cycle(1,1e-3) learner.save('one_epoch') # + hide_input=true show_doc(unet_learner) # - # This time the model will be a [`DynamicUnet`](/vision.models.unet.html#DynamicUnet) with an encoder based on `arch` (maybe `pretrained`) that is cut depending on `split_on`. `blur_final`, `norm_type`, `blur`, `self_attention`, `y_range`, `last_cross` and `bottle` are passed to unet constructor, the `kwargs` are passed to the initialization of the [`Learner`](/basic_train.html#Learner). # ### Get predictions # Once you've actually trained your model, you may want to use it on a single image. This is done by using the following method. # + hide_input=true show_doc(Learner.predict) # - img = learner.data.train_ds[0][0] learner.predict(img) # Here the predict class for our image is '3', which corresponds to a label of 0. The probabilities the model found for each class are 99.65% and 0.35% respectively, so its confidence is pretty high. # # Note that if you want to load your trained model and use it on inference mode with the previous function, you can create a `cnn_learner` from empty data. First export the relevant bits of your data object by typing: data.export() # And then you can load an empty data object that has the same internal state like this: empty_data = ImageDataBunch.load_empty(path) learn = create_cnn(empty_data, models.resnet18) learn = learn.load('one_epoch') # ### Customize your model # You can customize [`create_cnn`](/vision.learner.html#create_cnn) for your own model's default `cut` and `split_on` functions by adding them to the dictionary `model_meta`. The key should be your model and the value should be a dictionary with the keys `cut` and `split_on` (see the source code for examples). The constructor will call [`create_body`](/vision.learner.html#create_body) and [`create_head`](/vision.learner.html#create_head) for you based on `cut`; you can also call them yourself, which is particularly useful for testing. # + hide_input=true show_doc(create_body) # + hide_input=true show_doc(create_head, doc_string=False) # - # Model head that takes `nf` features, runs through `lin_ftrs`, and ends with `nc` classes. `ps` is the probability of the dropouts, as documented above in [`create_cnn`](/vision.learner.html#create_cnn). # + hide_input=true show_doc(ClassificationInterpretation, title_level=3) # - # This provides a confusion matrix and visualization of the most incorrect images. Pass in your [`data`](/vision.data.html#vision.data), calculated `preds`, actual `y`, and your `losses`, and then use the methods below to view the model interpretation results. For instance: learn = create_cnn(data, models.resnet18) learn.fit(1) preds,y,losses = learn.get_preds(with_loss=True) interp = ClassificationInterpretation(data, preds, y, losses) # The following factory method gives a more convenient way to create an instance of this class: # + hide_input=true show_doc(ClassificationInterpretation.from_learner) # - # You can also use a shortcut `learn.interpret()` to do the same. # + hide_input=true show_doc(Learner.interpret, full_name='interpret') # - # Note that this shortcut is a [`Learner`](/basic_train.html#Learner) object/class method that can be called as: `learn.interpret()`. # + hide_input=true show_doc(ClassificationInterpretation.plot_top_losses) # - # The `k` items are arranged as a square, so it will look best if `k` is a square number (4, 9, 16, etc). The title of each image shows: prediction, actual, loss, probability of actual class. # `plot_top_losses()` should be used with single-labeled datasets. See `plot_multi_top_losses()` below for a version capable of handling multi-labeled datasets. interp.plot_top_losses(9, figsize=(7,7)) # + hide_input=true show_doc(ClassificationInterpretation.top_losses) # - # Returns tuple of *(losses,indices)*. # + hide_input=true interp.top_losses(9) # - show_doc(ClassificationInterpretation.plot_multi_top_losses) # Similar to `plot_top_losses()` but aimed at multi-labeled datasets. It plots misclassified samples sorted by their respective loss. # Since you can have multiple labels for a single sample, they can easily overlap in a grid plot. So it plots just one sample per row. # Note that you can pass `save_misclassified=True` (by default it's `False`). In such case, the method will return a list containing the misclassified images which you can use to debug your model and/or tune its hyperparameters. # + hide_input=true show_doc(ClassificationInterpretation.plot_confusion_matrix) # - # If [`normalize`](/vision.data.html#normalize), plots the percentages with `norm_dec` digits. `slice_size` can be used to avoid out of memory error if your set is too big. `kwargs` are passed to `plt.figure`. interp.plot_confusion_matrix() # + hide_input=true show_doc(ClassificationInterpretation.confusion_matrix) # - interp.confusion_matrix() # + hide_input=true show_doc(ClassificationInterpretation.most_confused) # - # #### Working with large datasets # When working with large datasets, memory problems can arise when computing the confusion matrix. For example, an error can look like this: # # RuntimeError: $ Torch: not enough memory: you tried to allocate 64GB. Buy new RAM! # # In this case it is possible to force [`ClassificationInterpretation`](/train.html#ClassificationInterpretation) to compute the confusion matrix for data slices and then aggregate the result by specifying slice_size parameter. interp.confusion_matrix(slice_size=10) interp.plot_confusion_matrix(slice_size=10) interp.most_confused(slice_size=10) # ## Undocumented Methods - Methods moved below this line will intentionally be hidden # ## New Methods - Please document or move to the undocumented section
docs_src/vision.learner.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="LcrCNS6jc5-e" # # Shallow Neural Network in PyTorch # # In this notebook, we adapt our [TensorFlow Shallow Net](https://github.com/jonkrohn/DLTFpT/blob/master/notebooks/shallow_net_in_tensorflow.ipynb) to PyTorch. # + [markdown] colab_type="text" id="view-in-github" # <a href="https://colab.research.google.com/github/jonkrohn/DLTFpT/blob/master/notebooks/shallow_net_in_pytorch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] colab_type="text" id="mEygUgLVKJ7x" # #### Load dependencies # + colab={} colab_type="code" id="nfFVh41odSXB" import torch import torch.nn as nn from torchvision.datasets import MNIST from torchvision import transforms from torchsummary import summary import matplotlib.pyplot as plt # + [markdown] colab_type="text" id="6QCoX-S6dj54" # #### Load data # + colab={"base_uri": "https://localhost:8080/", "height": 259} colab_type="code" id="UXk2_Pazef4W" outputId="1482c5ea-0451-453a-b762-43a658f50d45" train = MNIST('data', train=True, transform=transforms.ToTensor(), download=True) test = MNIST('data', train=False, transform=transforms.ToTensor()) # ...toTensor() scales pixels from [0, 255] to [0, 1] # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="EdMVpcOHetgf" outputId="488de8ea-f066-438b-dafc-2748a6f28b8f" train.data.shape # + colab={"base_uri": "https://localhost:8080/", "height": 1002} colab_type="code" id="yZ8hKPF6exuw" outputId="210219ce-d5d8-4b06-9db4-bcbc1472f973" train.data[0] # not scaled! # + colab={"base_uri": "https://localhost:8080/", "height": 286} colab_type="code" id="vzITvYebe6NQ" outputId="6c3faad1-d5fd-4000-9337-2de757b1bef8" plt.imshow(train.data[0].numpy().squeeze(), cmap='gray_r') # + colab={"base_uri": "https://localhost:8080/", "height": 104} colab_type="code" id="kf4i8Q09fCpw" outputId="55a78ab8-7a11-47a0-e9a9-a59e2a4c803b" train.targets[0:100] # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="e6d0sd_8fQPH" outputId="3ecf50a1-8220-4ea7-9f59-d5efdf235bf7" train.targets.shape # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="0qST6tDffR9v" outputId="6f7fa323-d560-4e28-f753-1832658ed45b" test.data.shape # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="WyPpoB3dfiwo" outputId="15ac5f38-8716-4189-edd3-b8e13f84d4bd" test.targets.shape # + [markdown] colab_type="text" id="yYMXOGJvfkCo" # #### Batch data # + colab={} colab_type="code" id="8IySNK8Ef6Eq" train_loader = torch.utils.data.DataLoader(train, batch_size=128, shuffle=True) test_loader = torch.utils.data.DataLoader(test, batch_size=128) # ...DataLoader() can also sample and run multithreaded over a set number of workers # + colab={} colab_type="code" id="SLfWTrjshEsh" X_sample, y_sample = iter(train_loader).next() # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="5fc-M4JCiRTW" outputId="746dc866-ee0a-422d-98b9-a8045558070a" X_sample.shape # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="2TCZnZR-iWvo" outputId="396a086b-2155-476b-8b18-6c903dda106f" y_sample.shape # + colab={"base_uri": "https://localhost:8080/", "height": 121} colab_type="code" id="8uk1_iPDiXR7" outputId="a820ebe3-cc65-40db-9974-0d755eadb103" y_sample # + colab={"base_uri": "https://localhost:8080/", "height": 1952} colab_type="code" id="Sf4z56RKi1ja" outputId="a6ea24fe-4730-4ab5-9abf-36e99d12b1d1" X_sample[0] # + colab={} colab_type="code" id="zlj29yCske1c" X_flat_sample = X_sample.view(X_sample.shape[0], -1) # view() reshapes Tensor (confusingly) # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="8VtnEEvLi4UD" outputId="bf534ee2-d23d-4c01-8060-09ec72222cb0" X_flat_sample.shape # + colab={"base_uri": "https://localhost:8080/", "height": 1537} colab_type="code" id="Koet4ZSgkSHu" outputId="8334d8fb-0538-4e7e-d534-9d3829d995c1" X_flat_sample[0] # + [markdown] colab_type="text" id="s-lTFFhdkogC" # #### Design neural network architecture # + colab={} colab_type="code" id="mkwmSP10k8Y7" n_input = 784 n_dense = 64 n_out = 10 # + colab={} colab_type="code" id="XLAYTQcrk208" model = nn.Sequential( nn.Linear(n_input, n_dense), # hidden layer nn.Sigmoid(), # activation function nn.Linear(n_dense, n_out) # output layer ) # + colab={"base_uri": "https://localhost:8080/", "height": 294} colab_type="code" id="ELhOOEzcmMjN" outputId="0bedac30-6b93-493f-c1a7-50f6c528a772" summary(model, (1, n_input)) # + [markdown] colab_type="text" id="ad12qUaumQNF" # #### Configure training hyperparameters # + colab={} colab_type="code" id="MApHSXQGmfdE" cost_fxn = nn.CrossEntropyLoss() # includes softmax activation # + colab={} colab_type="code" id="K0c1Iqnpm32m" optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # + [markdown] colab_type="text" id="V3836ImZnQ6_" # #### Train # + colab={} colab_type="code" id="p9iTkEv6nVHB" def accuracy_pct(pred_y, true_y): _, prediction = torch.max(pred_y, 1) # returns maximum values, indices; fed tensor, dim to reduce correct = (prediction == true_y).sum().item() return (correct / true_y.shape[0]) * 100.0 # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="qkd4YuS4xBaF" outputId="9c633acb-b2f4-4384-f3cc-81a4884538ae" n_batches = len(train_loader) n_batches # + colab={"base_uri": "https://localhost:8080/", "height": 2142} colab_type="code" id="ka2rxjOcnY_1" outputId="54b4f4fb-62dc-4079-e734-2752ba245c8b" n_epochs = 20 print('Training for {} epochs. \n'.format(n_epochs)) for epoch in range(n_epochs): avg_cost = 0.0 avg_accuracy = 0.0 for i, (X, y) in enumerate(train_loader): # enumerate() provides count of iterations # forward propagation: X_flat = X.view(X.shape[0], -1) y_hat = model(X_flat) cost = cost_fxn(y_hat, y) avg_cost += cost / n_batches # backprop and optimization via gradient descent: optimizer.zero_grad() # set gradients to zero; .backward() accumulates them in buffers cost.backward() optimizer.step() # calculate accuracy metric: accuracy = accuracy_pct(y_hat, y) avg_accuracy += accuracy / n_batches if (i + 1) % 100 == 0: print('Step {}'.format(i + 1)) print('Epoch {}/{} complete: Cost: {:.3f}, Accuracy: {:.1f}% \n' .format(epoch + 1, n_epochs, avg_cost, avg_accuracy)) print('Training complete.') # + [markdown] colab_type="text" id="xmUI1Z7jj0XO" # #### Test model # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="r1-3E_YfkIL7" outputId="ff109e64-d8da-4bcf-a8b9-d6d1b1088b80" n_test_batches = len(test_loader) n_test_batches # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="DPU-rP_7jtk_" outputId="d9c513ed-4de9-4196-<PASSWORD>-8<PASSWORD>" model.eval() # disables dropout (and batch norm) with torch.no_grad(): # disables autograd, reducing memory consumption avg_test_cost = 0.0 avg_test_acc = 0.0 for X, y in test_loader: # make predictions: X_flat = X.view(X.shape[0], -1) y_hat = model(X_flat) # calculate cost: cost = cost_fxn(y_hat, y) avg_test_cost += cost / n_test_batches # calculate accuracy: test_accuracy = accuracy_pct(y_hat, y) avg_test_acc += test_accuracy / n_test_batches print('Test cost: {:.3f}, Test accuracy: {:.1f}%'.format(avg_test_cost, avg_test_acc)) # model.train() # 'undoes' model.eval() # -
notebooks/DLTFpT-notebooks/shallow_net_in_pytorch.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd # ### Use Habbyfun as a example to check what is not in adtimizer due to they don't have any of vungle ads-txt, so Adtimizer will print out all of the missing txt that what do they have. # #### http://api.adtimizer.co/vungle/check?domain=habby.fun&vungleId=5af96cda0bf9c14aa04bb8a8 stocks = pd.read_csv('habby.csv') if '1017355401' not in list(stocks['id']): print('acexchange.co.kr,1017355401,RESELLER') if '1081983882' not in list(stocks['id']): print('acexchange.co.kr,1081983882,RESELLER') if '1618149085' not in list(stocks['id']): print('acexchange.co.kr,1618149085,RESELLER') if '197af3936679d34e' not in list(stocks['id']): print('adcolony.com,197af3936679d34e,RESELLER,1ad675c9de6b5176') if '1efc6603710003ea' not in list(stocks['id']): print('adcolony.com, 1efc6603710003ea, RESELLER, 1ad675c9de6b5176') if '1efc6603710003ea' not in list(stocks['id']): print('adcolony.com,1efc6603710003ea,RESELLER,1ad675c9de6b5176') if '382d79cd1387e603' not in list(stocks['id']): print('adcolony.com, 382d79cd1387e603, RESELLER, 1ad675c9de6b5176') if '382d79cd1387e603' not in list(stocks['id']): print('adcolony.com,382d79cd1387e603,RESELLER,1ad675c9de6b5176') if '7d04a18a58085918' not in list(stocks['id']): print('adcolony.com, 7d04a18a58085918, RESELLER, 1ad675c9de6b5176') if '801e49d1be83b5f9' not in list(stocks['id']): print('adcolony.com, 801e49d1be83b5f9, RESELLER, 1ad675c9de6b5176') if '801e49d1be83b5f9' not in list(stocks['id']): print('adcolony.com, 801e49d1be83b5f9, RESELLER, 1ad675c9de6b5176') if '81685aa581edd381' not in list(stocks['id']): print('adcolony.com, 81685aa581edd381, RESELLER, 1ad675c9de6b5176') if 'c490f6e7399a25d6' not in list(stocks['id']): print('adcolony.com,c490f6e7399a25d6,RESELLER,1ad675c9de6b5176') if 'e8d70ef9dfabde92' not in list(stocks['id']): print('adcolony.com,e8d70ef9dfabde92,RESELLER,1ad675c9de6b5176') if 'f858ba060bce51ad' not in list(stocks['id']): print('adcolony.com, f858ba060bce51ad, RESELLER, 1ad675c9de6b5176') if '43' not in list(stocks['id']): print('admanmedia.com,43,RESELLER') if '48' not in list(stocks['id']): print('admanmedia.com, 48, RESELLER') if '48' not in list(stocks['id']): print('admanmedia.com,48,RESELLER') if '594' not in list(stocks['id']): print('admanmedia.com, 594, RESELLER') if '594' not in list(stocks['id']): print('admanmedia.com,594,RESELLER') if '1185' not in list(stocks['id']): print('admixer.co.kr,1185,RESELLER') if '1287' not in list(stocks['id']): print('admixer.co.kr, 1287, RESELLER') if '1287' not in list(stocks['id']): print('admixer.co.kr,1287,RESELLER') if '8676470' not in list(stocks['id']): print('admixer.com, 8676470, RESELLER') if '0072fb58-999b-445e-9a9b-3fc2a7194277' not in list(stocks['id']): print('admixer.net, 0072fb58-999b-445e-9a9b-3fc2a7194277, RESELLER') if '2878f07c-cc3f-4f8a-a26c-8e6033a539a6' not in list(stocks['id']): print('admixer.net, 2878f07c-cc3f-4f8a-a26c-8e6033a539a6, RESELLER') if '3d2ed9f3-1ce6-436c-896b-4d9c8418ad3f' not in list(stocks['id']): print('admixer.net, 3d2ed9f3-1ce6-436c-896b-4d9c8418ad3f, RESELLER') if '8e380da6-31ba-488c-939c-290c48d577e4' not in list(stocks['id']): print('admixer.net, 8e380da6-31ba-488c-939c-290c48d577e4, RESELLER') if 'de2ae535-59eb-4f0b-95e3-89f821933d47' not in list(stocks['id']): print('admixer.net, de2ae535-59eb-4f0b-95e3-89f821933d47, RESELLER') if 'de2ae535-59eb-4f0b-95e3-89f821933d47' not in list(stocks['id']): print('admixer.net,de2ae535-59eb-4f0b-95e3-89f821933d47,RESELLER') if 'a-126' not in list(stocks['id']): print('adtiming.com, a-126, RESELLER, bf66753b8f380142') if '25990' not in list(stocks['id']): print('advertising.com, 25990, RESELLER') if '28246' not in list(stocks['id']): print('advertising.com, 28246, RESELLER') if '28246' not in list(stocks['id']): print('advertising.com,28246,RESELLER') if '6814' not in list(stocks['id']): print('advertising.com, 6814, RESELLER') if '32076181' not in list(stocks['id']): print('adview.com, 32076181, RESELLER, 1b2cc038a11ea319') if '32076181' not in list(stocks['id']): print('adview.com,32076181,RESELLER,1b2cc038a11ea319') if '8676470' not in list(stocks['id']): print('adwmg.com, 8676470, RESELLER') if 'b4bf4fdd9b0b915f746f6747ff432bde' not in list(stocks['id']): print('adyoulike.com,b4bf4fdd9b0b915f746f6747ff432bde,RESELLER,4ad745ead2958bf7') if '54250' not in list(stocks['id']): print('algorix.co, 54250, RESELLER') if '57992' not in list(stocks['id']): print('aol.com,57992,RESELLER,e1a5b5b6e3255540') if '58905' not in list(stocks['id']): print('aol.com,58905,RESELLER,e1a5b5b6e3255540') if '59025' not in list(stocks['id']): print('aol.com, 59025, RESELLER, e1a5b5b6e3255540') if '107606' not in list(stocks['id']): print('appads.in, 107606, RESELLER') if '10005' not in list(stocks['id']): print('appnexus.com, 10005, RESELLER, f5ab79cb980f11d1') if '10128' not in list(stocks['id']): print('appnexus.com, 10128, RESELLER, f5<PASSWORD>cb<PASSWORD>') if '10824' not in list(stocks['id']): print('appnexus.com, 10824, RESELLER,f5ab79cb980f11d1') if '11452' not in list(stocks['id']): print('appnexus.com, 11452, RESELLER') if '12223' not in list(stocks['id']): print('appnexus.com, 12223, RESELLER, f5ab79cb980f11d1') if '13099' not in list(stocks['id']): print('appnexus.com,13099,RESELLER,f5ab79cb980f11d1') if '3368' not in list(stocks['id']): print('appnexus.com, 3368, RESELLER') if '3703' not in list(stocks['id']): print('appnexus.com, 3703, RESELLER, f5ab79cb980f11d1') if '3703' not in list(stocks['id']): print('appnexus.com,3703,RESELLER,f5ab79cb980f11d1') if '4052' not in list(stocks['id']): print('appnexus.com, 4052, RESELLER,f5ab79cb980f11d1') if '4052' not in list(stocks['id']): print('appnexus.com,4052,RESELLER,f5ab79cb980f11d1') if '8178' not in list(stocks['id']): print('appnexus.com, 8178, RESELLER, f5ab79cb980f11d1') if '8217' not in list(stocks['id']): print('appnexus.com, 8217, RESELLER, f5ab79cb980f11d1') if '9569' not in list(stocks['id']): print('appnexus.com, 9569, RESELLER,f5ab79cb980f11d1') if '9569' not in list(stocks['id']): print('appnexus.com,9569,RESELLER,f5ab79cb980f11d1') if 'par-2736764b3a38eb77fdeaeb7444ab844' not in list(stocks['id']): print('aralego.com,par-2736764B3A38EB77FDEAEB7444AB844,RESELLER') if 'par-8a2a4a443b29bb92f9622d3a67346ab' not in list(stocks['id']): print('aralego.com, par-8A2A4A443B29BB92F9622D3A67346AB, RESELLER') if 'par-be776b39322a364bc7767a69ab99bbd9' not in list(stocks['id']): print('aralego.com, par-BE776B39322A364BC7767A69AB99BBD9, RESELLER') if 'par-d232d76a227923da1d28d94aa9699ae8' not in list(stocks['id']): print('aralego.com, par-D232D76A227923DA1D28D94AA9699AE8, RESELLER') if 'par-d233672dd744287dcd7e2439b82494ad' not in list(stocks['id']): print('aralego.com, par-D233672DD744287DCD7E2439B82494AD, RESELLER') if 'pub-77229e766e887de6fb9ed63a78d6a629' not in list(stocks['id']): print('aralego.com,pub-77229E766E887DE6FB9ED63A78D6A629,RESELLER') if '56222' not in list(stocks['id']): print('axonix.com,56222,RESELLER') if '56222' not in list(stocks['id']): print('axonix.com,56222,RESELLER') if '57264' not in list(stocks['id']): print('axonix.com,57264,RESELLER') if '57716' not in list(stocks['id']): print('axonix.com,57716,RESELLER') if '57869' not in list(stocks['id']): print('axonix.com, 57869, RESELLER') if '805' not in list(stocks['id']): print('beachfront.com, 805, RESELLER, e2541279e8e2ca4d') if '43092' not in list(stocks['id']): print('betweendigital.com, 43092, RESELLER') if '43092' not in list(stocks['id']): print('betweendigital.com,43092,RESELLER') if '43843' not in list(stocks['id']): print('betweendigital.com,43843,RESELLER') if '3de04db04d6eb28b13281a39b1c16d67' not in list(stocks['id']): print('bidence.com,3de04db04d6eb28b13281a39b1c16d67,RESELLER') if '55' not in list(stocks['id']): print('bidmachine.io, 55, RESELLER') if '59' not in list(stocks['id']): print('bidmachine.io, 59, RESELLER') if '33' not in list(stocks['id']): print('blis.com,33,RESELLER,61453ae19a4b73f4') if '5eac93f341016b09ff0019b6' not in list(stocks['id']): print('chartboost.com, 5eac93f341016b09ff0019b6, RESELLER') if '105' not in list(stocks['id']): print('cmcm.com,105, RESELLER') if '127' not in list(stocks['id']): print('cmcm.com, 127, RESELLER') if '135' not in list(stocks['id']): print('cmcm.com, 135, RESELLER') if '271' not in list(stocks['id']): print('cmcm.com, 271, RESELLER') if '560288' not in list(stocks['id']): print('contextweb.com,560288,RESELLER,89ff185a4c4e857c') if '561849' not in list(stocks['id']): print('contextweb.com, 561849, RESELLER, 89ff185a4c4e857c') if '561884' not in list(stocks['id']): print('contextweb.com, 561884, RESELLER, 89ff185a4c4e857c') if '561913' not in list(stocks['id']): print('contextweb.com, 561913, RESELLER, 89ff185a4c4e857c') if '561998' not in list(stocks['id']): print('contextweb.com,561998,RESELLER,89ff185a4c4e857c') if '562122' not in list(stocks['id']): print('contextweb.com, 562122, RESELLER, 89ff185a4c4e857c') if '562122' not in list(stocks['id']): print('contextweb.com,562122,RESELLER,89ff185a4c4e857c') if '100081' not in list(stocks['id']): print('conversantmedia.com, 100081, RESELLER, 03113cd04947736d') if '100081' not in list(stocks['id']): print('conversantmedia.com,100081,RESELLER,03113cd04947736d') if '100246' not in list(stocks['id']): print('conversantmedia.com,100246,RESELLER,03113cd04947736d') if '100293' not in list(stocks['id']): print('conversantmedia.com, 100293, RESELLER, 03113cd04947736d') if '40881' not in list(stocks['id']): print('conversantmedia.com,40881,RESELLER,03113cd04947736d') if '186227' not in list(stocks['id']): print('criteo.com, 186227, RESELLER') if '14' not in list(stocks['id']): print('decenterads.com, 14, RESELLER') if '14' not in list(stocks['id']): print('decenterads.com,14,RESELLER') if '198' not in list(stocks['id']): print('decenterads.com,198,RESELLER') if '92' not in list(stocks['id']): print('decenterads.com, 92, RESELLER') if '101649' not in list(stocks['id']): print('districtm.io,101649,RESELLER,3fd707be9c4527c3') if '2af6560b926d20f9' not in list(stocks['id']): print('e-planning.net,2af6560b926d20f9,RESELLER,c1ba615865ed87b2') if 'a15ce31379a418ac' not in list(stocks['id']): print('e-planning.net,a15ce31379a418ac,RESELLER,c1ba615865ed87b2') if '1324' not in list(stocks['id']): print('EMXDGT.com, 1324, RESELLER, 1e1d41537f7cad7f') if '10181' not in list(stocks['id']): print('engagebdr.com, 10181, RESELLER') if '10252' not in list(stocks['id']): print('engagebdr.com, 10252, RESELLER') if '16' not in list(stocks['id']): print('engagebdr.com, 16, RESELLER') if '7' not in list(stocks['id']): print('engagebdr.com, 7, RESELLER') if '84' not in list(stocks['id']): print('engagebdr.com, 84, RESELLER') if '6' not in list(stocks['id']): print('flat-ads.com, 6, RESELLER') if '1058753' not in list(stocks['id']): print('freewheel.tv, 1058753, RESELLER') if '1058769' not in list(stocks['id']): print('freewheel.tv, 1058769, RESELLER') if '1161393' not in list(stocks['id']): print('freewheel.tv, 1161393, RESELLER') if '1162449' not in list(stocks['id']): print('freewheel.tv, 1162449, RESELLER') if '1173729' not in list(stocks['id']): print('freewheel.tv, 1173729, RESELLER') if '1173793' not in list(stocks['id']): print('freewheel.tv, 1173793, RESELLER') if '1192767' not in list(stocks['id']): print('freewheel.tv, 1192767, RESELLER') if '1192799' not in list(stocks['id']): print('freewheel.tv, 1192799, RESELLER') if '20393' not in list(stocks['id']): print('freewheel.tv,20393,RESELLER') if '24377' not in list(stocks['id']): print('freewheel.tv,24377,RESELLER') if '1521707344' not in list(stocks['id']): print('gammassp.com, 1521707344, RESELLER, 31ac53fec2772a83') if 'xlv' not in list(stocks['id']): print('gitberry.com, XLV, RESELLER') if 'pub-3769010358500643' not in list(stocks['id']): print('google.com,pub-3769010358500643,RESELLER,f08c47fec0942fa0') if 'pub-4568609371004228' not in list(stocks['id']): print('google.com,pub-4568609371004228,RESELLER,f08c47fec0942fa0') if 'pub-7214269347534569' not in list(stocks['id']): print('google.com, pub-7214269347534569, RESELLER, f08c47fec0942fa0') if 'pub-9685734445476814' not in list(stocks['id']): print('google.com, pub-9685734445476814, RESELLER, f08c47fec0942fa0') if '1339' not in list(stocks['id']): print('gothamads.com, 1339, RESELLER, d9c86e5dec870222') if '107' not in list(stocks['id']): print('groundtruth.com, 107, RESELLER, 81cbf0a75a5e0e9a') if '107' not in list(stocks['id']): print('groundtruth.com,107,RESELLER,81cbf0a75a5e0e9a') if '13706' not in list(stocks['id']): print('gumgum.com,13706,RESELLER,ffdef49475d318a9') if '8613985ec49eb8f757ae6439e879bb2a6784' not in list(stocks['id']): print('hitapps.com, 8613985ec49eb8f757ae6439e879bb2a6784, RESELLER') if '1210' not in list(stocks['id']): print('improvedigital.com, 1210, RESELLER') if '1221' not in list(stocks['id']): print('improvedigital.com, 1221, RESELLER') if '1331' not in list(stocks['id']): print('improvedigital.com, 1331, RESELLER') if '1331' not in list(stocks['id']): print('improvedigital.com,1331,RESELLER') if '1366' not in list(stocks['id']): print('improvedigital.com, 1366, RESELLER') if '1532' not in list(stocks['id']): print('improvedigital.com, 1532, RESELLER') if '1532' not in list(stocks['id']): print('improvedigital.com,1532,RESELLER') if '1556' not in list(stocks['id']): print('improvedigital.com,1556,RESELLER') if '184738' not in list(stocks['id']): print('indexexchange.com,184738,RESELLER,50b1c356f2c5c8fc') if '185578' not in list(stocks['id']): print('indexexchange.com, 185578, RESELLER, 50b1c356f2c5c8fc') if '185774' not in list(stocks['id']): print('indexexchange.com, 185774, RESELLER, 50b1c356f2c5c8fc') if '191332' not in list(stocks['id']): print('indexexchange.com, 191332, RESELLER, 50b1c356f2c5c8fc') if '191332' not in list(stocks['id']): print('indexexchange.com,191332,RESELLER,50b1c356f2c5c8fc') if '194730' not in list(stocks['id']): print('indexexchange.com,194730,RESELLER,50b1c356f2c5c8fc') if '22e5354e453f49348325184e25464adb' not in list(stocks['id']): print('inmobi.com, 22e5354e453f49348325184e25464adb, RESELLER, 83e75a7ae333ca9d') if '5baa7ca93ef847c0876297e737dac3ee' not in list(stocks['id']): print('inmobi.com, 5baa7ca93ef847c0876297e737dac3ee, RESELLER, 83e75a7ae333ca9d') if '61d733c3779d43e590c51c8bc078e10c' not in list(stocks['id']): print('inmobi.com,61d733c3779d43e590c51c8bc078e10c,RESELLER,83e75a7ae333ca9d') if '867c89bb53994aaeb9dae3ce75b03e78' not in list(stocks['id']): print('inmobi.com, 867c89bb53994aaeb9dae3ce75b03e78, RESELLER, 83e75a7ae333ca9d') if '867c89bb53994aaeb9dae3ce75b03e78' not in list(stocks['id']): print('inmobi.com,867c89bb53994aaeb9dae3ce75b03e78,RESELLER,83e75a7ae333ca9d') if 'ab915bcef5b24940bf745f1a8f427bec' not in list(stocks['id']): print('inmobi.com,ab915bcef5b24940bf745f1a8f427bec,RESELLER,83e75a7ae333ca9d') if 'c1e6d3502da64ebaa3ad0e4a4be15f11' not in list(stocks['id']): print('inmobi.com, c1e6d3502da64ebaa3ad0e4a4be15f11, RESELLER, 83e75a7ae333ca9d') if 'ec6f6ceb8bb1440ba5455644ec96c275' not in list(stocks['id']): print('inmobi.com,ec6f6ceb8bb1440ba5455644ec96c275,RESELLER,83e75a7ae333ca9d') if 'f3924290136e4129a5c082ff982c3a58' not in list(stocks['id']): print('inmobi.com, f3924290136e4129a5c082ff982c3a58, RESELLER, 83e75a7ae333ca9d') if '5eb2cb089c866' not in list(stocks['id']): print('kubient.com, 5eb2cb089c866, RESELLER, 4f12311e6ed900a3') if '273644' not in list(stocks['id']): print('lijit.com, 273644, RESELLER') if '203581' not in list(stocks['id']): print('Limpid.tv,203581,RESELLER') if '459' not in list(stocks['id']): print('lkqd.net, 459, RESELLER, 59c49fa9598a0117') if '647' not in list(stocks['id']): print('lkqd.net,647,RESELLER,59c49fa9598a0117') if '654' not in list(stocks['id']): print('lkqd.net,654,RESELLER,59c49fa9598a0117') if '10178' not in list(stocks['id']): print('loopme.com, 10178, RESELLER, 6c8d5f95897a5a3b') if '10178' not in list(stocks['id']): print('loopme.com,10178,RESELLER,6c8d5f95897a5a3b') if '10999' not in list(stocks['id']): print('loopme.com, 10999, RESELLER, 6c8d5f95897a5a3b') if '11189' not in list(stocks['id']): print('loopme.com, 11189, RESELLER, 6c8d5f95897a5a3b') if '11278' not in list(stocks['id']): print('loopme.com, 11278, RESELLER') if '11281' not in list(stocks['id']): print('loopme.com, 11281, RESELLER, 6c8d5f95897a5a3b') if '11296' not in list(stocks['id']): print('loopme.com, 11296, RESELLER, 6c8d5f95897a5a3b') if '11322' not in list(stocks['id']): print('loopme.com,11322,RESELLER,6c8d5f95897a5a3b') if '5679' not in list(stocks['id']): print('loopme.com,5679,RESELLER,6c8d5f95897a5a3b') if '9724' not in list(stocks['id']): print('loopme.com,9724,RESELLER,6c8d5f95897a5a3b') if 's-2411' not in list(stocks['id']): print('loopme.com, s-2411, RESELLER, 6c8d5f95897a5a3b') if '1010422' not in list(stocks['id']): print('mars.media, 1010422, RESELLER, 8624339f102fb076') if '102753' not in list(stocks['id']): print('mars.media, 102753, RESELLER') if '102753' not in list(stocks['id']): print('mars.media,102753,RESELLER') if '149' not in list(stocks['id']): print('meitu.com, 149, RESELLER') if '179' not in list(stocks['id']): print('meitu.com, 179, RESELLER') if '253' not in list(stocks['id']): print('meitu.com, 253, RESELLER') if '82593' not in list(stocks['id']): print('mobfox.com, 82593, RESELLER, 5529a3d1f59865be') if '149' not in list(stocks['id']): print('mobirtb.com, 149, RESELLER') if '100023' not in list(stocks['id']): print('olaex.biz,100023,RESELLER') if '59aa7be4921bac8' not in list(stocks['id']): print('onetag.com, 59aa7be4921bac8, RESELLER') if '59aa7be4921bac8' not in list(stocks['id']): print('onetag.com,59aa7be4921bac8,RESELLER') if '59d216e971852f2' not in list(stocks['id']): print('onetag.com, 59d216e971852f2, RESELLER') if '5a02ff98ba6be67' not in list(stocks['id']): print('onetag.com, 5a02ff98ba6be67, RESELLER') if '5d1628750185ace' not in list(stocks['id']): print('onetag.com, 5d1628750185ace, RESELLER') if '66cff8e37d871be' not in list(stocks['id']): print('onetag.com, 66cff8e37d871be, RESELLER') if '74ea58ae86fd4b0' not in list(stocks['id']): print('onetag.com,74ea58ae86fd4b0,RESELLER') if '537149888' not in list(stocks['id']): print('openx.com,537149888,RESELLER,6a698e2ec38604c6') if '537152826' not in list(stocks['id']): print('openx.com, 537152826, RESELLER, 6a698e2ec38604c6') if '539315083' not in list(stocks['id']): print('openx.com, 539315083, RESELLER, 6a698e2ec38604c6') if '539472296' not in list(stocks['id']): print('openx.com, 539472296, RESELLER, 6a698e2ec38604c6') if '540011801' not in list(stocks['id']): print('openx.com, 540011801, RESELLER, 6a698e2ec38604c6') if '540031703' not in list(stocks['id']): print('openx.com,540031703,RESELLER,6a698e2ec38604c6') if '540280728' not in list(stocks['id']): print('openx.com, 540280728, RESELLER, 6a698e2ec38604c6') if '540298543' not in list(stocks['id']): print('openx.com, 540298543, RESELLER, 6a698e2ec38604c6') if '540298543' not in list(stocks['id']): print('openx.com,540298543,RESELLER,6a698e2ec38604c6') if '540326226' not in list(stocks['id']): print('openx.com, 540326226, RESELLER, 6a698e2ec38604c6') if '540326226' not in list(stocks['id']): print('openx.com,540326226,RESELLER,6a698e2ec38604c6') if '540543195' not in list(stocks['id']): print('openx.com, 540543195, RESELLER, 6a698e2ec38604c6') if '540679900' not in list(stocks['id']): print('openx.com, 540679900, RESELLER, 6a698e2ec38604c6') if '540679900' not in list(stocks['id']): print('openx.com, 540679900, RESELLER, 6a698e2ec38604c6') if '541031350' not in list(stocks['id']): print('openx.com,541031350,RESELLER,6a698e2ec38604c6') if '541177349' not in list(stocks['id']): print('openx.com, 541177349, RESELLER') if '5610' not in list(stocks['id']): print('pokkt.com, 5610 , RESELLER, c45702d9311e25fd') if '7000' not in list(stocks['id']): print('pokkt.com, 7000, RESELLER, c45702d9311e25fd') if '7606' not in list(stocks['id']): print('pokkt.com, 7606, RESELLER, c45702d9311e25fd') if '7606' not in list(stocks['id']): print('pokkt.com,7606,RESELLER,c45702d9311e25fd') if '155975' not in list(stocks['id']): print('pubmatic.com, 155975, RESELLER, 5d62403b186f2ace') if '156439' not in list(stocks['id']): print('pubmatic.com,156439,RESELLER,5d62403b186f2ace') if '156517' not in list(stocks['id']): print('pubmatic.com, 156517, RESELLER, 5d62403b186f2ace') if '156520' not in list(stocks['id']): print('pubmatic.com, 156520, RESELLER, 5d62403b186f2ace') if '156631' not in list(stocks['id']): print('pubmatic.com,156631,RESELLER,5d62403b186f2ace') if '156835' not in list(stocks['id']): print('pubmatic.com, 156835, RESELLER, 5d62403b186f2ace') if '156835' not in list(stocks['id']): print('pubmatic.com,156835,RESELLER,5d62403b186f2ace') if '156931' not in list(stocks['id']): print('pubmatic.com,156931,RESELLER,5d62403b186f2ace') if '157097' not in list(stocks['id']): print('pubmatic.com,157097,RESELLER,5d62403b186f2ace') if '157654' not in list(stocks['id']): print('pubmatic.com, 157654, RESELLER, 5d62403b186f2ace') if '158060' not in list(stocks['id']): print('pubmatic.com, 158060, RESELLER, 5d62403b186f2ace') if '158100' not in list(stocks['id']): print('pubmatic.com,158100,RESELLER,5d62403b186f2ace') if '158154' not in list(stocks['id']): print('pubmatic.com, 158154, RESELLER, 5d62403b186f2ace') if '158154' not in list(stocks['id']): print('pubmatic.com,158154,RESELLER,5d62403b186f2ace') if '158271' not in list(stocks['id']): print('pubmatic.com, 158271, RESELLER, 5d62403b186f2ace') if '159035' not in list(stocks['id']): print('pubmatic.com,159035,RESELLER,5d62403b186f2ace') if '159542' not in list(stocks['id']): print('pubmatic.com, 159542, RESELLER') if '159668' not in list(stocks['id']): print('pubmatic.com, 159668, RESELLER') if '159831' not in list(stocks['id']): print('pubmatic.com, 159831, RESELLER, 5d62403b186f2ace') if '159846' not in list(stocks['id']): print('pubmatic.com, 159846, RESELLER, 5d62403b186f2ace') if '159897' not in list(stocks['id']): print('pubmatic.com, 159897, RESELLER, 5d62403b186f2ace') if '160145' not in list(stocks['id']): print('pubmatic.com,160145,RESELLER,5d62403b186f2ace') if '160194' not in list(stocks['id']): print('pubmatic.com, 160194, RESELLER, 5d62403b186f2ace') if '160195' not in list(stocks['id']): print('pubmatic.com, 160195, RESELLER, 5d62403b186f2ace') if '8676470' not in list(stocks['id']): print('pubmatic.com, 8676470, RESELLER') if '92509' not in list(stocks['id']): print('pubmatic.com,92509,RESELLER,5d62403b186f2ace') if '1006458' not in list(stocks['id']): print('pubnative.net, 1006458, RESELLER, d641df8625486a7b') if '1006576' not in list(stocks['id']): print('pubnative.net,1006576,RESELLER,d641df8625486a7b') if '1006936' not in list(stocks['id']): print('Pubnative.net, 1006936, RESELLER, d641df8625486a7b') if '1006936' not in list(stocks['id']): print('pubnative.net,1006936,RESELLER,d641df8625486a7b') if '1006951' not in list(stocks['id']): print('pubnative.net,1006951,RESELLER,d641df8625486a7b') if '1007302' not in list(stocks['id']): print('pubnative.net, 1007302, RESELLER, d641df8625486a7b') if '32076181' not in list(stocks['id']): print('pubwheel.com, 32076181, RESELLER, 1b2cc038a11ea319') if '353' not in list(stocks['id']): print('reforge.in, 353, RESELLER') if '188404962' not in list(stocks['id']): print('rhythmone.com,188404962,RESELLER,a670c89d4a324e47') if '2564526802' not in list(stocks['id']): print('rhythmone.com,2564526802,RESELLER,a670c89d4a324e47') if '3218195319' not in list(stocks['id']): print('rhythmone.com, 3218195319, RESELLER, a670c89d4a324e47') if '3218195319' not in list(stocks['id']): print('rhythmone.com,3218195319,RESELLER,a670c89d4a324e47') if '3880497124' not in list(stocks['id']): print('rhythmone.com, 3880497124, RESELLER') if '4173858586' not in list(stocks['id']): print('rhythmone.com, 4173858586, RESELLER, a670c89d4a324e47') if '4173858586' not in list(stocks['id']): print('rhythmone.com,4173858586,RESELLER,a670c89d4a324e47') if '4268206200' not in list(stocks['id']): print('rhythmone.com, 4268206200, RESELLER, a670c89d4a324e47') if '11726' not in list(stocks['id']): print('rubiconproject.com, 11726, RESELLER, 0bfd66d529a55807') if '11726' not in list(stocks['id']): print('rubiconproject.com,11726,RESELLER,0bfd66d529a55807') if '12186' not in list(stocks['id']): print('rubiconproject.com,12186,RESELLER,0bfd66d529a55807') if '12266' not in list(stocks['id']): print('rubiconproject.com, 12266, RESELLER, 0bfd66d529a55807') if '12266' not in list(stocks['id']): print('rubiconproject.com,12266,RESELLER,0bfd66d529a55807') if '13626' not in list(stocks['id']): print('rubiconproject.com, 13626, RESELLER, 0bfd66d529a55807') if '13856' not in list(stocks['id']): print('rubiconproject.com, 13856, RESELLER, 0bfd66d529a55807') if '13856' not in list(stocks['id']): print('rubiconproject.com,13856,RESELLER,0bfd66d529a55807') if '15278' not in list(stocks['id']): print('rubiconproject.com, 15278, RESELLER, 0bfd66d529a55807') if '16114' not in list(stocks['id']): print('rubiconproject.com, 16114, RESELLER, 0bfd66d529a55807') if '16114' not in list(stocks['id']): print('rubiconproject.com,16114,RESELLER,0bfd66d529a55807') if '16834' not in list(stocks['id']): print('rubiconproject.com, 16834, RESELLER, 0bfd66d529a55807') if '17328' not in list(stocks['id']): print('rubiconproject.com, 17328, RESELLER, 0bfd66d529a55807') if '17328' not in list(stocks['id']): print('rubiconproject.com,17328,RESELLER,0bfd66d529a55807') if '19724' not in list(stocks['id']): print('rubiconproject.com, 19724, RESELLER') if '19724' not in list(stocks['id']): print('rubiconproject.com,19724,RESELLER,0bfd66d529a55807') if '20744' not in list(stocks['id']): print('rubiconproject.com, 20744, RESELLER, 0bfd66d529a55807') if '20744' not in list(stocks['id']): print('rubiconproject.com,20744,RESELLER,0bfd66d529a55807') if '23644' not in list(stocks['id']): print('rubiconproject.com,23644,RESELLER,0bfd66d529a55807') if '23732' not in list(stocks['id']): print('rubiconproject.com,23732,RESELLER,0bfd66d529a55807') if '100032' not in list(stocks['id']): print('sabio.us, 100032, RESELLER, 96ed93aaa9795702') if '320' not in list(stocks['id']): print('silvermob.com,320,RESELLER') if '1100042823' not in list(stocks['id']): print('smaato.com, 1100042823, RESELLER, 07bcf65f187117b4') if '1100044045' not in list(stocks['id']): print('smaato.com,1100044045,RESELLER,07bcf65f187117b4') if '1100049757' not in list(stocks['id']): print('smaato.com,1100049757,RESELLER,07bcf65f187117b4') if '1692' not in list(stocks['id']): print('smartadserver.com, 1692, RESELLER') if '1692' not in list(stocks['id']): print('smartadserver.com,1692,RESELLER') if '3232' not in list(stocks['id']): print('smartadserver.com,3232,RESELLER') if '3797' not in list(stocks['id']): print('smartadserver.com, 3797, RESELLER') if '3797' not in list(stocks['id']): print('smartadserver.com,3797,RESELLER') if '4071' not in list(stocks['id']): print('smartadserver.com,4071,RESELLER') if '4111' not in list(stocks['id']): print('smartadserver.com,4111,RESELLER') if '368' not in list(stocks['id']): print('smartyads.com, 368, RESELLER') if 'cc3858f35e' not in list(stocks['id']): print('sonobi.com,cc3858f35e,RESELLER,d1a215d9eb5aee9e') if 'eaec54c63f' not in list(stocks['id']): print('sonobi.com, eaec54c63f, RESELLER, d1a215d9eb5aee9e') if 'eaec54c63f' not in list(stocks['id']): print('sonobi.com,eaec54c63f,RESELLER,d1a215d9eb5aee9e') if '273644' not in list(stocks['id']): print('sovrn.com, 273644, RESELLER') if '117872' not in list(stocks['id']): print('spotx.tv, 117872, RESELLER, 7842df1d2fe2db34') if '234183' not in list(stocks['id']): print('spotx.tv, 234183, RESELLER, 7842df1d2fe2db34') if '283422' not in list(stocks['id']): print('spotx.tv, 283422, RESELLER, 7842df1d2fe2db34') if '82068' not in list(stocks['id']): print('spotx.tv,82068,RESELLER,7842df1d2fe2db34') if '99441' not in list(stocks['id']): print('spotx.tv, 99441, RESELLER, 7842df1d2fe2db34') if '117872' not in list(stocks['id']): print('spotxchange.com, 117872, RESELLER, 7842df1d2fe2db34') if '234183' not in list(stocks['id']): print('spotxchange.com, 234183, RESELLER, 7842df1d2fe2db34') if '283422' not in list(stocks['id']): print('spotxchange.com, 283422, RESELLER, 7842df1d2fe2db34') if '82068' not in list(stocks['id']): print('spotxchange.com,82068,RESELLER,7842df1d2fe2db34') if '99441' not in list(stocks['id']): print('spotxchange.com, 99441, RESELLER, 7842df1d2fe2db34') if '14039' not in list(stocks['id']): print('tappx.com, 14039, RESELLER, 9f375a07da0318ec') if '14039' not in list(stocks['id']): print('tappx.com,14039,RESELLER,9f375a07da0318ec') if '8676470' not in list(stocks['id']): print('target.my.com, 8676470, RESELLER') if 's92od-u4sw5' not in list(stocks['id']): print('telaria.com, s92od-u4sw5, RESELLER, 1a4e959a1b50034a') if '368' not in list(stocks['id']): print('tpmn.io,368,RESELLER') if '406' not in list(stocks['id']): print('tpmn.io,406,RESELLER') if 's92od-u4sw5' not in list(stocks['id']): print('tremorhub.com, s92od-u4sw5, RESELLER, 1a4e959a1b50034a') if 'par-8a2a4a443b29bb92f9622d3a67346ab' not in list(stocks['id']): print('ucfunnel.com, par-8A2A4A443B29BB92F9622D3A67346AB, RESELLER') if 'par-be776b39322a364bc7767a69ab99bbd9' not in list(stocks['id']): print('ucfunnel.com, par-BE776B39322A364BC7767A69AB99BBD9, RESELLER') if 'par-d232d76a227923da1d28d94aa9699ae8' not in list(stocks['id']): print('ucfunnel.com, par-D232D76A227923DA1D28D94AA9699AE8, RESELLER') if 'par-d233672dd744287dcd7e2439b82494ad' not in list(stocks['id']): print('ucfunnel.com, par-D233672DD744287DCD7E2439B82494AD, RESELLER') if '15290' not in list(stocks['id']): print('verve.com, 15290, RESELLER, 0c8f5958fc2d6270') if '15290' not in list(stocks['id']): print('verve.com,15290,RESELLER,0c8f5958fc2d6270') if '15503' not in list(stocks['id']): print('verve.com, 15503, RESELLER, 0c8f5958fc2d6270') if '15503' not in list(stocks['id']): print('verve.com,15503,RESELLER,0c8f5958fc2d6270') if '5897' not in list(stocks['id']): print('verve.com,5897,RESELLER,0c8f5958fc2d6270') if '3704396951' not in list(stocks['id']): print('video.unrulymedia.com, 3704396951, RESELLER') if '4268206200' not in list(stocks['id']): print('video.unrulymedia.com,4268206200,RESELLER') if '70090' not in list(stocks['id']): print('webeyemob.com, 70090, RESELLER') if '70101' not in list(stocks['id']): print('webeyemob.com, 70101, RESELLER') if '958' not in list(stocks['id']): print('xad.com,958,RESELLER,81cbf0a75a5e0e9a') if '55771' not in list(stocks['id']): print('yahoo.com,55771,RESELLER,e1a5b5b6e3255540') if '57992' not in list(stocks['id']): print('yahoo.com,57992,RESELLER,e1a5b5b6e3255540') if '58905' not in list(stocks['id']): print('yahoo.com,58905,RESELLER,e1a5b5b6e3255540') if '59025' not in list(stocks['id']): print('yahoo.com, 59025, RESELLER, e1a5b5b6e3255540') if '2172218' not in list(stocks['id']): print('yieldlab.net, 2172218, RESELLER')
update need for adtimizer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #use timeIndex to mark the hurricaneSpeed at a certain time #Not really using the below functions so commented them out """ def numOfBuildingsFailingFromHurricane(hurricaneSpeedList,timeIndex, buildingWithstandSpeed,numOfBuilding,numOfBuildingLeft): if numOfBuildingLeft==0: return numOfBuilding elif hurricaneSpeedList[timeIndex]>buildingWithstandSpeed: return numOfBuildingsFailingFromHurricane(hurricaneSpeedList,timeIndex+1,buildingWithstandSpeed,numOfBuilding+1,numOfBuildingLeft-1) else: return numOfBuildingsFailingFromHurricane(hurricaneSpeedList,timeIndex+1,buildingWithstandSpeed,numOfBuilding+1,numOfBuildingLeft) def numOfBuildingsFailingFromDebris(DebrisInTheAir,numOfDebrisCanWithstand,numOfBuilding,numOfBuildingLeft,rateOfDebrisThrowing): if numOfBuildingLeft=0: return numOfBuilding if DebrisInTheAir>=numOfDebrisCanWithstand: return numOfBuildingsFailingFromDebris(DebrisInTheAir+rateOfDebrisThrowing,numOfDebrisCanWithstand,numOfBuilding+1,numOfBuildingLeft-1,rateOfDebrisThrowing) else: return numOfBuildingsFailingFromDebris(DebrisInTheAir,numOfDebrisCanWithstand,numOfBuilding,numOfBuildingLeft,rateOfDebrisThrowing) """ def isFailingFromHurricane(hurricaneSpeed, windSpeedBuildingCanWithstand): if hurricaneSpeed>=windSpeedBuildingCanWithstand: return 1 else: return 0 def isFailingFromDebris(DebrisInTheAir, numOfDebrisCanWithstand): if DebrisInTheAir<numOfDebrisCanWithstand: return 0 else: return 1 #For the hurricane Speed, since it's between 111 and 129 mph, I then assume that it is a normal #distribution with the mean of 120 and a standard deviation 3 so that 111 and 129 are both three #standard deviations away which includes 99% of the data import numpy as np L =np.random.normal(120, 3, 100000) #print(L) hurricaneSpeed = np.random.randn(1) * 3 + 120 print(hurricaneSpeed) numOfMH=100000*0.1 numOfRB=100000*0.7 numOfCB=100000*0.2 windSpeedMHCanWithstand=90 windSpeedRBCanWithstand=120 windSpeedCBCanWithstand=160 numOfDebrisMHCanWithstand=1 numOfDebrisRBCanWithstand=500 numOfDebrisCBCanWithstand=1000 #I assume that when Mobile Home fails it throws 1 debris into the air #when Residential Building fails it throws 200 debris into the air #when Commercial Building fails it throws 500 debris into the air numOfDebrisMHThrows=1 numOfDebrisRBThrows=200 numOfDebrisCBThrows=500 """ Pseudo Code isMHFailingFromHurricane=isFailingFromHurricane(hurricaneSpeed,windSpeedMHCanWithstand) isRBFailingFromHurricane=isFailingFromHurricane(hurricaneSpeed,windSpeedRBCanWithstand) isCBFailingFromHurricane=isFailingFromHurricane(hurricaneSpeed,windSpeedCBCanWithstand) isMHFailingFromDebris=isFailingFromDebris(numOfDebrisInTheAir,numOfDebrisMHCanWithstand) isRBFailingFromDebris=isFailingFromDebris(numOfDebrisInTheAir,numOfDebrisRBCanWithstand) isCBFailingFromDebris=isFailingFromDebris(numOfDebrisInTheAir,numOfDebrisCBCanWithstand) newDebris=debrisThrownFromHurricane+debrisThrownFromDebris debrisThrownFromHurricane=numOfBuildingsFailingFromHurricane(L,timeIndex, buildingWithstandSpeed,numOfBuilding,numOfBuildingLeft)+ isRBFailingFromHurricane*numOfRBFailingFromHurricane*numOfDebrisRBThrows+ isCBFailingFromHurricane*numOfRBFailingFromHurricane*numOfDebrisCBThrows debrisThrownFromDebris=isMHFailingFromDebris*numOfMHFailingFromDebris*numOfDebrisMHThrows+ isRBFailingFromDebris*numOfRBFailingFromDebris*numOfDebrisRBThrows+ isCBFailingFromDebris*numOfRBFailingFromDebris*numOfDebrisCBThrows numOfMHFailingFromHurricane+numOfMHFailingFromDebris<=numOfMH numOfRBFailingFromHurricane+numOfRBFailingFromDebris<=numOfRB numOfCBFailingFromHurricane+numOfMHFailingFromDebris<=numOfCB """ """import scipy.stats scipy.stats.norm.sf(160,120,3)""" def model(hurricaneSpeedList,time,numOfMH,numOfRB,numOfCB,windSpeedMHCanWithstand,windSpeedRBCanWithstand,windSpeedCBCanWithstand,numOfDebrisMHCanWithstand,numOfDebrisRBCanWithstand,numOfDebrisCBCanWithstand,numOfDebrisMHThrows,numOfDebrisRBThrows,numOfDebrisCBThrows): """ This is to build a simulation model based on the user's anticipated length of the hurricane and see how much damage the hurricane will do during its length. Logic: MHs are the first ones to fail, then they'll throw debris into the air, then we'll check if RBs and CBs can still withstand the wind speed of the hurricane, if not, they are also destroyed by the hurricane and throwing debris into the air. Then we'll check if the number of debris in the air exceeds the withstand rate of MHs, RBs, and CBs,(yes in that order, because MHs are the weakeast so they are always the first ones to fail, and the consequence of their failing should be counted in the input of outcome prediction for RBs and CBs and it's the same between RBs and CBs), and if not, the buildings fail and throw more debris into the air, but in the meantime we also check if there're still MHs,RBs,and CBs left for hurricane & debris to destroy. """ numOfDebris=0 for timeIndex in range(time): hurricaneSpeed=hurricaneSpeedList[timeIndex] if (isFailingFromHurricane(hurricaneSpeed, windSpeedMHCanWithstand)&(numOfMH>0)): numOfMH-=1 numOfDebris+=numOfDebrisMHThrows if (isFailingFromHurricane(hurricaneSpeed, windSpeedRBCanWithstand)&(numOfRB>0)): numOfRB-=1 numOfDebris+=numOfDebrisRBThrows if (isFailingFromHurricane(hurricaneSpeed, windSpeedCBCanWithstand)&(numOfCB>0)): numOfCB-=1 numOfDebris+=numODebrisInTheAirfDebrisCBThrows if (isFailingFromDebris(numOfDebris, numOfDebrisMHCanWithstand)&(numOfMH>0)): numOfMH-=1 numOfDebris+=numOfDebrisMHThrows if (isFailingFromDebris(numOfDebris, numOfDebrisRBCanWithstand)&(numOfRB>0)): numOfRB-=1 numOfDebris+=numOfDebrisRBThrows if (isFailingFromDebris(numOfDebris, numOfDebrisCBCanWithstand)&(numOfCB>0)): numOfCB-=1 numOfDebris+=numOfDebrisCBThrows if (isFailingFromDebris(numOfDebris, numOfDebrisMHCanWithstand)): numOfMH=0 numOfDebris+=numOfDebrisMHThrows*numOfMH if (isFailingFromDebris(numOfDebris, numOfDebrisRBCanWithstand)): numOfRB=0 numOfDebris+=numOfDebrisRBThrows*numOfRB if (isFailingFromDebris(numOfDebris, numOfDebrisCBCanWithstand)): numOfCB=0 numOfDebris+=numOfDebrisCBThrows*numOfCB print("After time units of "+str(time)+",") print("The number of Mobile Homes left is: "+str(numOfMH)+".") print("The number of Residential Buildings left is: "+str(numOfRB)+".") print("And the number of Commercial Buildings left is: "+str(numOfCB)+".") print("The number of Debris in the air is: "+str(numOfDebris)+".") if (numOfMH==0)&(numOfRB==0)&(numOfCB==0): print("Everything is destroyed") #I tried to write a model for finding the "no return" point but could not figure out where exactly #the "no return" point should lay. I found it hard to clarify what exactly a "no return" point is #If time unit is not cleanly cut in the consideration, everything will eventually fail. It's just #a matter of time. If time unit is cleanly cut in the consideration, at a certain time, the number #of debris in the air and the number of each type of buildings left could be calculated but it's not #like hurricane just disappears after that certain time units define...or could it? #example user experiment experiment_time=10 model(L,experiment_time,numOfMH,numOfRB,numOfCB,windSpeedMHCanWithstand,windSpeedRBCanWithstand,windSpeedCBCanWithstand,numOfDebrisMHCanWithstand,numOfDebrisRBCanWithstand,numOfDebrisCBCanWithstand,numOfDebrisMHThrows,numOfDebrisRBThrows,numOfDebrisCBThrows)
Assignments/System Thinking & Modeling/HW1/Simulation Code for HW1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="327aZS9Hcwse" # This notebook contains some simple code for viewing the node IDs from the Microsoft Academic Graph that we used for the real data experiments in our paper. # + id="C6_MjbUTbKww" import pickle import os # + id="RQDP8dHcbqsc" DATA_DIR = "data/" # + id="ctYbV-9tbhJs" # Dataset 1. # Each list contains the IDs of the nodes from the Microsoft Academic Graph that # we use in our experiments. train_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_1/train_nodes.pkl"), "rb")) val_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_1/val_nodes.pkl"), "rb")) test_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_1/test_nodes.pkl"), "rb")) # + id="ECjJv-yThBOb" class PaperIdAndIndexMap: def __init__(self, topo_sorted_nodes): self.paper_id_to_idx = {} self.idx_to_paper_id = {} for idx, paper_id in enumerate(topo_sorted_nodes): self.paper_id_to_idx[paper_id] = idx self.idx_to_paper_id[idx] = paper_id # + colab={"base_uri": "https://localhost:8080/"} id="-k4vymTIb3lG" outputId="55f75151-a88e-4213-ddfb-088da859ab4c" print("Number of training nodes: %d" % len(train_nodes)) print("Number of validation nodes: %d" % len(val_nodes)) print("Number of test nodes: %d" % len(test_nodes)) # + id="Wc-2RJIkb7nn" # Dataset 2. # Each list contains the IDs of the nodes from the Microsoft Academic Graph that # we use in our experiments. train_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_2/train_nodes.pkl"), "rb")) val_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_2/val_nodes.pkl"), "rb")) test_nodes = pickle.load(open(os.path.join(DATA_DIR, "dataset_2/test_nodes.pkl"), "rb")) # + colab={"base_uri": "https://localhost:8080/"} id="oIUV2y8Qco4F" outputId="b55d4e62-e764-43c8-b122-995693806f6f" print("Number of training nodes: %d" % len(train_nodes)) print("Number of validation nodes: %d" % len(val_nodes)) print("Number of test nodes: %d" % len(test_nodes)) # + [markdown] id="_Yf9tzrtNDob" # In our paper, we preprocess the paper text (title and abstract) and 768-dimensional embedding using [SciBERT](https://github.com/allenai/scibert) and [bert-as-a-service](https://github.com/hanxiao/bert-as-service). # # We provide the preprocessed data with the 768-dimensional embeddings for both # the datasets used in our paper. The data is in the form of a dictionary that maps each paper ID to its text embedding and can be loaded using the `pickle` library. The dataset can be found [here](https://drive.google.com/file/d/1cfR6strHk3SoSUHbYv_yY1fXbgWZaP5T/view?usp=sharing). # + id="3wGBImRMNH0O" # A dictionary where the key is Microsoft Academic Graph node ID representing # an academic paper and the value is a 768-dimensional `np.array` representing # the text embedding that we use in our training pipeline. # `nodes_to_scibert_embedding_dataset_{1,2}.pkl` can be downloaded from the links above. nodes_to_scibert = pickle.load(open(os.path.join(DATA_DIR, "nodes_to_scibert_embedding_dataset_1.pkl"), "rb"))
Nodes_for_the_real_data_experiments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/edwinnglabs/timeseries-notebooks/blob/main/orbit_hello.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="pxPf4jy3Omj_" # !pip install orbit-ml import logging, sys logging.disable(sys.maxsize) # + id="-KgmO47lOr3S" # !pip install microprediction # + [markdown] id="p2bh6KxE88So" # ### orbit-ml hello world # See https://www.microprediction.com/blog/popular-timeseries-packages for more packages # + id="DUhhIeHhOutZ" from microprediction import MicroReader mr = MicroReader() YS = mr.get_lagged_values(name='emojitracker-twitter-sparkles.json')[:20] # + colab={"base_uri": "https://localhost:8080/"} id="9umgvxRRi8LQ" outputId="1fceceb9-7910-468e-935a-01e311c358da" import orbit print(orbit.__version__) # + id="ODDpGjVDPDwS" from orbit.models import LGT import pandas as pd import numpy as np import datetime def orbit_lgt_next(ys:[float])->float: """ Predict the next point in a series """ df = pd.DataFrame(columns=['y'],data=ys) # log transform is recommended usually df['y'] = np.log1p(df['y']) df['ds'] = pd.date_range(start='2021-01-01', periods=len(ys), freq='D') lgt = LGT(response_col='y', date_col='ds', estimator='stan-map', seed=2022) lgt.fit(df) df = pd.DataFrame(columns=['y'],data=YS) df['ds'] = pd.date_range(start='2021-01-01', periods=len(YS), freq='D') future_df = df.loc[(df.shape[0] - 1):, ['ds']].reset_index(drop=True) future_df['ds'] = future_df['ds'] + pd.Timedelta(1, unit="D") forecast_df = lgt.predict(future) prediction = np.expm1(forecast_df['prediction'].values[0]) prediction = np.clip(prediction, a_min=0, a_max=np.inf) return prediction def run(ys): """ Slow, see river package or others if you don't like """ burnin = 10 y_hats = list() for t in range(len(ys)): if t>burnin: y_hat = orbit_lgt_next(ys[:t]) elif t>=1: y_hat = ys[t-1] else: y_hat = 0 y_hats.append(y_hat) return y_hats # + id="XmFAcUsWSA0I" XS = run(YS) # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="UsQalSXqS6a4" outputId="056bad5a-3ad5-45b3-bc0f-f7bdcd33a642" import matplotlib.pyplot as plt plt.plot(YS[:25],'*b') plt.plot(XS[:25],'g')
orbit_hello.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="43ZKMRXpm5Ud" colab_type="code" outputId="97fd665d-d838-4ddd-8c40-d0d7c7d3838b" executionInfo={"status": "ok", "timestamp": 1583427464554, "user_tz": -60, "elapsed": 14016, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 541} # !pip install --upgrade tables # !pip install eli5 # !pip install xgboost # + id="tWcDaFiVoPLU" colab_type="code" colab={} import pandas as pd import numpy as np from sklearn.dummy import DummyRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor import xgboost as xgb from sklearn.metrics import mean_absolute_error as mae from sklearn.model_selection import cross_val_score, KFold import eli5 from eli5.sklearn import PermutationImportance # + id="CjnGjF-vosEt" colab_type="code" outputId="a27efe5f-6ffb-4a5d-aa39-57dc5f1f1902" executionInfo={"status": "ok", "timestamp": 1583409863829, "user_tz": -60, "elapsed": 12001, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 34} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrix' # + id="Aakb-2OKov6g" colab_type="code" colab={} df = pd.read_hdf('data/car.h5') # + id="npWuUHgapiHH" colab_type="code" colab={} df = df[ df.price_currency != 'EUR' ] # + id="jzH8C5CMNwWg" colab_type="code" colab={} df.rename(columns = {'param_model-pojazdu':'param_model_pojazdu', 'param_liczba-drzwi' : 'param_liczba_drzwi'}, inplace = True) # + id="BnCVKFJK0eF0" colab_type="code" colab={} df['param_liczba_drzwi'].fillna(-1, inplace = True) df['param_liczba_drzwi'] = df['param_liczba_drzwi'].astype(np.int8) # + id="U0mDpZ40owaC" colab_type="code" colab={} suffix = '__cat' for feat in df.columns: if isinstance(df[feat][0], list): continue factorized_vals = df[feat].factorize()[0] if suffix in feat: df[feat] = factorized_vals else: df[feat + suffix] = factorized_vals # + id="Q-msDFXipAwD" colab_type="code" colab={} cat_feats = [x for x in df.columns if suffix in x] cat_feats = [x for x in cat_feats if 'price' not in x] # + id="-nh9_LfEpVWH" colab_type="code" colab={} def run_model(model, feats): X = df[feats].values y = df['price_value'].values scores = cross_val_score(model, X, y, cv=3, scoring='neg_mean_absolute_error') return np.mean(scores), np.std(scores) # + [markdown] id="VZe8EkRLqv_V" colab_type="text" # ### Decision Tree Model # + id="-9GM9WFtp6pU" colab_type="code" outputId="28055496-a8c3-44b4-9a53-21e173f38ecf" executionInfo={"status": "ok", "timestamp": 1583409871600, "user_tz": -60, "elapsed": 19519, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 34} run_model( DecisionTreeRegressor(max_depth=5), cat_feats ) # + [markdown] id="TESNNJjzqzwu" colab_type="text" # ### Random Forest Model # + id="q5r6UGXyp3XQ" colab_type="code" outputId="19108ff7-5a70-41ce-92ea-c44fe3d8185a" executionInfo={"status": "ok", "timestamp": 1583409992341, "user_tz": -60, "elapsed": 140217, "user": {"displayName": "<NAME>105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 34} model = RandomForestRegressor(max_depth=5, n_estimators=50, random_state=2020) run_model(model, cat_feats) # + [markdown] id="edZ04TRs5sko" colab_type="text" # ### XGBoost Model # + id="Q7RLKkKqrWEc" colab_type="code" outputId="ce528f50-88a9-4b79-b644-fa6511f40f78" executionInfo={"status": "ok", "timestamp": 1583410051188, "user_tz": -60, "elapsed": 198982, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 85} xgb_params = { 'max_depth': 5, 'n_estimators': 50, 'learning_rate': 0.1, 'seed': 2020 } model = xgb.XGBRegressor(**xgb_params) run_model(model, cat_feats) # + id="o3PySONO6Z5h" colab_type="code" outputId="9186e54f-9f8a-4b1b-ec96-cb4e344af0d8" executionInfo={"status": "ok", "timestamp": 1583410404612, "user_tz": -60, "elapsed": 552346, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 408} X = df[cat_feats].values y = df['price_value'].values m = xgb.XGBRegressor(**xgb_params) m.fit(X, y) imp = PermutationImportance(m, random_state=2020).fit(X, y) eli5.show_weights(imp, feature_names=cat_feats) # + id="_ULYJsV27O9G" colab_type="code" colab={} feats = ['param_napฤ™d__cat','param_rok-produkcji__cat','param_stan__cat','param_skrzynia-biegรณw__cat','param_faktura-vat__cat','param_moc__cat','param_marka-pojazdu__cat', 'param_typ__cat','feature_kamera-cofania__cat','param_pojemnoล›ฤ‡-skokowa__cat','seller_name__cat','param_kod-silnika__cat','param_model_pojazdu__cat', 'feature_wspomaganie-kierownicy__cat','param_wersja__cat','feature_czujniki-parkowania-przednie__cat','feature_asystent-pasa-ruchu__cat','feature_system-start-stop__cat', 'feature_regulowane-zawieszenie__cat','feature_ล›wiatล‚a-led__cat'] # + id="-DZnxZek9-Nw" colab_type="code" outputId="95ea48bd-b1d0-4303-ddf5-d28aad74c417" executionInfo={"status": "ok", "timestamp": 1583410417540, "user_tz": -60, "elapsed": 565216, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 85} run_model(model, feats) # + id="-ugaQRbUCTMN" colab_type="code" outputId="6291405b-9ea7-4fa3-8d21-0f3cc4ba183b" executionInfo={"status": "ok", "timestamp": 1583410417541, "user_tz": -60, "elapsed": 565154, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 187} df['param_rok-produkcji'].unique() # + id="lZWxhZzu-CpY" colab_type="code" colab={} df['param_rok-produkcji'] = df['param_rok-produkcji'].map(lambda x: -1 if str(x) == 'None' else int(x)) # + id="4nT_o6pfCWad" colab_type="code" outputId="61aaa35f-7a64-4d32-ce25-a80911a2b1da" executionInfo={"status": "ok", "timestamp": 1583410418181, "user_tz": -60, "elapsed": 565643, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 136} df['param_rok-produkcji'].unique() # + id="wDnQem25CXcf" colab_type="code" colab={} feats = ['param_napฤ™d__cat','param_rok-produkcji','param_stan__cat','param_skrzynia-biegรณw__cat','param_faktura-vat__cat','param_moc__cat','param_marka-pojazdu__cat', 'param_typ__cat','feature_kamera-cofania__cat','param_pojemnoล›ฤ‡-skokowa__cat','seller_name__cat','param_kod-silnika__cat','param_model_pojazdu__cat', 'feature_wspomaganie-kierownicy__cat','param_wersja__cat','feature_czujniki-parkowania-przednie__cat','feature_asystent-pasa-ruchu__cat','feature_system-start-stop__cat', 'feature_regulowane-zawieszenie__cat','feature_ล›wiatล‚a-led__cat'] # + id="ZOw-Z0RXCjMW" colab_type="code" outputId="35ed6a8a-7d77-47e6-bdec-765236d0eb86" executionInfo={"status": "ok", "timestamp": 1583410430915, "user_tz": -60, "elapsed": 578350, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 85} run_model(model, feats) # + id="_sxMpOThCjw1" colab_type="code" outputId="8a1d8c6b-28b0-4a6c-f972-0543a6ea61d5" executionInfo={"status": "ok", "timestamp": 1583410430916, "user_tz": -60, "elapsed": 578337, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 1000} df['param_moc'].unique() # + id="wypc6vWvC1eH" colab_type="code" colab={} df['param_moc'] = df['param_moc'].map( lambda x: -1 if str(x) == 'None' else int(x.split(' ')[0]) ) # + id="A6HmEAI9D6EL" colab_type="code" colab={} feats = ['param_napฤ™d__cat','param_rok-produkcji','param_stan__cat','param_skrzynia-biegรณw__cat','param_faktura-vat__cat','param_moc','param_marka-pojazdu__cat', 'param_typ__cat','feature_kamera-cofania__cat','param_pojemnoล›ฤ‡-skokowa__cat','seller_name__cat','param_kod-silnika__cat','param_model_pojazdu__cat', 'feature_wspomaganie-kierownicy__cat','param_wersja__cat','feature_czujniki-parkowania-przednie__cat','feature_asystent-pasa-ruchu__cat','feature_system-start-stop__cat', 'feature_regulowane-zawieszenie__cat','feature_ล›wiatล‚a-led__cat'] # + id="s4BW890uEBPQ" colab_type="code" outputId="d6266b1a-0f03-4be1-fb90-5874b31deeb2" executionInfo={"status": "ok", "timestamp": 1583410444313, "user_tz": -60, "elapsed": 591701, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 85} run_model(model, feats) # + id="20nqyeBNEDaN" colab_type="code" outputId="3fb85a42-f0c3-4987-a7a4-542b9c7b13fb" executionInfo={"status": "ok", "timestamp": 1583410444317, "user_tz": -60, "elapsed": 591694, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 51} df['param_pojemnoล›ฤ‡-skokowa'].unique() # + id="9yakbnvSEZMl" colab_type="code" colab={} df['param were_pojemnoล›ฤ‡-skokowa'] = df['param_pojemnoล›ฤ‡-skokowa'].map( lambda x: -1 if str(x) == 'None' elese int(str(x).split('cm')[0].replace(' ','')) ) # + id="g7v3UkDpFB6H" colab_type="code" outputId="93d6b3ab-5bc0-4104-b5f5-456800ca0953" executionInfo={"status": "ok", "timestamp": 1583410444953, "user_tz": -60, "elapsed": 592305, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 34} df['param_pojemnoล›ฤ‡-skokowa'].unique() # + id="tBEXOhpdE_-t" colab_type="code" colab={} feats = ['param_napฤ™d__cat','param_rok-produkcji','param_stan__cat','param_skrzynia-biegรณw__cat','param_faktura-vat__cat','param_moc','param_marka-pojazdu__cat', 'param_typ__cat','feature_kamera-cofania__cat','param_pojemnoล›ฤ‡-skokowa','seller_name__cat','param_kod-silnika__cat','param_model_pojazdu__cat', 'feature_wspomaganie-kierownicy__cat','param_wersja__cat','feature_czujniki-parkowania-przednie__cat','feature_asystent-pasa-ruchu__cat','feature_system-start-stop__cat', 'feature_regulowane-zawieszenie__cat','feature_ล›wiatล‚a-led__cat'] # + id="Mmwu0FzoFTq3" colab_type="code" outputId="4ddf2e8b-8324-4645-919c-d714c5985e80" executionInfo={"status": "ok", "timestamp": 1583410457544, "user_tz": -60, "elapsed": 604863, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 85} run_model(model, feats) # + id="J15zc-7ZOOey" colab_type="code" colab={} # Some cleaning # df.loc[df.param_typ == 'compact/sedan', 'param_typ'] = 'Sedan' # + [markdown] id="e_uTkKHJA2Cx" colab_type="text" # #Read cleaned dataframe # + id="dNjJvpfOwIoe" colab_type="code" outputId="03663af8-6779-4ca0-d791-4f5151482f0a" executionInfo={"status": "ok", "timestamp": 1583427520219, "user_tz": -60, "elapsed": 962, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 55} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrix/data' # + id="hrBahZ0vzIEF" colab_type="code" colab={} df = pd.read_hdf('car_data.h5') # + id="DsEX88_ozki0" colab_type="code" colab={} df['param_typ__cat'] = df['param_typ'].factorize()[0] # + id="rmCuvgVI__y_" colab_type="code" colab={} df.rename(columns = {'param_skrzynia-biegรณw':'param_skrzynia_biegรณw'}, inplace = True) # + id="Rj3oyhfPpgdz" colab_type="code" outputId="5aff52c9-b0f9-4e37-b08e-db06d6d2fc24" executionInfo={"status": "ok", "timestamp": 1583427818851, "user_tz": -60, "elapsed": 629, "user": {"displayName": "<NAME>105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 55} [x for x in df.columns if 'przebieg' in x] # + id="ZMepO006phNn" colab_type="code" outputId="54546952-52e0-44bb-f401-1c6123952552" executionInfo={"status": "ok", "timestamp": 1583427883375, "user_tz": -60, "elapsed": 763, "user": {"displayName": "<NAME>0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 73} df.param_przebieg.unique() # + id="XQbsp28--sox" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 84} outputId="39f7fdf0-cf99-47bf-a9bb-9a666128af4a" executionInfo={"status": "ok", "timestamp": 1583433757137, "user_tz": -60, "elapsed": 776, "user": {"displayName": "<NAME>105c", "photoUrl": "", "userId": "08572552845328219396"}} df.param_gearbox.unique() # + id="-U3_d1Lsrtb8" colab_type="code" colab={} df['param_przebieg_num'] = df['param_przebieg'].map( lambda x: -1 if str(x) == 'None' else int(str(x).split('km')[0].replace(' ', '')) ) # + id="iMLqs9M3-dCr" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="8504e33d-5254-423c-d0b8-ed918682502a" executionInfo={"status": "ok", "timestamp": 1583433275541, "user_tz": -60, "elapsed": 687, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} df.info(verbose=True) # + id="b6miSC6LuJkn" colab_type="code" colab={} xgb_params = {'max_depth': 5, 'n_estimators': 50, 'learning_rate': 0.1, 'seed': 2020 } # + id="NjwrO3DhuTOx" colab_type="code" colab={} model = xgb.XGBRegressor(**xgb_params) # + id="WqHhu8AazknG" colab_type="code" colab={} feats = ['param_napฤ™d__cat','param_rok-produkcji','param_stan__cat','param_skrzynia-biegรณw__cat','param_faktura-vat__cat','param_moc','param_marka-pojazdu__cat', 'param_typ__cat','feature_kamera-cofania__cat','param_pojemnoล›ฤ‡-skokowa','seller_name__cat','param_kod-silnika__cat','param_model_pojazdu__cat', 'feature_wspomaganie-kierownicy__cat','param_wersja__cat','feature_czujniki-parkowania-przednie__cat','feature_asystent-pasa-ruchu__cat','feature_system-start-stop__cat', 'feature_regulowane-zawieszenie__cat','feature_ล›wiatล‚a-led__cat', 'param_przebieg_num'] # + id="TMO_9yGfz5HP" colab_type="code" outputId="e15431a6-797d-4363-d08a-cd1c3507dd69" executionInfo={"status": "ok", "timestamp": 1583434137758, "user_tz": -60, "elapsed": 14016, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 84} run_model(model, feats) # + id="vsaUPNJh0P6D" colab_type="code" outputId="b244684a-1f18-4cb7-ea4e-ac5a4dec024e" executionInfo={"status": "ok", "timestamp": 1583434173313, "user_tz": -60, "elapsed": 48280, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 403} X = df[feats].values y = df['price_value'].values m = xgb.XGBRegressor(**xgb_params) m.fit(X, y) imp = PermutationImportance(m, random_state=2020).fit(X, y) eli5.show_weights(imp, feature_names=feats) # + id="RoFbUWVSGcou" colab_type="code" colab={} # !git config --global user.email "<EMAIL>" # !git config --global user.name "Mateusz" # + id="n0Fv8din1Eti" colab_type="code" outputId="430bc7d4-acd4-4cb3-d2a7-a884e6f78cc8" executionInfo={"status": "ok", "timestamp": 1583414009784, "user_tz": -60, "elapsed": 600, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 34} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrix' # + id="r4yKAfFhH4rT" colab_type="code" colab={} # !git add matrix_two/day4_xgboost.ipynb # + id="lJR9rMnWH7_F" colab_type="code" outputId="a6c22aa0-3da9-47a9-9093-caa966b5a863" executionInfo={"status": "ok", "timestamp": 1583414069369, "user_tz": -60, "elapsed": 1871, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 68} # !git commit -m 'Feature Engineering Warmup' # + id="xkahYWa-H_Pa" colab_type="code" outputId="ece030dd-71a2-4ad3-85e3-de7bbc3f4adf" executionInfo={"status": "ok", "timestamp": 1583414099688, "user_tz": -60, "elapsed": 4651, "user": {"displayName": "<NAME>\u0105c", "photoUrl": "", "userId": "08572552845328219396"}} colab={"base_uri": "https://localhost:8080/", "height": 170} # !git push -u origin master # + id="zKoIDk8rIBDk" colab_type="code" colab={}
matrix_two/day4_xgboost.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Using RNN to predict Bit Coin Currency # # Edited by Una # Date: 2021-07-14 # # #### Install packages: # # > pip3 install -r requirement.txt # # requirement.txt # # numpy # pandas # matplotlib # sklearn # torch # seaborn import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler import torch import math, time import torch.nn as nn from sklearn.metrics import mean_squared_error,mean_absolute_error # ## 1. Loadin data and data preprocessing # # normalization for close price : # # [MinMaxScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) ### Loadin the csv data dataset = pd.read_csv("BTC.csv", header=None, names = ["date","close","vol"], index_col=0, parse_dates=True) print(dataset.info()) dataset.head() plt.rcParams['figure.figsize'] = [10, 3] plt.title("BTC price") plt.plot(dataset.close.values) plt.show() ## Close price normalization to 0-1 scaler = MinMaxScaler()# default feature_range=(0,1) dataset_scaled = scaler.fit_transform(dataset.close.values.reshape(-1,1)) use_gpu = torch.cuda.is_available() device = torch.device("cuda" if use_gpu else "cpu") # + ## Convert the normalized close price to a vector of lookback-dimension with lookback history data def split_data(stock, lookback): data = [] for index in range(len(stock) - lookback): data.append(stock[index: index + lookback]) data = np.array(data) train_val_slip = int(0.8* data.shape[0]) x_train = data[:train_val_slip,:-1,:] y_train = data[:train_val_slip,-1,:] x_test = data[train_val_slip:,:-1] y_test = data[train_val_slip:,-1,:] return [x_train, y_train, x_test, y_test] lookback = 20 x_train, y_train, x_test, y_test = split_data(dataset_scaled, lookback) x_train_torch = torch.from_numpy(x_train).type(torch.Tensor) x_test_torch = torch.from_numpy(x_test).type(torch.Tensor) y_train_torch = torch.from_numpy(y_train).type(torch.Tensor) y_test_torch = torch.from_numpy(y_test).type(torch.Tensor) # - # ## 2. Creat NN model # ๆž„้€ ๆจกๅž‹ class RRN(nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, output_dim): super(RRN, self).__init__() self.hidden_dim = hidden_dim self.num_layers = num_layers self.rnn = nn.RNN(input_dim, hidden_dim, num_layers, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_().cuda() out, (hn) = self.rnn(x, (h0.detach())) out = self.fc(out[:, -1, :]) return out input_dim = 1 hidden_dim = 64 num_layers = 3 output_dim = 1 use_gpu = torch.cuda.is_available() device = torch.device("cuda" if use_gpu else "cpu") model = RRN(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers).to(device) # ## 3. Train the model num_epochs = 1000 criterion = torch.nn.MSELoss(reduction='mean') optimiser = torch.optim.Adam(model.parameters(), lr=0.001) # + hist = np.zeros(num_epochs) start_time = time.time() for t in range(num_epochs): y_train_pred = model(x_train_torch.to(device)) loss = criterion(y_train_pred, y_train_torch.to(device)) print("Epoch ", t, "MSE: ", loss.item()) hist[t] = loss.item() optimiser.zero_grad() loss.backward() optimiser.step() training_time = time.time()-start_time print("Training time: {}".format(training_time)) # + y_train_model = scaler.inverse_transform(y_train_pred.detach().cpu().numpy()) y_train_original = scaler.inverse_transform(y_train) #####Visulization # plt.plot(y_train_original, color = 'red', label = 'BTC True Price') # plt.plot(y_train_model, color = 'blue', label = 'BTC predicted Price') # plt.title('BTC Price') # plt.legend(['Training Prediction (RNN)','Data']) # plt.show() # - # ## 4. Predict on the testset # + y_test_pred = model(x_test_torch.to(device)) y_test_model = scaler.inverse_transform(y_test_pred.detach().cpu().numpy()) y_test_original = scaler.inverse_transform(y_test) # - # ่ฎก็ฎ—ๅฎž้™…ๆŸๅคฑ trainRMSE = math.sqrt(mean_squared_error(y_train_original, y_train_model)) trainMAE = mean_absolute_error(y_train_original, y_train_model) trainMAPE = np.mean(np.abs((y_train_model - y_train_original) / y_train_original)) * 100 print('Train Score: %.4f RMSE, %.4f MAE, %.4f MAPE' % (trainRMSE,trainMAE,trainMAPE)) testRMSE = math.sqrt(mean_squared_error(y_test_original, y_test_model)) testMAE = mean_absolute_error(y_test_original, y_test_model) testMAPE = np.mean(np.abs((y_test_model - y_test_original) / y_test_original)) * 100 print('Test Score: %.4f RMSE, %.4f MAE, %.4f MAPE' % (testRMSE,testMAE,testMAPE)) # ## 5. Visualization # + #####Visulization # plt.plot(y_test_original, color = 'red', label = 'BTC True Price') # plt.plot(y_test_model, color = 'blue', label = 'BTC predicted Price') # plt.title('BTC Price') # plt.legend(['Training Prediction (RNN)','Data']) # plt.show() # - N_original, N_test = len(y_train_original),len(y_test_model) index_test = [i for i in range(0,N_test)] index_test = np.array(index_test).reshape(-1,1) + N_original ## Show all curve plt.plot(y_train_original, color = 'blue', label = 'Price of BTC') plt.plot(y_train_model, color = 'green', label = 'In-sample Prediction') plt.xlabel('times') plt.ylabel('price') plt.plot(index_test, y_test_model, color = 'red', label = 'Out-sample Prediction') plt.plot(index_test, y_test_original, color = 'blue', label = 'Price of BTC') # plt.plot(index_test, y_test_model, color = 'red', label = 'Out-sample Prediction') plt.legend(['Price of BTC','In-sample Prediction','Out-sample Prediction']) plt.savefig("TestRNN20-3.png", dpi=500) plt.show() df_RNN_predict_train_20_3 = pd.DataFrame({'y_test_original_20_3':y_test_original.flatten(),'y_test_model_20_3':y_test_model.flatten()}) df_RNN_predict_train_20_3.to_csv(r"./data/df_RNN_predict_train_20_3.csv",sep=',')
DL/BTC_RNN.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import cv2 import matplotlib.pyplot as plt import PIL.Image as Image # i prefer PIL to draw the text, more beautiful import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont image = cv2.imread('straight-lane.jpg') plt.figure(figsize = (10, 10)) plt.subplot(1, 2, 1) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.subplot(1, 2, 2) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),cmap='gray') plt.show() # + def grayscale(img): return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): mask = np.zeros_like(img) if len(img.shape) > 2: channel_count = img.shape[2] ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 cv2.fillPoly(mask, vertices, ignore_mask_color) masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines(img, lines, color = [255, 0, 0], thickness = 2): for line in lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): # img is the output of the canny() lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength = min_line_len, maxLineGap = max_line_gap) line_img = np.zeros(img.shape, dtype=np.uint8) draw_lines(line_img, lines) return lines, line_img # - rows, cols = image.shape[:2] bottom_left = [int(cols*0.02), int(rows*1)] top_left = [int(cols*0.35), int(rows*0.65)] bottom_right = [int(cols*0.98), int(rows*1)] top_right = [int(cols*0.65), int(rows*0.65)] gaussian_7 = gaussian_blur(canny(image, 50, 150),7) copied = np.copy(gaussian_7) cv2.line(copied, tuple(bottom_left), tuple(bottom_right), (255,0,0), 5) cv2.line(copied, tuple(bottom_left), tuple(top_left), (255,0,0), 5) cv2.line(copied, tuple(top_left), tuple(top_right), (255,0,0), 5) cv2.line(copied, tuple(top_right), tuple(bottom_right), (255,0,0), 5) plt.imshow(copied) plt.show() copied = np.copy(gaussian_7) vertices = np.array([[bottom_left, top_left, top_right, bottom_right]], dtype=np.int32) interested = region_of_interest(copied, vertices) plt.imshow(interested) plt.show() copied = np.copy(gaussian_7) rho = 1 theta = np.pi / 90 threshold = 5 min_line_length = 10 max_line_gap = 8 interested = region_of_interest(copied, vertices) lines,image_lines = hough_lines(interested, rho, theta,threshold,min_line_length,max_line_gap) plt.imshow(image_lines) plt.show() right_sides = {'x':[],'y':[]} left_sides = {'x':[],'y':[]} half = image.shape[1]//2 for lane in lines: for x1,y1,x2,y2 in lane: if x1 < half: left_sides['x'].append(x2) left_sides['y'].append(y2) else: right_sides['x'].append(x1) right_sides['y'].append(y1) # + a_right, b_right = np.polyfit([np.min(right_sides['y']),np.max(right_sides['y'])], [np.min(right_sides['x']),np.max(right_sides['x'])],1) print(a_right, b_right) BottomRightX = int(image.shape[0]*a_right+b_right) a_left, b_left = np.polyfit([np.max(left_sides['y']),np.min(left_sides['y'])], [np.min(left_sides['x']),np.max(left_sides['x'])],1) print(a_left, b_left) BottomLeftX = int(image.shape[0]*a_left+b_left) # + copied = np.copy(image) * 0 color_edges = np.dstack((gaussian_7, gaussian_7, gaussian_7)) TopRightX = np.min(right_sides['x']) TopRightY = np.min(right_sides['y']) TopLeftX = np.max(left_sides['x']) TopLeftY = np.min(left_sides['y']) if TopRightY < TopLeftY: TopLeftY = TopRightY else: TopRightY = TopLeftY cv2.line(copied,(TopLeftX, TopLeftY),(BottomLeftX, image.shape[0]), (0, 255, 0), 8) cv2.line(copied,(TopRightX, TopRightY),(BottomRightX, image.shape[0]), (0, 255, 0), 8) top = (TopLeftX + int((TopRightX - TopLeftX) / 2), TopLeftY) bottom = (BottomLeftX + int((BottomRightX-BottomLeftX)/2), image.shape[0]) cv2.line(copied,top,bottom, (138,43,226), 1) ratio_road = int((image.shape[1]-(BottomRightX-BottomLeftX))/2) steering = (BottomLeftX / ratio_road) - 1 if steering < 0: string_steering = 'move to left: %.2fm'%(steering) else: string_steering = 'move to right: %.2fm'%(steering) copied = cv2.addWeighted(color_edges, 0.8, copied, 1, 0) pil_image = Image.fromarray(np.uint8(copied)) draw = ImageDraw.Draw(pil_image) font = ImageFont.truetype('Roboto-Regular.ttf', 24) draw.text((10, 10),string_steering,fill='white',font=font) plt.imshow(np.array(pil_image)) plt.show() # + plt.figure(figsize=(15,8)) copied = np.copy(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) cv2.line(copied,(TopLeftX, TopLeftY),(BottomLeftX, image.shape[0]), (255, 0, 0), 8) cv2.line(copied,(TopRightX, TopRightY),(BottomRightX, image.shape[0]), (255, 0, 0), 8) top = (TopLeftX + int((TopRightX - TopLeftX) / 2), TopLeftY) bottom = (BottomLeftX + int((BottomRightX-BottomLeftX)/2), image.shape[0]) cv2.line(copied,top,bottom, (255,255,255), 1) ratio_road = int((image.shape[1]-(BottomRightX-BottomLeftX))/2) steering = (BottomLeftX / ratio_road) - 1 if steering < 0: string_steering = 'move to left: %.2fm'%(steering) else: string_steering = 'move to right: %.2fm'%(steering) window_img = np.zeros_like(copied) polyfill = np.array([bottom_left,bottom_right,top_right,top_left]) cv2.fillPoly(window_img, pts =[polyfill], color=(0,255, 0)) copied = cv2.addWeighted(copied, 1, window_img, 0.3, 0) pil_image = Image.fromarray(np.uint8(copied)) draw = ImageDraw.Draw(pil_image) font = ImageFont.truetype('Roboto-Regular.ttf', 40) draw.text((10, 10),string_steering,fill='white',font=font) plt.imshow(np.array(pil_image)) plt.show() # - from moviepy.editor import VideoFileClip previous_a_right, previous_b_right = 0, 0 previous_a_left, previous_b_left = 0, 0 def process_image(image): global previous_a_right, previous_b_right, previous_a_left, previous_b_left without_smoothing = np.copy(image) gray = grayscale(image) low_threshold = 100 high_threshold = 150 edges = canny(gray, low_threshold, high_threshold) kernel_size = 7 blur_gray = gaussian_blur(edges,kernel_size) mask = np.zeros_like(edges) ignore_mask_color = 255 rows, cols = image.shape[:2] smoothing = 0.95 bottom_left = [int(cols*0.02), int(rows*1)] top_left = [int(cols*0.35), int(rows*0.65)] bottom_right = [int(cols*0.98), int(rows*1)] top_right = [int(cols*0.65), int(rows*0.65)] vertices = np.array([[bottom_left, top_left, top_right, bottom_right]], dtype=np.int32) interested = region_of_interest(edges, vertices) rho = 1 theta = np.pi / 90 threshold = 10 min_line_length = 10 max_line_gap = 8 lines = cv2.HoughLinesP(interested, rho, theta, threshold, np.array([]), minLineLength = min_line_length, maxLineGap = max_line_gap) right_sides = {'x':[],'y':[]} left_sides = {'x':[],'y':[]} half = image.shape[1]//2 for lane in lines: for x1,y1,x2,y2 in lane: if x1 < half: left_sides['x'].append(x2) left_sides['y'].append(y2) else: right_sides['x'].append(x1) right_sides['y'].append(y1) a_right, b_right = np.polyfit([np.min(right_sides['y']),np.max(right_sides['y'])], [np.min(right_sides['x']),np.max(right_sides['x'])],1) a_left, b_left = np.polyfit([np.max(left_sides['y']),np.min(left_sides['y'])], [np.min(left_sides['x']),np.max(left_sides['x'])],1) # for without smoothing without_a_right = a_right without_b_right = b_right without_a_left = a_left without_b_left = b_left if previous_a_right == 0 and previous_b_right == 0: previous_a_right = a_right previous_b_right = b_right else: # last * weight + (1 - weight) * point a_right = previous_a_right * smoothing + (1 - smoothing) * a_right previous_a_right = a_right b_right = previous_b_right * smoothing + (1 - smoothing) * b_right previous_b_right = b_right if previous_a_left == 0 and previous_b_left == 0: previous_a_left = a_left previous_b_left = b_left else: # last * weight + (1 - weight) * point a_left = previous_a_left * smoothing + (1 - smoothing) * a_left previous_a_left = a_left b_left = previous_b_left * smoothing + (1 - smoothing) * b_left previous_b_left = b_left BottomRightX = int(image.shape[0]*a_right+b_right) BottomLeftX = int(image.shape[0]*a_left+b_left) # for without smoothing without_BottomRightX = int(image.shape[0]*without_a_right+without_b_right) without_BottomLeftX = int(image.shape[0]*without_a_left+without_b_left) TopRightX = np.min(right_sides['x']) TopRightY = np.min(right_sides['y']) TopLeftX = np.max(left_sides['x']) TopLeftY = np.min(left_sides['y']) # for without smoothing without_TopRightX = np.min(right_sides['x']) without_TopRightY = np.min(right_sides['y']) without_TopLeftX = np.max(left_sides['x']) without_TopLeftY = np.min(left_sides['y']) if TopRightY < TopLeftY: TopLeftY = TopRightY TopLeftX = int(TopLeftY*a_left+b_left) else: TopRightY = TopLeftY TopRightX = int(TopRightY*a_right+b_right) # for without smoothing if without_TopRightY < without_TopLeftY: without_TopLeftY = without_TopRightY without_TopLeftX = int(without_TopLeftY*without_a_left+without_b_left) else: without_TopRightY = without_TopLeftY without_TopRightX = int(without_TopRightY*without_a_right+without_b_right) cv2.line(image,(TopLeftX, TopLeftY),(BottomLeftX, image.shape[0]), (255, 0, 0), 8) cv2.line(image,(TopRightX, TopRightY),(BottomRightX, image.shape[0]), (255, 0, 0), 8) # for without smoothing cv2.line(without_smoothing,(without_TopLeftX, without_TopLeftY), (without_BottomLeftX, image.shape[0]), (255, 0, 0), 8) cv2.line(without_smoothing,(without_TopRightX, without_TopRightY), (without_BottomRightX, image.shape[0]), (255, 0, 0), 8) top = (TopLeftX + int((TopRightX - TopLeftX) / 2), TopLeftY) bottom = (BottomLeftX + int((BottomRightX-BottomLeftX)/2), image.shape[0]) cv2.line(image,top,bottom, (255,255,255), 1) # for without smoothing top = (without_TopLeftX + int((without_TopRightX - without_TopLeftX) / 2), without_TopLeftY) bottom = (without_BottomLeftX + int((without_BottomRightX-without_BottomLeftX)/2), image.shape[0]) cv2.line(without_smoothing,top,bottom, (255,255,255), 1) ratio_road = int((image.shape[1]-(BottomRightX-BottomLeftX))/2) steering = (BottomLeftX / ratio_road) - 1 if steering < 0: string_steering = 'move to left: %.2fm'%(steering) else: string_steering = 'move to right: %.2fm'%(steering) window_img = np.zeros_like(image) polyfill = np.array([bottom_left,bottom_right,top_right,top_left]) cv2.fillPoly(window_img, pts =[polyfill], color=(0,255, 0)) image = cv2.addWeighted(image, 1, window_img, 0.3, 0) pil_image = Image.fromarray(np.uint8(image)) draw = ImageDraw.Draw(pil_image) font = ImageFont.truetype('Roboto-Regular.ttf', 40) draw.text((10, 60),'with smoothing',fill='white',font=font) draw.text((10, 10),string_steering,fill='white',font=font) image = np.array(pil_image) # for without smoothing ratio_road = int((image.shape[1]-(without_BottomRightX-without_BottomLeftX))/2) steering = (without_BottomLeftX / ratio_road) - 1 if steering < 0: string_steering = 'move to left: %.2fm'%(steering) else: string_steering = 'move to right: %.2fm'%(steering) window_img = np.zeros_like(image) polyfill = np.array([bottom_left,bottom_right,top_right,top_left]) cv2.fillPoly(window_img, pts =[polyfill], color=(0,255, 0)) without_smoothing = cv2.addWeighted(without_smoothing, 1, window_img, 0.3, 0) pil_image = Image.fromarray(np.uint8(without_smoothing)) draw = ImageDraw.Draw(pil_image) font = ImageFont.truetype('Roboto-Regular.ttf', 40) draw.text((10, 60),'without smoothing',fill='white',font=font) draw.text((10, 10),string_steering,fill='white',font=font) without_smoothing = np.array(pil_image) return np.concatenate([without_smoothing,image],axis=1) # + white_output = 'testwhite_both.mp4' clip1 = VideoFileClip("solidWhiteRight.mp4") white_clip = clip1.fl_image(process_image) # %time white_clip.write_videofile(white_output, audio = False) # -
12.gradient-smoothing/gradient-smoothing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="Zmw-nFX6Q_T7" # # Project CodeNet Language Classification # # > Copyright (c) 2021 International Business Machines Corporation # Prepared by [<NAME>](<EMAIL>>) # # ## Introduction # # This notebook takes you through the steps of a simple experiment that shows # how to create and exercise a Keras model to detect the language of a piece of # source code. We will be using TensorFlow as its backend. # For convenience, all the necessary steps will be in this single notebook. # One might want to factor out some parts and put them in separate Python files # for training, testing and inference. # # Let's start with a few obligatory imports: # + id="AdZRI-dTRLhk" import os import numpy as np import re import requests import tarfile import shutil # + [markdown] id="jJ6feP0BRQdO" # ## Approach # # Classification means determining the class a given sample belongs to. In our # case we want to determine the programming language in which a given piece of code # is written. There are many different ways of solving this problem. Here we # choose a neural network approach where we train a convolutional model to do # our bidding. The input will be a sample of source code and the output is an # indication of its language. # # We will treat the input at the character level. We will assume that the input # source file is mostly ASCII characters and the input to the neural network is # an encoding of a small, fixed set of characters. # + colab={"base_uri": "https://localhost:8080/"} id="-nrFdl8GRZZs" outputId="b213803b-9493-4e53-d591-ad572eb934a4" letter = 'abcdefghijklmnopqrstuvwxyz' digits = '0123456789' others = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' alphabet = letter + digits + others print('alphabet size:', len(alphabet)) # all-zeroes padding vector: pad_vector = [0 for x in alphabet] # pre-calculated one-hot vectors: supported_chars_map = {} for i, ch in enumerate(alphabet): vec = [0 for x in alphabet] vec[i] = 1 supported_chars_map[ch] = vec print('one-hot encoding for character c:', supported_chars_map['c']) # + [markdown] id="V3CtDPm-Rt8y" # ## Data # # For simplicity and to keep the (training) run-time within reasonable bounds, we # use a selection of source files from Project CodeNet written in 10 different # languages. For each language we select a 100 files of a size of at least 1000 # bytes but no larger than 5000 bytes. For each language, 10 files out the 100 # are set aside for testing the model. # # ### Download and extract # # # The data is available as a gzipped tar file `Project_CodeNet_LangClass.tgz`. # The directory structure is `data/train/<language>/<source>` and # `data/test/<language>/<source>`. Let's download the data and store it on the # local filesystem: # + file_name = "Project_CodeNet_LangClass.tar.gz" data_url = f"https://dax-cdn.cdn.appdomain.cloud/dax-project-codenet/1.0.0/{file_name}" # Download tar archive to local disk with open(file_name, "wb") as f: f.write(requests.get(data_url).content) # Extract contents of archive to local disk if os.path.exists("data"): shutil.rmtree("data") with tarfile.open(file_name) as tf: tf.extractall() # + colab={"base_uri": "https://localhost:8080/"} id="jyA0CQwaSZlB" outputId="c83ad084-4c22-41b2-82bb-3fb9d0cc3722" # !ls data data/train # + [markdown] id="CEwZLbmoqIHJ" # The 10 programming languages are C, C#, C++, D, Haskell, Java, JavaScript, PHP, # Python, and Rust. Note that some languages belong to the same family: C, C++, # and D are very close in lexical elements and syntax. # + id="SV4SN7rbqNJn" langs = [ "C", "C#", "C++", "D", "Haskell", "Java", "JavaScript", "PHP", "Python", "Rust" ] num_classes = len(langs) # + [markdown] id="RkC-R_EhiUy6" # ### Read a file and create samples # # Since the source files are of varying size and we want fixed length samples, # simply truncating each file might bias the training to artifacts that # typically only appear at the beginning of a file, such as copyrights statements # and documentation or class and type definitions. We would probably get more # interesting samples when we chunk each file. Here we split each file in 3 # parts based on the number of lines. Only then the parts will be truncated or # padded as needed. This means that the number of samples is no longer equal to # the number of files but up to 3 times as large. # + id="u_jqGu9kijOD" def get_source_snippets(file_name, breakup=True): # Read the file content and lower-case: text = "" with open(file_name, mode='r') as file: text = file.read().lower() lines = text.split('\n') nlines = len(lines) if breakup and nlines > 50: aThird = nlines//3 twoThirds = 2*aThird text1 = '\n'.join(lines[:aThird]) text2 = '\n'.join(lines[aThird:twoThirds]) text3 = '\n'.join(lines[twoThirds:]) return [text1, text2, text3] return [text] # + [markdown] id="JfhfLArikc26" # To see the effect of `get_source_snippets` let's run it on a single train file: # + colab={"base_uri": "https://localhost:8080/"} id="JuxCC8LOkykd" outputId="2556ccc9-1579-4b7e-a077-e84226935ae4" get_source_snippets('data/train/Haskell/s084836192.hs', breakup=True) # + [markdown] id="-ohVGLUWmHJN" # ### Prepare training data as numpy arrays # # Next we have to encode the snippets as one-hot vectors over the alphabet and # represent them as `numpy` arrays. Ultimately, # we do this for all files in a specified folder. But first the vectorization of a sample: # + id="weska_xsusUu" def turn_sample_to_vector(sample, sample_vectors_size=1024, normalize_whitespace=True): if normalize_whitespace: # Map (most) white-space to space and compact to single one: sample = sample.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') sample = re.sub('\s+', ' ', sample) # Encode the characters to one-hot vectors: sample_vectors = [] for ch in sample: if ch in supported_chars_map: sample_vectors.append(supported_chars_map[ch]) # Truncate to fixed length: sample_vectors = sample_vectors[0:sample_vectors_size] # Pad with 0 vectors: if len(sample_vectors) < sample_vectors_size: for i in range(0, sample_vectors_size - len(sample_vectors)): sample_vectors.append(pad_vector) return np.array(sample_vectors) # + colab={"base_uri": "https://localhost:8080/"} id="Dy9_ReRuvkzK" outputId="5805b740-7b25-4400-898c-7cb1cea6ffb4" sample = get_source_snippets('data/train/Haskell/s084836192.hs')[0] vec = turn_sample_to_vector(sample, sample_vectors_size=10) print('Encoded sample shape:', vec.shape) # + [markdown] id="Y1J7o6vTwqAk" # Now do this for a whole file instead of a sample: # + id="FXVbYeaQwtkl" def turn_file_to_vectors(file_name, sample_vectors_size=1024, normalize_whitespace=True, breakup=True): samples = get_source_snippets(file_name, breakup) return [turn_sample_to_vector(s, sample_vectors_size, normalize_whitespace) for s in samples] # + [markdown] id="REi5x9-TxnJu" # Lastly, pair the vectorized samples with their class labels: # + id="zrz3sh2KxxkE" def get_input_and_labels(root_folder, sample_vectors_size=1024, breakup=True): X = [] Y = [] for i, lang in enumerate(langs): print('Processing language:', lang) # One-hot class label vector: class_label = [0 for x in range(0, num_classes)] class_label[i] = 1 # For all files in language folder: folder = os.path.join(root_folder, lang) for fn in os.listdir(folder): if fn.startswith("."): continue # Skip hidden files and Jupyterlab cache directories file_name = os.path.join(folder, fn) sample_vectors = turn_file_to_vectors(file_name, sample_vectors_size=sample_vectors_size, breakup=breakup) for fv in sample_vectors: X.append(fv) # the sample feature vector Y.append(class_label) # the class ground-truth return np.array(X, dtype=np.int8), np.array(Y, dtype=np.int8) # + [markdown] id="C2L6t9o_09q3" # Now we can get all the training data in numpy arrays. For good measure we shuffle all the samples. Notice that the number of samples turns out to be 2098; starting from 900 source files it is obvious that not every file is split in 3. # + colab={"base_uri": "https://localhost:8080/"} id="aPa5tyR10EVY" outputId="6e679775-04d3-4a22-e914-124c7af21044" x, y = get_input_and_labels(root_folder='data/train') # Shuffle data shuffle_indices = np.random.permutation(np.arange(len(y))) x_shuffled = x[shuffle_indices] y_shuffled = y[shuffle_indices] print('samples shape', x_shuffled.shape) print('class labels shape:', y_shuffled.shape) # + [markdown] id="WzJqlvO42QYB" # ## Model # # A (batch of) encoded sample(s) is simultaneously input to 3 slightly different # convolutional stages. Each stage consists of a 1-dimensional convolution # followed by a 1-dimensional max pooling layer topped off by a flattening layer. # The kernel sizes of the stages are all different but the number of filters is # the same. The 3 stages are concatenated followed by 2 dense layers with a # dropout inbetween and lastly a softmax. The model summary does not show the nested model structure. `plot_model` however shows a nice graphical rendition of all the layers. # + colab={"base_uri": "https://localhost:8080/", "height": 862} id="hnRwAi_K2Zuu" outputId="265caa05-f2c2-4d6a-98ba-dd426827b4ea" from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Activation, Dense, Dropout, Flatten, Input from tensorflow.keras.layers import Conv1D, MaxPooling1D, Concatenate # Model Hyperparameters kernel_sizes = (3, 9, 19) pooling_sizes = (3, 9, 19) num_filters = 128 dropout_prob = 0.5 hidden_dims = 128 stage_in = Input(shape=(1024, 68)) convs = [] for i in range(0, len(kernel_sizes)): conv = Conv1D(filters=num_filters, kernel_size=kernel_sizes[i], padding='valid', activation='relu', strides=1)(stage_in) pool = MaxPooling1D(pool_size=pooling_sizes[i])(conv) flatten = Flatten()(pool) convs.append(flatten) if len(kernel_sizes) > 1: out = Concatenate()(convs) else: out = convs[0] stages = Model(inputs=stage_in, outputs=out) model = Sequential([ stages, Dense(hidden_dims, activation='relu'), Dropout(dropout_prob), Dense(num_classes, activation='softmax') ]) model.summary() # Note: also need pydot and GraphViz installed for this. #from tensorflow.keras.utils import plot_model #plot_model(model, show_shapes=True, expand_nested=True) # + [markdown] id="cBSSZjn_CV9p" # ## Training # # The 2098 samples with their ground truth (the class labels, i.e., the 10 # languages) are fed into the model. This constitutes one so-called epoch. To # achieve a reasonable accuracy we have to train for several epochs. To speed # things up, the samples are bundled in batches. # Of the samples used in training, 10% are reserved for the validation step # after each epoch. In our case that leaves 1888 for training and given a batch # size of 64, one epoch then comprises some 30 batches. # First the model is compiled and then we train it. If possible you should execute the `fit` call using a GPU. Otherwise, sit back and get yourself a cup of coffee. # + colab={"base_uri": "https://localhost:8080/"} id="NCvEE3z5CenC" outputId="b3c6055d-ac84-445d-a233-02eef4a69366" batch_size = 64 num_epochs = 20 val_split = 0.1 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(x_shuffled, y_shuffled, batch_size=batch_size, epochs=num_epochs, validation_split=val_split, verbose=1) # + [markdown] id="Nl_y6j_vEfK9" # It is illustrative to chart the training process. The `history` contains all # the information that we need. # + colab={"base_uri": "https://localhost:8080/", "height": 337} id="iBiHBmI-Ehr_" outputId="12a19474-7a78-45cb-e795-8d4b7428f0d7" import matplotlib.pyplot as plt plt.style.use('ggplot') def plot_history(history): acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] x = range(1, len(acc) + 1) plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(x, acc, 'b', label='Training acc') plt.plot(x, val_acc, 'r', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(x, loss, 'b', label='Training loss') plt.plot(x, val_loss, 'r', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() plot_history(history) # + [markdown] id="0OJVXeXwIb0U" # ## Test # # Finally, let's exercise our mint new model and see how it performs on a set of # samples hitherto unseen, in other words predict the language of the test set. # We re-use the `get_input_and_labels` and have it process all files in the # `test` directory. We predict the outcome of each sample and compare it against # the expected label (language). # + colab={"base_uri": "https://localhost:8080/"} id="gQawmBrRIjG8" outputId="1fa488a0-0fa3-4609-b8b1-c7985f858d00" x, y = get_input_and_labels(root_folder='data/test', breakup=False) print('shape of test samples', x.shape) y_hat = model.predict(x) # + [markdown] id="Oyfbx8CMT7o_" # Here is a very simple evaluation of the model. For each language we count the number of correct prediction, i.e., the softmax output with the highest probability (viz. `argmax`): # + colab={"base_uri": "https://localhost:8080/"} id="jF5sKu52PhxD" outputId="99943b29-ab28-461b-edfc-2d03057f9d25" hits = {} for lang in langs: hits[lang] = 0 for i in range(len(x)): expected_lang = langs[np.argmax(y[i], axis=0)] predicted_lang = langs[np.argmax(y_hat[i], axis=0)] if predicted_lang == expected_lang: hits[expected_lang] += 1 for lang in langs: print("%-10s: %3d correct" % (lang, hits[lang])) # + [markdown] id="NwQQbaIgUm0c" # ### Home work # # Find out which test files are incorrectly predicted, and as what? Also, do a more thorough analysis and print the precision, recall, and F1 score of each class. # + [markdown] id="tCTepYLlnQF1" # ## Acknowledgement # # The idea and much of the Python source code for this notebook was derived from the github https://github.com/aliostad/deep-learning-lang-detection by <NAME>.
notebooks/Project_CodeNet_LangClass.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # First contact with df # #### Batch data # Data can be loaded in through a CSV, JSON, XML, or a Parquet file. # # It can also be created using an existing RDD and through any other database, like Hive or Cassandra as well. # # It can also take in data from HDFS or the local file system. # + import findspark import pyspark import time import operator from pyspark import SparkConf from pyspark import SparkContext import pandas as pd conf = SparkConf() conf.setMaster("local") conf.setAppName("spark-basic") sc = SparkContext(conf = conf) # - # A first example with 'fake' data: # + data1 = {'PassengerId': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6 }, 'Name': {0: 'Owen', 1: 'Florence', 2: 'Laina', 3: 'Lily', 4: 'William', 5: 'Jack'}, 'Sex': {0: 'male', 1: 'female', 2: 'female', 3: 'female', 4: 'male', 5: 'male'}, 'Survived': {0: 0, 1: 1, 2: 1, 3: 1, 4: 0, 5: 0}} data2 = {'Id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'Age': {0: 22, 1: 38, 2: 26, 3: 35, 4: 35}, 'Fare': {0: 7.3, 1: 71.3, 2: 7.9, 3: 53.1, 4: 8.0}, 'Pclass': {0: 3, 1: 1, 2: 3, 3: 1, 4: 3}} df1_pd = pd.DataFrame(data1, columns=data1.keys()) df2_pd = pd.DataFrame(data2, columns=data2.keys()) # - # We will need a spark session to process this type of data. Caution, many examples on the Internet do not specify what "spark." is # + from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() df1 = spark.createDataFrame(df1_pd) df2 = spark.createDataFrame(df2_pd) df1.show() # - # Summary of the properties of our object df1.printSchema() type(df1) # ### Operating with dataframes # # If you have experience coding with the package dplyr from R, you have more than half of it covered! # # **Filter**, **select**, **mutate**, **summarize** and **arrange** are the basic verbs here too, although some of them have different names... df1.select(["Name","Sex"]).show() df1.filter(df1.Sex == 'female').filter(df1.Survived == 1).show() # But we can also do it SQL-style. Note that this is not a python syntax! df1.filter("Sex='female'").show() # And this is the equivalent of mutate.... hello = df2.withColumn('PricePerYear', df2.Fare/df2.Age) hello # Groupby is needed when we want to summarize our data... the use is identical than in lists or dictionaries df2.groupby('Pclass').avg(*["Age","Fare"]).show() df2.groupby('Pclass').agg({'Age': 'avg', 'Fare': 'avg'}).show() # If you are not familiar with the syntax *****, it refers to "unpack", so we have to provide an unpacked list. # # If we want multiple functions at the same time, we need an dictionary df2.groupby('Pclass').agg({'*': 'count', 'Age': 'avg', 'Fare': 'sum'}).show() # To present the summarized data in a nicer format, we can un toDF() to rename the columns ( df2.groupby('Pclass').agg({'*': 'count', 'Age': 'avg', 'Fare':'sum'}) .toDF('Pclass', 'counts', 'average_age', 'total_fare') .show() ) # And finally, we can **arrange** dataframes using the method sort df2.sort('Age', ascending=True).show() # Good reference: https://dzone.com/articles/pyspark-dataframe-tutorial-introduction-to-datafra # ## Basic joins and unions df1.join(df2, df2.Id == df1.PassengerId).show() df1.show() # Is it symmetric? Where is Jack? :'( # # If you have some time, explore with other types of join, such as "left", "right", "cross", "inner" # + #### Your code here # - print((df1.count(), len(df1.columns))) print((df2.count(), len(df2.columns))) df2.show() left_join = df1.join(df2, df2.Id == df1.PassengerId, how='left') left_join.show() left_join.filter(col('df2.Id').isNull()).show() # And union doesn't do what we could expect... why would we need it? df1.union(df2).show() # Some weird join procedure... what is going on here? Are you able to find why would it be useful? (and dangerous?) df1.join(df2, df1.PassengerId <= df2.Id).show() # And... what about doing joins with SQL? # # If we want to do that, we will need temporary Views! Sounds worse than it actually is # + df1.createOrReplaceTempView('df1_temp') df2.createOrReplaceTempView('df2_temp') query = ''' select * from df1_temp a, df2_temp b where a.PassengerId = b.Id''' spark.sql(query).show() # + from pyspark.sql.functions import round, col resumen = df2.groupby('Pclass').avg("Age").toDF("Clase","Media") resumen.select("*",round(col("Media"),2)).show() # - resumen = df2.groupby('Pclass').avg("Age").toDF("Clase","Media") resumen.select("*",round(resumen["Media"],2)).show() # ## Importing and exporting data # #### Indirectly # !pip3 install openpyxl prod = pd.read_excel("FoodMarket.xlsx",sheet_name="Products") cust = pd.read_excel("FoodMarket.xlsx",sheet_name="Customers") purc = pd.read_excel("FoodMarket.xlsx",sheet_name="Purchases") sell = pd.read_excel("FoodMarket.xlsx",sheet_name="Sellers") type(prod) prod = spark.createDataFrame(prod) cust = spark.createDataFrame(cust) purc = spark.createDataFrame(purc) sell = spark.createDataFrame(sell) purc.show() # #### Directly sc. spark.read.csv("C:/Users/joangj/OneDrive - NETMIND/BTS/2020/data/FoodMarket.csv",sep=";",header = True).show() # How would you solve the problem of the decimal format? # #### Writing the file back again # An easy way, but generates a new folder and extra files... prod.write.csv("Newdata",header = True) # Using pandas... prod.toPandas().to_csv('mycsv.csv') # Let's see how many partitions do we have in our data! purc.rdd.getNumPartitions() new_df = purc.groupBy("Seller").count() new_df.show() new_df.rdd.getNumPartitions() # As you can see the partition number suddenly increases. This is due to the fact that the Spark SQL module contains the following default configuration: spark.sql.shuffle.partitions set to 200. # Depending on your use case, this can be benefitial or harmfull. In this particular case, one can see that the data volume is not enough to fill all the partitions when there are 200 of them, which causes unnecessary map reduce operations, and ultimately causes the creation of very small files in HDFS, which is not desirable. # # If we want to change this parameter (and many others) we can do it through the SQLContext... from pyspark.sql import SQLContext sqlContext = SQLContext(sc) sqlContext.setConf("spark.sql.shuffle.partitions", "10")
Working with DataFrames.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Dealing with Structured Data- Global Terrorism Database # ### Thanks to <NAME> (6980 2020 QTR 1) for identifying this dynamic # Import libraries to aid your analysis import pandas as pd #pandas places ones data in tables format from bokeh.plotting import figure, output_notebook, show #builds interactive graphs for python from bokeh.models import Range1d import math #this is used in graphic section to use the irrational number pi output_notebook() #Allows inline plotting for Juptyer notebook # ### Let's look at the data # Datasheet was downbloaed form GTD and being read in form a local .csv file GTD = pd.read_excel(r"C:\Users\ymamo\Documents\Classes\688\Fall_2021\Lesson 2\Code\globalterrorismdb_0919dist.csv", encoding = "ISO-8859-1", engine = 'python') # had some issues with the data types, had to search online for example to read properly GTD.head() # see the structure--default is first five rows # Pandas library has a describe function to apply algorithms against the data... # whether approriate or not GTD.describe() #Identifies the total number of rows len(GTD) #provides information about the dataframe GTD.info() #See the titles of the 135 columns for col in GTD.columns: print(col) # !!!! Look in the GTD_Codebook to get more information about each column !!!! # # Problem 1: Change the Country (do after going through the whole notebook) # reduce the dataframe down to just the philippines country = GTD[GTD["country_txt"]=="Niger"] # store the information in an object called country #you can change Philippines to any country in the dataset country.head(10) #by putting in 10 I changed the default setting of 1st 5 rows to 1st 10 rows # ### Let's deep dive in a country # + attacks_by_group = {} #make an empty datastructure (dictionary) to fill #This loop goes through each row and counts the number of entries by group for index, row in country.iterrows(): if row["gname"] in attacks_by_group.keys(): attacks_by_group[row["gname"]] += 1 #if group is in the dictionary add 1 attack else: attacks_by_group[row["gname"]] = 1 #add group name to dictionary if not in dictionary attacks_by_group # - # Make X and Y axis for a bar chart plotting attacks groups = list(attacks_by_group.keys()) attacks = list(attacks_by_group.values()) #Sort from smallest to largest sorted_groups = sorted(groups, key=lambda x: attacks[groups.index(x)]) sorted_attacks = sorted(attacks) # # Problem 2: For any country only do plot the top 5 groups (Hint: Use list slicing e.g sorted_attacks[-10:]) # + # Uses the bokeh library to plot an interactive graph ---this is very basic view of its capability # makes the figure p = figure(x_range = sorted_groups, plot_width=800, plot_height=1200) #Plots the data p.vbar(x=sorted_groups, width=0.5, bottom=0, top= sorted_attacks, color="firebrick") p.xaxis.major_label_orientation = math.pi/2 #Rotates the labels on the X axis # - show(p) # ## Now lets plot the attacks in a map #Imports necessary aspects of Bokeh for plotting on a map from bokeh.tile_providers import get_provider, Vendors from pyproj import Transformer tile_provider = get_provider('STAMEN_TERRAIN') # + # Take the data reduced to a country and get the lat/long of the attacks and the name of the group country_map = country[["latitude", 'longitude', 'gname']] #see the data this time first 7 rows country_map.head(7) # - #create pyproj transformer to convert form lat/long to web mercator transformer = Transformer.from_crs('epsg:4326','epsg:3857') # + map_dict = {} # empty dictionary to track group attacks by lat long nan_count = {} # some data doesn't have a lat/long so we need to know what we are losing # Iterate through tables and associate group with lat/long for idx, row in country_map.iterrows(): if row['gname'] in map_dict.keys(): if math.isnan(row["latitude"]): #This counts no data if row['gname'] in nan_count.keys(): nan_count[row['gname']] += 1 else: nan_count[row['gname']] = 1 else: #This has to convert the lat/long to a mercator projection point = transformer.transform(row["latitude"],row["longitude"]) map_dict[row['gname']].append([point[0],point[1]]) #BOTH the if an else statement do the same thing but since it is a dictionary one needs to add the group name first else: if math.isnan(row["latitude"]): nan_count[row['gname']] = 1 else: point = transformer.transform(row["latitude"],row["longitude"]) map_dict[row['gname']] =[[point[0],point[1]]] #This tells how many attacks we are losing nan_count # - # # Problem 3: Print the top 5 groups from the map_dict structure # # Problem 4: Change the map to show a new country. # ## You can get the lat/long for different places here : https://www.latlong.net/ pts = [(11.00,0.00), (23.00, 15.90)] bbox = [] for pt in transformer.itransform(pts): bbox.append(pt) NPA_x = [] NPA_y = [] for k,v in map_dict.items(): for pt in v: NPA_x.append(pt[0]) NPA_y.append(pt[1]) # + #Plots the bounding box p = figure(x_range=(bbox[0][0], bbox[1][0]),y_range=(bbox[0][1], bbox[1][1]),x_axis_type="mercator", y_axis_type="mercator") #add the map form the Bokeh map vendor in this case Stamen_Terrain --- see documentation p.add_tile(tile_provider) # Places a circle for each converted lat/long attack p.circle(x = NPA_x, y = NPA_y, color= "firebrick") #shows the plot show(p) # -
Session 3/Session_3_GTD_Structured Data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Import Modules from bs4 import BeautifulSoup import requests # ## Get Page Content from URL url = 'https://www.thehindu.com/news/national/coronavirus-live-updates-may-29-2021/article34672944.ece?homepage=true' page = requests.get(url) page # display page content page.content # parse the data soup = BeautifulSoup(page.content, 'html.parser') print(soup.prettify()) # find the image src link img_tag = soup.find('source') img_tag img_tag['srcset'] img_url = img_tag['srcset'] # ## Download the Image from URL image = requests.get(img_url) # store the image in file with open('image.jpg', 'wb') as file: for chunk in image.iter_content(chunk_size=1024): file.write(chunk) # ## Download PPT from URL ppt = requests.get('http://www.howtowebscrape.com/examples/media/images/SampleSlides.pptx') with open('sample.pptx', 'wb') as file: for chunk in ppt.iter_content(chunk_size=1024): file.write(chunk) # ## Download Video from URL video = requests.get('http://www.howtowebscrape.com/examples/media/images/BigRabbit.mp4') with open('BigRabbit.mp4', 'wb') as file: for chunk in video.iter_content(chunk_size=1024): file.write(chunk)
Scraping Multimedia Files using Beautiful Soup.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # #!/usr/bin/python import random def makeTerrainData(n_points=1000): ############################################################################### ### make the toy dataset random.seed(42) grade = [random.random() for ii in range(0,n_points)] bumpy = [random.random() for ii in range(0,n_points)] error = [random.random() for ii in range(0,n_points)] y = [round(grade[ii]*bumpy[ii]+0.3+0.1*error[ii]) for ii in range(0,n_points)] for ii in range(0, len(y)): if grade[ii]>0.8 or bumpy[ii]>0.8: y[ii] = 1.0 ### split into train/test sets X = [[gg, ss] for gg, ss in zip(grade, bumpy)] split = int(0.75*n_points) X_train = X[0:split] X_test = X[split:] y_train = y[0:split] y_test = y[split:] grade_sig = [X_train[ii][0] for ii in range(0, len(X_train)) if y_train[ii]==0] bumpy_sig = [X_train[ii][1] for ii in range(0, len(X_train)) if y_train[ii]==0] grade_bkg = [X_train[ii][0] for ii in range(0, len(X_train)) if y_train[ii]==1] bumpy_bkg = [X_train[ii][1] for ii in range(0, len(X_train)) if y_train[ii]==1] # training_data = {"fast":{"grade":grade_sig, "bumpiness":bumpy_sig} # , "slow":{"grade":grade_bkg, "bumpiness":bumpy_bkg}} grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0] bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0] grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1] bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1] test_data = {"fast":{"grade":grade_sig, "bumpiness":bumpy_sig} , "slow":{"grade":grade_bkg, "bumpiness":bumpy_bkg}} return X_train, y_train, X_test, y_test # return training_data, test_data # + import warnings warnings.filterwarnings("ignore") import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import pylab as pl import numpy as np #import numpy as np #import matplotlib.pyplot as plt #plt.ioff() def prettyPicture(clf, X_test, y_test): x_min = 0.0; x_max = 1.0 y_min = 0.0; y_max = 1.0 # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. h = .01 # step size in the mesh xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic) # Plot also the test points grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0] bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0] grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1] bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1] plt.scatter(grade_sig, bumpy_sig, color = "b", label="fast") plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="slow") plt.legend() plt.xlabel("bumpiness") plt.ylabel("grade") plt.savefig("test.png") # + import base64 import json import subprocess def output_image(name, format, bytes): image_start = "BEGIN_IMAGE_f9825uweof8jw9fj4r8" image_end = "END_IMAGE_0238jfw08fjsiufhw8frs" data = {} data['name'] = name data['format'] = format data['bytes'] = bytes # print(image_start+json.dumps(data)+image_end) # - import numpy as np from sklearn.naive_bayes import GaussianNB def classify(features_train, labels_train): X = features_train Y = labels_train clf = GaussianNB() clf.fit(X, Y) return clf # + import pylab as pl features_train, labels_train, features_test, labels_test = makeTerrainData() ### the training data (features_train, labels_train) have both "fast" and "slow" points mixed ### in together--separate them so we can give them different colors in the scatterplot, ### and visually identify them grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0] bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0] grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1] bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1] # You will need to complete this function imported from the ClassifyNB script. # Be sure to change to that code tab to complete this quiz. clf = classify(features_train, labels_train) ### draw the decision boundary with the text points overlaid prettyPicture(clf, features_test, labels_test) # output_image("test.png", "png", open("test.png", "rb").read()) # - print('accuracy: ' + str(clf.score(features_test, labels_test)*100)+ ' %') # + ########################## SVM ################################# ### we handle the import statement and SVC creation for you here from sklearn.svm import SVC clf = SVC(kernel="linear") #### now your job is to fit the classifier #### using the training features/labels, and to #### make a set of predictions on the test data clf.fit(features_train, labels_train) # print(labels_train) pred = clf.predict(features_test) #### store your predictions in a list named pred clf.score(features_test, labels_test) from sklearn.metrics import accuracy_score acc = accuracy_score(pred, labels_test) print('accuracy: ' + str(acc*100)+ ' %') prettyPicture(clf, features_test, labels_test) # + from sklearn.tree import DecisionTreeClassifier ### your code goes here--should return a trained decision tree classifer clf = DecisionTreeClassifier(random_state=0) clf.fit(features_train, labels_train) pred = clf.predict(features_test) #### store your predictions in a list named pred clf.score(features_test, labels_test) prettyPicture(clf, features_test, labels_test) # + # Define a function that takes an image, a list of bounding boxes, # and optional color tuple and line thickness as inputs # then draws boxes in that color on the output def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6): # make a copy of the image draw_img = np.copy(img) for bbox in bboxes: cv2.rectangle(draw_img, bbox[0], bbox[1], color, thick) # draw each bounding box on your image copy using cv2.rectangle() # return the image copy with boxes drawn return draw_img # Change this line to return image copy with boxes # - # Define a function to search for template matches # and return a list of bounding boxes def find_matches(img, template_list): # Define an empty list to take bbox coords bbox_list = [] # Define matching method # Other options include: cv2.TM_CCORR_NORMED', 'cv2.TM_CCOEFF', 'cv2.TM_CCORR', # 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED' method = cv2.TM_CCOEFF_NORMED # Iterate through template list for temp in template_list: # Read in templates one by one tmp = mpimg.imread(temp) # Use cv2.matchTemplate() to search the image result = cv2.matchTemplate(img, tmp, method) # Use cv2.minMaxLoc() to extract the location of the best match min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) # Determine a bounding box for the match w, h = (tmp.shape[1], tmp.shape[0]) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) # Append bbox position to list bbox_list.append((top_left, bottom_right)) # Return the list of bounding boxes return bbox_list # + import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg image = mpimg.imread('cutout1.jpg') # Define a function to compute color histogram features def color_hist(img, nbins=32, bins_range=(0, 256)): # Compute the histogram of the RGB channels separately rhist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) ghist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) bhist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Generating bin centers bin_edges = rhist[1] bin_centers = (bin_edges[1:] + bin_edges[0:len(bin_edges)-1])/2 # Concatenate the histograms into a single feature vector hist_features = np.concatenate((rhist[0], ghist[0], bhist[0])) # Return the individual histograms, bin_centers and feature vector return rhist, ghist, bhist, bin_centers, hist_features rh, gh, bh, bincen, feature_vec = color_hist(image, nbins=32, bins_range=(0, 256)) # Plot a figure with all three bar charts if rh is not None: fig = plt.figure(figsize=(12,3)) plt.subplot(131) plt.bar(bincen, rh[0]) plt.xlim(0, 256) plt.title('R Histogram') plt.subplot(132) plt.bar(bincen, gh[0]) plt.xlim(0, 256) plt.title('G Histogram') plt.subplot(133) plt.bar(bincen, bh[0]) plt.xlim(0, 256) plt.title('B Histogram') fig.tight_layout() else: print('Your function is returning None for at least one variable...') # + import cv2 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot3d(pixels, colors_rgb, axis_labels=list("RGB"), axis_limits=((0, 255), (0, 255), (0, 255))): """Plot pixels in 3D.""" # Create figure and 3D axes fig = plt.figure(figsize=(8, 8)) ax = Axes3D(fig) # Set axis limits ax.set_xlim(*axis_limits[0]) ax.set_ylim(*axis_limits[1]) ax.set_zlim(*axis_limits[2]) # Set axis labels and sizes ax.tick_params(axis='both', which='major', labelsize=14, pad=8) ax.set_xlabel(axis_labels[0], fontsize=16, labelpad=16) ax.set_ylabel(axis_labels[1], fontsize=16, labelpad=16) ax.set_zlabel(axis_labels[2], fontsize=16, labelpad=16) # Plot pixel values with colors given in colors_rgb ax.scatter( pixels[:, :, 0].ravel(), pixels[:, :, 1].ravel(), pixels[:, :, 2].ravel(), c=colors_rgb.reshape((-1, 3)), edgecolors='none') return ax # return Axes3D object for further manipulation # Read a color image img = cv2.imread("000275.png") # Select a small fraction of pixels to plot by subsampling it scale = max(img.shape[0], img.shape[1], 64) / 64 # at most 64 rows and columns img_small = cv2.resize(img, (np.int(img.shape[1] / scale), np.int(img.shape[0] / scale)), interpolation=cv2.INTER_NEAREST) # Convert subsampled image to desired color space(s) img_small_RGB = cv2.cvtColor(img_small, cv2.COLOR_BGR2RGB) # OpenCV uses BGR, matplotlib likes RGB img_small_HSV = cv2.cvtColor(img_small, cv2.COLOR_BGR2HSV) img_small_rgb = img_small_RGB / 255. # scaled to [0, 1], only for plotting # Plot and show plot3d(img_small_RGB, img_small_rgb) plt.show() plot3d(img_small_HSV, img_small_rgb, axis_labels=list("HSV")) plt.show() # + import cv2 import matplotlib.image as mpimg image = mpimg.imread('test_img.jpg') small_img = cv2.resize(image, (32, 32)) print(small_img.shape) (32, 32, 3) feature_vec = small_img.ravel() print(feature_vec.shape) (3072,) # + import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg # Read in an image # You can also read cutout2, 3, 4 etc. to see other examples image = mpimg.imread('cutout1.jpg') # Define a function to compute color histogram features # Pass the color_space flag as 3-letter all caps string # like 'HSV' or 'LUV' etc. # KEEP IN MIND IF YOU DECIDE TO USE THIS FUNCTION LATER # IN YOUR PROJECT THAT IF YOU READ THE IMAGE WITH # cv2.imread() INSTEAD YOU START WITH BGR COLOR! # Define a function to compute color histogram features # Pass the color_space flag as 3-letter all caps string # like 'HSV' or 'LUV' etc. def bin_spatial(img, color_space='RGB', size=(32, 32)): # Convert image to new color space (if specified) if color_space != 'RGB': if color_space == 'HSV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) elif color_space == 'LUV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV) elif color_space == 'HLS': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) elif color_space == 'YUV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV) elif color_space == 'YCrCb': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb) else: feature_image = np.copy(img) # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(feature_image, size).ravel() # Return the feature vector return features feature_vec = bin_spatial(image, color_space='RGB', size=(32, 32)) # Plot features plt.plot(feature_vec) plt.title('Spatially Binned Features') # - def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=True, feature_vec=True): """ Function accepts params and returns HOG features (optionally flattened) and an optional matrix for visualization. Features will always be the first return (flattened if feature_vector= True). A visualization matrix will be the second return if visualize = True. """ return_list = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=False, visualise= vis, feature_vector= feature_vec) # name returns explicitly hog_features = return_list[0] if vis: hog_image = return_list[1] return hog_features, hog_image else: return hog_features import numpy as np feature_list = [feature_vec1, feature_vec2, ...] # Create an array stack, NOTE: StandardScaler() expects np.float64 X = np.vstack(feature_list).astype(np.float64) from sklearn.preprocessing import StandardScaler # Fit a per-column scaler X_scaler = StandardScaler().fit(X) # Apply the scaler to X scaled_X = X_scaler.transform(X) # + import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from sklearn.preprocessing import StandardScaler import glob # Define a function to compute binned color features def bin_spatial(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(img, size).ravel() # Return the feature vector return features # Define a function to compute color histogram features def color_hist(img, nbins=32, bins_range=(0, 256)): # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) # Return the individual histograms, bin_centers and feature vector return hist_features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, cspace='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256)): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file) # apply color conversion if other than 'RGB' if cspace != 'RGB': if cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif cspace == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) elif cspace == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) else: feature_image = np.copy(image) # Apply bin_spatial() to get spatial color features spatial_features = bin_spatial(feature_image, size=spatial_size) # Apply color_hist() also with a color space option now hist_features = color_hist(feature_image, nbins=hist_bins, bins_range=hist_range) # Append the new feature vector to the features list features.append(np.concatenate((spatial_features, hist_features))) # Return list of feature vectors return features images = glob.glob('*.jpeg') cars = [] notcars = [] for image in images: if 'image' in image or 'extra' in image: notcars.append(image) else: cars.append(image) car_features = extract_features(cars, cspace='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256)) notcar_features = extract_features(notcars, cspace='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256)) if len(car_features) > 0: # Create an array stack of feature vectors X = np.vstack((car_features, notcar_features)).astype(np.float64) # Fit a per-column scaler X_scaler = StandardScaler().fit(X) # Apply the scaler to X scaled_X = X_scaler.transform(X) car_ind = np.random.randint(0, len(cars)) # Plot an example of raw and scaled features fig = plt.figure(figsize=(12,4)) plt.subplot(131) plt.imshow(mpimg.imread(cars[car_ind])) plt.title('Original Image') plt.subplot(132) plt.plot(X[car_ind]) plt.title('Raw Features') plt.subplot(133) plt.plot(scaled_X[car_ind]) plt.title('Normalized Features') fig.tight_layout() else: print('Your function only returns empty feature vectors...') # + import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 import glob import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler # NOTE: the next import is only valid # for scikit-learn version <= 0.17 # if you are using scikit-learn >= 0.18 then use this: # from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split # Define a function to compute binned color features def bin_spatial(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(img, size).ravel() # Return the feature vector return features # Define a function to compute color histogram features def color_hist(img, nbins=32, bins_range=(0, 256)): # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) # Return the individual histograms, bin_centers and feature vector return hist_features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, cspace='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256)): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file) # apply color conversion if other than 'RGB' if cspace != 'RGB': if cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif cspace == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) elif cspace == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) else: feature_image = np.copy(image) # Apply bin_spatial() to get spatial color features spatial_features = bin_spatial(feature_image, size=spatial_size) # Apply color_hist() also with a color space option now hist_features = color_hist(feature_image, nbins=hist_bins, bins_range=hist_range) # Append the new feature vector to the features list features.append(np.concatenate((spatial_features, hist_features))) # Return list of feature vectors return features # Read in car and non-car images images = glob.glob('*.jpeg') cars = [] notcars = [] for image in images: if 'image' in image or 'extra' in image: notcars.append(image) else: cars.append(image) # TODO play with these values to see how your classifier # performs under different binning scenarios spatial = 32 histbin = 32 car_features = extract_features(cars, cspace='RGB', spatial_size=(spatial, spatial), hist_bins=histbin, hist_range=(0, 256)) notcar_features = extract_features(notcars, cspace='RGB', spatial_size=(spatial, spatial), hist_bins=histbin, hist_range=(0, 256)) # Create an array stack of feature vectors X = np.vstack((car_features, notcar_features)).astype(np.float64) # Define the labels vector y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features)))) # Split up data into randomized training and test sets rand_state = np.random.randint(0, 100) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=rand_state) # Fit a per-column scaler only on the training data X_scaler = StandardScaler().fit(X_train) # Apply the scaler to X_train and X_test X_train = X_scaler.transform(X_train) X_test = X_scaler.transform(X_test) print('Using spatial binning of:',spatial, 'and', histbin,'histogram bins') print('Feature vector length:', len(X_train[0])) # Use a linear SVC svc = LinearSVC() # Check the training time for the SVC t=time.time() svc.fit(X_train, y_train) t2 = time.time() print(round(t2-t, 2), 'Seconds to train SVC...') # Check the score of the SVC print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4)) # Check the prediction time for a single sample t=time.time() n_predict = 10 print('My SVC predicts: ', svc.predict(X_test[0:n_predict])) print('For these',n_predict, 'labels: ', y_test[0:n_predict]) t2 = time.time() print(round(t2-t, 5), 'Seconds to predict', n_predict,'labels with SVC') # + import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 import glob import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from skimage.feature import hog # NOTE: the next import is only valid for scikit-learn version <= 0.17 # for scikit-learn >= 0.18 use: # from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split # Define a function to return HOG features and visualization def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): # Call with two outputs if vis==True if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features, hog_image # Otherwise call with one output else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, cspace='RGB', orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file) # apply color conversion if other than 'RGB' if cspace != 'RGB': if cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif cspace == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) elif cspace == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) elif cspace == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb) else: feature_image = np.copy(image) # Call get_hog_features() with vis=False, feature_vec=True if hog_channel == 'ALL': hog_features = [] for channel in range(feature_image.shape[2]): hog_features.append(get_hog_features(feature_image[:,:,channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True)) hog_features = np.ravel(hog_features) else: hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True) # Append the new feature vector to the features list features.append(hog_features) # Return list of feature vectors return features # Divide up into cars and notcars images = glob.glob('*.jpeg') cars = [] notcars = [] for image in images: if 'image' in image or 'extra' in image: notcars.append(image) else: cars.append(image) # Reduce the sample size because HOG features are slow to compute # The quiz evaluator times out after 13s of CPU time sample_size = 500 cars = cars[0:sample_size] notcars = notcars[0:sample_size] ### TODO: Tweak these parameters and see how the results change. colorspace = 'RGB' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb orient = 9 pix_per_cell = 8 cell_per_block = 2 hog_channel = 0 # Can be 0, 1, 2, or "ALL" t=time.time() car_features = extract_features(cars, cspace=colorspace, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel) notcar_features = extract_features(notcars, cspace=colorspace, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel) t2 = time.time() print(round(t2-t, 2), 'Seconds to extract HOG features...') # Create an array stack of feature vectors X = np.vstack((car_features, notcar_features)).astype(np.float64) # Define the labels vector y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features)))) # Split up data into randomized training and test sets rand_state = np.random.randint(0, 100) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=rand_state) # Fit a per-column scaler X_scaler = StandardScaler().fit(X_train) # Apply the scaler to X X_train = X_scaler.transform(X_train) X_test = X_scaler.transform(X_test) print('Using:',orient,'orientations',pix_per_cell, 'pixels per cell and', cell_per_block,'cells per block') print('Feature vector length:', len(X_train[0])) # Use a linear SVC svc = LinearSVC() # Check the training time for the SVC t=time.time() svc.fit(X_train, y_train) t2 = time.time() print(round(t2-t, 2), 'Seconds to train SVC...') # Check the score of the SVC print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4)) # Check the prediction time for a single sample t=time.time() n_predict = 10 print('My SVC predicts: ', svc.predict(X_test[0:n_predict])) print('For these',n_predict, 'labels: ', y_test[0:n_predict]) t2 = time.time() print(round(t2-t, 5), 'Seconds to predict', n_predict,'labels with SVC') # + import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg image = mpimg.imread('bbox-example-image.jpg') # Here is your draw_boxes function from the previous exercise def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6): # Make a copy of the image imcopy = np.copy(img) # Iterate through the bounding boxes for bbox in bboxes: # Draw a rectangle given bbox coordinates cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick) # Return the image copy with boxes drawn return imcopy # Define a function that takes an image, # start and stop positions in both x and y, # window size (x and y dimensions), # and overlap fraction (for both x and y) def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(64, 64), xy_overlap=(0.5, 0.5)): # If x and/or y start/stop positions not defined, set to image size if x_start_stop[0] == None: x_start_stop[0] = 0 if x_start_stop[1] == None: x_start_stop[1] = img.shape[1] if y_start_stop[0] == None: y_start_stop[0] = 0 if y_start_stop[1] == None: y_start_stop[1] = img.shape[0] # Compute the span of the region to be searched xspan = x_start_stop[1] - x_start_stop[0] yspan = y_start_stop[1] - y_start_stop[0] # Compute the number of pixels per step in x/y nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0])) ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1])) # Compute the number of windows in x/y nx_buffer = np.int(xy_window[0]*(xy_overlap[0])) ny_buffer = np.int(xy_window[1]*(xy_overlap[1])) nx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step) ny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step) # Initialize a list to append window positions to window_list = [] # Loop through finding x and y window positions # Note: you could vectorize this step, but in practice # you'll be considering windows one by one with your # classifier, so looping makes sense for ys in range(ny_windows): for xs in range(nx_windows): # Calculate window position startx = xs*nx_pix_per_step + x_start_stop[0] endx = startx + xy_window[0] starty = ys*ny_pix_per_step + y_start_stop[0] endy = starty + xy_window[1] # Append window position to list window_list.append(((startx, starty), (endx, endy))) # Return the list of windows return window_list windows = slide_window(image, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(128, 128), xy_overlap=(0.5, 0.5)) window_img = draw_boxes(image, windows, color=(0, 0, 255), thick=6) plt.imshow(window_img) # + import matplotlib.image as mpimg import numpy as np import cv2 from skimage.feature import hog # Define a function to return HOG features and visualization def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): # Call with two outputs if vis==True if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), block_norm= 'L2-Hys', cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features, hog_image # Otherwise call with one output else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features # Define a function to compute binned color features def bin_spatial(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(img, size).ravel() # Return the feature vector return features # Define a function to compute color histogram features # NEED TO CHANGE bins_range if reading .png files with mpimg! def color_hist(img, nbins=32, bins_range=(0, 256)): # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) # Return the individual histograms, bin_centers and feature vector return hist_features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, color_space='RGB', spatial_size=(32, 32), hist_bins=32, orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_feat=True, hist_feat=True, hog_feat=True): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: file_features = [] # Read in each one by one image = mpimg.imread(file) # apply color conversion if other than 'RGB' if color_space != 'RGB': if color_space == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif color_space == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif color_space == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) elif color_space == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) elif color_space == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb) else: feature_image = np.copy(image) if spatial_feat == True: spatial_features = bin_spatial(feature_image, size=spatial_size) file_features.append(spatial_features) if hist_feat == True: # Apply color_hist() hist_features = color_hist(feature_image, nbins=hist_bins) file_features.append(hist_features) if hog_feat == True: # Call get_hog_features() with vis=False, feature_vec=True if hog_channel == 'ALL': hog_features = [] for channel in range(feature_image.shape[2]): hog_features.append(get_hog_features(feature_image[:,:,channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True)) hog_features = np.ravel(hog_features) else: hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True) # Append the new feature vector to the features list file_features.append(hog_features) features.append(np.concatenate(file_features)) # Return list of feature vectors return features # Define a function that takes an image, # start and stop positions in both x and y, # window size (x and y dimensions), # and overlap fraction (for both x and y) def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(64, 64), xy_overlap=(0.5, 0.5)): # If x and/or y start/stop positions not defined, set to image size if x_start_stop[0] == None: x_start_stop[0] = 0 if x_start_stop[1] == None: x_start_stop[1] = img.shape[1] if y_start_stop[0] == None: y_start_stop[0] = 0 if y_start_stop[1] == None: y_start_stop[1] = img.shape[0] # Compute the span of the region to be searched xspan = x_start_stop[1] - x_start_stop[0] yspan = y_start_stop[1] - y_start_stop[0] # Compute the number of pixels per step in x/y nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0])) ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1])) # Compute the number of windows in x/y nx_buffer = np.int(xy_window[0]*(xy_overlap[0])) ny_buffer = np.int(xy_window[1]*(xy_overlap[1])) nx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step) ny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step) # Initialize a list to append window positions to window_list = [] # Loop through finding x and y window positions # Note: you could vectorize this step, but in practice # you'll be considering windows one by one with your # classifier, so looping makes sense for ys in range(ny_windows): for xs in range(nx_windows): # Calculate window position startx = xs*nx_pix_per_step + x_start_stop[0] endx = startx + xy_window[0] starty = ys*ny_pix_per_step + y_start_stop[0] endy = starty + xy_window[1] # Append window position to list window_list.append(((startx, starty), (endx, endy))) # Return the list of windows return window_list # Define a function to draw bounding boxes def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6): # Make a copy of the image imcopy = np.copy(img) # Iterate through the bounding boxes for bbox in bboxes: # Draw a rectangle given bbox coordinates cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick) # Return the image copy with boxes drawn return imcopy # + import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 import glob import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from skimage.feature import hog from lesson_functions import * # NOTE: the next import is only valid for scikit-learn version <= 0.17 # for scikit-learn >= 0.18 use: # from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split # Define a function to extract features from a single image window # This function is very similar to extract_features() # just for a single image rather than list of images def single_img_features(img, color_space='RGB', spatial_size=(32, 32), hist_bins=32, orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_feat=True, hist_feat=True, hog_feat=True): #1) Define an empty list to receive features img_features = [] #2) Apply color conversion if other than 'RGB' if color_space != 'RGB': if color_space == 'HSV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) elif color_space == 'LUV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV) elif color_space == 'HLS': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) elif color_space == 'YUV': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV) elif color_space == 'YCrCb': feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb) else: feature_image = np.copy(img) #3) Compute spatial features if flag is set if spatial_feat == True: spatial_features = bin_spatial(feature_image, size=spatial_size) #4) Append features to list img_features.append(spatial_features) #5) Compute histogram features if flag is set if hist_feat == True: hist_features = color_hist(feature_image, nbins=hist_bins) #6) Append features to list img_features.append(hist_features) #7) Compute HOG features if flag is set if hog_feat == True: if hog_channel == 'ALL': hog_features = [] for channel in range(feature_image.shape[2]): hog_features.extend(get_hog_features(feature_image[:,:,channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True)) else: hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True) #8) Append features to list img_features.append(hog_features) #9) Return concatenated array of features return np.concatenate(img_features) # Define a function you will pass an image # and the list of windows to be searched (output of slide_windows()) def search_windows(img, windows, clf, scaler, color_space='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256), orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_feat=True, hist_feat=True, hog_feat=True): #1) Create an empty list to receive positive detection windows on_windows = [] #2) Iterate over all windows in the list for window in windows: #3) Extract the test window from original image test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64)) #4) Extract features for that window using single_img_features() features = single_img_features(test_img, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) #5) Scale extracted features to be fed to classifier test_features = scaler.transform(np.array(features).reshape(1, -1)) #6) Predict using your classifier prediction = clf.predict(test_features) #7) If positive (prediction == 1) then save the window if prediction == 1: on_windows.append(window) #8) Return windows for positive detections return on_windows # Read in cars and notcars images = glob.glob('*.jpeg') cars = [] notcars = [] for image in images: if 'image' in image or 'extra' in image: notcars.append(image) else: cars.append(image) # Reduce the sample size because # The quiz evaluator times out after 13s of CPU time sample_size = 500 cars = cars[0:sample_size] notcars = notcars[0:sample_size] ### TODO: Tweak these parameters and see how the results change. color_space = 'RGB' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb orient = 9 # HOG orientations pix_per_cell = 8 # HOG pixels per cell cell_per_block = 2 # HOG cells per block hog_channel = 0 # Can be 0, 1, 2, or "ALL" spatial_size = (16, 16) # Spatial binning dimensions hist_bins = 16 # Number of histogram bins spatial_feat = True # Spatial features on or off hist_feat = True # Histogram features on or off hog_feat = True # HOG features on or off y_start_stop = [None, None] # Min and max in y to search in slide_window() car_features = extract_features(cars, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) notcar_features = extract_features(notcars, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) # Create an array stack of feature vectors X = np.vstack((car_features, notcar_features)).astype(np.float64) # Define the labels vector y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features)))) # Split up data into randomized training and test sets rand_state = np.random.randint(0, 100) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=rand_state) # Fit a per-column scaler X_scaler = StandardScaler().fit(X_train) # Apply the scaler to X X_train = X_scaler.transform(X_train) X_test = X_scaler.transform(X_test) print('Using:',orient,'orientations',pix_per_cell, 'pixels per cell and', cell_per_block,'cells per block') print('Feature vector length:', len(X_train[0])) # Use a linear SVC svc = LinearSVC() # Check the training time for the SVC t=time.time() svc.fit(X_train, y_train) t2 = time.time() print(round(t2-t, 2), 'Seconds to train SVC...') # Check the score of the SVC print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4)) # Check the prediction time for a single sample t=time.time() image = mpimg.imread('bbox-example-image.jpg') draw_image = np.copy(image) # Uncomment the following line if you extracted training # data from .png images (scaled 0 to 1 by mpimg) and the # image you are searching is a .jpg (scaled 0 to 255) #image = image.astype(np.float32)/255 windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop, xy_window=(96, 96), xy_overlap=(0.5, 0.5)) hot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) window_img = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6) plt.imshow(window_img) # + import numpy as np import cv2 from skimage.feature import hog def convert_color(img, conv='RGB2YCrCb'): if conv == 'RGB2YCrCb': return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb) if conv == 'BGR2YCrCb': return cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) if conv == 'RGB2LUV': return cv2.cvtColor(img, cv2.COLOR_RGB2LUV) def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): # Call with two outputs if vis==True if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=False, visualise=vis, feature_vector=feature_vec) return features, hog_image # Otherwise call with one output else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), block_norm= 'L2-Hys', transform_sqrt=False, visualise=vis, feature_vector=feature_vec) return features def bin_spatial(img, size=(32, 32)): color1 = cv2.resize(img[:,:,0], size).ravel() color2 = cv2.resize(img[:,:,1], size).ravel() color3 = cv2.resize(img[:,:,2], size).ravel() return np.hstack((color1, color2, color3)) def color_hist(img, nbins=32): #bins_range=(0, 256) # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins) channel2_hist = np.histogram(img[:,:,1], bins=nbins) channel3_hist = np.histogram(img[:,:,2], bins=nbins) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) # Return the individual histograms, bin_centers and feature vector return hist_features # + import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import pickle import cv2 from lesson_functions import * # load a pe-trained svc model from a serialized (pickle) file dist_pickle = pickle.load( open("svc_pickle.p", "rb" ) ) # get attributes of our svc object svc = dist_pickle["svc"] X_scaler = dist_pickle["scaler"] orient = dist_pickle["orient"] pix_per_cell = dist_pickle["pix_per_cell"] cell_per_block = dist_pickle["cell_per_block"] spatial_size = dist_pickle["spatial_size"] hist_bins = dist_pickle["hist_bins"] img = mpimg.imread('test_image.jpg') # Define a single function that can extract features using hog sub-sampling and make predictions def find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins): draw_img = np.copy(img) img = img.astype(np.float32)/255 img_tosearch = img[ystart:ystop,:,:] ctrans_tosearch = convert_color(img_tosearch, conv='RGB2YCrCb') if scale != 1: imshape = ctrans_tosearch.shape ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale))) ch1 = ctrans_tosearch[:,:,0] ch2 = ctrans_tosearch[:,:,1] ch3 = ctrans_tosearch[:,:,2] # Define blocks and steps as above nxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1 nyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1 nfeat_per_block = orient*cell_per_block**2 # 64 was the orginal sampling rate, with 8 cells and 8 pix per cell window = 64 nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1 cells_per_step = 2 # Instead of overlap, define how many cells to step nxsteps = (nxblocks - nblocks_per_window) // cells_per_step + 1 nysteps = (nyblocks - nblocks_per_window) // cells_per_step + 1 # Compute individual channel HOG features for the entire image hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False) hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False) hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False) for xb in range(nxsteps): for yb in range(nysteps): ypos = yb*cells_per_step xpos = xb*cells_per_step # Extract HOG for this patch hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() hog_feat2 = hog2[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() hog_feat3 = hog3[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3)) xleft = xpos*pix_per_cell ytop = ypos*pix_per_cell # Extract the image patch subimg = cv2.resize(ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], (64,64)) # Get color features spatial_features = bin_spatial(subimg, size=spatial_size) hist_features = color_hist(subimg, nbins=hist_bins) # Scale features and make a prediction test_features = X_scaler.transform(np.hstack((spatial_features, hist_features, hog_features)).reshape(1, -1)) #test_features = X_scaler.transform(np.hstack((shape_feat, hist_feat)).reshape(1, -1)) test_prediction = svc.predict(test_features) if test_prediction == 1: xbox_left = np.int(xleft*scale) ytop_draw = np.int(ytop*scale) win_draw = np.int(window*scale) cv2.rectangle(draw_img,(xbox_left, ytop_draw+ystart),(xbox_left+win_draw,ytop_draw+win_draw+ystart),(0,0,255),6) return draw_img ystart = 400 ystop = 656 scale = 1.5 out_img = find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins) plt.imshow(out_img) # + import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import pickle import cv2 from scipy.ndimage.measurements import label # Read in a pickle file with bboxes saved # Each item in the "all_bboxes" list will contain a # list of boxes for one of the images shown above box_list = pickle.load( open( "bbox_pickle.p", "rb" )) # Read in image similar to one shown above image = mpimg.imread('test_image.jpg') heat = np.zeros_like(image[:,:,0]).astype(np.float) def add_heat(heatmap, bbox_list): # Iterate through list of bboxes for box in bbox_list: # Add += 1 for all pixels inside each bbox # Assuming each "box" takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 # Return updated heatmap return heatmap# Iterate through list of bboxes def apply_threshold(heatmap, threshold): # Zero out pixels below the threshold heatmap[heatmap <= threshold] = 0 # Return thresholded map return heatmap def draw_labeled_bboxes(img, labels): # Iterate through all detected cars for car_number in range(1, labels[1]+1): # Find pixels with each car_number label value nonzero = (labels[0] == car_number).nonzero() # Identify x and y values of those pixels nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Define a bounding box based on min/max x and y bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy))) # Draw the box on the image cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6) # Return the image return img # Add heat to each box in box list heat = add_heat(heat,box_list) # Apply threshold to help remove false positives heat = apply_threshold(heat,1) # Visualize the heatmap when displaying heatmap = np.clip(heat, 0, 255) # Find final boxes from heatmap using label function labels = label(heatmap) draw_img = draw_labeled_bboxes(np.copy(image), labels) fig = plt.figure() plt.subplot(121) plt.imshow(draw_img) plt.title('Car Positions') plt.subplot(122) plt.imshow(heatmap, cmap='hot') plt.title('Heat Map') fig.tight_layout()
naive_bayes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from __future__ import print_function, unicode_literals, absolute_import, division import sys import numpy as np import matplotlib matplotlib.rcParams["image.interpolation"] = None import matplotlib.pyplot as plt # %matplotlib inline # %config InlineBackend.figure_format = 'retina' from glob import glob from tqdm import tqdm from tifffile import imread from csbdeep.utils import Path, normalize from stardist import fill_label_holes, random_label_cmap, calculate_extents, gputools_available from stardist import Rays_GoldenSpiral from stardist.matching import matching, matching_dataset from stardist.models import Config3D, StarDist3D, StarDistData3D np.random.seed(42) lbl_cmap = random_label_cmap() # - # # Data # # We assume that data has already been downloaded via notebook [1_data.ipynb](1_data.ipynb). # # <div class="alert alert-block alert-info"> # Training data (for input `X` with associated label masks `Y`) can be provided via lists of numpy arrays, where each image can have a different size. Alternatively, a single numpy array can also be used if all images have the same size. # Input images can either be three-dimensional (single-channel) or four-dimensional (multi-channel) arrays, where the channel axis comes last. Label images need to be integer-valued. # </div> X = sorted(glob('data/train/images/*.tif')) Y = sorted(glob('data/train/masks/*.tif')) assert all(Path(x).name==Path(y).name for x,y in zip(X,Y)) X = list(map(imread,X)) Y = list(map(imread,Y)) n_channel = 1 if X[0].ndim == 3 else X[0].shape[-1] # Normalize images and fill small label holes. # + axis_norm = (0,1,2) # normalize channels independently # axis_norm = (0,1,2,3) # normalize channels jointly if n_channel > 1: print("Normalizing image channels %s." % ('jointly' if axis_norm is None or 3 in axis_norm else 'independently')) sys.stdout.flush() X = [normalize(x,1,99.8,axis=axis_norm) for x in tqdm(X)] Y = [fill_label_holes(y) for y in tqdm(Y)] # - # Split into train and validation datasets. assert len(X) > 1, "not enough training data" rng = np.random.RandomState(42) ind = rng.permutation(len(X)) n_val = max(1, int(round(0.15 * len(ind)))) ind_train, ind_val = ind[:-n_val], ind[-n_val:] X_val, Y_val = [X[i] for i in ind_val] , [Y[i] for i in ind_val] X_trn, Y_trn = [X[i] for i in ind_train], [Y[i] for i in ind_train] print('number of images: %3d' % len(X)) print('- training: %3d' % len(X_trn)) print('- validation: %3d' % len(X_val)) # Training data consists of pairs of input image and label instances. def plot_img_label(img, lbl, img_title="image (XY slice)", lbl_title="label (XY slice)", z=None, **kwargs): if z is None: z = img.shape[0] // 2 fig, (ai,al) = plt.subplots(1,2, figsize=(12,5), gridspec_kw=dict(width_ratios=(1.25,1))) im = ai.imshow(img[z], cmap='gray', clim=(0,1)) ai.set_title(img_title) fig.colorbar(im, ax=ai) al.imshow(lbl[z], cmap=lbl_cmap) al.set_title(lbl_title) plt.tight_layout() i = 0 img, lbl = X[i], Y[i] assert img.ndim in (3,4) img = img if img.ndim==3 else img[...,:3] plot_img_label(img,lbl) None; # # Configuration # # A `StarDist3D` model is specified via a `Config3D` object. print(Config3D.__doc__) extents = calculate_extents(Y) anisotropy = tuple(np.max(extents) / extents) print('empirical anisotropy of labeled objects = %s' % str(anisotropy)) # + # 96 is a good default choice (see 1_data.ipynb) n_rays = 96 # Use OpenCL-based computations for data generator during training (requires 'gputools') use_gpu = False and gputools_available() # Predict on subsampled grid for increased efficiency and larger field of view grid = tuple(1 if a > 1.5 else 2 for a in anisotropy) # Use rays on a Fibonacci lattice adjusted for measured anisotropy of the training data rays = Rays_GoldenSpiral(n_rays, anisotropy=anisotropy) conf = Config3D ( rays = rays, grid = grid, anisotropy = anisotropy, use_gpu = use_gpu, n_channel_in = n_channel, # adjust for your data below (make patch size as large as possible) train_patch_size = (48,96,96), train_batch_size = 2, ) print(conf) vars(conf) # - if use_gpu: from csbdeep.utils.tf import limit_gpu_memory # adjust as necessary: limit GPU memory to be used by TensorFlow to leave some to OpenCL-based computations limit_gpu_memory(0.8) # alternatively, try this: # limit_gpu_memory(None, allow_growth=True) # **Note:** The trained `StarDist3D` model will *not* predict completed shapes for partially visible objects at the image boundary. model = StarDist3D(conf, name='stardist', basedir='models') # Check if the neural network has a large enough field of view to see up to the boundary of most objects. median_size = calculate_extents(Y, np.median) fov = np.array(model._axes_tile_overlap('ZYX')) print(f"median object size: {median_size}") print(f"network field of view : {fov}") if any(median_size > fov): print("WARNING: median object size larger than field of view of the neural network.") # # Data Augmentation # You can define a function/callable that applies augmentation to each batch of the data generator. # We here use an `augmenter` that applies random rotations, flips, and intensity changes, which are typically sensible for (3D) microscopy images (but you can disable augmentation by setting `augmenter = None`). # + def random_fliprot(img, mask, axis=None): if axis is None: axis = tuple(range(mask.ndim)) axis = tuple(axis) assert img.ndim>=mask.ndim perm = tuple(np.random.permutation(axis)) transpose_axis = np.arange(mask.ndim) for a, p in zip(axis, perm): transpose_axis[a] = p transpose_axis = tuple(transpose_axis) img = img.transpose(transpose_axis + tuple(range(mask.ndim, img.ndim))) mask = mask.transpose(transpose_axis) for ax in axis: if np.random.rand() > 0.5: img = np.flip(img, axis=ax) mask = np.flip(mask, axis=ax) return img, mask def random_intensity_change(img): img = img*np.random.uniform(0.6,2) + np.random.uniform(-0.2,0.2) return img def augmenter(x, y): """Augmentation of a single input/label image pair. x is an input image y is the corresponding ground-truth label image """ # Note that we only use fliprots along axis=(1,2), i.e. the yx axis # as 3D microscopy acquisitions are usually not axially symmetric x, y = random_fliprot(x, y, axis=(1,2)) x = random_intensity_change(x) return x, y # - # plot some augmented examples img, lbl = X[0],Y[0] plot_img_label(img, lbl) for _ in range(3): img_aug, lbl_aug = augmenter(img,lbl) plot_img_label(img_aug, lbl_aug, img_title="image augmented (XY slice)", lbl_title="label augmented (XY slice)") # # Training # We recommend to monitor the progress during training with [TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard). You can start it in the shell from the current working directory like this: # # $ tensorboard --logdir=. # # Then connect to [http://localhost:6006/](http://localhost:6006/) with your browser. # # + quick_demo = True if quick_demo: print ( "NOTE: This is only for a quick demonstration!\n" " Please set the variable 'quick_demo = False' for proper (long) training.", file=sys.stderr, flush=True ) model.train(X_trn, Y_trn, validation_data=(X_val,Y_val), augmenter=augmenter, epochs=2, steps_per_epoch=5) print("====> Stopping training and loading previously trained demo model from disk.", file=sys.stderr, flush=True) model = StarDist3D.from_pretrained('3D_demo') else: model.train(X_trn, Y_trn, validation_data=(X_val,Y_val), augmenter=augmenter) None; # - # # Threshold optimization # While the default values for the probability and non-maximum suppression thresholds already yield good results in many cases, we still recommend to adapt the thresholds to your data. The optimized threshold values are saved to disk and will be automatically loaded with the model. if quick_demo: # only use a single validation image for demo model.optimize_thresholds(X_val[:1], Y_val[:1]) else: model.optimize_thresholds(X_val, Y_val) # # Evaluation and Detection Performance # Besides the losses and metrics during training, we can also quantitatively evaluate the actual detection/segmentation performance on the validation data by considering objects in the ground truth to be correctly matched if there are predicted objects with overlap (here [intersection over union (IoU)](https://en.wikipedia.org/wiki/Jaccard_index)) beyond a chosen IoU threshold $\tau$. # # The corresponding matching statistics (average overlap, accuracy, recall, precision, etc.) are typically of greater practical relevance than the losses/metrics computed during training (but harder to formulate as a loss function). # The value of $\tau$ can be between 0 (even slightly overlapping objects count as correctly predicted) and 1 (only pixel-perfectly overlapping objects count) and which $\tau$ to use depends on the needed segmentation precision/application. # # Please see `help(matching)` for definitions of the abbreviations used in the evaluation below and see the Wikipedia page on [Sensitivity and specificity](https://en.wikipedia.org/wiki/Sensitivity_and_specificity) for further details. # + # help(matching) # - # First predict the labels for all validation images: Y_val_pred = [model.predict_instances(x, n_tiles=model._guess_n_tiles(x), show_tile_progress=False)[0] for x in tqdm(X_val)] # Plot a GT/prediction example plot_img_label(X_val[0],Y_val[0], lbl_title="label GT (XY slice)") plot_img_label(X_val[0],Y_val_pred[0], lbl_title="label Pred (XY slice)") # Choose several IoU thresholds $\tau$ that might be of interest and for each compute matching statistics for the validation data. taus = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] stats = [matching_dataset(Y_val, Y_val_pred, thresh=t, show_progress=False) for t in tqdm(taus)] # Example: Print all available matching statistics for $\tau=0.7$ stats[taus.index(0.7)] # Plot the matching statistics and the number of true/false positives/negatives as a function of the IoU threshold $\tau$. # + fig, (ax1,ax2) = plt.subplots(1,2, figsize=(15,5)) for m in ('precision', 'recall', 'accuracy', 'f1', 'mean_true_score', 'mean_matched_score', 'panoptic_quality'): ax1.plot(taus, [s._asdict()[m] for s in stats], '.-', lw=2, label=m) ax1.set_xlabel(r'IoU threshold $\tau$') ax1.set_ylabel('Metric value') ax1.grid() ax1.legend() for m in ('fp', 'tp', 'fn'): ax2.plot(taus, [s._asdict()[m] for s in stats], '.-', lw=2, label=m) ax2.set_xlabel(r'IoU threshold $\tau$') ax2.set_ylabel('Number #') ax2.grid() ax2.legend();
examples/3D/2_training.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Training with multiple GPUs from scratch # # This tutorial shows how we can increase performance by distributing training across multiple GPUs. # So, as you might expect, running this tutorial requires at least 2 GPUs. # And these days multi-GPU machines are actually quite common. # The following figure depicts 4 GPUs on a single machine and connected to the CPU through a PCIe switch. # # ![](../img/multi-gpu.svg) # # If an NVIDIA driver is installed on our machine, # then we can check how many GPUs are available by running the command `nvidia-smi`. # !nvidia-smi # We want to use all of the GPUs on together for the purpose of significantly speeding up training (in terms of wall clock). # Remember that CPUs and GPUs each can have multiple cores. # CPUs on a laptop might have 2 or 4 cores, and on a server might have up to 16 or 32 cores. # GPUs tend to have many more cores - an NVIDIA K80 GPU has 4992 - but run at slower clock speeds. # Exploiting the parallelism across the GPU cores is how GPUs get their speed advantage in the first place. # # As compared to the single CPU or single GPU setting where all the cores are typically used by default, # parallelism across devices is a little more complicated. # That's because most layers of a neural network can only run on a single device. # So, in order to parallelize across devices, we need to do a little extra. # Therefore, we need to do some additional work to partition a workload across multiple GPUs. # This can be done in a few ways. # # ## Data Parallelism # # For deep learning, data parallelism is by far the most widely used approach for partitioning workloads. # It works like this: Assume that we have *k* GPUs. We split the examples in a data batch into *k* parts, # and send each part to a different GPUs which then computes the gradient that part of the batch. # Finally, we collect the gradients from each of the GPUs and sum them together before updating the weights. # # The following pseudo-code shows how to train one data batch on *k* GPUs. # # # ``` # def train_batch(data, k): # split data into k parts # for i = 1, ..., k: # run in parallel # compute grad_i w.r.t. weight_i using data_i on the i-th GPU # grad = grad_1 + ... + grad_k # for i = 1, ..., k: # run in parallel # copy grad to i-th GPU # update weight_i by using grad # ``` # # Next we will present how to implement this algorithm from scratch. # # # ## Automatic Parallelization # # We first demonstrate how to run workloads in parallel. # Writing parallel code in Python in non-trivial, but fortunately, # MXNet is able to automatically parallelize the workloads. # Two technologies help to achieve this goal. # # First, workloads, such as `nd.dot` are pushed into the backend engine for *lazy evaluation*. # That is, Python merely pushes the workload `nd.dot` and returns immediately # without waiting for the computation to be finished. # We keep pushing until the results need to be copied out from MXNet, # such as `print(x)` or are converted into numpy by `x.asnumpy()`. # At that time, the Python thread is blocked until the results are ready. # + from mxnet import nd from time import time start = time() x = nd.random_uniform(shape=(2000,2000)) y = nd.dot(x, x) print('=== workloads are pushed into the backend engine ===\n%f sec' % (time() - start)) z = y.asnumpy() print('=== workloads are finished ===\n%f sec' % (time() - start)) # - # Second, MXNet depends on a powerful scheduling algorithm that analyzes the dependencies of the pushed workloads. # This scheduler checks to see if two workloads are independent of each other. # If they are, then the engine may run them in parallel. # If a workload depend on results that have not yet been computed, it will be made to wait until its inputs are ready. # # For example, if we call three operators: # # ``` # a = nd.random_uniform(...) # b = nd.random_uniform(...) # c = a + b # ``` # # Then the computation for `a` and `b` may run in parallel, # while `c` cannot be computed until both `a` and `b` are ready. # # The following code shows that the engine effectively parallelizes the `dot` operations on two GPUs: # + from mxnet import gpu def run(x): """push 10 matrix-matrix multiplications""" return [nd.dot(x,x) for i in range(10)] def wait(x): """explicitly wait until all results are ready""" for y in x: y.wait_to_read() x0 = nd.random_uniform(shape=(4000, 4000), ctx=gpu(0)) x1 = x0.copyto(gpu(1)) print('=== Run on GPU 0 and 1 in sequential ===') start = time() wait(run(x0)) wait(run(x1)) print('time: %f sec' %(time() - start)) print('=== Run on GPU 0 and 1 in parallel ===') start = time() y0 = run(x0) y1 = run(x1) wait(y0) wait(y1) print('time: %f sec' %(time() - start)) # + from mxnet import cpu def copy(x, ctx): """copy data to a device""" return [y.copyto(ctx) for y in x] print('=== Run on GPU 0 and then copy results to CPU in sequential ===') start = time() y0 = run(x0) wait(y0) z0 = copy(y0, cpu()) wait(z0) print(time() - start) print('=== Run and copy in parallel ===') start = time() y0 = run(x0) z0 = copy(y0, cpu()) wait(z0) print(time() - start) # - # ## Define model and updater # # We will use the convolutional neural networks and plain SGD introduced in [cnn-scratch]() as an example workload. # + from mxnet import gluon # initialize parameters scale = .01 W1 = nd.random_normal(shape=(20,1,3,3))*scale b1 = nd.zeros(shape=20) W2 = nd.random_normal(shape=(50,20,5,5))*scale b2 = nd.zeros(shape=50) W3 = nd.random_normal(shape=(800,128))*scale b3 = nd.zeros(shape=128) W4 = nd.random_normal(shape=(128,10))*scale b4 = nd.zeros(shape=10) params = [W1, b1, W2, b2, W3, b3, W4, b4] # network and loss def lenet(X, params): # first conv h1_conv = nd.Convolution(data=X, weight=params[0], bias=params[1], kernel=(3,3), num_filter=20) h1_activation = nd.relu(h1_conv) h1 = nd.Pooling(data=h1_activation, pool_type="max", kernel=(2,2), stride=(2,2)) # second conv h2_conv = nd.Convolution(data=h1, weight=params[2], bias=params[3], kernel=(5,5), num_filter=50) h2_activation = nd.relu(h2_conv) h2 = nd.Pooling(data=h2_activation, pool_type="max", kernel=(2,2), stride=(2,2)) h2 = nd.flatten(h2) # first fullc h3_linear = nd.dot(h2, params[4]) + params[5] h3 = nd.relu(h3_linear) # second fullc yhat = nd.dot(h3, params[6]) + params[7] return yhat loss = gluon.loss.SoftmaxCrossEntropyLoss() # plain SGD def SGD(params, lr): for p in params: p[:] = p - lr * p.grad # - # ## Utility functions to synchronize data across GPUs # The following function copies the parameters into a particular GPU and initializes the gradients. # + def get_params(params, ctx): new_params = [p.copyto(ctx) for p in params] for p in new_params: p.attach_grad() return new_params new_params = get_params(params, gpu(0)) print('=== copy b1 to GPU(0) ===\nweight = {}\ngrad = {}'.format( new_params[1], new_params[1].grad)) # - # Given a list of data that spans multiple GPUs, we then define a function to sum the data # and broadcast the results to each GPU. # + def allreduce(data): # sum on data[0].context, and then broadcast for i in range(1, len(data)): data[0][:] += data[i].copyto(data[0].context) for i in range(1, len(data)): data[0].copyto(data[i]) data = [nd.ones((1,2), ctx=gpu(i))*(i+1) for i in range(2)] print("=== before allreduce ===\n {}".format(data)) allreduce(data) print("\n=== after allreduce ===\n {}".format(data)) # - # Given a data batch, we define a function that splits this batch and copies each part into the corresponding GPU. # + def split_and_load(data, ctx): n, k = data.shape[0], len(ctx) assert (n//k)*k == n, '# examples is not divided by # devices' idx = list(range(0, n+1, n//k)) return [data[idx[i]:idx[i+1]].as_in_context(ctx[i]) for i in range(k)] batch = nd.arange(16).reshape((4,4)) print('=== original data ==={}'.format(batch)) ctx = [gpu(0), gpu(1)] splitted = split_and_load(batch, ctx) print('\n=== splitted into {} ==={}\n{}'.format(ctx, splitted[0], splitted[1])) # - # ## Train and inference one data batch # # Now we are ready to implement how to train one data batch with data parallelism. def train_batch(batch, params, ctx, lr): # split the data batch and load them on GPUs data = split_and_load(batch.data[0], ctx) label = split_and_load(batch.label[0], ctx) # run forward on each GPU with gluon.autograd.record(): losses = [loss(lenet(X, W), Y) for X, Y, W in zip(data, label, params)] # run backward on each gpu for l in losses: l.backward() # aggregate gradient over GPUs for i in range(len(params[0])): allreduce([params[c][i].grad for c in range(len(ctx))]) # update parameters with SGD on each GPU for p in params: SGD(p, lr/batch.data[0].shape[0]) # For inference, we simply let it run on the first GPU. We leave a data parallelism implementation as an exercise. def valid_batch(batch, params, ctx): data = batch.data[0].as_in_context(ctx[0]) pred = nd.argmax(lenet(data, params[0]), axis=1) return nd.sum(pred == batch.label[0].as_in_context(ctx[0])).asscalar() # ## Put all things together # # Define the program that trains and validates the model on MNIST. # + from mxnet.test_utils import get_mnist from mxnet.io import NDArrayIter def run(num_gpus, batch_size, lr): # the list of GPUs will be used ctx = [gpu(i) for i in range(num_gpus)] print('Running on {}'.format(ctx)) # data iterator mnist = get_mnist() train_data = NDArrayIter(mnist["train_data"], mnist["train_label"], batch_size) valid_data = NDArrayIter(mnist["test_data"], mnist["test_label"], batch_size) print('Batch size is {}'.format(batch_size)) # copy parameters to all GPUs dev_params = [get_params(params, c) for c in ctx] for epoch in range(5): # train start = time() train_data.reset() for batch in train_data: train_batch(batch, dev_params, ctx, lr) nd.waitall() # wait all computations are finished to benchmark the time print('Epoch %d, training time = %.1f sec'%(epoch, time()-start)) # validating valid_data.reset() correct, num = 0.0, 0.0 for batch in valid_data: correct += valid_batch(batch, dev_params, ctx) num += batch.data[0].shape[0] print(' validation accuracy = %.4f'%(correct/num)) # - # First run on a single GPU with batch size 64. run(1, 64, 0.3) # Running on multiple GPUs, we often want to increase the batch size so that each GPU still gets a large enough batch size for good computation performance. (A larger batch size sometimes slows down the convergence, we often want to increases the learning rate as well but in this case we'll keep it same. Feel free to try higher learning rates.) run(2, 128, 0.3) # ## Conclusion # # We have shown how to implement data parallelism on a deep neural network from scratch. Thanks to the auto-parallelism, we only need to write serial codes while the engine is able to parallelize them on multiple GPUs. # ## Next # [Training with multiple GPUs with gluon](../chapter07_distributed-learning/multiple-gpus-gluon.ipynb) # For whinges or inquiries, [open an issue on GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)
chapter07_distributed-learning/multiple-gpus-scratch.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="DVmCTrbwNYh3" #@title Install efs # !pip install git+https://github.com/cloudwalk/simple-evolutionary-feature-search.git # + id="XM9Ck-_XNjzg" #@title Import efs import evfs from evfs import efs # + id="3-8UbPpQSGSu" #@title Installing the database # ! wget https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data # + id="D8JFRHdAl4ba" #@title Import the database import pandas as pd dataset = pd.read_csv('spambase.data', header=None) # + id="e5ngxkJOmBbD" #@title Intialize Features in the database dataset.columns=['word_freq_make', 'word_freq_address', 'word_freq_all', 'word_freq_3d', 'word_freq_our', 'word_freq_over', 'word_freq_remove', 'word_freq_internet', 'word_freq_order', 'word_freq_mail', 'word_freq_receive', 'word_freq_will', 'word_freq_people', 'word_freq_report', 'word_freq_addresses', 'word_freq_free', 'word_freq_business', 'word_freq_email', 'word_freq_you', 'word_freq_credit', 'word_freq_your', 'word_freq_font', 'word_freq_000', 'word_freq_money', 'word_freq_hp', 'word_freq_hpl', 'word_freq_george', 'word_freq_650', 'word_freq_lab', 'word_freq_labs', 'word_freq_telnet', 'word_freq_857', 'word_freq_data', 'word_freq_415', 'word_freq_85', 'word_freq_technology', 'word_freq_1999', 'word_freq_parts', 'word_freq_pm', 'word_freq_direct', 'word_freq_cs', 'word_freq_meeting', 'word_freq_original', 'word_freq_project', 'word_freq_re', 'word_freq_edu', 'word_freq_table', 'word_freq_conference', 'char_freq_%3B', 'char_freq_%28', 'char_freq_%5B', 'char_freq_%21', 'char_freq_%24', 'char_freq_%23', 'capital_run_length_average', 'capital_run_length_longest', 'capital_run_length_total', 'class'] labels=dataset["class"] dataset=dataset.drop(["class"],axis=1) # + id="1bPpQL8OogTU" #@title Clean up the database from sklearn.model_selection import train_test_split features=list(dataset.columns) for string in features: dataset[string]=dataset[string].fillna(dataset[string].mean()) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_values = scaler.fit_transform(dataset) dataset.loc[:,:] = scaled_values x_train,x_test,y_train,y_test= train_test_split(dataset,labels.values,test_size=0.34,shuffle=True,random_state=0) # + id="b_lxECI5m4pU" #@title Define eval function from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import accuracy_score class evalFunction(): def __init__(self,features): self.features=features #can_be_changed def func(self,x_train,x_test,y_train,y_test,gen): testModel=AdaBoostClassifier().fit(x_train[self.features],y_train) pred=testModel.predict(x_test[self.features]) scores=accuracy_score(y_test,pred) return scores # + cellView="form" id="e74SVqAToGp3" #@title Define variables variables=[x_train,x_test,y_train,y_test] # + cellView="form" id="6h-Oe0v0onyV" #@title Intialize EFS test=efs.EvolutionaryFeatureSelector(2,features,"spambaseResults",6) # + cellView="form" id="cZgMpJDHo0x9" # %%time #@title Run the EFS bestFeature,winningValue,tracking,vectorFeature,listOfFeatures=test.select_features(variables,evalFunction)
how_to_use.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import sys sys.path.append("../") from chic import Structure import networkx as nx import matplotlib.pyplot as plt from IPython.display import HTML # - # --- # # Example 1: coarse-graining ZIF-8 # # By way of a coarse-graining example, we take the prototypical ZIF-8 structure (CCDC code: VELVOY), average the proton disorder found for the methyl-group protons, and remove the oxygen atoms in the pore. We then `reduce()` the structure to its fundamental building units (Zn A sites and methyl-imidazolate B sites), `coarse_grain()` the structure by placing placeholder atoms at the centroid of each of the B site organic ligands. # # Throughout we visualise the crystal structures using ASE's write HTML functionality and using `IPython.display.HTML`. Note this does not account for periodic boundary conditions such that all molecules are "completed", but it serves well for illustrative purposes. Alternatively, you could output the current full-atomistic structure using `Structure.dump(fileName)` and then use your own CIF visualisation software. # read in CIF and visualise the unit cell. Note the H-disorder and the prescence of non-framework oxygens. zif8 = Structure("VELVOY.cif") HTML(zif8.atoms_html()) # --- # ## `Structure.repair_disorder()` # # From the above image, we see the methyl group protons are disordered and there are oxygen atoms in the pores. We "repair" this disorder using the `pairwiseElement` and `loneElement` arguements of the `Structure.repair_disorder()` method. For each of these, we specify the element that we are targetting by its chemical symbol, and give cut-off distances. # # For `pairwiseElement` the cut-off can either be a single `float` which specifies the upper limit to consider two atoms of the given element as a disordered pair (lower limit defaults to zero). Alternatively, a `tuple` of `floats` may be given to specify the upper and lower bounds. # In this ZIF-8 example, the methyl-group protons are disorderd, and there # are oxygen atoms in the pores. Both of these are "solved" with the following # two functions. zif8.repair_disorder("pairwiseElement", element="H", cutoff=(0,0.8)) zif8.repair_disorder("loneElement", element="O", cutoff=2.0) HTML(zif8.atoms_html()) # --- # ## `Structure.reduce()` # # Next, we identify the buidling units in the structure. We do this by calling the `Structure.reduce()` method. In this example, the structure is relatively "simple" and so the default parameters are suffice. However, for more complicated MOF structures, more care may be needed to be taken to ensure the building units are determined correctly. The following parameters may be tuned for this purpose: # # * **skipSites** (default=None) # # Skip the cluster-crawl algorithm for a given site-type, and instead iterate through all atoms within this site-type and add them as individual building units. Note, this is the expected behaviour for "single node" representations. # # * **intraWeight** (default=0.2) # # The CrystalNN neighour searching algorithm gives relative weightings of proposed neighbour atoms. intraWeight sets the minimum weight for a given bond required for it to be considered a bond within the same building unit. # # * **interWeight** (default=0.4) # # As before, but intraWeight sets the minimum weight required to consider an atom to be a bond between a building unit atom and an atom of another site-type. # # * **intraBond** (default=None) # # Maximum bond length between two atoms for it to be considered a bond between a building unit atom and an atom of another site-type. # # * **interBond** (default=None) # # Maximum bond length between two atoms for it to be considered a bond between two building units. # # * **cLimit** (default=None) # # Maximum connectivity allowed for each site-type (list of ints). If more connections are found than than permitted by cLimit, the connections are ordered by maximum weighting and cut-off at cLimit. # identify all of the building units (Zn A sites and mIm B sites) using the reduce() command. zif8.reduce() # --- # After calling `Structure.reduce()`, the `Structure.units` dictionary attribute is now populated with all of the building units found. They will be labelled with a letter corresponding to the site-type (a, b, c, etc.) and a number to distinguish between different units of a given site-type. The `buildingUnit` class (see bu.py) stores information about the molecule's position, bonds, and formula. # # By way of an example, if we extract the first building unit of the second site-type ("B") for our ZIF-8 example, we expect to get the methyl-imidazolate ligand (H<sub>3</sub>C-C<sub>3</sub>N<sub>2</sub>H<sub>2</sub>). First of all, let us visualise it in the same way as before. # visualise an example of the B site building units (print composition and visualise molecule). bu_b1 = zif8.units["b1"] HTML(bu_b1.bu_html()) # We can also extract other properties about the building unit. # # * formula: `buildingUnit.composition()`. # * coordination number: `buildUnit.cn()` # print formula and connectivity of the building unit. print(f"Building unit 'b1' formula:\t{bu_b1.composition()}") print(f"Building unit 'b1' CN:\t\t{bu_b1.cn()}") # note, can also get the composition as a Pymatgen Composition object. # this has other functionality that can be explored; see: # https://pymatgen.org/pymatgen.core.composition.html bu_b1.composition(asPymatgen=True) # --- # ## `Structure.coarse_grain()` # # ### (i) centroid # # The simplest way of coarse-graining can now be carried out; namely, taking the centroid of the cartesian coordinates for all atoms in the molecule and placing the dummy atom there. # # To do this we call `Structure.coarse_grain(method="centroid")`. We can visualise how the coarse-graining has been carried out in CIF format by calling `Structure.overlay(fileName, siteMap)` where the `siteMap = ["Si", "Ce"]` arguement means that all A sites (Zn) will be coarse-grained to "Si" and all B sites (mIm) will be coarse-grained to "Ce". This CIF will display both the original full-atomistic structure and the dummy atoms together. # # We can also visualise the HTML-formatted coarse-grained structure as before. # + # replace the organic linkers with a placeholder O atom at the centroid # and set all A sites to Si. zif8.coarse_grain(method="centroid") # output CIF with both full-atomistic structure and coarse-grained structure overlaid. zif8.overlay(f"zif8_overlay_centroid.cif", siteMap=["Si", "Ce"]) # visualise coarse-grained structure. HTML(zif8.cg_atoms_html(siteMap=["Si", "Li"])) # - # we can also visualise the overlaid structure in HTML form. Here the B sites (large purple) can be seen to be # in the rings, skewed towards the methyl group substituent. HTML(zif8.overlay(f"zif8_overlay_centroid.cif", siteMap=["Si", "Li"], return_html=True)) # --- # # ### (ii) shortest_path # # We store the connectivity (intraBonds) of the building unit as a graph (`buildingUnit.graph`), built on the NetworkX graph object (stored in `buildingUnit.graph.g`). Each node is stored as the index of the atom from the full atomistic structure, and has its chemical symbol stored as a property of the node. We can therefore visualise the graph using `matplotlib.pyplot`. # + # we can also look at the NetworkX graph for this building unit. # note: NetworkX visualisation of graphs is only to serve as a rough guide, # if the molecule is not clear, try re-executing the cell unitl a reasonable # graph is shown. options = { 'node_color': 'white', 'node_size': 1000, 'width': 2, 'font_weight':"bold" } nx.draw(bu_b1.graph.g, labels=dict(bu_b1.graph.g.nodes(data="symbol")), **options) plt.show() # - # --- # From the graph, we can find the shortest path between the "connecting atoms" (i.e. the two N atoms that bond to the Zn atoms in the ZIF framework). Then, we can define a new coarse-grained site as the middle of the path (i.e. on the C bonded to both Ns and the methyl group). If we visualise this coarse-grained structure, we can note the B sites sitting ontop of that carbon. See the CIF outputs to see more clearly. # + # replace the organic linkers with a placeholder Ce atom at the centroid # and set all A sites to Si. zif8.coarse_grain(method="shortest_path") zif8.overlay(f"zif8_overlay_shortest_path.cif", siteMap=["Si", "Ce"]) # view HTML structure. HTML(zif8.overlay(f"zif8_overlay_shortest_path.cif", siteMap=["Si", "Li"], return_html=True)) # - # --- # # ### (iii) shortest_path with cycles # # A third coarse-graining option is to identify the rings (or cycles) within the building unit and use the centroids to define the shortest paths. This can be achieved using `Structure.coarse_grain(method="shortest_path", useCycles=True)`. This algorithm proceeds by: # # * identify all simple cycles in the graph; # * contract the cycles to a new single node (cX), and reconnect the "external" nodes that would previously connected to the "internal" nodes in the cycle; # * find the shortest path using the cycle nodes replaced with cX; # * find the middle node(s) of this path. If this corresponds to a cX node, replace with all nodes of original cycle so that the centroid is the average of the cycle. # # We can visualise the effect of contracting the cycles in graph form. Here, the new cX node is labelled "X". # get contracted cycles graph. ccg, _ = bu_b1.graph.contracted_cycles nx.draw(ccg, labels=dict(ccg.nodes(data="symbol")), **options) plt.show() # + # replace the organic linkers with a placeholder Ce atom at the centroid # of the ring and set all A sites to Si. zif8.coarse_grain(method="shortest_path", useCycles=True) zif8.overlay(f"zif8_overlay_shortest_path_rings.cif", siteMap=["Si", "Ce"]) # we can also visualise the overlaid structure in HTML form. Here the B sites (large purple) can be seen to be # at the centre of the rings, rather than skewed towards the methyl substituent as before. HTML(zif8.overlay(f"zif8_overlay_centroid.cif", siteMap=["Si", "Li"], return_html=True)) # - # --- # ## `Structure.write_cg_cif()` # # Finally, once a given coarse-grained procedure has been decided upon (each time `Structure.coarse_grain()` is called, the final coarse-grained positions will be given by the most recent parameters), the structure can be output to a CIF, with the connectivity included according to the topoCIF specification. # # The coarse-grained structure can also be scaled to some characteristic bond length by setting the `scale` and `scaleValue` parameters. # write the coarse-grained structure to a CIF with the TopoCIF data block. zif8.write_cg_cif("zif8.cif", scale="min_ab", scaleValue=1.0, siteMap=["Si", "O"]) # --- # ## `Structure.get_cg_atoms()` # # You can also extract the coarse-grained structure information (optionally with either a Pymatgen `Structure` object or ASE `Atoms` object as well) for subsequent analysis. # get structure infomration with Pymatgen Structure object. cg_info, s = zif8.get_cg_atoms(scale="min_ab", siteMap=["Si", "O"], package="pymatgen") # print out what is contained in cg_info. cg_info.keys() # print repr for Pymatgen Structure. print(s)
examples/example1 (coarse-graining ZIF-8).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.6 64-bit (''tf2'': conda)' # name: python37664bittf2conda034469ea11204d31b38329519e9d7dbe # --- # + # %load_ext autoreload # %autoreload 2 import tensorflow as tf # Make tensorflow not take over the entire GPU memory for gpu in tf.config.experimental.list_physical_devices('GPU'): tf.config.experimental.set_memory_growth(gpu, True) from matplotlib import pyplot as plt from tfga import GeometricAlgebra # - ga = GeometricAlgebra([0, 1, 1]) print(ga.basis_mvs) # + """ p_4 p_2 p_3 p_5 p_1 p: x e_20 + y e_01 + e_12 """ def mv_length(mv): return tf.sqrt((mv * ~mv).tensor)[..., 0] def dist_point_line(point, line): point_normalized = point.tensor / mv_length(point) line_normalized = line.tensor / mv_length(line) return ga(point_normalized) & ga(line_normalized) def dist_points(point_a, point_b): point_a_normalized = point_a.tensor / mv_length(point_a) point_b_normalized = point_b.tensor / mv_length(point_b) return ga(point_a_normalized) & ga(point_b_normalized) def proj_point_line(point, line): return (point | line) * line def intersect_lines(line_a, line_b): return line_a ^ line_b def point_coordinates(point): z = point("12") x = point("20") / z y = point("01") / z return x, y # Shift up vertically shift_23 = 0.5 * ga.e01 p_1 = ga(ga.e12 - ga.e01) p_2 = ga(ga.e12 - ga.e20 + shift_23) p_3 = ga(ga.e12 + ga.e20 + shift_23) p_4 = ga(ga.e12 + ga.e01) p_5 = ga(ga.e12) l_14 = p_1 & p_4 l_23 = p_2 & p_3 p2_on_l14 = proj_point_line(p_2, l_14) print("P1:", p_1) print("P2:", p_2) print("P3:", p_3) print("P4:", p_4) print("P5:", p_5) print("L14:", l_14) print("Signed distance between P2 and L14:", dist_point_line(p_2, l_14)) print("Signed distance between P3 and L14:", dist_point_line(p_3, l_14)) print("P2 on L14:", p2_on_l14) # + # Plot the results def plot_point(point, name): xy = point_coordinates(point) plt.scatter(*xy, marker="x") plt.annotate(name, xy) plt.figure(figsize=(8, 8)) plot_point(p_1, "P1") plot_point(p_2, "P2") plot_point(p_3, "P3") plot_point(p_4, "P4") plot_point(p_5, "P5") plot_point(p2_on_l14, "P2 on L14") plt.xlabel("X") plt.ylabel("Y") plt.title("Points") plt.show() # -
notebooks/pga.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Some basic concepts # # # * SQL to save jobs # * log output in a home dir # * Python native # # Classes: Task # #
playground.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.10 64-bit (''base'': conda)' # name: python3 # --- # !pwd # + import os import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) train_dir='../dataset/cats_and_dogs_small/train' validation_dir='../dataset/cats_and_dogs_small/validation' test_dir='../dataset/cats_and_dogs_small/test' train_cats_dir= os.path.join(train_dir,'cats') train_dogs_dir=os.path.join(train_dir,'dogs') validation_cats_dir=os.path.join(validation_dir,'cats') validation_dogs_dir=os.path.join(validation_dir,'dogs') test_cats_dir= os.path.join(test_dir,'cats') test_dogs_dir= os.path.join(test_dir,'dogs') print('ํ›ˆ๋ จ์šฉ ๊ณ ์–‘์ด ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(train_cats_dir))) print('ํ›ˆ๋ จ์šฉ ๊ฐ•์•„์ง€ ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(train_dogs_dir))) print('๊ฒ€์ฆ์šฉ ๊ณ ์–‘์ด ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(validation_cats_dir))) print('๊ฒ€์ฆ์šฉ ๊ฐ•์•„์ง€ ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(validation_dogs_dir))) print('ํ…Œ์ŠคํŠธ์šฉ ๊ณ ์–‘์ด ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(test_cats_dir))) print('ํ…Œ์ŠคํŠธ์šฉ ๊ฐ•์•„์ง€ ์ด๋ฏธ์ง€ ์ „์ฒด ๊ฐœ์ˆ˜:', len(os.listdir(test_dogs_dir))) # parameter batch_size=20 learning_rate=0.0001 epochs=30 # + train_dir='../dataset/cats_and_dogs_small/train' validation_dir='../dataset/cats_and_dogs_small/validation' test_dir='../dataset/cats_and_dogs_small/test' train_cats_dir= os.path.join(train_dir,'cats') train_dogs_dir=os.path.join(train_dir,'dogs') validation_cats_dir=os.path.join(validation_dir,'cats') validation_dogs_dir=os.path.join(validation_dir,'dogs') test_cats_dir= os.path.join(test_dir,'cats') test_dogs_dir= os.path.join(test_dir,'dogs') print(train_cats_dir) # + ## DATA๋ฅผ ๋งŒ๋“ฆ train_datagen = tf.keras.preprocessing.image.ImageDataGenerator() valid_datagen = tf.keras.preprocessing.image.ImageDataGenerator() test_datagen = tf.keras.preprocessing.image.ImageDataGenerator() # + ## ๋งŒ๋“ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์™€์„œ ํŒŒ์”ฝํ•˜๋ฉด์„œ ํ•™์Šต ๋ฐ์ดํ„ฐ ์ƒ์„ฑ train_generator = train_datagen.flow_from_directory( directory=train_dir, # ํƒ€๊นƒ ๋””๋ ‰ํ„ฐ๋ฆฌ target_size=(128, 128), # ๋ชจ๋“  ์ด๋ฏธ์ง€๋ฅผ 150 ร— 150 ํฌ๊ธฐ๋กœ ๋ฐ”๊ฟ‰๋‹ˆ๋‹ค batch_size=batch_size, interpolation='bilinear', ## resize์‹œ interpolatrion ๊ธฐ๋ฒ• color_mode ='rgb', shuffle='True', # binary_crossentropy ์†์‹ค์„ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด์ง„ ๋ ˆ์ด๋ธ”์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค class_mode='binary') # binary, categorical , sparse , input ## class์˜ ์ธ๋ฑ์Šค๋ฅผ ํ™•์ธ. #print(train_generator.__dict__) print(train_generator.class_indices) print(train_generator.classes) validation_generator = valid_datagen.flow_from_directory( directory=validation_dir, target_size=(128, 128), batch_size=batch_size, shuffle='True', interpolation='bilinear', ## resize์‹œ interpolatrion ๊ธฐ๋ฒ• color_mode='rgb', class_mode='binary') test_generator = test_datagen.flow_from_directory( directory=test_dir, target_size=(128, 128), batch_size=batch_size, shuffle='True', interpolation='bilinear', ## resize์‹œ interpolatrion ๊ธฐ๋ฒ• color_mode='rgb', class_mode='binary') ## ํŒŒ์”ฝํ•œ ๋ฐ์ดํ„ฐ์˜ ๋ฐฐ์น˜์‚ฌ์ด์ฆˆ ํ™•์ธํ•˜๊ธฐ for data_batch, labels_batch in train_generator: print('๋ฐฐ์น˜ ๋ฐ์ดํ„ฐ ํฌ๊ธฐ:', data_batch.shape) print('๋ฐฐ์น˜ ๋ ˆ์ด๋ธ” ํฌ๊ธฐ:', labels_batch.shape) print('class :',train_generator.class_indices) break # + ## ๋ชจ๋ธ input_Layer = tf.keras.layers.Input(shape=(128,128,3)) x=tf.keras.layers.Conv2D(32,(3,3),strides=1, activation=None)(input_Layer) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) x=tf.keras.layers.MaxPool2D((2,2))(x) x=tf.keras.layers.Conv2D(64,(3,3),strides=1,activation=None)(x) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) x=tf.keras.layers.MaxPool2D((2,2))(x) x=tf.keras.layers.Conv2D(128,(3,3),strides=1,activation=None)(x) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) x=tf.keras.layers.Conv2D(64,(3,3),strides=1,activation=None)(x) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) x=tf.keras.layers.MaxPool2D((2,2))(x) x=tf.keras.layers.Flatten()(x) x= tf.keras.layers.Dense(256, activation=None)(x) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) x= tf.keras.layers.Dropout(rate=0.4)(x) x= tf.keras.layers.Dense(512, activation=None)(x) x= tf.keras.layers.BatchNormalization()(x) x= tf.keras.layers.Activation(activation='relu')(x) Out_Layer= tf.keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.Model(inputs=[input_Layer], outputs=[Out_Layer]) model.summary() # + loss_function=tf.keras.losses.binary_crossentropy #optimize=tf.keras.optimizers.RMSprop(learning_rate=learning_rate) optimize=tf.keras.optimizers.Adam(learning_rate=0.01) metric=tf.keras.metrics.binary_accuracy model.compile(loss=loss_function, optimizer=optimize, metrics=[metric]) callbacks_list= [tf.keras.callbacks.TensorBoard(log_dir='log_dir', histogram_freq=1)] ## generator๋Š” ์ž…๋ ฅ๊ณผ ํƒ€๊นƒ์˜ ๋ฐฐ์น˜์‚ฌ์ด์ฆˆ ๋งŒํผ ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ•จ. ## steps_pr_epoch๊ฐ€ 100์ด๋ฉด ์œ„์—์„œ ์„ ์–ธ๋œ ๋ฐฐ์น˜ ์ˆ˜๋งŒํผ์˜ ์ธํ’‹/์•„์›ƒํ’‹๋ฐ์ดํ„ฐ๊ฐ€ 100๋ฒˆ ์ƒ์„ฑ๋˜์–ด ํ•™์Šต์ด ๋œ๋‹ค. ##์ฆ‰, ๋ฐฐ์น˜๊ฐ€ 20์ด๋ฉด 20์˜ ๋ฐฐ์น˜์ธ ๋ฐ์ดํ„ฐ๊ฐ€ 100๋ฒˆ๋งŒํผ ์ƒ์„ฑ๋˜์–ด ํ•™์Šตํ•œ๋‹ค. ์ฆ‰, 20์˜ ๋ฐฐ์น˜ ๋ฐ์ดํ„ฐ๋ฅผ 100๋ฒˆ ํ•™์Šต์™„๋ฃŒํ•˜๋ฉด 1์—ํฌํฌ ## ๋‹จ, 20์˜ ๋ฐฐ์น˜๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ• ๋•Œ๋งˆ๋‹ค ๋žœ๋ค์ ์œผ๋กœ ์ƒ์„ฑํ•œ๋‹ค. ## ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฐฐ์น˜์‚ฌ์ด์ฆˆ/์ „์ฒด ๋ฐ์ดํ„ฐ ๊ธธ์ด๋ฅผ steps_per_epoch๋กœ ์„ค์ •ํ•œ๋‹ค. history = model.fit( train_generator, steps_per_epoch=(len(os.listdir(train_cats_dir)) + len(os.listdir(train_dogs_dir)))/batch_size, epochs=100, validation_data=validation_generator, # callbacks=callbacks_list, validation_freq=1 ) print(model.evaluate(test_generator)) model.save('cats_and_dogs_binary_classification.hdf5') # + import matplotlib.pyplot as plt acc = history.history['binary_accuracy'] val_acc = history.history['val_binary_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show()
tensorflow/day4/practice/P_04_07_dog_cat_binary_classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/allnes/age_classifier/blob/master/train_age_9_class_random.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="-6Xki-tu-rQH" colab_type="text" # ## Connect to Google Drive # + id="_nMY9IssT-NZ" colab_type="code" outputId="e2698266-b649-4aa2-c8d2-d6e09c38ce33" colab={"base_uri": "https://localhost:8080/", "height": 161} from google.colab import drive import os, natsort as nsrt, numpy as np, re from scipy.sparse import coo_matrix, csgraph, csr_matrix import matplotlib.pyplot as plt import cv2 as cv drive.mount('/content/drive') PATH_PROJECT='/content/drive/My Drive/DL_DATA_GRAPH/' PATH_CNN_REPO=PATH_PROJECT + 'BUILD/cnn_graph/' os.chdir(PATH_CNN_REPO) from lib import models, graph, coarsening, utils # %ls # # !git clone https://github.com/mdeff/cnn_graph # !git pull origin master os.chdir(PATH_PROJECT) # %ls # %matplotlib inline # + [markdown] id="R0w9O8In_oEO" colab_type="text" # ## Preprocessing data # + id="flIZlmyt_r9B" colab_type="code" outputId="8a05cb49-7ed4-48c1-9969-afd377950dea" colab={"base_uri": "https://localhost:8080/", "height": 71} PATH_GRAPHS=PATH_PROJECT + 'DATA/mini_graphs/graphs/' list_grpahs = [] for (_, _, filenames) in os.walk(PATH_GRAPHS): list_grpahs = list_grpahs + filenames list_grpahs = nsrt.natsorted(list_grpahs)[0::2] num_samples = int(np.load(PATH_GRAPHS + list_grpahs[0])['num_samples']) num_features = int(np.load(PATH_GRAPHS + list_grpahs[0])['num_features']) def save_zip(save_size): list_of_rows = [] list_of_cols = [] list_of_max_vertices = [] list_of_data = [] zip_size = save_size for graph_name in list_grpahs: with np.load(PATH_GRAPHS + graph_name) as raw_graph: raw_edges = raw_graph['E'].transpose() rows = np.array(raw_edges[0]) cols = np.array(raw_edges[1]) max_range = max(np.max(rows), np.max(cols)) unused_indexes = [] for index in range(max_range): if (not index in rows) and (not index in cols): unused_indexes.append(index) unused_indexes = np.array(unused_indexes) used_indexes = np.concatenate((rows, cols)) used_indexes = np.unique(used_indexes, axis=0) used_indexes[::-1].sort() for used_var, unused_var in zip(used_indexes, unused_indexes): np.place(rows, rows == used_var, unused_var) np.place(cols, cols == used_var, unused_var) max_range = max(np.max(rows), np.max(cols)) raw_data = raw_graph['D'] list_of_rows.append(rows) list_of_cols.append(cols) list_of_max_vertices.append(max_range) list_of_data.append(raw_data) # print('used vertices shape: ', used_indexes.shape) # print('unused vertices shape:', unused_indexes.shape) # print('new max of vertices: ', max_range) assert np.max(list_of_max_vertices) == np.min(list_of_max_vertices) size_matrix = np.max(list_of_max_vertices) + 1 X = [] for raw_data, rows, cols in zip(list_of_data, list_of_rows, list_of_cols): sparse_graph = coo_matrix((raw_data, (rows, cols)), shape=(size_matrix, size_matrix)) dense_graph = sparse_graph.todense() X.append(cv.resize(dense_graph, dsize=(zip_size, zip_size), interpolation=cv.INTER_CUBIC)) X = np.array(X) X = X.reshape((X.shape[0], X.shape[1] * X.shape[2])) PATH_LABELS=PATH_PROJECT + 'DATA/mini_graphs/GSE87571_samples.txt' raw_file = open(PATH_LABELS, 'r') y = [] for line in raw_file.readlines(): match_obj = re.match(r'(GSM[0-9]*)\s*([M,F])\s*([0-9]*)\s*([0-9]*)', line) if not match_obj is None: y.append(int(match_obj.group(3))) y = np.array(y) assert len(y) == num_samples assert len(X) == num_samples print(raw_graph.files) print(X.shape) print(y.shape) # outfile = PATH_PROJECT + 'DATA/converted_data.npz' outfile = PATH_PROJECT + 'DATA/converted_data_resize_' + str(zip_size) + '.npz' np.savez(outfile, X, y) zip_size = 128 # save_zip(zip_size) # PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data.npz' # PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data_resize_' + str(zip_size) + '.npz' PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data_resize_875_random.npz' # PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data_resize_875_edmonds.npz' # PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data_resize_875_hard.npz' # PATH_CONVERTED_DATA = PATH_PROJECT + 'DATA/converted_data_resize_128.npz' npzfile = np.load(PATH_CONVERTED_DATA) print(npzfile.files) X = npzfile['arr_0'].astype(np.float32) y = npzfile['arr_1'] print(X.shape) print(y.shape) # + [markdown] id="uoKk77Y_PfWK" colab_type="text" # ## Train # + id="FisV3-Fidabk" colab_type="code" outputId="382ae385-c2fb-4795-87d0-fc6f2b75f9af" colab={"base_uri": "https://localhost:8080/", "height": 53} print('--> Reshape data') n_train = (num_samples * 3) // 4 n_val = num_samples // 10 X_train = X[:n_train] X_val = X[n_train:n_train+n_val] X_test = X[n_train+n_val:] y = y // 10 - 1 # y = y // 25 y_train = y[:n_train] y_val = y[n_train:n_train+n_val] y_test = y[n_train+n_val:] print(np.unique(y)) # + id="V0TgRm51wPnX" colab_type="code" outputId="8bdbaff3-96b3-4134-e6fb-a37d7d5772ab" colab={"base_uri": "https://localhost:8080/", "height": 305} print('--> Get distance graph') dist, idx = graph.distance_scipy_spatial(X_train.T, k=4, metric='euclidean') A = graph.adjacency(dist, idx).astype(np.float32) print('d = |V| = {}, k|V| < |E| = {}'.format(zip_size, A.nnz)) plt.spy(A, markersize=2, color='black'); # + id="FaVIbB4jpJUi" colab_type="code" outputId="ddc1996c-b460-4cb2-b678-2d855e87d4b5" colab={"base_uri": "https://localhost:8080/", "height": 161} print('--> Get laplacian matrix') graphs, perm = coarsening.coarsen(A, levels=3, self_connections=True) X_train = coarsening.perm_data(X_train, perm) print(X_train.shape) X_val = coarsening.perm_data(X_val, perm) print(X_val.shape) X_test = coarsening.perm_data(X_test, perm) print(X_test.shape) # + id="lKwoS5I0ub2e" colab_type="code" colab={} L = [graph.laplacian(A, normalized=True) for A in graphs] # + id="ZGn1wtFvpaeb" colab_type="code" colab={} params = dict() params['dir_name'] = 'demo' params['num_epochs'] = 32 params['batch_size'] = 16 params['eval_frequency'] = 100 # Building blocks. params['filter'] = 'chebyshev5' params['brelu'] = 'b1relu' params['brelu'] = 'b2relu' params['pool'] = 'apool1' params['pool'] = 'mpool1' # Number of classes. C = y.max() + 1 assert C == np.unique(y).size # Architecture. params['F'] = [32, 32] # Number of graph convolutional filters. params['K'] = [16, 16] # Polynomial orders. params['p'] = [4, 2] # Pooling sizes. params['M'] = [1000, C] # Output dimensionality of fully connected layers. # Optimization. params['regularization'] = 5e-4 params['dropout'] = 1 params['learning_rate'] = 1e-3 params['decay_rate'] = 0.95 params['momentum'] = 0 params['decay_steps'] = n_train / params['batch_size'] # + id="NNrt9IQGs6mJ" colab_type="code" outputId="eb8ab086-aaa7-40f5-bedb-700890674320" colab={"base_uri": "https://localhost:8080/", "height": 1000} model = models.cgcnn(L, **params) accuracy, loss, t_step = model.fit(X_train, y_train, X_val, y_val) # + id="HR2L4Q7etAdp" colab_type="code" outputId="b311f61f-2b94-4407-ee8b-eedde403e35a" colab={"base_uri": "https://localhost:8080/", "height": 320} fig, ax1 = plt.subplots(figsize=(15, 5)) ax1.plot(accuracy, 'b.-') ax1.set_ylabel('validation accuracy', color='b') ax2 = ax1.twinx() ax2.plot(loss, 'g.-') ax2.set_ylabel('training loss', color='g') plt.show() # + id="_SJdlx4otEwh" colab_type="code" outputId="beb8a241-7b54-4b4c-9824-58c97797406b" colab={"base_uri": "https://localhost:8080/", "height": 35} print('Time per step: {:.2f} ms'.format(t_step*1000)) # + id="VN_abqdZtG8-" colab_type="code" outputId="6b4fdd5b-60ca-4106-9634-a1e6e712a8ec" colab={"base_uri": "https://localhost:8080/", "height": 71} res = model.evaluate(X_test, y_test) print(res[0])
experiments/train_age_9_class_random.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # orphan: true # --- # + tags=["remove-cell"] # %matplotlib inline # + tags=["remove-cell"] # flake8: noqa # - # # Tune's Scikit Learn Adapters # # Scikit-Learn is one of the most widely used tools in the ML community for working with data, # offering dozens of easy-to-use machine learning algorithms. # However, to achieve high performance for these algorithms, you often need to perform **model selection**. # # ```{image} /images/tune-sklearn.png # :align: center # :width: 50% # ``` # # ```{contents} # :backlinks: none # :local: true # ``` # # Scikit-Learn [has an existing module for model selection](https://scikit-learn.org/stable/modules/grid_search.html), # but the algorithms offered (Grid Search via ``GridSearchCV`` and Random Search via ``RandomizedSearchCV``) # are often considered inefficient. # In this tutorial, we'll cover ``tune-sklearn``, a drop-in replacement for Scikit-Learn's model selection module # with state-of-the-art optimization features such as early stopping and Bayesian Optimization. # # ```{tip} # Check out the [tune-sklearn code](https://github.com/ray-project/tune-sklearn) and {ref}`documentation <tune-sklearn-docs>`. # ``` # # ## Overview # # ``tune-sklearn`` is a module that integrates Ray Tune's hyperparameter tuning and scikit-learn's Classifier API. # ``tune-sklearn`` has two APIs: {ref}`TuneSearchCV <tunesearchcv-docs>`, and {ref}`TuneGridSearchCV <tunegridsearchcv-docs>`. # They are drop-in replacements for Scikit-learn's RandomizedSearchCV and GridSearchCV, so you only need to change # less than 5 lines in a standard Scikit-Learn script to use the API. # # Ray Tune's Scikit-learn APIs allows you to easily leverage Bayesian Optimization, HyperBand, and other cutting edge # tuning techniques by simply toggling a few parameters. It also supports and provides examples for many other # frameworks with Scikit-Learn wrappers such as Skorch (Pytorch), KerasClassifiers (Keras), and XGBoostClassifiers (XGBoost). # # Run ``pip install "ray[tune]" tune-sklearn`` to get started. # # ## Walkthrough # # Let's compare Tune's Scikit-Learn APIs to the standard scikit-learn GridSearchCV. For this example, we'll be using # ``TuneGridSearchCV`` with a # [SGDClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html). # # # ```{thebe-button} Activate code examples # ``` # # To start out, change the import statement to get tune-scikit-learnโ€™s grid search cross validation interface: # + # Keep this here for https://github.com/ray-project/ray/issues/11547 from sklearn.model_selection import GridSearchCV # Replace above line with: from ray.tune.sklearn import TuneGridSearchCV # - # And from there, we would proceed just like how we would in Scikit-Learnโ€™s interface! # # The `SGDClassifier` has a ``partial_fit`` API, which enables it to stop fitting to the data for a certain # hyperparameter configuration. # If the estimator does not support early stopping, we would fall back to a parallel grid search. # + # Other imports from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from sklearn.datasets import make_classification import numpy as np # Create dataset X, y = make_classification( n_samples=11000, n_features=1000, n_informative=50, n_redundant=0, n_classes=10, class_sep=2.5, ) x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=1000) # Example parameters to tune from SGDClassifier parameter_grid = {"alpha": [1e-4, 1e-1, 1], "epsilon": [0.01, 0.1]} # - # As you can see, the setup here is exactly how you would do it for Scikit-Learn. # Now, let's try fitting a model. # + tune_search = TuneGridSearchCV( SGDClassifier(), parameter_grid, early_stopping=True, max_iters=10 ) import time # Just to compare fit times start = time.time() tune_search.fit(x_train, y_train) end = time.time() print("Tune GridSearch Fit Time:", end - start) # Tune GridSearch Fit Time: 15.436315774917603 (for an 8 core laptop) # - # Note the slight differences we introduced above: # # * a `early_stopping`, and # * a specification of `max_iters` parameter # # The ``early_stopping`` parameter allows us to terminate unpromising configurations. If ``early_stopping=True``, # TuneGridSearchCV will default to using Tune's ASHAScheduler. # You can pass in a custom algorithm - see {ref}`Tune's documentation on schedulers <tune-schedulers>` # here for a full list to choose from. # ``max_iters`` is the maximum number of iterations a given hyperparameter set could run for; # it may run for fewer iterations if it is early stopped. # # Try running this compared to the GridSearchCV equivalent, and see the speedup for yourself! # + from sklearn.model_selection import GridSearchCV # n_jobs=-1 enables use of all cores like Tune does sklearn_search = GridSearchCV(SGDClassifier(), parameter_grid, n_jobs=-1) start = time.time() sklearn_search.fit(x_train, y_train) end = time.time() print("Sklearn Fit Time:", end - start) # Sklearn Fit Time: 47.48055911064148 (for an 8 core laptop) # - # ## Using Bayesian Optimization # # In addition to the grid search interface, tune-sklearn also provides an interface, # TuneSearchCV, for sampling from **distributions of hyperparameters**. # In the following example we'll be using the # [digits dataset from scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) # # In addition, you can easily enable Bayesian optimization over the distributions in only 2 lines of code: # + # First run `pip install bayesian-optimization` from ray.tune.sklearn import TuneSearchCV from sklearn.linear_model import SGDClassifier from sklearn import datasets from sklearn.model_selection import train_test_split import numpy as np digits = datasets.load_digits() x = digits.data y = digits.target x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) clf = SGDClassifier() parameter_grid = {"alpha": (1e-4, 1), "epsilon": (0.01, 0.1)} tune_search = TuneSearchCV( clf, parameter_grid, search_optimization="bayesian", n_trials=3, early_stopping=True, max_iters=10, ) tune_search.fit(x_train, y_train) print(tune_search.best_params_) # {'alpha': 0.37460266483547777, 'epsilon': 0.09556428757689246} # - # As you can see, itโ€™s very simple to integrate tune-sklearn into existing code. # Distributed execution is also easy - you can simply run ``ray.init(address="auto")`` before # TuneSearchCV to connect to the Ray cluster and parallelize tuning across multiple nodes, # as you would in any other Ray Tune script. # # ## More Scikit-Learn Examples # # See the [ray-project/tune-sklearn examples](https://github.com/ray-project/tune-sklearn/tree/master/examples) # for a comprehensive list of examples leveraging Tune's sklearn interface. # Check out more detailed examples and get started with tune-sklearn! # # * [Skorch with tune-sklearn](https://github.com/ray-project/tune-sklearn/blob/master/examples/torch_nn.py) # * [Scikit-Learn Pipelines with tune-sklearn](https://github.com/ray-project/tune-sklearn/blob/master/examples/sklearn_pipeline.py) # * [XGBoost with tune-sklearn](https://github.com/ray-project/tune-sklearn/blob/master/examples/xgbclassifier.py) # * [KerasClassifier with tune-sklearn](https://github.com/ray-project/tune-sklearn/blob/master/examples/keras_example.py) # * [LightGBM with tune-sklearn](https://github.com/ray-project/tune-sklearn/blob/master/examples/lgbm.py) # # ## Further Reading # # If you're using scikit-learn for other tasks, take a look at Rayโ€™s {ref}`replacement for joblib <ray-joblib>`, # which allows users to parallelize scikit learn jobs over multiple nodes.
doc/source/tune/examples/tune-sklearn.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd #attatch files School_data= '/Users/miguelvelez/Desktop/schools_complete.csv' student_data= '/Users/miguelvelez/Desktop/students_complete.csv' #read them in school= pd.read_csv(School_data) student= pd.read_csv(student_data) #now combine the two data sets in to a single set school_data_complete= pd.merge(student,school, how="left", on=["school_name","school_name"]) school_data_complete.head(10) # + #calculate total number of schools Total_schools= len(school_data_complete["school_name"].unique()) #print(Total_schools) Total_students= len(school_data_complete["Student ID"].unique()) #print(Total_students) Total_budget= float(school_data_complete["budget"].sum()) #print(Total_budget) #find the averages now. #average math score average_math_score= round(float(school_data_complete["math_score"].mean()),3) #print(average_math_score) average_reading_score= round(float(school_data_complete["reading_score"].mean()),3) #print(average_reading_score) pass_math= len(school_data_complete.loc[school_data_complete["math_score"]>=70]["Student ID"]) #print(pass_math) now change this into a percent per_pass_math= float(round(pass_math / Total_students *100, 2)) #print(per_pass_math) #now do the same for reading, start with making a list using .loc() to find all the passing reading scores pass_reading= len(school_data_complete.loc[school_data_complete["reading_score"]>=70]["Student ID"]) #check it out using print() if it works then change it into a percent. #print(pass_reading) per_pass_reading= float(round(pass_reading / Total_students *100, 2)) #print(per_pass_reading) overall_pass= round((per_pass_reading + per_pass_math)/ 2, 2) #print(overall_pass) #great! it all works! now lets create a NEW data frame! start by making a dictionary district_data= pd.DataFrame({"Total Schools":Total_schools, "Total Students":Total_students,"Total Budget":Total_budget, "Average Math Score":average_math_score, "Average Reading Score":average_reading_score, "Percent Passing Math":per_pass_math, "Percent Passing Reading":per_pass_reading, "Overall Passing":overall_pass},index=[0]) #print(district_data) #Time to clean this up... district_data["Total Students"]= district_data["Total Students"].map('{:,}'.format) district_data["Total Budget"]= district_data["Total Budget"].map('${:,}'.format) district_data["Percent Passing Math"]= district_data["Percent Passing Math"].map('{}%'.format) district_data["Percent Passing Reading"]= district_data["Percent Passing Reading"].map('{}%'.format) district_data["Overall Passing"]= district_data["Overall Passing"].map('{}%'.format) #print(district_data) notice the addition of '%' and '$' district_data.head() # + Grouped_schools= school_data_complete.groupby("school_name") school_summary = pd.DataFrame({"School Name":school["school_name"], "School Type":school["type"], "Total Budget":school["budget"]}) #print(school_summary) school_summary = school_summary.set_index("School Name") school_summary = school_summary.sort_values("School Name") #print(school_summary) #calcualte data from groupedby df school_summary["Total Students"]= Grouped_schools["Student ID"].count() school_summary["Budget Per Student"]=school_summary["Total Budget"] / school_summary["Total Students"] school_summary["Average Math Score"]= round(Grouped_schools["math_score"].mean(), 2) school_summary["Average Reading Score"]= round(Grouped_schools["reading_score"].mean(), 2) #calculate now the percentage school_summary["Percent Passing Math"] = round((Grouped_schools.apply(lambda x: (x["math_score"] >= 70).sum()) / school_summary["Total Students"]) * 100, 2) school_summary["Percent Passing Reading"] = round((Grouped_schools.apply(lambda x: (x["reading_score"] >= 70).sum()) / school_summary["Total Students"]) * 100, 2) school_summary["Overall Passing Rate"] = round((school_summary["Percent Passing Math"] + school_summary["Percent Passing Reading"]) / 2, 2) school_summary = school_summary.sort_values("Overall Passing Rate", ascending=False) #Now lets format the above... school_summary["Total Budget"] = school_summary["Total Budget"].map('${:,}'.format) #school_summary["Budget Per Students"]= school_summary["Budget Per Student"].map('${:,}'.format) #School_summary= pd.DataFrame({"School Type": school["school_type"], "Total Budget": "budget", "Total Students": "Total_students", "Budget Per Student":"school"}) #check it out using .head school_summary.head(10) # + #top preforming school school_summary= school_summary.sort_values("Overall Passing Rate", ascending=False) school_summary.head() # + #Bottom preforming school school_summary= school_summary.sort_values("Overall Passing Rate", ascending=True) school_summary.head() # + #math scores by grade ninth= school_data_complete.loc[school_data_complete["grade"] == "9th"] tenth= school_data_complete.loc[school_data_complete["grade"] == "10th"] eleventh= school_data_complete.loc[school_data_complete["grade"] == "11th"] twelfth= school_data_complete.loc[school_data_complete["grade"] == "12th"] #here we are combining the data sets math_ninth = ninth.groupby("school_name")["math_score"].mean() math_tenth = tenth.groupby("school_name")["math_score"].mean() math_eleventh = eleventh.groupby("school_name")["math_score"].mean() math_twelfth = twelfth.groupby("school_name")["math_score"].mean() math_grades = pd.DataFrame({"9th":math_ninth, "10th":math_tenth, "11th":math_eleventh, "12th":math_twelfth}) math_grades = round(math_grades, 1) print(math_grades) # + # Reading Scores by Grade just copy the above, and change it around. ninth= school_data_complete.loc[school_data_complete["grade"] == "9th"] tenth= school_data_complete.loc[school_data_complete["grade"] == "10th"] eleventh= school_data_complete.loc[school_data_complete["grade"] == "11th"] twelfth= school_data_complete.loc[school_data_complete["grade"] == "12th"] reading_ninth = ninth.groupby("school_name")["reading_score"].mean() reading_tenth = tenth.groupby("school_name")["reading_score"].mean() reading_eleventh = eleventh.groupby("school_name")["reading_score"].mean() reading_twelfth = twelfth.groupby("school_name")["reading_score"].mean() reading_grades = pd.DataFrame({"9th":reading_ninth, "10th":reading_tenth, "11th":reading_eleventh, "12th":reading_twelfth}) reading_grades = round(reading_grades, 1) print(reading_grades) # + #Scores by School spending spending_bins = [0,585, 615, 645, 675] group_names = ["<$585", "$585-629", "$630-644", "$645-675"] #the group names will be acting as a bucket to refrence the table # + #now were building the table school_summary["Spending Ranges Per Student"]= pd.cut(school_summary["Budget Per Student"], spending_bins , labels=group_names).head() spending_groups = school_summary.loc[:, ["Spending Ranges Per Student","Average Math Score", "Average Reading Score", "Percent Passing Math", "Percent Passing Reading", "Overall Passing Rate"]].groupby("Spending Ranges Per Student") spending_groups.mean() # - school_summary.dtypes # + size_bins = [0, 1000, 3000, 5000] group_names = ["Small (<1000)", "Medium (1000-3000)", "Large (3000-5000)"] school_summary["Size Ranges"] = pd.cut(school_summary["Total Students"], size_bins, labels=group_names) size_groups = school_summary.loc[:, ["Size Ranges","Average Math Score", "Average Reading Score", "Percent Passing Math", "Percent Passing Reading", "Overall Passing Rate"]].groupby("Size Ranges") size_groups.mean() # + #sources by type district_groups = school_summary.loc[:, ["School Type", "Average Math Score", "Average Reading Score", "Percent Passing Math", "Percent Passing Reading", "Overall Passing Rate"]].groupby("School Type") district_groups.mean() # -
PyCitySchool2.ipynb