markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Observations:* The expected error is always smaller under the Projection DPP distribution compared to the Volume Sampling distribution.* The expected error for the Volume Sampling distribution is constant for a contant D* However the expected error for the Projection DPP distribution depends on the k-sum* For X_0 and ...
previous_Q = NAL_1.multi_Q lv_0 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[0,:,:]) lv_1 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[1,:,:]) lv_2 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[2,:,:]) lv_3 = estimate_leverage_scores_from_orthogonal_matrix(previous_Q[3,:,:...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
In this example the objective is Q and the initialization is Q_0 (the rectangular identity)We have with respect to the Schur-order (or the majorization):$$Q = Q_5 \prec_{S} Q_4 \prec_{S} Q_3 \prec_{S} Q_2 \prec_{S} Q_1 \prec_{S} Q_0 $$
plt.plot(index_list[0:10], lv_0[0:10], 'c--',index_list[0:10], lv_1[0:10], 'k--', index_list[0:10], lv_2[0:10], 'r--', index_list[0:10], lv_3[0:10], 'b--',index_list[0:10], lv_4[0:10], 'g--',index_list[0:10], lv_5[0:10], 'y--') plt.xlabel('index') plt.ylabel('leverage score') cyan_patch = mpatches.Patch(color='cyan', l...
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
III-1-2 The case of a projection spectrumWe mean by a projection spectrum matrix, a matrix with equal the first k singular values.We observe that the two distributions are very similar.... \todo{reword}
cov_2 = np.diag(np.concatenate(([1000,1000,1000,1,0.1],cov_test))) NAL_2 = Numrerical_Analysis_DPP(N,real_dim,r,k,versions_number,mean,cov_2,lv_scores_vector) projection_DPP_res_2 = NAL_2.get_expected_error_for_projection_DPP() volume_sampling_res_2 = NAL_2.get_expected_error_for_volume_sampling() deterministic_selecti...
[ 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3] [ 1. 1. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [-0.7 -0.7 -0.7 -0.7 -0.7 -0.7 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3 0.3] 5 6
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
III-2 The influence of the "spread" of VIn this section we investigate the influence of the "spread" (to be defined formally) of the cloud of points. We can change this "spread" by changing the initialization of the generator of orthogonal matrices: we replace the rectangular identity by "other" orthogonal matrices. ...
np.power(np.linspace(1, k, num=k),2) matrices_array = [ np.zeros((4,4)) for comb in combinations(range(5),4)] matrix_sum = np.sum(matrices_array) matrix_sum matrices_array
_____no_output_____
MIT
.ipynb_checkpoints/Numerical_Analysis_Volume_Sampling_vs_Projection_DPP-ollld-checkpoint.ipynb
AyoubBelhadji/FrameBuilder
Convolutional Neural Network ExampleBuild a convolutional neural network with TensorFlow.- Author: Aymeric Damien- Project: https://github.com/aymericdamien/TensorFlow-Examples/These lessons are adapted from [aymericdamien TensorFlow tutorials](https://github.com/aymericdamien/TensorFlow-Examples) / [GitHub](https://...
from __future__ import division, print_function, absolute_import import tensorflow as tf # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # Training Parameters learning_rate = 0.001 num_steps = 500 batch_size = 128 display_ste...
Step 1, Minibatch Loss= 63763.3047, Training Accuracy= 0.141 Step 10, Minibatch Loss= 26429.6680, Training Accuracy= 0.242 Step 20, Minibatch Loss= 12171.8584, Training Accuracy= 0.586 Step 30, Minibatch Loss= 6306.6318, Training Accuracy= 0.734 Step 40, Minibatch Loss= 5113.7583, Training Accuracy= 0.711 Step 50, Mini...
MIT
Deep_Learning/TensorFlow-aymericdamien/notebooks/3_NeuralNetworks/convolutional_network_raw.ipynb
Chau-Xochitl/INFO_7390
Google Cloud CMIP6 Public Data: Basic Python ExampleThis notebooks shows how to query the catalog and load the data using python
from matplotlib import pyplot as plt import numpy as np import pandas as pd import xarray as xr import zarr import fsspec %matplotlib inline %config InlineBackend.figure_format = 'retina' plt.rcParams['figure.figsize'] = 12, 6
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Browse CatalogThe data catatalog is stored as a CSV file. Here we read it with Pandas.
df = pd.read_csv('https://storage.googleapis.com/cmip6/cmip6-zarr-consolidated-stores.csv') df.head()
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
The columns of the dataframe correspond to the CMI6 controlled vocabulary. A beginners' guide to these terms is available in [this document](https://docs.google.com/document/d/1yUx6jr9EdedCOLd--CPdTfGDwEwzPpCF6p1jRmqx-0Q). Here we filter the data to find monthly surface air temperature for historical experiments.
df_ta = df.query("activity_id=='CMIP' & table_id == 'Amon' & variable_id == 'tas' & experiment_id == 'historical'") df_ta
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Now we do further filtering to find just the models from NCAR.
df_ta_ncar = df_ta.query('institution_id == "NCAR"') df_ta_ncar
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Load DataNow we will load a single store using fsspec, zarr, and xarray.
# get the path to a specific zarr store (the first one from the dataframe above) zstore = df_ta_ncar.zstore.values[-1] print(zstore) # create a mutable-mapping-style interface to the store mapper = fsspec.get_mapper(zstore) # open it using xarray and zarr ds = xr.open_zarr(mapper, consolidated=True) ds
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Plot a map from a specific date.
ds.tas.sel(time='1950-01').squeeze().plot()
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Create a timeseries of global-average surface air temperature. For this we need the area weighting factor for each gridpoint.
df_area = df.query("variable_id == 'areacella' & source_id == 'CESM2'") ds_area = xr.open_zarr(fsspec.get_mapper(df_area.zstore.values[0]), consolidated=True) ds_area total_area = ds_area.areacella.sum(dim=['lon', 'lat']) ta_timeseries = (ds.tas * ds_area.areacella).sum(dim=['lon', 'lat']) / total_area ta_timeseries
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
By default the data are loaded lazily, as Dask arrays. Here we trigger computation explicitly.
%time ta_timeseries.load() ta_timeseries.plot(label='monthly') ta_timeseries.rolling(time=12).mean().plot(label='12 month rolling mean') plt.legend() plt.title('Global Mean Surface Air Temperature')
_____no_output_____
MIT
basic_search_and_load.ipynb
pangeo-gallery/cmip6
Figures for the section on approximately computing the stream structure
# Load the smooth and peppered stream sdf_smooth= gd1_util.setup_gd1model() pepperfilename= 'gd1pepper.pkl' if os.path.exists(pepperfilename): with open(pepperfilename,'rb') as savefile: sdf_pepper= pickle.load(savefile) else: timpacts= simulate_streampepper.parse_times('256sampling',9.) sdf_pepper=...
galpyWarning: WARNING: Rnorm keyword input to streamdf is deprecated in favor of the standard ro keyword galpyWarning: WARNING: Vnorm keyword input to streamdf is deprecated in favor of the standard vo keyword galpyWarning: Using C implementation to integrate orbits
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Is the mean perpendicular frequency close to zero?
# Sampling functions massrange=[5.,9.] plummer= False Xrs= 5. nsubhalo= simulate_streampepper.nsubhalo rs= simulate_streampepper.rs dNencdm= simulate_streampepper.dNencdm sample_GM= lambda: (10.**((-0.5)*massrange[0])\ +(10.**((-0.5)*massrange[1])\ ...
This stream had 61 impacts
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Test the single-impact approximations
# Setup a single, large impact m= 10.**8. GM= 10**8./bovy_conversion.mass_in_msol(V0,R0) timpactIndx= numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-1.3/bovy_conversion.time_in_Gyr(V0,R0))) # Load the single-impact stream gapfilename= 'gd1single.pkl' if os.path.exists(gapfilename): with open(gapfilen...
186.439969323 0.519882548939 5.57736194495
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Test the multiple-impact approximations
# Setup a four, intermediate impacts m= [10.**7.,10.**7.25,10.**6.75,10.**7.5] GM= [mm/bovy_conversion.mass_in_msol(V0,R0) for mm in m] timpactIndx= [numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq_timpact)-1.3/bovy_conversion.time_in_Gyr(V0,R0))), numpy.argmin(numpy.fabs(numpy.array(sdf_pepper._uniq...
2007.35482303 8.63206025326
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Computational speed
nimp= 2**numpy.arange(1,9) ntrials= 3 nsample= [10,10,10,10,10,10,33,33,33] compt= numpy.zeros(len(nimp)) for ii,ni in enumerate(nimp): tcompt= 0. for t in range(ntrials): nimpact=ni timpacts= numpy.random.permutation(numpy.array(sdf_pepper._uniq_timpact))[:ni] print len(timpacts) ...
_____no_output_____
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Example densities and tracks Single masses
# Load our fiducial simulation's output, for apars and smooth stream data= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime', 'gd1_t64sampling_X5_5-9_dens.dat'), delimiter=',',max_rows=2) apars= data[0] dens_unp= data[1] data=...
_____no_output_____
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Full mass range First look at low apar resolution:
apars= apars[::30] dens_unp= dens_unp[::30] omega_unp= omega_unp[::30] # Sampling functions massrange=[5.,9.] plummer= False Xrs= 5. nsubhalo= simulate_streampepper.nsubhalo rs= simulate_streampepper.rs dNencdm= simulate_streampepper.dNencdm sample_GM= lambda: (10.**((-0.5)*massrange[0])\ ...
_____no_output_____
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
At full apar resolution:
# Load our fiducial simulation's output, for apars and smooth stream data= numpy.genfromtxt(os.path.join(os.getenv('DATADIR'),'streamgap-pepper','gd1_multtime', 'gd1_t64sampling_X5_5-9_dens.dat'), delimiter=',',max_rows=2) apars= data[0] dens_unp= data[1] data=...
_____no_output_____
BSD-3-Clause
meanOperpAndApproxImpacts.ipynb
jobovy/streamgap-pepper
Examples Example 1: Move A FileAKA cut and paste. Moving files is a fast operation because we are just changing a pointer to the ones and zeros to point to something else. We are not actually pushing bits around disk to make the move happen.The module shutil is filled with all kinds of file handling goodies.In the root...
import shutil as sh import os if not 'script_dir' in globals(): script_dir = os.getcwd() data_directory = 'data\\' example_directory = 'BasicFileOpsExample\\' target_directory = 'In\\' file_name = 'forestfires.csv' source_path = os.path.join(script_dir,data_directory,example_directory,file_name) target_path ...
_____no_output_____
MIT
03 Advanced/20-basic-file-io.ipynb
MassStreetUniversity/tutorial-python
Example 2: Archiving A FileWe are now done processing the file and we need to archive it in case we need to drag it out and reload the system. The process of archiving is multi step. Zip up the file. Move the file to the Archive folder. Blow away the original.Once you run the example, check the Archive folder and the I...
import zipfile as zf import os if not 'script_dir' in globals(): script_dir = os.getcwd() data_directory = 'data\\' example_directory = 'BasicFileOpsExample\\' source_directory = 'In\\' target_directory = 'Archive\\' file_name = 'forestfires.csv' archive_name = 'forestfires.zip' target_path = os.path.join(sc...
_____no_output_____
MIT
03 Advanced/20-basic-file-io.ipynb
MassStreetUniversity/tutorial-python
Exercises Q 1The energy required to get from point $\vec{r}_1$ to point $\vec{r}_2$ for a plane is given by$$ E = \alpha \int_{C} \left| \frac{d\vec{r}}{dt} \right| dt - \int_C \vec{F} \cdot \frac{d\vec{r}}{dt}dt $$Suppose that $\alpha=5$ and our start and ends points are $\vec{r}_1 = (0,0)$ and $\vec{r}_2 = (0, 10)$...
t_m = np.array([ 0., 1.04347826, 2.08695652, 3.13043478, 4.17391304, 5.2173913 , 6.26086957, 7.30434783, 8.34782609, 9.39130435, 10.43478261, 11.47826087, 12.52173913, 13.56521739, 14.60869565, 15.65217391, 16.69565217, 17.73913043, 18.7826087 , 19.82608696, 20.86956522, 21.91304348...
_____no_output_____
Unlicense
day4/04. Scipy - Exercises.ipynb
ubutnux/bosscha-python-workshop-2022
Look At It
# Load image - individual 100307. img = ci.load("fmri_data/rfMRI_REST1_LR_Atlas_hp2000_clean_filt_sm6.HCPMMP.ptseries.nii") fmri_data = np.array(img.get_fdata()) # Visualize data, i.e. inspect the first 60 timesteps of each parcel. # Generate heatmap. timesteps = 60 displayed_data = np.transpose(fmri_data[range(timest...
_____no_output_____
Apache-2.0
docs/tutorials/time_series/fmri_analysis.ipynb
RebeccaYin7/hyppo
Set Up Hyperparameters
# From Ting: Regions-of-Interest (ROIs) roi_keys = np.array([1, 23, 18, 53, 24, 96, 117, 50, 143, 109, 148, 60, 38, 135, 93, 83, 149, 150, 65, 161, 132, 71]) - 1 roi_labels = np.array([ "Visual", "Visual", "Visual", "SM", "SM", "dAtt", "dAtt", "dAtt", "dAtt", "vAtt", "vAtt", ...
_____no_output_____
Apache-2.0
docs/tutorials/time_series/fmri_analysis.ipynb
RebeccaYin7/hyppo
Run Experiment
mgcx = MGCX(max_lag = max_lag) def worker(i, j): X = roi_data[:, i] Y = roi_data[:, j] stat, pval, mgcx_dict = mgcx.test(X, Y, reps = reps, workers = workers) opt_lag = mgcx_dict['opt_lag'] opt_scale_x, opt_scale_y = mgcx_dict['opt_scale'] return stat, pval, opt_lag, opt_scale_x, opt_...
_____no_output_____
Apache-2.0
docs/tutorials/time_series/fmri_analysis.ipynb
RebeccaYin7/hyppo
Visualize Matrices
def plot_heatmap(matrix, labels, title, filename): # sns.set() cmap = mpl.cm.get_cmap('Purples') cc = np.linspace(0, 1, 256) cmap = mpl.colors.ListedColormap(cmap(cc)) heatmap_kws = dict( cbar=False, font_scale=1.4, inner_hier_labels=labels, hier_label_fontsize=20, ...
_____no_output_____
Apache-2.0
docs/tutorials/time_series/fmri_analysis.ipynb
RebeccaYin7/hyppo
p-value Matrix
# Apply negative log10 transform. # matrix = pickle.load(open('fmri_data/pval_matrix.pkl', 'rb')) # matrix = -np.log10(matrix) # pickle.dump(matrix, open('fmri_data/nl10_pval_matrix.pkl', 'wb')) matrix = pickle.load(open('fmri_data/nl10_pval_matrix.pkl', 'rb')) plot_heatmap(matrix, roi_labels, 'p-Value', 'pval')
_____no_output_____
Apache-2.0
docs/tutorials/time_series/fmri_analysis.ipynb
RebeccaYin7/hyppo
Buffered Text-to-SpeechIn this tutorial, we are going to build a state machine that controls a text-to-speech synthesis. The problem we solve is the following:- Speaking the text takes time, depending on how long the text is that the computer should speak.- Commands for speaking can arrive at any time, and we would li...
from os import system def text_to_speech(text): system('say {}'.format(text))
_____no_output_____
MIT
notebooks/Buffered Text-to-Speech.ipynb
Hallvardd/ttm4115-project
Run the above cell so the function is available in the following, and then execute the following cell to test it:
text_to_speech("Hello. I am a computer.")
_____no_output_____
MIT
notebooks/Buffered Text-to-Speech.ipynb
Hallvardd/ttm4115-project
WindowsTODO: We should have some code to run text to speech on Windows, too! State Machine 1With this function, we can create our first state machine that accepts a message and then speaks out some text. (Let's for now ignore how we get the text into the method, we will do that later.)![](images/speaking/speaking-stm...
print('Before speaking.') text_to_speech("Hello. I am a computer.") print('After speaking.')
_____no_output_____
MIT
notebooks/Buffered Text-to-Speech.ipynb
Hallvardd/ttm4115-project
You see that the string _"After speaking"_ is printed after the speaking is finished. During the execution, the program is blocked and does not do anything else. When our program should also do other stuff at the same time, either completely unrelated to speech or even just accepting new speech commands, this is not wo...
from stmpy import Machine, Driver from os import system import logging debug_level = logging.DEBUG logger = logging.getLogger('stmpy') logger.setLevel(debug_level) ch = logging.StreamHandler() ch.setLevel(debug_level) formatter = logging.Formatter('%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s') ch.setForm...
_____no_output_____
MIT
notebooks/Buffered Text-to-Speech.ipynb
Hallvardd/ttm4115-project
The state machine 2 still has a problem, but this time another one: If we receive a new message with more text to speak _while_ we are in state `speaking`, this message is discarded. Our next state machine will fix this. State Machine 3As you know, events arriving in a state that do not declare outgoing triggers with ...
s1 = {'name': 'speaking', 'do': 'speak(*)', 'speak': 'defer'} stm = Machine(name='stm', transitions=[t0, t1, t2], states=[s1], obj=speaker) speaker.stm = stm driver = Driver() driver.add_machine(stm) driver.start() driver.send('speak', 'stm', args=['My first sentence.']) driver.send('speak', 'stm', args=['My second ...
_____no_output_____
MIT
notebooks/Buffered Text-to-Speech.ipynb
Hallvardd/ttm4115-project
概要- 101クラス分類- 対象:料理画像- VGG16による転移学習 1. 全結合層 1. 全層- RXなし
RUN = 100
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
使用するGPUメモリの制限
import tensorflow as tf tf_ver = tf.__version__ if tf_ver.startswith('1.'): from tensorflow.keras.backend import set_session config = tf.ConfigProto() config.gpu_options.allow_growth = True config.log_device_placement = True sess = tf.Session(config=config) set_session(sess)
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
使用するGPUを指定
import os os.environ["CUDA_VISIBLE_DEVICES"]="0"
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
matplotlibでプロットしたグラフをファイルへ保存
import os def save_fig(plt, file_prefix): if file_prefix == '': return parent = os.path.dirname(os.path.abspath(file_prefix)) os.makedirs(parent, exist_ok=True) plt.savefig(f'{file_prefix}.pdf', transparent=True, bbox_inches='tight', pad_inches = 0) plt.savefig(f'{file_prefix}.png', tra...
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
指定フォルダ以下にある画像リストを作成- サブフォルダはラベルに対応する数字であること- TOP_DIR - 0 - 00001.jpg - 00002.jpg - 1 - 00003.jpg - 00004.jpg
import pathlib import random import os TOP_DIR = '/data1/Datasets/Food-101/03_all' sub_dirs = pathlib.Path(TOP_DIR).glob('*/**') label2files = dict() for s in sub_dirs: files = pathlib.Path(s).glob('**/*.jpg') label = int(os.path.basename(s)) label2files[label] = list(files)
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
画像とラベルを訓練データと検証データに分割する
ratio = 0.8 train_list = [] train_labels = [] val_list = [] val_labels = [] for k, v in label2files.items(): random.shuffle(v) N = len(v) N_train = int(N * ratio) train_list.extend(v[:N_train]) train_labels.extend([k] * N_train) val_list.extend(v[N_train:]) val_labels.extend([k] * (N ...
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
画像ファイルリストとラベルから教師データを生成するクラス
import math import numpy as np from PIL import Image import matplotlib.pyplot as plt %matplotlib inline import keras from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.applications.vgg16 import preprocess_input import tensorflow as tf ...
Using TensorFlow backend.
MIT
VGG16.ipynb
KoshinoK/RandomExchange
モデル保存用のディレクトリを作成★
import os from datetime import datetime # モデル保存用ディレクトリの準備 model_dir = os.path.join( f'../run/VGG16_run{RUN}' ) os.makedirs(model_dir, exist_ok=True) print('model_dir:', model_dir) # 保存先のディレクトリ名を表示 dir_weights = model_dir os.makedirs(dir_weights, exist_ok=True)
model_dir: ../run/VGG16_run100
MIT
VGG16.ipynb
KoshinoK/RandomExchange
VGGモデルのロード
from tensorflow.keras.applications.vgg16 import VGG16 # 既存の1000クラスの出力を使わないため、 # `incliude_top=False`として出力層を含まない状態でロード vgg16 = VGG16(include_top=False, input_shape=(224, 224, 3)) # モデルのサマリを確認。出力層が含まれてないことがわかる vgg16.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 224, 224, 3) 0 ________________________________________________________...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
VGG16を利用したモデルの作成と学習方法の設定★
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten # モデルを編集し、ネットワークを生成する関数の定義 def build_transfer_model(vgg16): # 読み出したモデルを使って、新しいモデルを作成 model = Sequential(vgg16.layers) # 読み出した重みの一部は再学習しないように設定。 # ここでは、追加する層と出力層に近い層の重みのみを再学習 for layer i...
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
全結合層とそれに近い畳み込み層の学習★ モデル作成
# 定義した関数を呼び出して、ネットワークを生成 model = build_transfer_model(vgg16)
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
ネットワーク構造の保存★
import json import pickle # ネットワークの保存 model_json = os.path.join(model_dir, 'model.json') with open(model_json, 'w') as f: json.dump(model.to_json(), f)
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
最適化アルゴリズムなどを指定してモデルをコンパイルする
from tensorflow.keras.optimizers import SGD model.compile( loss='categorical_crossentropy', optimizer=SGD(lr=1e-4, momentum=0.9), metrics=['accuracy'] ) # モデルのサマリを確認 model.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 ________________________________________________________...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
シーケンス生成
batch_size = 25 img_seq_train = ImageSequence(train_list, train_labels, batch_size=batch_size) img_seq_validation = ImageSequence(val_list, val_labels, batch_size=batch_size) print('Train images =', len(img_seq_train) * batch_size) print('Validation images =', len(img_seq_validation) * batch_size)
Train images = 80800 Validation images = 20200
MIT
VGG16.ipynb
KoshinoK/RandomExchange
Callbackの生成★
from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping, ReduceLROnPlateau # Callbacksの設定 cp_filepath = os.path.join(dir_weights, 'ep_{epoch:04d}_ls_{loss:.1f}.h5') cp = ModelCheckpoint( cp_filepath, monitor='val_acc', verbose=...
WARNING:tensorflow:`epsilon` argument is deprecated and will be removed, use `min_delta` instead.
MIT
VGG16.ipynb
KoshinoK/RandomExchange
学習
n_epoch = 200 # モデルの学習 history = model.fit_generator( img_seq_train, epochs=n_epoch, # 学習するエポック数 steps_per_epoch=len(img_seq_train), validation_data=img_seq_validation, validation_steps=len(img_seq_validation), verbose=1, callbacks=[cp, csv, es, rl] )
Epoch 1/200 3232/3232 [==============================] - 1217s 377ms/step - loss: 4.6143 - acc: 0.0148 - val_loss: 4.5334 - val_acc: 0.0410 Epoch 2/200 3232/3232 [==============================] - 499s 155ms/step - loss: 4.4336 - acc: 0.0381 - val_loss: 4.0951 - val_acc: 0.1068 Epoch 3/200 3232/3232 [==================...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
Stage1の損失と正解率の保存
h = history.history stage1_loss = h['loss'] stage1_val_loss = h['val_loss'] stage1_acc = h['acc'] stage1_val_acc = h['val_acc']
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
全層の学習 Stage1の最良モデルパラメータをロード
import pathlib checkpoints = pathlib.Path(model_dir).glob('*.h5') checkpoints = sorted(checkpoints, key=lambda cp:cp.stat().st_mtime) latest = str(checkpoints[-1]) model.load_weights(latest)
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
全層を学習可能にする
for l in model.layers: l.trainable = True model.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 ________________________________________________________...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
最適化アルゴリズムなどを指定してモデルをコンパイルする
from tensorflow.keras.optimizers import SGD model.compile( loss='categorical_crossentropy', optimizer=SGD(lr=1e-4, momentum=0.9), metrics=['accuracy'] )
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
シーケンス生成
batch_size = 25 img_seq_train = ImageSequence(train_list, train_labels, batch_size=batch_size) img_seq_validation = ImageSequence(val_list, val_labels, batch_size=batch_size) print('Train images =', len(img_seq_train) * batch_size) print('Validation images =', len(img_seq_validation) * batch_size)
Train images = 80800 Validation images = 20200
MIT
VGG16.ipynb
KoshinoK/RandomExchange
Callbackの生成★
from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping, ReduceLROnPlateau # Callbacksの設定 cp_filepath = os.path.join(dir_weights, 'ep_{epoch:04d}_ls_{loss:.1f}.h5') cp = ModelCheckpoint( cp_filepath, monitor='val_acc', verbose=...
WARNING:tensorflow:`epsilon` argument is deprecated and will be removed, use `min_delta` instead.
MIT
VGG16.ipynb
KoshinoK/RandomExchange
学習
n_epoch = 500 initial_epoch = len(stage1_loss) # モデルの学習 history = model.fit_generator( img_seq_train, epochs=n_epoch, # 学習するエポック数 steps_per_epoch=len(img_seq_train), validation_data=img_seq_validation, validation_steps=len(img_seq_validation), verbose=1, callbacks=[cp, csv, es, rl], i...
Epoch 113/500 3232/3232 [==============================] - 800s 247ms/step - loss: 1.0005 - acc: 0.7156 - val_loss: 1.5914 - val_acc: 0.6010 Epoch 114/500 3232/3232 [==============================] - 797s 247ms/step - loss: 0.8781 - acc: 0.7448 - val_loss: 1.5427 - val_acc: 0.6180 Epoch 115/500 3232/3232 [=============...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
結果 損失関数のプロット
plt.figure(figsize=(8, 6)) h = history.history loss = stage1_loss + h['loss'] val_loss = stage1_val_loss + h['val_loss'] ep = np.arange(1, len(loss) + 1) plt.title('Loss', fontsize=16) plt.plot(ep, loss, label='Training') plt.plot(ep, val_loss, label='Validation') plt.legend(fontsize=16) plt.xticks(fontsize=14) plt.yt...
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
正解率のプロット
plt.figure(figsize=(8, 6)) h = history.history acc = stage1_acc + h['acc'] val_acc = stage1_val_acc + h['val_acc'] ep = np.arange(1, len(loss) + 1) plt.title('Accuracy', fontsize=16) plt.plot(ep, acc, label='Training') plt.plot(ep, val_acc, label='Validation') plt.legend(fontsize=16) plt.xticks(fontsize=14) plt.yticks...
_____no_output_____
MIT
VGG16.ipynb
KoshinoK/RandomExchange
汎化能力の推定
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score import seaborn as sns def evalulate(y_true, y_pred, file_prefix=''): cm = confusion_matrix(y_true, y_pred) # print(cm) accuracy = accuracy_score(y_true, y_pred) precision = precision_score(y_true, y_pred, a...
正解率 0.6573267326732674 精度 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 ...
MIT
VGG16.ipynb
KoshinoK/RandomExchange
Query Classifier Tutorial[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial14_Query_Classifier.ipynb)In this tutorial we introduce the query classifier the goal of introducing this feature was to optim...
# Install the latest release of Haystack in your own environment #! pip install farm-haystack # Install the latest master of Haystack !pip install --upgrade pip !pip install git+https://github.com/deepset-ai/haystack.git#egg=farm-haystack[colab] # Install pygraphviz !apt install libgraphviz-dev !pip install pygraphv...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
If running from Colab or a no Docker environment, you will want to start Elasticsearch from source InitializationHere are some core imports Then let's fetch some data (in this case, pages from the Game of Thrones wiki) and prepare it so that it canbe used indexed into our `DocumentStore`
from haystack.utils import ( print_answers, print_documents, fetch_archive_from_http, convert_files_to_docs, clean_wiki_text, launch_es, ) from haystack.pipelines import Pipeline from haystack.document_stores import ElasticsearchDocumentStore from haystack.nodes import ( BM25Retriever, E...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
Keyword vs Question/Statement ClassifierThe keyword vs question/statement query classifier essentially distinguishes between the keyword queries and statements/questions. So you can intelligently route to different retrieval nodes based on the nature of the query. Using this classifier can potentially yield the follow...
# Here we build the pipeline sklearn_keyword_classifier = Pipeline() sklearn_keyword_classifier.add_node(component=SklearnQueryClassifier(), name="QueryClassifier", inputs=["Query"]) sklearn_keyword_classifier.add_node( component=embedding_retriever, name="EmbeddingRetriever", inputs=["QueryClassifier.output_1"] ) ...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
Transformer Keyword vs Question/Statement ClassifierFirstly, it's essential to understand the trade-offs between SkLearn and Transformer query classifiers. The transformer classifier is more accurate than SkLearn classifier however, it requires more memory and most probably GPU for faster inference however the transfo...
# Here we build the pipeline transformer_keyword_classifier = Pipeline() transformer_keyword_classifier.add_node( component=TransformersQueryClassifier(), name="QueryClassifier", inputs=["Query"] ) transformer_keyword_classifier.add_node( component=embedding_retriever, name="EmbeddingRetriever", inputs=["QueryC...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
Question vs Statement ClassifierOne possible use case of this classifier could be to route queries after the document retrieval to only send questions to QA reader and in case of declarative sentence, just return the DPR/ES results back to user to enhance user experience and only show answers when user explicitly asks...
# Here we build the pipeline transformer_question_classifier = Pipeline() transformer_question_classifier.add_node(component=embedding_retriever, name="EmbeddingRetriever", inputs=["Query"]) transformer_question_classifier.add_node( component=TransformersQueryClassifier(model_name_or_path="shahrukhx01/question-vs-s...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
Standalone Query ClassifierBelow we run queries classifiers standalone to better understand their outputs on each of the three types of queries
# Here we create the keyword vs question/statement query classifier from haystack.nodes import TransformersQueryClassifier queries = [ "arya stark father", "jon snow country", "who is the father of arya stark", "which country was jon snow filmed?", ] keyword_classifier = TransformersQueryClassifier() ...
_____no_output_____
Apache-2.0
tutorials/Tutorial14_Query_Classifier.ipynb
askainet/haystack
Chapter 3: Inferential statistics[Link to outline](https://docs.google.com/document/d/1fwep23-95U-w1QMPU31nOvUnUXE2X3s_Dbk5JuLlKAY/editheading=h.uutryzqeo2av)Concept map:![concepts_STATS.png](attachment:09eb3a54-abf3-4e54-bf16-6a6399de6438.png) Notebook setup
# loading Python modules import math import random import numpy as np import pandas as pd import seaborn as sns from scipy.stats.distributions import norm # set random seed for repeatability np.random.seed(42) # notebooks figs setup %matplotlib inline import matplotlib.pyplot as plt sns.set(rc={'figure.figsize':(8,5)...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Overview- Main idea = learn about a population based on a sample- Recall Amy's two research questions about the employee lifetime value (ELV) data: - Question 1 = Is there a difference between ELV of the two groups? → **hypothesis testing** - Question 2 = How much difference in ELV does stats training provide? → **e...
def dmeans(xA, xB): """ Estimator for the difference between group means. """ d = np.mean(xA) - np.mean(xB) return d
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Note the difference between group means is precisely the estimator Amy need for her analysis (**Group S** and **Group NS**). We intentionally use the labels **A** and **B** to illustrate the general case.
# example parameters for each group muA, sigmaA = 300, 10 muB, sigmaB = 200, 20 # size of samples for each group nA = 5 nB = 4
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Particular value of the estimator `dmeans`
xA = norm(muA, sigmaA).rvs(nA) # random sample from Group A xB = norm(muB, sigmaB).rvs(nB) # random sample from Group B d = dmeans(xA, xB) d
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
The value of $d$ computed from the samples is an estimate for the difference between means of two groups: $\Delta = \mu_A - \mu_{B}$ (which we know is $100$ in this example). Sampling distribution of the estimator `dmeans`How well does the estimate $d$ approximate the true value $\Delta$?**What is the accuracy and va...
def get_sampling_dist(statfunc, meanA, stdA, nA, meanB, stdB, nB, N=1000): """ Obtain the sampling distribution of the statistic `statfunc` from `N` random samples drawn from groups A and B with parmeters: - Group A: `nA` values taken from `norm(meanA, stdA)` - Group B: `nB` values taken from `n...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Plot the sampling distribution of `dmeans`
fig3, ax3 = plt.subplots() title3 = "Samping distribution of D = mean($\mathbf{X}_A$) - mean($\mathbf{X}_B$) " + \ "for samples of size $n_A$ = " + str(nA) + \ " from $\mathcal{N}$(" + str(muA) + "," + str(sigmaA) + ")" + \ " and $n_B$ = " + str(nB) + \ " from $\mathcal{N}$(" + str(m...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Theoretical model for the sampling distribution of `dmeans` Let's use probability theory to build a theoretical model for the sampling distribution of the difference-between-means estimator `dmeans`.- The central limit theorem the rules of to obtain a model for the random variable $D = \overline{X}_A - \overline{X}_{...
Dmean = muA - muB Dstd = np.sqrt(sigmaA**2/nA + sigmaB**2/nB) print("Probability theory predicts the sampling distribution had" "mean", round(Dmean, 3), "and standard deviation", round(Dstd, 3)) x = np.linspace(min(dmeans_sdist), max(dmeans_sdist), 10000) D = norm(Dmean, Dstd).pdf(x) label = 'Theory predic...
Probability theory predicts the sampling distribution hadmean 100 and standard deviation 10.954
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Regroup and reality checkHow are you doing, dear readers?I know this was a lot of math and a lot of code, but the good news is we're done now!The key things to remember is that we have two ways to compute sampling distribution for any estimator: - Repeatedly generate random samples from model and compute the esti...
df = pd.read_csv('data/employee_lifetime_values.csv') df # remember the descriptive statistics df.groupby("group").describe() def dmeans(sample): """ Compute the difference between groups means. """ xS = sample[sample["group"]=="S"]["ELV"] xNS = sample[sample["group"]=="NS"]["ELV"] d = np.mean(x...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Our goal is to determine how likely or unlikely this observed value is under the null hypothesis $H_0$.In the next two sections, we'll look at two different approaches for obtaining the sampling distribution of $D$ under $H_0$. Approach 1: Permutation test for hypothesis testing- The permutation test allow us to rej...
def resample_under_H0(sample, groupcol="group"): """ Return a copy of the dataframe `sample` with the labels in the column `groupcol` modified based on a random permutation of the values in the original sample. """ resample = sample.copy() labels = sample[groupcol].values newlabels = np.rand...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
The steps in the above code cell give us a simple way to generate samples from the null hypothesis and compute the value of `dmeans` statistic for these samples. We used the assumption of "no difference" under the null hypothesis, and translated this to the "forget the labels" interpretation. Running a permutation tes...
def permutation_test(sample, statfunc, groupcol="group", permutations=10000): """ Compute the p-value of the observed `statfunc(sample)` under the null hypothesis where the labels in the `groupcol` are randomized. """ # 1. compute the observed value of the statistic for the sample obsstat = stat...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
- Once we have the sampling distribution of `D` under $H_0$, we can see where the observed value $d=130$ falls within this distribution.- p-value: the probability of observing value $d$ or more extreme under the null hypothesis
pvalue
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
We can now make the decision based on the $p$-value and a pre-determined threshold:- If the observed value $d$ is unlikely under $H_0$ ($p$-value less than 5% chance of occurring), then our decision will be to "reject the null hypothesis."- Otherwise, if the observed value $d$ is not that unusual ($p$-value greater th...
if pvalue < 0.05: print("DECISION: Reject H0", "( p-value =", pvalue, ")") print(" There is a statistically significant difference between xS and xNS means") else: print("DECISION: Fail to reject H0") print(" The difference between groups means could have occurred by chance")
DECISION: Reject H0 ( p-value = 0.046 ) There is a statistically significant difference between xS and xNS means
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Permutations test using SciPy The above code was given only for illustrative purposes.In practice, you can use the SciPy implementation of permutation test,by calling `ttest_ind(..., permutations=10000)` to perform a permutation test, then obtain the $p$-value.
from scipy.stats import ttest_ind xS = df[df["group"]=="S"]["ELV"] xNS = df[df["group"]=="NS"]["ELV"] ttest_ind(xS, xNS, permutations=10000).pvalue
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Discussion - The procedure we used is called a **permutations test** for comparison of group means. - The permutation test takes it's name from the action of mixing up the group-membership labels and computing a statistic which is a way to generate samples from the null hypothesis in situations where we're com...
from scipy.stats import ttest_ind # extract data for two groups xS = df[df["group"]=="S"]['ELV'] xNS = df[df["group"]=="NS"]['ELV'] # run the complete t-test procedure for ind-ependent samples: result = ttest_ind(xS, xNS) result.pvalue
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
The $p$-value is less than 0.05 so our decision is to **reject the null hypothesis**. Student's t-test under the hoodThe computations hidden behind the function `ttest_ind` involve a six step procedure that makes use of the pooled variance $s^2_p$.
from statistics import stdev from scipy.stats.distributions import t # 1. calculate the mean in each group meanS, meanNS = np.mean(xS), np.mean(xNS) # 2. calculate d, the observed difference between means d = meanS - meanNS # 3. calculate the standard deviations in each group stdS, stdNS = stdev(xS), stdev(xNS) nS, ...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Welch's t-test (unpooled variances)An [alternative t-test procedure](https://statkat.com/stattest.php?&t=9) that doesn't assume the variances in groups are equal.
result2 = ttest_ind(xS, xNS, equal_var=False) result2.pvalue
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Welch's $t$-test differs only in steps 4 through 6 as shown below:
# 4'. compute the unpooled standard deviation of D stdD = np.sqrt(stdS**2/nS + stdNS**2/nNS) # 5'. compute the value of the t-statistic tstat = d / stdD # 6'. obtain the p-value from a t-distribution with # (insert crazy formula here) degrees of freedom dof = (stdS**2/nS + stdNS**2/nNS)**2 / \ ((stdS**2/nS)**...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Summary of Question 1We saw two ways to answer Question 1 (is there a difference between group means) and obtain the p-value.We interpreted the small p-values as evidence that the observed difference, $d=130$, is unlikely to be due to chance,i.e. we rejected the null hypothesis.Note this whole procedure is just a sani...
from statistics import mean def bootstrap_stat(sample, statfunc=mean, B=5000): """ Compute the bootstrap estimate of the function `statfunc` from the sample. Returns a list of statistic values from bootstrap samples. """ n = len(sample) bstats = [] for i in range(0, B): bsample = np...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
SciPy bootstrap method
from scipy.stats import bootstrap def dmeans2(sample1, sample2): return np.mean(sample1) - np.mean(sample2) res = bootstrap((xS, xNS), statistic=dmeans2, vectorized=False, confidence_level=0.9, n_resamples=5000, method='percentile') CI_boot2 = [res.confidence_interval.low, res.confidence_interval...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Approach 2: Estimates using analytical approximation method - Assumption 1: populations for **Group S** and **Group NS** are normally distributed - Assumption 2: the variance of the two populations is the same (or approximately equal) - Using the theoretical model for the populations, we can obtain a formula f...
from scipy.stats.distributions import t d = np.mean(xS) - np.mean(xNS) nS, nNS = len(xS), len(xNS) stdS, stdNS = stdev(xS), stdev(xNS) var_pooled = ((nS-1)*stdS**2 + (nNS-1)*stdNS**2)/(nS + nNS - 2) std_pooled = np.sqrt(var_pooled) std_err = std_pooled * np.sqrt(1/nS + 1/nNS) dof = nS + nNS - 2 # for 90% confidence...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Using unpooled varianceThe calculations are similar to the Welch's t-test for hypothesis testing.
d = np.mean(xS) - np.mean(xNS) nS, nNS = len(xS), len(xNS) stdS, stdNS = stdev(xS), stdev(xNS) stdD = np.sqrt(stdS**2/nS + stdNS**2/nNS) dof = (stdS**2/nS + stdNS**2/nNS)**2 / \ ((stdS**2/nS)**2/(nS-1) + (stdNS**2/nNS)**2/(nNS-1) ) # for 90% confidence interval, need 10% in tails alpha = 0.10 # now use inverse-...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Summary of Question 2 resultsWe now have all the information we need to give a precise and nuanced answer to Question 2: "How big is the increase in ELV produced by stats training?".The basic estimate of the difference is $130$ can be reported, and additionally can can report the 90% confidence interval for the differ...
CI_boot, CI_boot2, CI_tpooled, CI_tunpooled
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Standardized effect size (optional)It is sometimes useful to report the effect size using a "standardized" measure for effect sizes.*Cohen's $d$* one such measure, and it is defined as the difference between two means divided by the pooled standard deviation.
def cohend(sample1, sample2): """ Compute Cohen's d measure of effect size for two independent samples. """ n1, n2 = len(sample1), len(sample2) mean1, mean2 = np.mean(sample1), np.mean(sample2) var1, var2 = np.var(sample1, ddof=1), np.var(sample2, ddof=1) # calculate the pooled variance and ...
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
We can interpret the value of Cohen's d obtained using the [reference table](https://en.wikipedia.org/wiki/Effect_sizeCohen's_d) of values:| Cohen's d | Effect size || ----------- | ----------- || 0.01 | very small || 0.20 | small || 0.50 | medium || 0.80 | large |We can ...
code = list(["um"])
_____no_output_____
MIT
stats_overview/03_STATS.ipynb
minireference/noBSstatsnotebooks
Compare built-in Sagemaker classification algorithms for a binary classification problem using Iris dataset In the notebook tutorial, we build 3 classification models using HPO and then compare the AUC on test dataset on 3 deployed modelsIRIS is perhaps the best known database to be found in the pattern recognition li...
rm(list=ls()) library(reticulate) # be careful not to install reticulate again. since it can cause problems. library(tidyverse) library(pROC) set.seed(1324)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
SageMaker needs to be imported using the reticulate library. If this was performed in a local computer, we would have to make sure that Python and appropriate SageMaker libraries are installed, but inside a SageMaker notebook R kernels, these are all pre-loaded and the R user does not have to worry about installing ret...
sagemaker <- import('sagemaker') session <- sagemaker$Session() bucket <- session$default_bucket() # you may replace with name of your personal S3 bucket role_arn <- sagemaker$get_execution_role()
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Input the data and basic pre-processing
head(iris) summary(iris)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
In above, we see that there are 50 flowers of the setosa species, 50 flowers of the versicolor species, and 50 flowers of the virginica species. In this case, the target variable is the Species prediction. We are trying to predict the species of the flower given its numerical measurements of Sepal length, sepal width, ...
iris1 <- iris %>% dplyr::select(Species,Sepal.Length,Sepal.Width,Petal.Length,Petal.Width) %>% # change order of columns such that the label column is the first column. dplyr::filter(Species %in% c("setosa","versicolor")) %>% #only select two flower for binary classification. dplyr::mut...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We now obtain some basic descriptive statistics of the features.
iris1 %>% group_by(Species) %>% summarize(mean_sepal_length = mean(Sepal.Length), mean_petal_length = mean(Petal.Length), mean_sepal_width = mean(Sepal.Width), mean_petal_width = mean(Petal.Width),...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
In the summary statistics, we observe that mean sepal length is longer than mean petal length for both flowers. Prepare for modelling We split the train and test and validate into 70%, 15%, and 15%, using random sampling.
iris_train <- iris1 %>% sample_frac(size = 0.7) iris_test <- anti_join(iris1, iris_train) %>% sample_frac(size = 0.5) iris_validate <- anti_join(iris1, iris_train) %>% anti_join(., iris_test)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We do a check of the summary statistics to make sure train, test, validate datasets are appropriately split and have proper class balance.
table(iris_train$Species) nrow(iris_train)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We see that the class balance between 0 and 1 is almost 50% each for the binary classification. We also see that there are 70 rows in the train dataset.
table(iris_validate$Species) nrow(iris_validate)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We see that the class balance in validation dataset between 0 and 1 is almost 50% each for the binary classification. We also see that there are 15 rows in the validation dataset.
table(iris_test$Species) nrow(iris_test)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We see that the class balance in test dataset between 0 and 1 is almost 50% each for the binary classification. We also see that there are 15 rows in the test dataset. Write the data to Amazon S3 Different algorithms in SageMaker will have different data formats required for training and for testing. These formats are...
write_csv(iris_train, 'iris_train.csv', col_names = FALSE) write_csv(iris_validate, 'iris_valid.csv', col_names = FALSE) write_csv(iris_test, 'iris_test.csv', col_names = FALSE) s3_train <- session$upload_data(path = 'iris_train.csv', bucket = bucket, ke...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples