text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` import pandas as pd import matplotlib.pyplot as plt import xlrd import os ``` 打开excel文件并获取sheet数量及各sheet的名称 ``` path = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\Original.XLS' # df = pd.read_excel(path) data = xlrd.open_workbook(path) count = len(data.sheets()) sheet_name = [] for sheet in data.sheets(): sheet_name.append(sheet.name) count, sheet_name ``` 加载test data ``` test = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\Reinjection1.XLS' ``` 测试:concat所有sheet ``` test_path = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\test.xlsx' test_data = xlrd.open_workbook(test_path) dataframe = pd.DataFrame() for sheet in test_data.sheets(): name = sheet.name df = pd.read_excel(test_path, sheet_name = name) dataframe = pd.concat([dataframe, df], ignore_index = True) dataframe ``` 在original data上测试concat ``` original_dataframe = pd.DataFrame() for sheet in data.sheets(): name = sheet.name df = pd.read_excel(path, sheet_name = name) original_dataframe = pd.concat([original_dataframe, df], ignore_index = True) original_dataframe.shape ``` 测试:合并信息到最后一行 ``` snippet = original_dataframe.head(10) snippet list(snippet.columns)==["t[s]", "EYEQDG_CMN_Params_s.COM_Cam_Frame_ID_b32[]", "EYEQDG_CMN_Params_s.COM_EyeQ_Frame_ID_b32[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Lat_Distance_b12[]", "EYEQDG_CMN_Params_s.COM_Sync_Frame_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_Sync_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_VD_CIPV_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_VD_CIPV_Lost_b2[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Relative_Long_Velocity_b13[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Long_Distance_b14[]"] result = pd.DataFrame(columns = original_dataframe.columns) result result.loc[0, "t[s]"] = snippet.loc[9, "t[s]"] for i in range(len(snippet)): replace_with = snippet.iloc[i, 10-i] print(replace_with) result.iloc[0,10-i] = replace_with result ``` 用来检测是否有异常值并删除异常值的函数 ``` def detect_irregular(dataframe): # 10 is default based on the data provided, subject to change detect = len(dataframe) % 10 if detect != 0: new_df = dataframe.copy() for i in range(detect): new_df = new_df.drop(len(new_df)-1) return new_df return dataframe data = detect_irregular(original_dataframe) ``` 将data分割成10行一组,分别处理(很慢) ``` # the number 9 and 10 are based on the number of lines in the data, subject to change def process_ten_lines(snippet, result_df, current_index, end_index): result_df.loc[current_index, "t[s]"] = snippet.loc[end_index, "t[s]"] for i in range(len(snippet)): replace_with = snippet.iloc[i, 10-i] result_df.iloc[current_index,10-i] = replace_with return result_df def merge_data(dataframe): result = pd.DataFrame(columns = dataframe.columns) # 10 is default based on the data provided, subject to change for j in range(len(dataframe) // 10): start = j*10 end = (j+1)*10 result = process_ten_lines(dataframe.iloc[start:end], result, j, end-1) return result ``` 尝试处理整个dataframe之后dropna(FOR LOOP比较慢) ``` def process_by_ten_lines(dataframe): dataframe_copy = dataframe.copy() iters = len(dataframe_copy)//10 for p in range(iters): start = p*10 end = (p+1)*10 for i in range(10): replace_with = dataframe_copy.iloc[start+i, 10-i] dataframe_copy.iloc[end-1,10-i] = replace_with return dataframe_copy result = process_by_ten_lines(data).dropna(subset = ["EYEQDG_CMN_Params_s.COM_Cam_Frame_ID_b32[]"]) result ``` 利用shift优化速度(可以直接dropna而不需要把数据数量变为10的倍数) ``` def shift_columns(dataframe): dataframe_copy = dataframe.copy() iters = dataframe_copy.shape[1] for index, col in enumerate(dataframe.columns[2:]): dataframe_copy[col] = dataframe_copy[col].shift(index+1) return dataframe_copy def dropnan(dataframe): return dataframe.dropna(subset = ["EYEQDG_CMN_Params_s.COM_Cam_Frame_ID_b32[]"]) after_process=dropnan(shift_columns(original_dataframe)) after_process ``` 数据处理和画图 ``` # set the index as the camera ID new_col = ['T', 'Cam_id', 'EQ_id', 'Lat_D', 'Com_Sync_id', 'OBJ_Sync_id', 'OBJ_CIPV_ID', 'OBJ_CIPV_Lost', 'OBJ_id', 'OBJ_Re_Long_V', 'OBJ_Long_D'] after_process.columns = new_col current_data = after_process.set_index('Cam_id') current_data # matplotlib fig = plt.figure(figsize=(20,8),dpi=80) ax = plt.subplot(111) #plt.plot(current_data.index, current_data['OBJ_Re_Long_V'], color = 'b') plt.plot(current_data.index, current_data['OBJ_Long_D'], color = 'r') # plt.plot(current_data.index, df['RNA_ITS-CAN::FrCamera_ITS_A1::CamLateralDistanceObject00_ITS[m]'], color = 'g') # plt.plot(current_data.index, df['RNA_ITS-CAN::FrCamera_ITS_A1::CamRelativeVelocityObject00_ITS[m/s]'], color = 'y') ``` 搜索、加载、合并data的函数 ``` def search_dir(directory): files = os.listdir(directory) original_file = None test_file = [] for f in files: if f.endswith(".XLS"): if f.startswith("Reinjection"): test_file.append(f) elif f.startswith("Original"): original_file = f return original_file, test_file directory = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis' search_dir(directory) ``` 加载test data 1 ``` def check_header(dataframe, header_list): return list(dataframe.columns) == header_list def load_and_concate_test_data(path): dataframe = pd.DataFrame() header_list = ["t[s]", "EYEQDG_CMN_Params_s.COM_Cam_Frame_ID_b32[]", "EYEQDG_CMN_Params_s.COM_EyeQ_Frame_ID_b32[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Lat_Distance_b12[]", "EYEQDG_CMN_Params_s.COM_Sync_Frame_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_Sync_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_VD_CIPV_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvH_Params_s.OBJ_VD_CIPV_Lost_b2[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_ID_b8[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Relative_Long_Velocity_b13[]", "EYEQDG_OBJT_Params_s.EYEQDG_OBJTvO_Params_as._0_.OBJ_Long_Distance_b14[]"] data = xlrd.open_workbook(path) for sheet in data.sheets(): name = sheet.name print(name) df = pd.read_excel(path, sheet_name = name) if not check_header(df, header_list): df.columns = header_list dataframe = pd.concat([dataframe, df], ignore_index = True, sort=False) # remove some tail rows that are not numeric data dataframe_rows = len(dataframe) dataframe = dataframe.drop(list(range(dataframe_rows-8, dataframe_rows))) return dataframe test1_path = directory = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\Reinjection1.XLS' df1 = load_and_concate_test_data(test1_path) df1 df1_copy = dropnan(shift_columns(df1)) df1_copy ``` 测试删除“outlier” ``` dataframe filt = dataframe["name1"] == "adsf" new = dataframe.drop(dataframe[filt].index) new.reset_index() dataframe test2 = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\Reinjection2.XLS' def check_first_row(dataframe, header_list): return list(dataframe.loc[0]) == header_list test_path = 'C:\\Users\\Z0050908\\Documents\\Jupyter_scipt\\group5\\group5\\Result analysis\\test.xlsx' dataframe = pd.DataFrame() data = xlrd.open_workbook(test_path) first_name = data.sheets()[0].name final_name = data.sheets()[-1].name head = ["t[s]", "name1", "name2", "name3", "name4"] print(final_name) for sheet in data.sheets(): name = sheet.name print("Processing:", name) if name == final_name: df = pd.read_excel(test_path, names = head, header = None, sheet_name = name, skipfooter = 8) else: df = pd.read_excel(test_path, names = head, header = None, sheet_name = name) if check_first_row(df, head): df = df.drop(0) print(12) dataframe = pd.concat([dataframe, df], ignore_index = True, sort=False) # remove some tail rows that are not numeric data # dataframe_rows = len(dataframe) # dataframe = dataframe.drop(list(range(dataframe_rows-8, dataframe_rows))) dataframe dataframe.columns=head dataframe dataframe.columns = dataframe.loc[0] dataframe dataframe dataframe.loc[:, ["t[s]", "name2"]] for i in range(1, 1): print(i) ```
github_jupyter
# Fine-Tuning a BERT Model and Create a Text Classifier We have already performed the Feature Engineering to create BERT embeddings from the `reviews_body` text using the pre-trained BERT model, and split the dataset into train, validation and test files. To optimize for Tensorflow training, we saved the files in TFRecord format. Now, let’s fine-tune the BERT model to our Customer Reviews Dataset and add a new classification layer to predict the `star_rating` for a given `review_body`. ![BERT Training](img/bert_training.png) As mentioned earlier, BERT’s attention mechanism is called a Transformer. This is, not coincidentally, the name of the popular BERT Python library, “Transformers,” maintained by a company called [HuggingFace](https://github.com/huggingface/transformers). We will use a variant of BERT called [DistilBert](https://arxiv.org/pdf/1910.01108.pdf) which requires less memory and compute, but maintains very good accuracy on our dataset. # DEMO 1: # Develop Model Training Code In Noteboook ``` !pip install -q tensorflow==2.1.0 !pip install -q transformers==2.8.0 !pip install -q scikit-learn==0.23.1 train_data = "./input/data/train" validation_data = "./input/data/validation" test_data = "./input/data/test" local_model_dir = "./model/" num_gpus = 0 input_data_config = "File" epochs = 1 learning_rate = 0.00001 epsilon = 0.00000001 train_batch_size = 8 validation_batch_size = 8 test_batch_size = 8 train_steps_per_epoch = 1 validation_steps = 1 test_steps = 1 use_xla = True use_amp = False max_seq_length = 64 freeze_bert_layer = True run_validation = True run_test = True run_sample_predictions = True import time import random import pandas as pd import easydict from glob import glob import pprint import argparse import json import subprocess import sys import os import tensorflow as tf from transformers import DistilBertTokenizer from transformers import TFDistilBertForSequenceClassification from transformers import TextClassificationPipeline from transformers.configuration_distilbert import DistilBertConfig from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.models import load_model CLASSES = [1, 2, 3, 4, 5] def select_data_and_label_from_record(record): x = {"input_ids": record["input_ids"], "input_mask": record["input_mask"], "segment_ids": record["segment_ids"]} y = record["label_ids"] return (x, y) def file_based_input_dataset_builder( channel, input_filenames, pipe_mode, is_training, drop_remainder, batch_size, epochs, steps_per_epoch, max_seq_length, ): # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if pipe_mode: print("***** Using pipe_mode with channel {}".format(channel)) from sagemaker_tensorflow import PipeModeDataset dataset = PipeModeDataset(channel=channel, record_format="TFRecord") else: print("***** Using input_filenames {}".format(input_filenames)) dataset = tf.data.TFRecordDataset(input_filenames) dataset = dataset.repeat(epochs * steps_per_epoch * 100) name_to_features = { "input_ids": tf.io.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.io.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.io.FixedLenFeature([max_seq_length], tf.int64), "label_ids": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example.""" record = tf.io.parse_single_example(record, name_to_features) return record dataset = dataset.apply( tf.data.experimental.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder, num_parallel_calls=tf.data.experimental.AUTOTUNE, ) ) dataset = dataset.shuffle(buffer_size=1000, reshuffle_each_iteration=True) row_count = 0 print("**************** {} *****************".format(channel)) for row in dataset.as_numpy_iterator(): if row_count == 1: break print(row) row_count = row_count + 1 return dataset if __name__ == "__main__": args = easydict.EasyDict( { "train_data": train_data, "validation_data": validation_data, "test_data": test_data, "local_model_dir": local_model_dir, "num_gpus": num_gpus, "use_xla": use_xla, "use_amp": use_amp, "max_seq_length": max_seq_length, "train_batch_size": train_batch_size, "validation_batch_size": validation_batch_size, "test_batch_size": test_batch_size, "epochs": epochs, "learning_rate": learning_rate, "epsilon": epsilon, "train_steps_per_epoch": train_steps_per_epoch, "validation_steps": validation_steps, "test_steps": test_steps, "freeze_bert_layer": freeze_bert_layer, "run_validation": run_validation, "run_test": run_test, "run_sample_predictions": run_sample_predictions, "input_data_config": input_data_config, } ) env_var = os.environ print("Environment Variables:") pprint.pprint(dict(env_var), width=1) train_data = args.train_data print("train_data {}".format(train_data)) validation_data = args.validation_data print("validation_data {}".format(validation_data)) test_data = args.test_data print("test_data {}".format(test_data)) local_model_dir = args.local_model_dir print("local_model_dir {}".format(local_model_dir)) num_gpus = args.num_gpus print("num_gpus {}".format(num_gpus)) use_xla = args.use_xla print("use_xla {}".format(use_xla)) use_amp = args.use_amp print("use_amp {}".format(use_amp)) max_seq_length = args.max_seq_length print("max_seq_length {}".format(max_seq_length)) train_batch_size = args.train_batch_size print("train_batch_size {}".format(train_batch_size)) validation_batch_size = args.validation_batch_size print("validation_batch_size {}".format(validation_batch_size)) test_batch_size = args.test_batch_size print("test_batch_size {}".format(test_batch_size)) epochs = args.epochs print("epochs {}".format(epochs)) learning_rate = args.learning_rate print("learning_rate {}".format(learning_rate)) epsilon = args.epsilon print("epsilon {}".format(epsilon)) train_steps_per_epoch = args.train_steps_per_epoch print("train_steps_per_epoch {}".format(train_steps_per_epoch)) validation_steps = args.validation_steps print("validation_steps {}".format(validation_steps)) test_steps = args.test_steps print("test_steps {}".format(test_steps)) freeze_bert_layer = args.freeze_bert_layer print("freeze_bert_layer {}".format(freeze_bert_layer)) run_validation = args.run_validation print("run_validation {}".format(run_validation)) run_test = args.run_test print("run_test {}".format(run_test)) run_sample_predictions = args.run_sample_predictions print("run_sample_predictions {}".format(run_sample_predictions)) input_data_config = args.input_data_config print("input_data_config {}".format(input_data_config)) # Determine if PipeMode is enabled pipe_mode = input_data_config.find("Pipe") >= 0 print("Using pipe_mode: {}".format(pipe_mode)) # Model Output transformer_fine_tuned_model_path = os.path.join(local_model_dir, "transformers/fine-tuned/") os.makedirs(transformer_fine_tuned_model_path, exist_ok=True) # SavedModel Output tensorflow_saved_model_path = os.path.join(local_model_dir, "tensorflow/saved_model/0") os.makedirs(tensorflow_saved_model_path, exist_ok=True) distributed_strategy = tf.distribute.MirroredStrategy() with distributed_strategy.scope(): tf.config.optimizer.set_jit(use_xla) tf.config.optimizer.set_experimental_options({"auto_mixed_precision": use_amp}) train_data_filenames = glob(os.path.join(train_data, "*.tfrecord")) print("train_data_filenames {}".format(train_data_filenames)) train_dataset = file_based_input_dataset_builder( channel="train", input_filenames=train_data_filenames, pipe_mode=pipe_mode, is_training=True, drop_remainder=False, batch_size=train_batch_size, epochs=epochs, steps_per_epoch=train_steps_per_epoch, max_seq_length=max_seq_length, ).map(select_data_and_label_from_record) tokenizer = None config = None model = None successful_download = False retries = 0 while retries < 5 and not successful_download: try: tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") config = DistilBertConfig.from_pretrained("distilbert-base-uncased", num_labels=len(CLASSES)) model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", config=config) successful_download = True print("Sucessfully downloaded after {} retries.".format(retries)) except: retries = retries + 1 random_sleep = random.randint(1, 30) print("Retry #{}. Sleeping for {} seconds".format(retries, random_sleep)) time.sleep(random_sleep) callbacks = [] initial_epoch_number = 0 if not tokenizer or not model or not config: print("Not properly initialized...") optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, epsilon=epsilon) print("** use_amp {}".format(use_amp)) if use_amp: # loss scaling is currently required when using mixed precision optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(optimizer, "dynamic") print("*** OPTIMIZER {} ***".format(optimizer)) loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) metric = tf.keras.metrics.SparseCategoricalAccuracy("accuracy") model.compile(optimizer=optimizer, loss=loss, metrics=[metric]) print("Compiled model {}".format(model)) model.layers[0].trainable = not freeze_bert_layer print(model.summary()) if run_validation: validation_data_filenames = glob(os.path.join(validation_data, "*.tfrecord")) print("validation_data_filenames {}".format(validation_data_filenames)) validation_dataset = file_based_input_dataset_builder( channel="validation", input_filenames=validation_data_filenames, pipe_mode=pipe_mode, is_training=False, drop_remainder=False, batch_size=validation_batch_size, epochs=epochs, steps_per_epoch=validation_steps, max_seq_length=max_seq_length, ).map(select_data_and_label_from_record) print("Starting Training and Validation...") validation_dataset = validation_dataset.take(validation_steps) train_and_validation_history = model.fit( train_dataset, shuffle=True, epochs=epochs, initial_epoch=initial_epoch_number, steps_per_epoch=train_steps_per_epoch, validation_data=validation_dataset, validation_steps=validation_steps, callbacks=callbacks, ) print(train_and_validation_history) else: # Not running validation print("Starting Training (Without Validation)...") train_history = model.fit( train_dataset, shuffle=True, epochs=epochs, initial_epoch=initial_epoch_number, steps_per_epoch=train_steps_per_epoch, callbacks=callbacks, ) print(train_history) if run_test: test_data_filenames = glob(os.path.join(test_data, "*.tfrecord")) print("test_data_filenames {}".format(test_data_filenames)) test_dataset = file_based_input_dataset_builder( channel="test", input_filenames=test_data_filenames, pipe_mode=pipe_mode, is_training=False, drop_remainder=False, batch_size=test_batch_size, epochs=epochs, steps_per_epoch=test_steps, max_seq_length=max_seq_length, ).map(select_data_and_label_from_record) print("Starting test...") test_history = model.evaluate(test_dataset, steps=test_steps, callbacks=callbacks) print("Test history {}".format(test_history)) # Save the Fine-Tuned Transformers Model as a New "Pre-Trained" Model print("transformer_fine_tuned_model_path {}".format(transformer_fine_tuned_model_path)) model.save_pretrained(transformer_fine_tuned_model_path) # Save the TensorFlow SavedModel for Serving Predictions print("tensorflow_saved_model_path {}".format(tensorflow_saved_model_path)) model.save(tensorflow_saved_model_path, save_format="tf") if run_sample_predictions: loaded_model = TFDistilBertForSequenceClassification.from_pretrained( transformer_fine_tuned_model_path, id2label={0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, label2id={1: 0, 2: 1, 3: 2, 4: 3, 5: 4}, ) tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") if num_gpus >= 1: inference_device = 0 # GPU 0 else: inference_device = -1 # CPU print("inference_device {}".format(inference_device)) inference_pipeline = TextClassificationPipeline( model=loaded_model, tokenizer=tokenizer, framework="tf", device=inference_device ) print( """I loved it! I will recommend this to everyone.""", inference_pipeline("""I loved it! I will recommend this to everyone."""), ) print("""It's OK.""", inference_pipeline("""It's OK.""")) print( """Really bad. I hope they don't make this anymore.""", inference_pipeline("""Really bad. I hope they don't make this anymore."""), ) ```
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import numpy as np %matplotlib inline df = pd.read_csv("/data/iris.csv") df.head() features = ["SepalLengthCm", "PetalLengthCm"] df.Species.value_counts() fig, ax = plt.subplots() colors = ["red", "green", "blue"] for i, v in enumerate(df.Species.unique()): df[df.Species == v].plot.scatter(features[0], features[1], label = v , ax = ax, color = colors[i]) from sklearn import * from mlxtend.plotting import plot_decision_regions y = np.where(df.Species == "Iris-setosa", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=2 # , include_bias=False)), ("scaler", preprocessing.StandardScaler()), ("est", linear_model.LogisticRegression(random_state = 1, solver="lbfgs")) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-virginica", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=2 # , include_bias=False)), ("scaler", preprocessing.StandardScaler()), ("est", linear_model.LogisticRegression(random_state = 1, solver="lbfgs")) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-versicolor", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=2 # , include_bias=False)), ("scaler", preprocessing.StandardScaler()), ("est", linear_model.LogisticRegression(random_state = 1, solver="lbfgs")) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-versicolor", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ ("poly", preprocessing.PolynomialFeatures(degree=4 , include_bias=False)), ("scaler", preprocessing.StandardScaler()), ("est", linear_model.LogisticRegression(random_state = 1, solver="lbfgs")) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-versicolor", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=4 # , include_bias=False)), #("scaler", preprocessing.StandardScaler()), ("est", tree.DecisionTreeClassifier(random_state = 1, max_depth=3)) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-versicolor", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=4 # , include_bias=False)), #("scaler", preprocessing.StandardScaler()), ("est", ensemble.RandomForestClassifier(random_state = 1, max_depth=3, n_estimators=20)) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = np.where(df.Species == "Iris-versicolor", 1, 0) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=4 # , include_bias=False)), #("scaler", preprocessing.StandardScaler()), ("est", neighbors.KNeighborsClassifier(n_neighbors=5)) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) print("precision:", metrics.precision_score(y_test, y_test_pred)) print("recall:", metrics.recall_score(y_test, y_test_pred)) print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = preprocessing.LabelEncoder().fit_transform(df.Species) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ #("poly", preprocessing.PolynomialFeatures(degree=4 # , include_bias=False)), #("scaler", preprocessing.StandardScaler()), ("est", neighbors.KNeighborsClassifier(n_neighbors=5)) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) #print("precision:", metrics.precision_score(y_test, y_test_pred)) ##print("recall:", metrics.recall_score(y_test, y_test_pred)) #print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) y = preprocessing.LabelEncoder().fit_transform(df.Species) X = df[features].values X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y , test_size = 0.3, random_state = 1) pipe = pipeline.Pipeline([ ("poly", preprocessing.PolynomialFeatures(degree=3 , include_bias=False)), ("scaler", preprocessing.StandardScaler()), ("est", linear_model.LogisticRegression(random_state=1 , multi_class="ovr" , solver = "liblinear")) ]) pipe.fit(X_train, y_train) y_train_pred = pipe.predict(X_train) y_test_pred = pipe.predict(X_test) y_test_prob = pipe.predict_proba(X_test)[:,1] print("accuracy:", metrics.accuracy_score(y_test, y_test_pred)) #print("precision:", metrics.precision_score(y_test, y_test_pred)) ##print("recall:", metrics.recall_score(y_test, y_test_pred)) #print("f1_score:", metrics.f1_score(y_test, y_test_pred)) plt.figure(figsize = (8,8)) plot_decision_regions(X, y, pipe, X_highlight=X_test) ```
github_jupyter
##### Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); 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. # JAX Quickstart Dougal Maclaurin, Peter Hawkins, Matthew Johnson, Roy Frostig, Alex Wiltschko, Chris Leary ![](https://raw.githubusercontent.com/google/jax/master/images/jax_logo_250px.png) #### [JAX](https://github.com/google/jax) is NumPy on the CPU, GPU, and TPU, with great automatic differentiation for high-performance machine learning research. With its updated version of [Autograd](https://github.com/hips/autograd), JAX can automatically differentiate native Python and NumPy code. It can differentiate through a large subset of Python’s features, including loops, ifs, recursion, and closures, and it can even take derivatives of derivatives of derivatives. It supports reverse-mode as well as forward-mode differentiation, and the two can be composed arbitrarily to any order. What’s new is that JAX uses [XLA](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/g3doc/overview.md) to compile and run your NumPy code on accelerators, like GPUs and TPUs. Compilation happens under the hood by default, with library calls getting just-in-time compiled and executed. But JAX even lets you just-in-time compile your own Python functions into XLA-optimized kernels using a one-function API. Compilation and automatic differentiation can be composed arbitrarily, so you can express sophisticated algorithms and get maximal performance without having to leave Python. ``` !pip install --upgrade -q https://storage.googleapis.com/jax-releases/cuda$(echo $CUDA_VERSION | sed -e 's/\.//' -e 's/\..*//')/jaxlib-0.1.23-cp36-none-linux_x86_64.whl !pip install --upgrade -q jax from __future__ import print_function, division import jax.numpy as np from jax import grad, jit, vmap from jax import random ``` ### Multiplying Matrices We'll be generating random data in the following examples. One big difference between NumPy and JAX is how you generate random numbers. For more details, see the readme. ``` key = random.PRNGKey(0) x = random.normal(key, (10,)) print(x) ``` Let's dive right in and multiply two big matrices. ``` size = 3000 x = random.normal(key, (size, size), dtype=np.float32) %timeit np.dot(x, x.T).block_until_ready() # runs on the GPU ``` JAX NumPy functions work on regular NumPy arrays. ``` import numpy as onp # original CPU-backed NumPy x = onp.random.normal(size=(size, size)).astype(onp.float32) %timeit np.dot(x, x.T).block_until_ready() ``` That's slower because it has to transfer data to the GPU every time. You can ensure that an NDArray is backed by device memory using `device_put`. ``` from jax import device_put x = onp.random.normal(size=(size, size)).astype(onp.float32) x = device_put(x) %timeit np.dot(x, x.T).block_until_ready() ``` The output of `device_put` still acts like an NDArray. If you have a GPU (or TPU!) these calls run on the accelerator and have the potential to be much faster than on CPU. ``` x = onp.random.normal(size=(size, size)).astype(onp.float32) %timeit onp.dot(x, x.T) ``` JAX is much more than just a GPU-backed NumPy. It also comes with a few program transformations that are useful when writing numerical code. For now, there's three main ones: - `jit`, for speeding up your code - `grad`, for taking derivatives - `vmap`, for automatic vectorization or batching. Let's go over these, one-by-one. We'll also end up composing these in interesting ways. ### Using `jit` to speed up functions JAX runs transparently on the GPU (or CPU, if you don't have one, and TPU coming soon!). However, in the above example, JAX is dispatching kernels to the GPU one operation at a time. If we have a sequence of operations, we can use the `@jit` decorator to compile multiple operations together using [XLA](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/g3doc/overview.md). Let's try that. ``` def selu(x, alpha=1.67, lmbda=1.05): return lmbda * np.where(x > 0, x, alpha * np.exp(x) - alpha) x = random.normal(key, (1000000,)) %timeit selu(x).block_until_ready() ``` We can speed it up with `@jit`, which will jit-compile the first time `selu` is called and will be cached thereafter. ``` selu_jit = jit(selu) %timeit selu_jit(x).block_until_ready() ``` ### Taking derivatives with `grad` In addition to evaluating numerical functions, we also want to transform them. One transformation is [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). In JAX, just like in [Autograd](https://github.com/HIPS/autograd), you can compute gradients with the `grad` function. ``` def sum_logistic(x): return np.sum(1.0 / (1.0 + np.exp(-x))) x_small = np.arange(3.) derivative_fn = grad(sum_logistic) print(derivative_fn(x_small)) ``` Let's verify with finite differences that our result is correct. ``` def first_finite_differences(f, x): eps = 1e-3 return np.array([(f(x + eps * v) - f(x - eps * v)) / (2 * eps) for v in onp.eye(len(x))]) print(first_finite_differences(sum_logistic, x_small)) ``` Taking derivatives is as easy as calling `grad`. `grad` and `jit` compose and can be mixed arbitrarily. In the above example we jitted `sum_logistic` and then took its derivative. We can go further: ``` print(grad(jit(grad(jit(grad(sum_logistic)))))(1.0)) ``` For more advanced autodiff, you can use `jax.vjp` for reverse-mode vector-Jacobian products and `jax.jvp` for forward-mode Jacobian-vector products. The two can be composed arbitrarily with one another, and with other JAX transformations. Here's one way to compose them to make a function that efficiently computes full Hessian matrices: ``` from jax import jacfwd, jacrev def hessian(fun): return jit(jacfwd(jacrev(fun))) ``` ### Auto-vectorization with `vmap` JAX has one more transformation in its API that you might find useful: `vmap`, the vectorizing map. It has the familiar semantics of mapping a function along array axes, but instead of keeping the loop on the outside, it pushes the loop down into a function’s primitive operations for better performance. When composed with `jit`, it can be just as fast as adding the batch dimensions by hand. We're going to work with a simple example, and promote matrix-vector products into matrix-matrix products using `vmap`. Although this is easy to do by hand in this specific case, the same technique can apply to more complicated functions. ``` mat = random.normal(key, (150, 100)) batched_x = random.normal(key, (10, 100)) def apply_matrix(v): return np.dot(mat, v) ``` Given a function such as `apply_matrix`, we can loop over a batch dimension in Python, but usually the performance of doing so is poor. ``` def naively_batched_apply_matrix(v_batched): return np.stack([apply_matrix(v) for v in v_batched]) print('Naively batched') %timeit naively_batched_apply_matrix(batched_x).block_until_ready() ``` We know how to batch this operation manually. In this case, `np.dot` handles extra batch dimensions transparently. ``` @jit def batched_apply_matrix(v_batched): return np.dot(v_batched, mat.T) print('Manually batched') %timeit batched_apply_matrix(batched_x).block_until_ready() ``` However, suppose we had a more complicated function without batching support. We can use `vmap` to add batching support automatically. ``` @jit def vmap_batched_apply_matrix(v_batched): return vmap(apply_matrix)(v_batched) print('Auto-vectorized with vmap') %timeit vmap_batched_apply_matrix(batched_x).block_until_ready() ``` Of course, `vmap` can be arbitrarily composed with `jit`, `grad`, and any other JAX transformation. This is just a taste of what JAX can do. We're really excited to see what you do with it!
github_jupyter
### Preprocessing ``` # import relevant statistical packages import numpy as np import pandas as pd # import relevant data visualisation packages import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # load Default dataset url = "/Users/arpanganguli/Documents/Professional/Finance/ISLR/Datasets/Default.csv" Default = pd.read_csv(url, index_col = 'Unnamed: 0') Default.head() Default.info() dfX = Default[['student', 'balance','income']] dfX = pd.get_dummies(data = dfX, drop_first=True) dfy = Default['default'] dfX.head() dfy.head() ``` ### 5.a. Fitting a logistic regression model ``` from sklearn.linear_model import LogisticRegression X = dfX[['income', 'balance']] y = dfy glmfit = LogisticRegression(solver = 'liblinear').fit(X, y) glmfit.coef_ ``` ### 5.b. Validation set approach ``` from sklearn.model_selection import train_test_split X = dfX[['income', 'balance']] y = dfy X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) from sklearn.metrics import confusion_matrix conf_mat = confusion_matrix(y_test, glmpred) conf_mat round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) ``` ### 5.c. Same process repeated thrice with different splits** ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) conf_mat = confusion_matrix(y_test, glmpred) round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) conf_mat = confusion_matrix(y_test, glmpred) round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.75, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) conf_mat = confusion_matrix(y_test, glmpred) round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) ``` #### Checking for multiple splits ``` sample = np.linspace(start = 0.05, stop = 0.95, num = 20) sample X = dfX[['income', 'balance']] y = dfy confpd = pd.DataFrame() for i in sample: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=i, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) conf_mat = confusion_matrix(y_test, glmpred) sum = round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) confpd = confpd.append([sum]) confpd.reset_index(drop=True, inplace=True) confpd.columns = ['Error'] confpd.head() confpd.mean() plt.xkcd() plt.figure(figsize = (25, 10)) plt.plot(confpd, marker = 'o', markersize = 10) plt.title("split% vs error rates") plt.ylabel("error rates") plt.xlabel("split%") ``` **We notice that the error rate asymptotically settle around ~0.62, but the growth really begins to plateau around 0.2.** ### 5.d. Fitting a logistic regression using income, balance and a dummy variable for student ``` X = dfX # no need to change since dfX already incorporates the dummy variable transformation for 'student' y = dfy ``` #### Using the validation set approach ``` X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) confusion_matrix(y_test, glmpred) round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) ``` #### Checking for multiple splits ``` sample = np.linspace(start = 0.05, stop = 0.95, num = 20) sample X = dfX y = dfy confpd = pd.DataFrame() for i in sample: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=i, random_state=42) print("X_train, ", X_train.shape, "y_train, ", y_train.shape, "X_test: ", X_test.shape, "y_test: ", y_test.shape) glmfit = LogisticRegression(solver='liblinear').fit(X_train, y_train) glmpred = glmfit.predict(X_test) conf_mat = confusion_matrix(y_test, glmpred) sum = round((conf_mat[0][1] + conf_mat[1][0]) / y_train.shape[0], 4) confpd = confpd.append([sum]) confpd.reset_index(drop=True, inplace=True) confpd.columns = ['Error'] confpd.head() confpd.mean() plt.xkcd() plt.figure(figsize = (25, 10)) plt.plot(confpd, marker = 'o', markersize = 10) plt.title("split% vs error rates") plt.ylabel("error rates") plt.xlabel("split%") ``` **We notice the same graph as that for logit without the dummy variable. So, we can conclude that the dummy variable does not lead to a reduction in the test error rate**
github_jupyter
``` import pandas as pd import numpy as np import scipy.stats import matplotlib.pyplot as plt import tensorflow as tf import statistics as stats from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import OneHotEncoder from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.optimizers import Adam from keras.regularizers import l2 from numpy.random import seed from keras.wrappers.scikit_learn import KerasRegressor from keras.regularizers import l2 from sklearn.model_selection import GridSearchCV # ensure repeatability np.random.seed(23) data = pd.read_csv("ML_data.csv", sep="|") pd.set_option("display.max_columns", None) data.head() ############ DATA PRE-PROCESSING ############ x_data = data.iloc[:, 10:53] y_data = data.iloc[:, 6:10] # separate categorical and continuous data categorical=pd.DataFrame() continuous=pd.DataFrame() for index in x_data.columns: if(x_data[index].dtypes == "int"): categorical[index]=x_data[index] elif(x_data[index].dtypes == "float"): continuous[index]=x_data[index] else: pass # one hot encode categorical data onehotencoder = OneHotEncoder() categorical = onehotencoder.fit_transform(categorical).toarray() # standardize continuous data scaler = StandardScaler() continuous = scaler.fit_transform(continuous) # re-combine categorical and continuous data x = np.concatenate((continuous, categorical), axis=1) # extract y data and standardize (DFT predicted / output) y = scaler.fit_transform(y_data) # split training and testing data x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=23) # input and output dimension in_dim = x.shape[1] out_dim = y.shape[1] # construct model def construct_model(learning_rate=5e-4, reg=0.05, d_o=0.01): # Create and add layers to model model = Sequential() model.add(Dense(out_dim*308, input_dim=in_dim, activation='relu', kernel_regularizer=l2(reg))) model.add(Dropout(d_o)) model.add(Dense(out_dim*308, activation='relu', )) model.add(Dense(out_dim*154, activation='relu')) model.add(Dropout(d_o)) model.add(Dense(out_dim*154, activation='relu')) model.add(Dense(out_dim)) # configure optimizer & compile model opt = Adam(lr=learning_rate, decay=0) ### need editing later (learning_rate, adam_decay) model.compile(loss="mse", optimizer=opt) #### summarize model # print(model.summary()) return model # parameter grid epochs = [50] batch_size = [10] learning_rate = [2.5e-3] #, 2.3e-3, 2.1e-3] reg = [0.01, 0.05] d_o = [.01] hyperparameters = dict(epochs=epochs, batch_size=batch_size, learning_rate=learning_rate, reg=reg, d_o=d_o ) neural_network = KerasRegressor(build_fn=construct_model, verbose=0) grid = GridSearchCV(estimator=neural_network, cv=2, param_grid=hyperparameters, n_jobs=-1, verbose=18) grid_result = grid.fit(x, y) print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) from datetime import datetime import pytz tz_NY = pytz.timezone('America/Los_Angeles') datetime_NY = datetime.now(tz_NY) print("Finished Time:", datetime_NY.strftime("%H:%M:%S")) ```
github_jupyter
# Laboratorio 3.1 *Elaborado por Oscar Franco-Bedoya* *`Proyecto Mision TIC 2021* ## Objetivo Aplicar el concepto de modulos mediante la impementación de programas que utilizan librerias de Python como math y random. ## La calculadora de Trigo ### Contexto El profesor de matemáticas del colegio de la esquina ha decidido desarrollar un programa en Python que realiza las operaciones trigonométricas y así, ayudar a sus estudiantes olvidadizos que olvidan traer su Calculadora científica para la clase: Las operaciones que desea realizar son - Seno(a) - Coseno(a) - Tangente(a) - Cotangente(a) - Arcoseno(a) - Arcocoseno(x) - Arcotangente(x) x es un angulo en grados Como el profesor sabe de funciones en programación y entiende la importancia de la programación modular, ha decidido implementar la aplicación utilizando funciones ``` """ Laboratorio 3.1 La calculadora de Trigo Oscar Franco-Bedoya Mayo 10-2021 """ # Importar modulos/librerias import math as m # Definición de Funciones (Dividir) def calcular_seno(angulo_grados): """ Parameters ---------- nangulo_grados:float un numero entre 0 y 360 que representa un ángulo en graados ------- Return seno:float el seno del angulo_grados """ seno= m.sin(m.radians(angulo_grados)) return seno #TODO: Ayudar al profe con las demás funciones """ - calcular_coseno(angulo_grados) - calcular_tangente(angulo_grados) - calcular_cotangente(angulo_grados) - calcular_arcoseno(angulo_grados) - calcular_arcocoseno(angulo_grados) - calcular_arcotangente(angulo_grados) """ #====================================================================== # Algoritmo principal Punto de entrada a la aplicación (Conquistar) # ===================================================================== #lectura angulo angulo_g=float(input("Ingresa un ángulo entre 0 y 360 ")) r_seno=calcular_seno(angulo_g) print("Seno(",angulo_g,")=",r_seno) ``` ## La raiz 4 Nos han pedido un pequeño programa que calcule la raíz cuarta de un número. No se diga más, ¡a escribirlo en la siguiente celda de código! <details> <summary>Dale a la flecha si necesitas una pista</summary> <pre><code> Afortunadamente tenemos la lista de funciones de math <a href="https://docs.python.org/3/library/math.html">Modulo math</a> Solo sera buscar la funcion respectiva ¿O no? <code><pre> </details> <details> <summary>Dale a la flecha si necesitas AUN MAS AYUDA</summary> <pre><code> Por ahi dicen que la raiz cuarta es la raiz cuadrada de la raiz cuadrada : <code><pre> </details> ``` import math as m valor=float(input("Ingresa un numero ")) #raiz_cuarta=m.sqrt(?()) #TODO: completar el código ``` ## La raiz n Debido al éxito arrollador del programa que calcula la raíz cuarta, nos han pedido un programa que calcule cualquier raíz n (n número entero) para un numero dado. <details> <summary>Dale a la flecha si necesitas una pista</summary> <pre><code> La raiz nesima de X es igual a X elevado a la 1/n <code><pre> </details> ``` import math as m valor=float(input("Ingresa un numero ")) raiz=int(input("Ingresa la raiz que quieres calcular ")) #raiz_n= #TODO: completar el código ``` ## Juego de Dados Vamos a realizar una función que simula el lanzamiento de un dado de 6 caras. Para ello se debe utilizar un modulo de Python llamado [random.py](https://docs.python.org/3/library/random.html) Dale clic para ver sus funciones. ``` """ Laboratorio 3.1 Lanzamiento de dados Oscar Franco-Bedoya Mayo 10-2021 """ # Importar modulos/librerias #TODO: 1) Que debo importar aqui # Definición de Funciones (Dividir) def lanzar_dado(): #TODO: 2) Terminar la función #====================================================================== # Algoritmo principal Punto de entrada a la aplicación (Conquistar) # ===================================================================== #TODO: 3) Programa principal ``` <details> <summary>Dale a la flecha si necesitas una pista</summary> <pre><code> 1) para importar un modulo se usa la palabra import seguida del nombre del módulo 2) la función que genera un numero aleatorio es random.randint(1, 6) 3) Solo llama a la fución lanzar_dado() <code><pre> </details> ## Dos dados Para hacer el juego mas interesante modifique el programa para que simule el lanzamiento de dos dados ### NOTA No deben definirse mas funciones, solo modifique el programa principal <details> <summary>Dale a la flecha si necesitas una pista</summary> <pre><code> Recuerda que una función puede llamarse varias veces <code><pre> </details> ``` """ Laboratorio 3.1 Lanzamiento de DOS dados Oscar Franco-Bedoya Mayo 10-2021 """ #TODO: Copiar y pegar el anterior programa y cambiar el programa principal ``` --- FINAL LABORATORIO ---
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import math import cv2 from skimage import io, color, exposure, feature, filters, util, measure from skimage import img_as_ubyte from skimage import img_as_float from skimage.filters import threshold_otsu from skimage.draw import ellipse_perimeter from skimage.draw import line from skimage.draw import ellipse from skimage.transform import hough_ellipse from skimage.morphology import reconstruction from skimage.feature import peak_local_max from skimage.measure import label, regionprops from scipy import ndimage as ndi def show(img): fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3)) ax1.imshow(img, cmap=plt.cm.gray) ax2.hist(img.ravel(), lw=0) ax2.set_xlim(0, img.max()) ax2.set_title('Histogram') ax2.set_yticks([]) plt.show() image = io.imread('input_image.jpg') plt.imshow(image) plt.title('Input Image') from skimage.transform import resize input_img = image[:,:,0] # sr = satuan resized sr = 2 ix = input_img.shape[0] if ix >=500: while ix >= 250: ix = ix // (sr) sr = sr+2 print('satuan resize =', sr) image_resized = resize(input_img, (input_img.shape[0] // sr, input_img.shape[1] // sr), anti_aliasing=True) image_resized2 = resize(input_img, (input_img.shape[0] // sr, input_img.shape[1] // sr), anti_aliasing=True) else: print('Sumbu Y tidak mencapai 1000 pixel, resize tidak dilakukan.') image_resized = input_img image_resized2 = input_img show(image_resized) image_resized.dtype #io.imsave("8_resize.jpg", np.uint8(image_resized*255)) g = filters.gaussian(image_resized, 2, multichannel=False) show(g) #io.imsave("8_gaussian.jpg", np.uint8(g*255)) hasil_ex = exposure.rescale_intensity(g, in_range=(0.4,0.95), out_range=(0,1)) show(hasil_ex) #io.imsave("8_rescaleintensity.jpg", np.uint8(hasil_ex*255)) hasil_ex = hasil_ex / hasil_ex.max() hasil_ex = 255 * hasil_ex img = hasil_ex.astype(np.uint8) clahe = exposure.equalize_adapthist(img) show(clahe) #io.imsave("8_clahe.jpg", np.uint8(clahe*255)) edges = filters.sobel(clahe) plt.imshow(edges, cmap='gray') plt.title('Sobel Edge Filtering') #io.imsave("8_sobel.jpg", np.uint8(edges*255)) low = 0.14 high = 0.3 lowt = (edges > low).astype(int) hight = (edges > high).astype(int) hyst = filters.apply_hysteresis_threshold(edges, low, high) plt.imshow(hight + hyst, cmap='gray') plt.title('Hysteresis Threshold Filtering') #io.imsave("8_hysteresisthreshold.jpg", np.uint8((hight + hyst)*255)) edges2 = feature.canny(hight + hyst, sigma=3.8, low_threshold=0.1, high_threshold=0.71) plt.imshow(edges2, cmap='gray') plt.title('Canny Edge Filtering') #io.imsave("8_canny.jpg", np.uint8(edges2*255)) x, y = np.where(edges2[...]>=1) coords = np.column_stack((x,y)) n = len(coords) maks = 0 for i in range(0,n): X1 = coords[i][1] Y1 = coords[i][0] for j in range(1,n): X2 = coords[j][1] Y2 = coords[j][0] jarak = math.sqrt((X2 - X1)**2 + (Y2 - Y1)**2) if jarak > maks: maks = jarak x1 = X1 y1 = Y1 x2 = X2 y2 = Y2 x0 = (x1+x2)/2 y0 = (y1+y2)/2 fig, (ax1) = plt.subplots(1, 1, figsize = (10,8)) ax1.imshow(edges2,cmap='gray') ax1.set_title('Randomized Hough Transform Points \n major points (red and yellow), ellipse center point (green)') ax1.plot(x1,y1,'or', markersize=5) ax1.plot(x2,y2,'oy', markersize=5) ax1.plot(x0,y0,'og', markersize=5) acc = [] max_element = [] jarak1 = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) a = (math.sqrt((x2-x1)**2+(y2-y1)**2))/2 alpha = math.atan((y2-y1)/(x2-x1)) for k in range(0,n): x3 = coords[k][1] y3 = coords[k][0] jarak2 = math.sqrt((x3 - x0)**2 + (y3 - y0)**2) if (jarak2 >= 60) and (jarak2 < a): d = jarak2 #print(a,d) f1 = math.sqrt((x3 - x1)**2 + (y3 - y1)**2) f2 = math.sqrt((x3 - x2)**2 + (y3 - y2)**2) if f1<f2: f = f1 elif f1>f2: f = f2 cos_teta = ((a**2) + (d**2) - (f**2))/(2 * a * d) if cos_teta<1: sin_teta = math.sqrt(1-(cos_teta**2)) b = math.sqrt(((a**2) * (d**2) * (sin_teta**2))/((a**2) - (d**2) * (cos_teta**2))) #print(b) acc.append(b) if len(acc) >= 1: max_element.append(max(acc)) result = np.argmax(acc) #print(max_element) semimajor = a semiminor = max(max_element) print(semimajor, semiminor) konstruksi_elips = np.zeros((edges2.shape[0],edges2.shape[1])) rr, cc = ellipse(y0, x0, semiminor, semimajor, konstruksi_elips.shape, rotation=(-alpha)) konstruksi_elips[rr,cc] = 255 plt.imshow(konstruksi_elips, cmap='gray') plt.title('Ellipse Region') label_img = label(konstruksi_elips) regions = regionprops(label_img, coordinates='rc') konstruksi_elips.dtype background = image_resized.copy() foreground = konstruksi_elips.copy() output = image_resized.copy() alfa = 1 #transparency parameter beta = 0.005 test = cv2.addWeighted(background,alfa,foreground,beta,0,output) fig, (ax1) = plt.subplots(1, 1, figsize = (10,8)) ax1.imshow(edges2,cmap='gray') ax1.set_title('Randomized Hough Transform Points \n major points (red and yellow), ellipse center point (green)') ax1.imshow(test, cmap='gray') ax1.plot(x1,y1,'or', markersize=5) ax1.plot(x2,y2,'oy', markersize=5) ax1.plot(x0,y0,'og', markersize=5) fig, ax = plt.subplots() ax.imshow(konstruksi_elips, cmap=plt.cm.gray) ax.set_title('Ellipse ROI Based on RHT') for props in regions: minr, minc, maxr, maxc = props.bbox bx = (minc, maxc, maxc, minc, minc) by = (minr, minr, maxr, maxr, minr) ax.plot(bx, by, '-b', linewidth=2.5) plt.show() ROI = konstruksi_elips[minr:maxr,minc:maxc] plt.imshow(ROI,cmap='gray') plt.title('Focused ROI') ROI.dtype label_img_ROI = label(ROI) regions_ROI = regionprops(label_img_ROI, coordinates='rc') ori_roi = image_resized2[minr:maxr,minc:maxc] plt.imshow(ori_roi,cmap='gray') plt.title('Raw Image ROI') ori_roi = 255 * ori_roi if(len(ori_roi.shape)<3): Z = ori_roi.reshape((-1,1)) elif len(ori_roi.shape)==3: Z = ori_roi.reshape((-1,3)) # convert to np.float32 Z = np.float32(Z) Z.dtype # define criteria, number of clusters(K) and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 2 ret,label,center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) labels = label.flatten() res = center[labels] Clustered_Image = res.reshape((ori_roi.shape)) plt.imshow(Clustered_Image,cmap='gray') plt.title('CLustered Image \n K = 2') x, y = np.where(Clustered_Image[...] >= 120) image_seg=np.zeros((Clustered_Image.shape[0],Clustered_Image.shape[1])) rr, cc = x,y image_seg[rr,cc] = 255 inpc = image_seg.astype(np.uint8) plt.imshow(inpc,cmap='gray') plt.title('Highest Image Cluster') inpc.dtype from skimage.measure import label, regionprops import matplotlib.patches as mpatches label_image = label(inpc) low = 270 #1000 high = 300 #1200 fig, ax = plt.subplots(figsize=(8, 4)) ax.imshow(label_image) ax.set_title('Choroid Plexus Area') for region in regionprops(label_image): # take regions with large enough areas print(region.area) if (region.area >= low) and (region.area < high): # draw rectangle around segmented coins minr, minc, maxr, maxc = region.bbox rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) ax.add_patch(rect) ax.set_axis_off() plt.tight_layout() plt.show() # Finding contours for the thresholded image contours, hierarchy = cv2.findContours(inpc, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(ori_roi, contours, -1, (0,255,0), -10) plt.imshow(ori_roi) plt.title('ROI Contour') lowc = low-(low*0.1) highc = high+(high*0.1) for i in range(len(contours)): area = cv2.contourArea(contours[i]) if (area >= lowc) and (area <= highc): CP = i LA = area print('array ke = ', i, '| luas area = ', LA) break image_seg_hasil=np.zeros((ROI.shape[0],ROI.shape[1])) for j in range(len(contours[CP])): rr = contours[CP][j][0][1] cc = contours[CP][j][0][0] image_seg_hasil[rr,cc] = 255 plt.imshow(image_seg_hasil,cmap='gray') plt.title('CP Contour') hull = cv2.convexHull(contours[CP]) cv2.drawContours(image_seg_hasil, [hull], -1, (255,0,0), -3) plt.imshow(image_seg_hasil, cmap='gray') plt.title('Convex Hull Area') label_image2 = label(image_seg_hasil) fig, ax = plt.subplots(figsize=(8, 4)) ax.imshow(label_image2, cmap='gray') ax.set_title('Convex Hull Area') for region in regionprops(label_image2): VCH = region.area print('VOLUME CONVEX HULL = ', VCH) ax.set_axis_off() plt.tight_layout() plt.show() solidity = (LA/VCH) error_solidity = ((1-solidity)/1) * 100 print('Solidity = ', solidity, '| Error Percentage = ', error_solidity, '%') invert_segmen = util.invert(image_seg_hasil) CP_point_img = invert_segmen+ROI plt.imshow(CP_point_img,cmap='gray') plt.title('ROI Compared to CP') xluarlingkar, yluarlingkar = np.where(ROI[...]<=0) coordsluar = np.column_stack((xluarlingkar, yluarlingkar)) xcp, ycp = np.where(image_seg_hasil[...]>=255) coordscp = np.column_stack((xcp, ycp)) print(coordsluar) jarak_min = math.sqrt((coordsluar[0][1]-coordscp[0][1])**2 + (coordsluar[0][0]-coordscp[0][0])**2) print(jarak_min) x_ll = [] y_ll = [] x_cp =[] y_cp = [] for i in range(0,len(coordsluar)): xx = coordsluar[i][1] yy = coordsluar[i][0] for i in range(0,len(coordscp)): xx2 = coordscp[i][1] yy2 = coordscp[i][0] jarakini = math.sqrt((xx-xx2)**2 + (yy-yy2)**2) #print(jarakini) if jarakini < jarak_min: jarak_min = jarakini x_ll.append(xx) y_ll.append(yy) x_cp.append(xx2) y_cp.append(yy2) x_ll = x_ll[len(x_ll)-1] y_ll = y_ll[len(y_ll)-1] x_cp = x_cp[len(x_cp)-1] y_cp = y_cp[len(y_cp)-1] fig, ax = plt.subplots() ax.plot(x_ll, y_ll, 'r.') ax.plot(x_cp, y_cp, 'g.') ax.plot((x_ll, x_cp), (y_ll, y_cp), '-y', linewidth=2.5) ax.imshow(CP_point_img, cmap=plt.cm.gray) ax.set_title('Shortest Line in Between Black Area (yellow)') fig, ax = plt.subplots() ax.imshow(ROI, cmap=plt.cm.gray) ax.set_title('Ellipse Parameter \n CP/Ventricle point (green), semimajor (blue) & semiminor (red) lines') for props in regions_ROI: y0, x0 = props.centroid orientation = props.orientation x1 = int(x0 + math.cos(orientation) * 0.5 * props.minor_axis_length) #minor y1 = int(y0 - math.sin(orientation) * 0.5 * props.minor_axis_length) #minor x2 = int(x0 - math.sin(orientation) * 0.5 * props.major_axis_length) #mayor y2 = int(y0 - math.cos(orientation) * 0.5 * props.major_axis_length) #mayor ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5) ax.plot((x0, x2), (y0, y2), '-b', linewidth=2.5) ax.plot(x_cp, y_cp, 'g.', markersize=10) # titik CP ax.plot(x0, y0, '.g', markersize=10) minr_r, minc_r, maxr_r, maxc_r = props.bbox bx = (minc_r, maxc_r, maxc_r, minc_r, minc_r) by = (minr_r, minr_r, maxr_r, maxr_r, minr_r) ax.plot(bx, by, '-b', linewidth=2.5) plt.show() HW = 0.5 * props.minor_axis_length def slope(x1,y1,x2,y2): a = y1-y2 b = x1-x2 if a == 0: m = print('gradien adalah 0 karena garis sejajar sumbu x') searched_points_paralel_x(x_cp,y_cp) elif b == 0: m2 = print('gradien tak terhingga karena garis sejajar sumbu y') searched_points_paralel_y(x_cp,y_cp) else: m1 = a/b m2 = (-1/m1) return searched_points(m2,x_cp,y_cp) def searched_points_paralel_x(xi,yi): sp = [] for x in range(CP_point_img.shape[1]): y = yi sp.append([x,y]) return sp def searched_points_paralel_y(xi,yi): sp = [] for y in range(CP_point_img.shape[0]): x = xi sp.append([x,y]) return sp def searched_points(m,xi,yi): sp = [] for x in range(CP_point_img.shape[1]): y = int(abs(((m*x)-(m*xi))+yi)) sp.append([x,y]) return sp sp = slope(x2,y2,x0,y0) #print(sp) def available_points(x1,y1,x2,y2): ap = [] a = x2-x1 b = y2-y1 for x in range(CP_point_img.shape[1]): y = int(((b*x-b*x1)+a*y1)/a) ap.append([x,y]) return ap ap = available_points(int(x2),int(y2),int(x0),int(y0)) #print(ap) mp = np.zeros((1)) for x in sp: for y in ap: if x == y: mp = x else: for i in range(len(sp)): if (sp[i][1] == ap[i][1]) or (sp[i][1]+1 == ap[i][1]) or (sp[i][1]+2 == ap[i][1]): mp = sp[i] break print(mp) #print(cpx,cpy) xp = mp[0] yp = mp[1] fig, ax = plt.subplots() ax.plot((x_cp, xp), (y_cp, yp), '-y', linewidth=2.5) #51,75 #49,72 ax.plot((x2, x0), (y2, y0), '-b', linewidth=2.5) ax.plot(x0, y0, '.g', markersize=10) ax.plot(x_cp, y_cp, 'r.') ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5) ax.imshow(ROI, cmap=plt.cm.gray) ax.set_title('Semimajor (blue), LVW (yellow) & HW (red)') fig, ax = plt.subplots() ax.plot((x_cp, xp), (y_cp, yp), '-y', linewidth=2.5) ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5) ax.set_title('LVW (yellow) & HW (red)') ax.imshow(ROI, cmap=plt.cm.gray) def distance(x1,y1,x2,y2): dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return dist LVW = distance(x_cp,y_cp,xp,yp) # 1 pixel 91dpi = 0.264583333 mm LVW_Final = LVW*sr #print('Lateral Ventricle Width = ', LVW_Final, 'mm') print('Lateral Ventricle Width = ', LVW, 'px') HW_Final = HW*sr #print('Hemisphreci Width = ', HW_Final, 'mm') print('Hemisphreci Width = ', HW, 'px') Ratio = (LVW_Final/HW_Final)*100 print('Ratio = ', Ratio, '%') ```
github_jupyter
### Problem Statement Given a linked list with integer data, arrange the elements in such a manner that all nodes with even numbers are placed after odd numbers. **Do not create any new nodes and avoid using any other data structure. The relative order of even and odd elements must not change.** **Example:** * `linked list = 1 2 3 4 5 6` * `output = 1 3 5 2 4 6` ``` class Node: def __init__(self, data): self.data = data self.next = None ``` ### Exercise - Write the function definition here ``` def even_after_odd(head): """ :param - head - head of linked list return - updated list with all even elements are odd elements """ if head is None: return head even_head = None even_tail = None odd_head = None odd_tail = None current = head while current: next_node = current.next if current.data % 2 == 0: if even_head is None: even_head = current even_tail = even_head else: even_tail.next = current even_tail = even_tail.next else: if odd_head is None: odd_head = current odd_tail = odd_head else: odd_tail.next = current odd_tail = odd_tail.next current.next = None current = next_node if odd_head is None: return even_head odd_tail.next = even_head return odd_head ``` <span class="graffiti-highlight graffiti-id_xpuflcm-id_9q4n7o8"><i></i><button>Hide Solution</button></span> ``` """ parameter: - head of the given linked list return: - head of the updated list with all even elements placed after odd elements """ #--------------------------------------------------# ''' The Idea: Traverse the given LinkedList, and build two sub-lists: EVEN and ODD. For this purpose, we will use four helper references, that denotes starting and current ending of EVEN and ODD sub-list respectively. 1. For each Node in the LinkedList, check if its data is even/odd. Change the "next" reference (pointer) of each Node, based on the following rules: - First even valued Node will be referenced by head of EVEN sub-list - Subsequent even valued Node will be appended to the tail of EVEN sub-list - First odd valued Node will be referenced by head of ODD sub-list - Subsequent odd valued Node will be appended to the tail of ODD sub-list 2. After the loop, append the EVEN sub-list to the tail of ODD sub-list. ''' #--------------------------------------------------# def even_after_odd(head): if head is None: return head # Helper references ''' `even_head` and `even_tail` represents the starting and current ending of the "EVEN" sub-list ''' even_head = None even_tail = None ''' `odd_head` and `odd_tail` represents the starting and current ending of the "ODD" sub-list ''' odd_head = None odd_tail = None current = head # <-- "current" represents the current Node. # Loop untill there are Nodes available in the LinkedList while current: # <-- "current" will be updated at the end of each iteration next_node = current.next # <-- "next_node" represents the next Node w.r.t. the current Node if current.data % 2 == 0: # <-- current Node is even # Below if even_head is None: # <-- Make the current Node as the starting Node of EVEN sub-list even_head = current # `even_head` will now point where `current` is already pointing even_tail = even_head else: # <-- Append the current even node to the tail of EVEN sub-list even_tail.next = current even_tail = even_tail.next else: if odd_head is None: # <-- Make the current Node as the starting Node of ODD sub-list odd_head = current odd_tail = odd_head else: # <-- Append the current odd node to the tail of ODD sub-list odd_tail.next = current odd_tail = odd_tail.next current.next = None current = next_node # <-- Update "head" Node, for next iteration if odd_head is None: # <-- Special case, when there are no odd Nodes return even_head odd_tail.next = even_head # <-- Append the EVEN sub-list to the tail of ODD sub-list return odd_head ``` ### Test - Let's test your function ``` # helper functions for testing purpose def create_linked_list(arr): if len(arr)==0: return None head = Node(arr[0]) tail = head for data in arr[1:]: tail.next = Node(data) tail = tail.next return head def print_linked_list(head): while head: print(head.data, end=' ') head = head.next print() def test_function(test_case): head = test_case[0] solution = test_case[1] node_tracker = dict({}) node_tracker['nodes'] = list() temp = head while temp: node_tracker['nodes'].append(temp) temp = temp.next head = even_after_odd(head) temp = head index = 0 try: while temp: if temp.data != solution[index] or temp not in node_tracker['nodes']: print("Fail") return temp = temp.next index += 1 print("Pass") except Exception as e: print("Fail") arr = [1, 2, 3, 4, 5, 6] solution = [1, 3, 5, 2, 4, 6] head = create_linked_list(arr) test_case = [head, solution] test_function(test_case) arr = [1, 3, 5, 7] solution = [1, 3, 5, 7] head = create_linked_list(arr) test_case = [head, solution] test_function(test_case) arr = [2, 4, 6, 8] solution = [2, 4, 6, 8] head = create_linked_list(arr) test_case = [head, solution] test_function(test_case) ```
github_jupyter
# PYNQ tutorial: DMA to streamed interfaces Overlay consists of two DMAs and an AXI Stream FIFO (input and output AXI stream interfaces). The FIFO represents an accelerator. A single DMA could be used with a read and write channel enabled, but for demonstration purposes, two different DMAs will be used. * The first DMA with read channel enabled is connected from DDR to IP input stream (reading from DDR, and sending to AXI stream). * The second DMA has a write channel enabled and is connected to IP output stream to DDR (receiving from AXI stream, and writing to DDR memory). There are other IP in the design (not shown) which will be ignored for now. ![](images/dma_stream_example.png) ## 1. Downloading overlay The overlay can be downloaded automatically when instantiating an overlay class. ``` from pynq import Overlay overlay = Overlay("./bitstream/pynq_tutorial.bit") ``` We can check the IPs in this overlay. Notice the DMAs *axi_dma_from_pl_to_ps* and *axi_dma_from_pl_to_ps*. ``` overlay.ip_dict ``` ## 2. Create DMA instances Using the labels for the DMAs listed above, we can create two DMA objects. ``` import pynq.lib.dma dma_send = overlay.axi_dma_from_ps_to_pl dma_recv = overlay.axi_dma_from_pl_to_ps ``` ## 5. Read DMA We will read some data from memory, and write to FIFO in the following cells. The first step is to create the a contiguous memory block. Xlnk will be used to allocate the buffer, and NumPy will be used to specify the type of the buffer. ``` from pynq import Xlnk import numpy as np data_size = 100 xlnk = Xlnk() input_buffer = xlnk.cma_array(shape=(data_size,), dtype=np.uint32) ``` The array can be used like any other NumPy array. We can write some test data to the array. Later the data will be transferred by the DMA to the FIFO. ``` for i in range(data_size): input_buffer[i] = i + 0xcafe0000 ``` Let's check the contents of the array. The data in the following cell will be sent from PS (DDR memory) to PL (streaming FIFO). ``` print("Print first few values of buffer ...") for i in range(10): print(hex(input_buffer[i])) ``` Now we are ready to carry out DMA transfer from a memory block in DDR to FIFO. ``` dma_send.sendchannel.transfer(input_buffer) ``` ## 5. Write DMA Let's read the data back from FIFO stream, and write to MM memory. The steps are similar. We will prepare an empty array before reading data back from FIFO. ``` output_buffer = xlnk.cma_array(shape=(data_size,), dtype=np.uint32) print("Print first few values ...") for i in range(10): print('0x' + format(output_buffer[i], '02x')) dma_recv.recvchannel.transfer(output_buffer) ``` The next cell will print out the data received from PL (streaming FIFO) to PS (DDR memory). This should be the same as the data we sent previously. ``` print("Print first few values ...") for i in range(10): print('0x' + format(output_buffer[i], '02x')) ``` ## 6. Free all the memory buffers Don't forget to free the memory buffers to avoid memory leaks! ``` del input_buffer, output_buffer ``` ## Appendix ## AXI DMA pdf PDFs can be linked from, or embedded in a Jupyter notebook. The pdf for the AXI DMA documentation is embedded in this notebook below: ``` from IPython.display import IFrame IFrame("pg021_axi_dma.pdf", width=800, height=800) ```
github_jupyter
# Machine Learning Engineer Nanodegree ## Reinforcement Learning ## Project: Train a Smartcab to Drive Welcome to the fourth project of the Machine Learning Engineer Nanodegree! In this notebook, template code has already been provided for you to aid in your analysis of the *Smartcab* and your implemented learning algorithm. You will not need to modify the included code beyond what is requested. There will be questions that you must answer which relate to the project and the visualizations provided in the notebook. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide in `agent.py`. >**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. ----- ## Getting Started In this project, you will work towards constructing an optimized Q-Learning driving agent that will navigate a *Smartcab* through its environment towards a goal. Since the *Smartcab* is expected to drive passengers from one location to another, the driving agent will be evaluated on two very important metrics: **Safety** and **Reliability**. A driving agent that gets the *Smartcab* to its destination while running red lights or narrowly avoiding accidents would be considered **unsafe**. Similarly, a driving agent that frequently fails to reach the destination in time would be considered **unreliable**. Maximizing the driving agent's **safety** and **reliability** would ensure that *Smartcabs* have a permanent place in the transportation industry. **Safety** and **Reliability** are measured using a letter-grade system as follows: | Grade | Safety | Reliability | |:-----: |:------: |:-----------: | | A+ | Agent commits no traffic violations,<br/>and always chooses the correct action. | Agent reaches the destination in time<br />for 100% of trips. | | A | Agent commits few minor traffic violations,<br/>such as failing to move on a green light. | Agent reaches the destination on time<br />for at least 90% of trips. | | B | Agent commits frequent minor traffic violations,<br/>such as failing to move on a green light. | Agent reaches the destination on time<br />for at least 80% of trips. | | C | Agent commits at least one major traffic violation,<br/> such as driving through a red light. | Agent reaches the destination on time<br />for at least 70% of trips. | | D | Agent causes at least one minor accident,<br/> such as turning left on green with oncoming traffic. | Agent reaches the destination on time<br />for at least 60% of trips. | | F | Agent causes at least one major accident,<br />such as driving through a red light with cross-traffic. | Agent fails to reach the destination on time<br />for at least 60% of trips. | To assist evaluating these important metrics, you will need to load visualization code that will be used later on in the project. Run the code cell below to import this code which is required for your analysis. ``` # Import the visualization code import visuals as vs # Pretty display for notebooks %matplotlib inline ``` ### Understand the World Before starting to work on implementing your driving agent, it's necessary to first understand the world (environment) which the *Smartcab* and driving agent work in. One of the major components to building a self-learning agent is understanding the characteristics about the agent, which includes how the agent operates. To begin, simply run the `agent.py` agent code exactly how it is -- no need to make any additions whatsoever. Let the resulting simulation run for some time to see the various working components. Note that in the visual simulation (if enabled), the **white vehicle** is the *Smartcab*. ### Question 1 In a few sentences, describe what you observe during the simulation when running the default `agent.py` agent code. Some things you could consider: - *Does the Smartcab move at all during the simulation?* - *What kind of rewards is the driving agent receiving?* - *How does the light changing color affect the rewards?* **Hint:** From the `/smartcab/` top-level directory (where this notebook is located), run the command ```bash 'python smartcab/agent.py' ``` **Answer:** The Smartcab does not move at all during the simulation whether or not the light is red. It does not update its status, so it appears that the simulation does not affects its disposition.The driving agent is receiving positive rewards at the beginning when the Smartcab is stopped at a red light. Later, when the red light is changed to green light and there are no oncoming traffic, the reward soon becomes negative, however, the agent still remains where it is, idle at the current intersection. The cab is basically receiving awards based on its following of the traffic laws, but it is not moving at all, so it is not receiving a reward for when the light is green. ### Understand the Code In addition to understanding the world, it is also necessary to understand the code itself that governs how the world, simulation, and so on operate. Attempting to create a driving agent would be difficult without having at least explored the *"hidden"* devices that make everything work. In the `/smartcab/` top-level directory, there are two folders: `/logs/` (which will be used later) and `/smartcab/`. Open the `/smartcab/` folder and explore each Python file included, then answer the following question. ### Question 2 - *In the *`agent.py`* Python file, choose three flags that can be set and explain how they change the simulation.* - *In the *`environment.py`* Python file, what Environment class function is called when an agent performs an action?* - *In the *`simulator.py`* Python file, what is the difference between the *`'render_text()'`* function and the *`'render()'`* function?* - *In the *`planner.py`* Python file, will the *`'next_waypoint()`* function consider the North-South or East-West direction first?* **Answer:** In the *`agent.py`* Python file, there are the following flags: - learning: indicates whether the cab is in the learning mode or not. If it's in the learning mode, its actions will influence its decision making proccess in the next rounds. - num_dummies – discrete number of dummy agents in the environment: The number of dummy agents will affect the performance of our agent. Since we have to wait for other cars who has higher priority, more dummy agents will delay our agent in the intersection. Also we may have higher chance to have accident in the intersection, then the safety will be affected. - display: This flag enables the visual simulation that PyGame GUI provides if set to True, but is not expected to change the simulation outcome except not display the GUI. The default value of this flag is set to True. This may save time when we are running large numbers of Monte Carlo runs and trying to find the optimal parameters such as epsilon and alphs. In the *`environments.py`* Python file, the act() function is called when an agent performs an action. This functions enables the agent to act in the environment and receive the reward of his action. In the *`simulator.py`*, Python file, the 'render_text()' function display the current state in a textual format. The 'render()' function displays this in a nice Graphical User Interface (GUI) using the Python PyGame module. Both are needed, in my opinion, since the GUI's simulation display will not have historical information, but we can scroll back in the textural render to find historical information. In the *`planner.py`* Python file, the next_waypoint() function will consider the East-West direction first and then North-South direction. ----- ## Implement a Basic Driving Agent The first step to creating an optimized Q-Learning driving agent is getting the agent to actually take valid actions. In this case, a valid action is one of `None`, (do nothing) `'left'` (turn left), `right'` (turn right), or `'forward'` (go forward). For your first implementation, navigate to the `'choose_action()'` agent function and make the driving agent randomly choose one of these actions. Note that you have access to several class variables that will help you write this functionality, such as `'self.learning'` and `'self.valid_actions'`. Once implemented, run the agent file and simulation briefly to confirm that your driving agent is taking a random action each time step. ### Basic Agent Simulation Results To obtain results from the initial simulation, you will need to adjust following flags: - `'enforce_deadline'` - Set this to `True` to force the driving agent to capture whether it reaches the destination in time. - `'update_delay'` - Set this to a small value (such as `0.01`) to reduce the time between steps in each trial. - `'log_metrics'` - Set this to `True` to log the simluation results as a `.csv` file in `/logs/`. - `'n_test'` - Set this to `'10'` to perform 10 testing trials. Optionally, you may disable to the visual simulation (which can make the trials go faster) by setting the `'display'` flag to `False`. Flags that have been set here should be returned to their default setting when debugging. It is important that you understand what each flag does and how it affects the simulation! Once you have successfully completed the initial simulation (there should have been 20 training trials and 10 testing trials), run the code cell below to visualize the results. Note that log files are overwritten when identical simulations are run, so be careful with what log file is being loaded! Run the agent.py file after setting the flags from projects/smartcab folder instead of projects/smartcab/smartcab. ``` # Load the 'sim_no-learning' log file from the initial simulation results vs.plot_trials('sim_no-learning.csv') ``` ### Question 3 Using the visualization above that was produced from your initial simulation, provide an analysis and make several observations about the driving agent. Be sure that you are making at least one observation about each panel present in the visualization. Some things you could consider: - *How frequently is the driving agent making bad decisions? How many of those bad decisions cause accidents?* - *Given that the agent is driving randomly, does the rate of reliability make sense?* - *What kind of rewards is the agent receiving for its actions? Do the rewards suggest it has been penalized heavily?* - *As the number of trials increases, does the outcome of results change significantly?* - *Would this Smartcab be considered safe and/or reliable for its passengers? Why or why not?* **Answer:** - The driving agent is making bad decisions somewhere between about 38% and 42% of the time. These bad decisions lead to a decent amount of accidents, with minor accidents occurring around 5% of the time, and major accidents between roughly 4.8% and 6% of the time. - Given that the agent is driving randomly and is not learning, this result does make sense. This shouldn't be a surprise since it's choosing its actions randomly and with no consideration with where it should go or what the traffic conditions are like. - The rewards received on average are between -4 and -6, showing it is getting heavily penalized. And it did not improve with time, showing that random choice is by no means a 'self-learning' algorithm. - As the number of trials increases, the accident frequence does not imporve significantly. The reliablility rate does not change overall and stays a constant around 30%. This could be because our agent is still making decisions randomly and not learning from it's mistakes. - As it is right now, the Smartcab would not be considered safe and it should not be allowed to actually be on the road. This Smartcab is both unsafe and unreliable (getting F's in both). To be safe, we would want very few accidents or violations, and to be reliable it would need to arrive on time much closer to 100% of the time. ----- ## Inform the Driving Agent The second step to creating an optimized Q-learning driving agent is defining a set of states that the agent can occupy in the environment. Depending on the input, sensory data, and additional variables available to the driving agent, a set of states can be defined for the agent so that it can eventually *learn* what action it should take when occupying a state. The condition of `'if state then action'` for each state is called a **policy**, and is ultimately what the driving agent is expected to learn. Without defining states, the driving agent would never understand which action is most optimal -- or even what environmental variables and conditions it cares about! ### Identify States Inspecting the `'build_state()'` agent function shows that the driving agent is given the following data from the environment: - `'waypoint'`, which is the direction the *Smartcab* should drive leading to the destination, relative to the *Smartcab*'s heading. - `'inputs'`, which is the sensor data from the *Smartcab*. It includes - `'light'`, the color of the light. - `'left'`, the intended direction of travel for a vehicle to the *Smartcab*'s left. Returns `None` if no vehicle is present. - `'right'`, the intended direction of travel for a vehicle to the *Smartcab*'s right. Returns `None` if no vehicle is present. - `'oncoming'`, the intended direction of travel for a vehicle across the intersection from the *Smartcab*. Returns `None` if no vehicle is present. - `'deadline'`, which is the number of actions remaining for the *Smartcab* to reach the destination before running out of time. ### Question 4 *Which features available to the agent are most relevant for learning both **safety** and **efficiency**? Why are these features appropriate for modeling the *Smartcab* in the environment? If you did not choose some features, why are those features* not *appropriate? Please note that whatever features you eventually choose for your agent's state, must be argued for here. That is: your code in agent.py should reflect the features chosen in this answer. * NOTE: You are not allowed to engineer new features for the smartcab. **Answer:** The four features as below ('waypoint', 'oncoming', 'left', and 'light' ) are most relevant for learning both safety and efficiency: - The 'waypoint' helps leads the Smartcab to the destination in the correct derection through the most optimal way, improving the efficiency. - The 'oncoming' and 'left' features contain the intended directions of travel of other cars near the Smartcab in the environment. The Smartcab must know if there is a vehicle coming in the opposite direction when it is trying to make a left turn, so as to not go into a road with oncoming traffic when deciding to turn left. If the agent decides to drive into oncoming traffic, then it will cause either a minor traffic violation or, if there is a vehicle present, a major accident. - The 'light' is the key feature that Smartcab must to know as to learn it will be penalized for being in idle state when the light is green, or going through intersections with red traffic lights which will cause traffic violations and even accidents. The two feature ('Right' and 'deadline') I would not consider as relivent for the following reasons: - The 'right' we don't need to care about, as they won't shouldn't forward on a red light, assuming they follow traffic rules, though we do need to check out for cars on the left before taking a right turn at a traffic light. - The 'deadline' seems important; however, the Smartcab may start to learn to be more dangerous in order to meet its deadline, and we don't want that. Setting it this way may help improve on its reliability by causing minor safety violations to major accidents. This is something to avoid, but I think we want the agent to learn it on its own. ### Define a State Space When defining a set of states that the agent can occupy, it is necessary to consider the *size* of the state space. That is to say, if you expect the driving agent to learn a **policy** for each state, you would need to have an optimal action for *every* state the agent can occupy. If the number of all possible states is very large, it might be the case that the driving agent never learns what to do in some states, which can lead to uninformed decisions. For example, consider a case where the following features are used to define the state of the *Smartcab*: `('is_raining', 'is_foggy', 'is_red_light', 'turn_left', 'no_traffic', 'previous_turn_left', 'time_of_day')`. How frequently would the agent occupy a state like `(False, True, True, True, False, False, '3AM')`? Without a near-infinite amount of time for training, it's doubtful the agent would ever learn the proper action! ### Question 5 *If a state is defined using the features you've selected from **Question 4**, what would be the size of the state space? Given what you know about the environment and how it is simulated, do you think the driving agent could learn a policy for each possible state within a reasonable number of training trials?* **Hint:** Consider the *combinations* of features to calculate the total number of states! **Answer:** Given that I am using four features, the states are summary as below: | Feature | Number of states | States | | :---: | :---: | :---: | | waypoint | 3 | forward, left, right | | inputs: oncoming | 4 | None, forward, left, right | | inputs: left | 4 | None, forward, left, right | | inputs: light | 2 | red, green | The number of combinations here will, thus, be 3x4x4x2 = 96. It is not a large number. I think it is a reasonable number of policies for the agent to learn within a reasonable number of training trials. In a few hundred trials, our agent should be able to see each state at-least once. So the driving agent could learn a policy for each possible state within a reasonable number of training trials. ### Update the Driving Agent State For your second implementation, navigate to the `'build_state()'` agent function. With the justification you've provided in **Question 4**, you will now set the `'state'` variable to a tuple of all the features necessary for Q-Learning. Confirm your driving agent is updating its state by running the agent file and simulation briefly and note whether the state is displaying. If the visual simulation is used, confirm that the updated state corresponds with what is seen in the simulation. **Note:** Remember to reset simulation flags to their default setting when making this observation! ----- ## Implement a Q-Learning Driving Agent The third step to creating an optimized Q-Learning agent is to begin implementing the functionality of Q-Learning itself. The concept of Q-Learning is fairly straightforward: For every state the agent visits, create an entry in the Q-table for all state-action pairs available. Then, when the agent encounters a state and performs an action, update the Q-value associated with that state-action pair based on the reward received and the iterative update rule implemented. Of course, additional benefits come from Q-Learning, such that we can have the agent choose the *best* action for each state based on the Q-values of each state-action pair possible. For this project, you will be implementing a *decaying,* $\epsilon$*-greedy* Q-learning algorithm with *no* discount factor. Follow the implementation instructions under each **TODO** in the agent functions. Note that the agent attribute `self.Q` is a dictionary: This is how the Q-table will be formed. Each state will be a key of the `self.Q` dictionary, and each value will then be another dictionary that holds the *action* and *Q-value*. Here is an example: ``` { 'state-1': { 'action-1' : Qvalue-1, 'action-2' : Qvalue-2, ... }, 'state-2': { 'action-1' : Qvalue-1, ... }, ... } ``` Furthermore, note that you are expected to use a *decaying* $\epsilon$ *(exploration) factor*. Hence, as the number of trials increases, $\epsilon$ should decrease towards 0. This is because the agent is expected to learn from its behavior and begin acting on its learned behavior. Additionally, The agent will be tested on what it has learned after $\epsilon$ has passed a certain threshold (the default threshold is 0.05). For the initial Q-Learning implementation, you will be implementing a linear decaying function for $\epsilon$. ### Q-Learning Simulation Results To obtain results from the initial Q-Learning implementation, you will need to adjust the following flags and setup: - `'enforce_deadline'` - Set this to `True` to force the driving agent to capture whether it reaches the destination in time. - `'update_delay'` - Set this to a small value (such as `0.01`) to reduce the time between steps in each trial. - `'log_metrics'` - Set this to `True` to log the simluation results as a `.csv` file and the Q-table as a `.txt` file in `/logs/`. - `'n_test'` - Set this to `'10'` to perform 10 testing trials. - `'learning'` - Set this to `'True'` to tell the driving agent to use your Q-Learning implementation. In addition, use the following decay function for $\epsilon$: $$ \epsilon_{t+1} = \epsilon_{t} - 0.05, \hspace{10px}\textrm{for trial number } t$$ If you have difficulty getting your implementation to work, try setting the `'verbose'` flag to `True` to help debug. Flags that have been set here should be returned to their default setting when debugging. It is important that you understand what each flag does and how it affects the simulation! Once you have successfully completed the initial Q-Learning simulation, run the code cell below to visualize the results. Note that log files are overwritten when identical simulations are run, so be careful with what log file is being loaded! ``` # Load the 'sim_default-learning' file from the default Q-Learning simulation vs.plot_trials('sim_default-learning.csv') ``` ### Question 6 Using the visualization above that was produced from your default Q-Learning simulation, provide an analysis and make observations about the driving agent like in **Question 3**. Note that the simulation should have also produced the Q-table in a text file which can help you make observations about the agent's learning. Some additional things you could consider: - *Are there any observations that are similar between the basic driving agent and the default Q-Learning agent?* - *Approximately how many training trials did the driving agent require before testing? Does that number make sense given the epsilon-tolerance?* - *Is the decaying function you implemented for $\epsilon$ (the exploration factor) accurately represented in the parameters panel?* - *As the number of training trials increased, did the number of bad actions decrease? Did the average reward increase?* - *How does the safety and reliability rating compare to the initial driving agent?* **Answer:** - Frequency of total bad actions has dropped down to around 18% from 35% of an agent with no learning, and it keeps going down as the number of training trials increases. We can also see a decrease in the major and minor traffic violations. This agent clearly got better based on above performance. - The agent required 20 trials before testing, which makes sense given that the epsilon was decreasing by 0.05. So, 1.0 - (20 x 0.05) = 0.0 < 0.05. When epsilon hit zero, it began testing. - Yes, my decaying function is accurately represented in the parameters panel, as it steadily decreased each trial across the 20 trials. - As the number of training trails increase, the number of bad action actually decrease from ~35% to under 20%, Similarly, the average reward increased substantially from nearly -5 to around -1.5. - The safety rating are still F. Even though the new Q-Learning agent performance has improved compare to the basic driving agent, it has not improved enough to earn a better rating for safety. We'll need further improvements to get better ratings. However, reliability is now a B, a complete flip from the F for the initial driving agent. ----- ## Improve the Q-Learning Driving Agent The third step to creating an optimized Q-Learning agent is to perform the optimization! Now that the Q-Learning algorithm is implemented and the driving agent is successfully learning, it's necessary to tune settings and adjust learning paramaters so the driving agent learns both **safety** and **efficiency**. Typically this step will require a lot of trial and error, as some settings will invariably make the learning worse. One thing to keep in mind is the act of learning itself and the time that this takes: In theory, we could allow the agent to learn for an incredibly long amount of time; however, another goal of Q-Learning is to *transition from experimenting with unlearned behavior to acting on learned behavior*. For example, always allowing the agent to perform a random action during training (if $\epsilon = 1$ and never decays) will certainly make it *learn*, but never let it *act*. When improving on your Q-Learning implementation, consider the implications it creates and whether it is logistically sensible to make a particular adjustment. ### Improved Q-Learning Simulation Results To obtain results from the initial Q-Learning implementation, you will need to adjust the following flags and setup: - `'enforce_deadline'` - Set this to `True` to force the driving agent to capture whether it reaches the destination in time. - `'update_delay'` - Set this to a small value (such as `0.01`) to reduce the time between steps in each trial. - `'log_metrics'` - Set this to `True` to log the simluation results as a `.csv` file and the Q-table as a `.txt` file in `/logs/`. - `'learning'` - Set this to `'True'` to tell the driving agent to use your Q-Learning implementation. - `'optimized'` - Set this to `'True'` to tell the driving agent you are performing an optimized version of the Q-Learning implementation. Additional flags that can be adjusted as part of optimizing the Q-Learning agent: - `'n_test'` - Set this to some positive number (previously 10) to perform that many testing trials. - `'alpha'` - Set this to a real number between 0 - 1 to adjust the learning rate of the Q-Learning algorithm. - `'epsilon'` - Set this to a real number between 0 - 1 to adjust the starting exploration factor of the Q-Learning algorithm. - `'tolerance'` - set this to some small value larger than 0 (default was 0.05) to set the epsilon threshold for testing. Furthermore, use a decaying function of your choice for $\epsilon$ (the exploration factor). Note that whichever function you use, it **must decay to **`'tolerance'`** at a reasonable rate**. The Q-Learning agent will not begin testing until this occurs. Some example decaying functions (for $t$, the number of trials): $$ \epsilon = a^t, \textrm{for } 0 < a < 1 \hspace{50px}\epsilon = \frac{1}{t^2}\hspace{50px}\epsilon = e^{-at}, \textrm{for } 0 < a < 1 \hspace{50px} \epsilon = \cos(at), \textrm{for } 0 < a < 1$$ You may also use a decaying function for $\alpha$ (the learning rate) if you so choose, however this is typically less common. If you do so, be sure that it adheres to the inequality $0 \leq \alpha \leq 1$. If you have difficulty getting your implementation to work, try setting the `'verbose'` flag to `True` to help debug. Flags that have been set here should be returned to their default setting when debugging. It is important that you understand what each flag does and how it affects the simulation! Once you have successfully completed the improved Q-Learning simulation, run the code cell below to visualize the results. Note that log files are overwritten when identical simulations are run, so be careful with what log file is being loaded! ``` # Load the 'sim_improved-learning' file from the improved Q-Learning simulation print("decaying functions-1: e=a**t, best parameters: Alpha: 0.5, Tolerance: 0.005") vs.plot_trials('sim_improved-learning.csv') # Load the 'sim_improved-learning' file from the improved Q-Learning simulation print("decaying functions-2: e=1/(t**2), best parameters: Alpha: 0.5, Tolerance: 0.0005") vs.plot_trials('sim_improved-learning.csv') # Load the 'sim_improved-learning' file from the improved Q-Learning simulation print("decaying functions-3: e=ABS(cos(a*t/t**2), best parameters: Alpha: 0.5, Tolerance: 0.0005") vs.plot_trials('sim_improved-learning.csv') # Load the 'sim_improved-learning' file from the improved Q-Learning simulation print("decaying functions-3: e=np.exp(-0.01*self.t), best parameters: Alpha: 0.5, Tolerance: 0.005") vs.plot_trials('sim_improved-learning.csv') ``` ### Question 7 Using the visualization above that was produced from your improved Q-Learning simulation, provide a final analysis and make observations about the improved driving agent like in **Question 6**. Questions you should answer: - *What decaying function was used for epsilon (the exploration factor)?* - *Approximately how many training trials were needed for your agent before begining testing?* - *What epsilon-tolerance and alpha (learning rate) did you use? Why did you use them?* - *How much improvement was made with this Q-Learner when compared to the default Q-Learner from the previous section?* - *Would you say that the Q-Learner results show that your driving agent successfully learned an appropriate policy?* - *Are you satisfied with the safety and reliability ratings of the *Smartcab*?* **Answer:** There are 3 factor in my experiment factorial design of final Q-Learning Simulation results: **Alpha: 0.5/0.2/0.1**, **Tolerance: 0.05/0.005/0.0005**, and **4 decaying functions** ($\epsilon = a^t, \epsilon = \frac{1}{t^2}, \epsilon = e^{-at}, \epsilon = \frac{cos(at)}{t^2}$). I made 36 attempts **(3X3X4=36)** before deriving the final optimized Q-Learning agent with differnt epsilons, alpha and tolerance values, including these combinations (some of their outcomes in the below table and in the charts are displayed above). I settle on using the $\epsilon = e^{-at}$ as the final exploration factor with alpha 0.5 and tolerance 0.005 (as above decaying functions-4). All results, bad actions, violations, accidents, rate of reliability, etc. do not behave the same between the basic driving agent, the default and the final optimized Q-Learning agents. Bad actions, violations, accidents all dramatically went down over time for the final optimized Q-Learning agent even when compared to the default Q-Learning agent which was clearly superior to the basic driving agent. The reliability has gone up (from ~20% to ~100%), and safety is now an A+ after failing before! Total bad actions dropped to around 0.01%, which is much improved from still being around 44% at the end of the default Q-learner's training. It is now consistently getting a positive award by the end of training. I would definitely say that the results show that the driving agent has learned an appropriate policy - the average reward being positive, along with **double A+**(high reliability and safety), show it has become very effective. I am certainly satisfied with these safety and reliability ratings. - Decaying functions-1: $ \epsilon = a^t, \textrm{for } a=0.01 $ | Attempt | Decaying functions | Alpha | Tolerance | Safety | Reliability | n_test | | :------: | :----------------: | :---: | :-------: | :----: | :---------: | :---: | | 1 | $\epsilon = a^t$ | 0.5 | 0.05 | F | F | 10 | | 2 | $\epsilon = a^t$ | 0.5 | 0.005 | **F** | **A+** | 10 | | 3 | $\epsilon = a^t$ | 0.5 | 0.0005 | F | F | 10 | | 4 | $\epsilon = a^t$ | 0.2 | 0.05 | F | B | 10 | | 5 | $\epsilon = a^t$ | 0.2 | 0.005 | F | F | 10 | | 6 | $\epsilon = a^t$ | 0.2 | 0.0005 | F | F | 10 | | 7 | $\epsilon = a^t$ | 0.1 | 0.05 | F | F | 10 | | 8 | $\epsilon = a^t$ | 0.1 | 0.005 | F | F | 10 | | 9 | $\epsilon = a^t$ | 0.1 | 0.0005 | F | F | 10 | - Decaying functions-2: $\epsilon = \frac{1}{t^2}\hspace{50px}$ | Attempt | Decaying functions | Alpha | Tolerance | Safety | Reliability | n_test | | :------: | :----------------: | :---: | :-------: | :----: | :---------: | :---: | | 1 | $\epsilon = \frac{1}{t^2}$ | 0.5 | 0.05 | F | F | 10 | | 2 | $\epsilon = \frac{1}{t^2}$ | 0.5 | 0.005 | F | D | 10 | | 3 | $\epsilon = \frac{1}{t^2}$ | 0.5 | 0.0005 | **C** | **D** | 10 | | 4 | $\epsilon = \frac{1}{t^2}$ | 0.2 | 0.05 | F | F | 10 | | 5 | $\epsilon = \frac{1}{t^2}$ | 0.2 | 0.005 | F | F | 10 | | 6 | $\epsilon = \frac{1}{t^2}$ | 0.2 | 0.0005 | F | F | 10 | | 7 | $\epsilon = \frac{1}{t^2}$ | 0.1 | 0.05 | F | F | 10 | | 8 | $\epsilon = \frac{1}{t^2}$ | 0.1 | 0.005 | F | F | 10 | | 9 | $\epsilon = \frac{1}{t^2}$ | 0.1 | 0.0005 | F | F | 10 | - Decaying functions-3: $\epsilon = \frac{cos(at)}{t^2}, \textrm{for } a=0.01 $ | Attempt | Decaying functions | Alpha | Tolerance | Safety | Reliability | n_test | | :------: | :----------------: | :---: | :-------: | :----: | :---------: | :---: | | 1 | $\epsilon = \frac{cos(at)}{t^2}$| 0.5 | 0.05 | D | C | 10 | | 2 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.5 | 0.005 | F | F | 10 | | 3 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.5 | 0.0005 | **C** | **C** | 10 | | 4 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.2 | 0.05 | F | F | 10 | | 5 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.2 | 0.005 | F | F | 10 | | 6 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.2 | 0.0005 | F | F | 10 | | 7 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.1 | 0.05 | F | F | 10 | | 8 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.1 | 0.005 | F | F | 10 | | 9 | $\epsilon = \frac{cos(at)}{t^2}$ | 0.1 | 0.0005 | F | F | 10 | - Decaying functions-4: $\epsilon = e^{-at}, \textrm{for } a=0.01 $ | Attempt | Decaying functions | Alpha | Tolerance | Safety | Reliability | n_test | | :------: | :----------------: | :---: | :-------: | :----: | :---------: | :---: | | 1 | $\epsilon = e^{-at}$ | 0.5 | 0.05 | **A+** | **A+** | 10 | | 2 | $\epsilon = e^{-at}$ | 0.5 | 0.005 | **A+** | **A+** | 10 | | 3 | $\epsilon = e^{-at}$ | 0.5 | 0.0005 | **A+** | **A+** | 10 | | 4 | $\epsilon = e^{-at}$ | 0.2 | 0.05 | A+ | A+ | 10 | | 5 | $\epsilon = e^{-at}$ | 0.2 | 0.005 | A | A | 10 | | 6 | $\epsilon = e^{-at}$ | 0.2 | 0.0005 | A+ | A | 10 | | 7 | $\epsilon = e^{-at}$ | 0.1 | 0.05 | A | A | 10 | | 8 | $\epsilon = e^{-at}$ | 0.1 | 0.005 | A | A | 10 | | 9 | $\epsilon = e^{-at}$ | 0.1 | 0.0005 | A | A | 10 | ### Define an Optimal Policy Sometimes, the answer to the important question *"what am I trying to get my agent to learn?"* only has a theoretical answer and cannot be concretely described. Here, however, you can concretely define what it is the agent is trying to learn, and that is the U.S. right-of-way traffic laws. Since these laws are known information, you can further define, for each state the *Smartcab* is occupying, the optimal action for the driving agent based on these laws. In that case, we call the set of optimal state-action pairs an **optimal policy**. Hence, unlike some theoretical answers, it is clear whether the agent is acting "incorrectly" not only by the reward (penalty) it receives, but also by pure observation. If the agent drives through a red light, we both see it receive a negative reward but also know that it is not the correct behavior. This can be used to your advantage for verifying whether the **policy** your driving agent has learned is the correct one, or if it is a **suboptimal policy**. ### Question 8 1. Please summarize what the optimal policy is for the smartcab in the given environment. What would be the best set of instructions possible given what we know about the environment? _You can explain with words or a table, but you should thoroughly discuss the optimal policy._ 2. Next, investigate the `'sim_improved-learning.txt'` text file to see the results of your improved Q-Learning algorithm. _For each state that has been recorded from the simulation, is the **policy** (the action with the highest value) correct for the given state? Are there any states where the policy is different than what would be expected from an optimal policy?_ 3. Provide a few examples from your recorded Q-table which demonstrate that your smartcab learned the optimal policy. Explain why these entries demonstrate the optimal policy. 4. Try to find at least one entry where the smartcab did _not_ learn the optimal policy. Discuss why your cab may have not learned the correct policy for the given state. Be sure to document your `state` dictionary below, it should be easy for the reader to understand what each state represents. **Answer:** Definition of optimal policy: If the light is green and the waypoint is forward, no matter where oncoming traffic to go, the agend can go forward. If the light is green and the waypoint is right, no matter where oncoming traffic to go, the agend can go right, Otherwise, if the waypoint is left and there is no oncoming car, the car can go left. If the light is green and the waypoint is left and there is oncoming car go forward or left, the agend should wait, otherwise, if there is oncoming car go right, the agend can go left with the inside lane (because the oncoming direction is also going left), or go forward and turn left at next intersection. If the light is red and the waypoing is right without any vehicles on the left, the car should go right on a red light (allowed in U.S.). Otherwise, the car need to wait. Not all the learned policy actions are the correct ones according to our optimal policy definition. The optimal policy would be the following: | light | waypoint | left traffic | oncoming traffic | Agent Should do | | :------: | :---: | :--------: | :-------: | :-------------: | | green | forward | - | forward/right/left | forward | | green | right | - | forward/right/left | right | | green | left | - | None | left | | green | left | - | forward | wait | | green | left | - | left | wait | | green | left | - | right | left(with inside lane)/forward | | red | right | None | - | right | | red | right | right/left | - | right | | red | right | forward | - | wait | | red | forward/left | - | - | wait | **Correct policy observation:** In the "sim_improved-learning.txt" policy mostly follows the above optimal policy. For example: - case1: ('right', 'green', 'forward', 'right') -- forward : 0.89 -- right : 0.00 -- None : 0.00 -- left : 0.00 When the waypoint is 'right' and the light is 'green' with left car 'forward' and oncoming car 'right', the agend can turns right, which is the optimal action. - case2: ('forward', 'red', None, None) -- forward : -10.15 -- right : 1.10 -- None : 2.30 -- left : -10.06 When the waypoint is ‘forward’ and the light is ‘red’, the driving agent waits without doing anything which is the optimal action. Going forward or turning left will violate the law and cause accident, so the penalty is large(-10.15 and -10.06). **Incorrect/unexpected policy observation:** - case1: ('right', 'red', 'forward', None) -- forward : -8.92 -- right : 2.05 -- None : 0.25 -- left : -9.77 When the light is red and we need to go right, we should be able to go right, but since the left traffic is going forward (to our right) they have the right of way so we shouldn't go anywhere. But in this case, there is a positive reward associated with going right (2.05) and it is large than 'None' (0.25). - case2: ('left', 'red', 'right', 'forward') -- forward : -19.73 -- right : 0.12 -- None : 2.09 -- left : 0.00 We need to go left and the light is red, so we should stay put, which is what the car would do. But there is a positive reward associated with going right, even though that would make us father away from the target. Perhaps this is because we are still following the traffic laws. However, if we are being efficient, we shouldn't go right. ----- ### Optional: Future Rewards - Discount Factor, `'gamma'` Curiously, as part of the Q-Learning algorithm, you were asked to **not** use the discount factor, `'gamma'` in the implementation. Including future rewards in the algorithm is used to aid in propagating positive rewards backwards from a future state to the current state. Essentially, if the driving agent is given the option to make several actions to arrive at different states, including future rewards will bias the agent towards states that could provide even more rewards. An example of this would be the driving agent moving towards a goal: With all actions and rewards equal, moving towards the goal would theoretically yield better rewards if there is an additional reward for reaching the goal. However, even though in this project, the driving agent is trying to reach a destination in the allotted time, including future rewards will not benefit the agent. In fact, if the agent were given many trials to learn, it could negatively affect Q-values! ### Optional Question 9 *There are two characteristics about the project that invalidate the use of future rewards in the Q-Learning algorithm. One characteristic has to do with the *Smartcab* itself, and the other has to do with the environment. Can you figure out what they are and why future rewards won't work for this project?* **Answer:** For the smartcab itself, since each state is local, there is no benefit to 'linking' actions together in this scenario. The objective of smartcab is to learn how to obey traffic rules, and get to the destination. Both of them can be learned from immediate reward, which has nothing to do with the future rewards. Furthermore, the cab is not aware of the overall environment, but just the intersection it is at. The environment does not expose this (X,Y) coordinate location information to the Smartcab agent. the Smartcab has no knowledge of its (X,Y) location in the grid world, so cannot be bias to move away from that to another (X,Y) location that it also does not know about. It can only go towards its destination based on directions given by its environment alone at its current state. For the environment, the states at each step are mostly independent. The choice the Smartcab makes at a certain step does not effect the state of the light or traffic on the next step. The ‘waypoint’ is the only feature of the state that may be dependent on the previous action but the disavantages of adding the future reward could negatively affect Q-values! > **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 **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.
github_jupyter
# Using Automated Machine Learning There are many kinds of machine learning algorithm that you can use to train a model, and sometimes it's not easy to determine the most effective algorithm for your particular data and prediction requirements. Additionally, you can significantly affect the predictive performance of a model by preprocessing the training data, using techniques such as normalization, missing feature imputation, and others. In your quest to find the *best* model for your requirements, you may need to try many combinations of algorithms and preprocessing transformations; which takes a lot of time and compute resources. Azure Machine Learning enables you to automate the comparison of models trained using different algorithms and preprocessing options. You can use the visual interface in [Azure Machine Learning studio](https://ml/azure.com) or the SDK to leverage this capability. he SDK gives you greater control over the settings for the automated machine learning experiment, but the visual interface is easier to use. In this lab, you'll explore automated machine learning using the SDK. ## Connect to Your Workspace The first thing you need to do is to connect to your workspace using the Azure ML SDK. > **Note**: If the authenticated session with your Azure subscription has expired since you completed the previous exercise, you'll be prompted to reauthenticate. ``` import azureml.core from azureml.core import Workspace # Load the workspace from the saved config file ws = Workspace.from_config() print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name)) ``` ## Prepare Data for Automated Machine Learning You don't need to create a training script for automated machine learning, but you do need to load the training data. In this case, you'll create a dataset containing details of diabetes patients (just as you did in previous labs), and then split this into two datasets: one for training, and another for model validation. ``` from azureml.core import Dataset default_ds = ws.get_default_datastore() if 'diabetes dataset' not in ws.datasets: default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data target_path='diabetes-data/', # Put it in a folder path in the datastore overwrite=True, # Replace existing files of the same name show_progress=True) #Create a tabular dataset from the path on the datastore (this may take a short while) tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv')) # Register the tabular dataset try: tab_data_set = tab_data_set.register(workspace=ws, name='diabetes dataset', description='diabetes data', tags = {'format':'CSV'}, create_new_version=True) print('Dataset registered.') except Exception as ex: print(ex) else: print('Dataset already registered.') # Split the dataset into training and validation subsets diabetes_ds = ws.datasets.get("diabetes dataset") train_ds, test_ds = diabetes_ds.random_split(percentage=0.7, seed=123) print("Data ready!") ``` ## Prepare a Compute Target One of the benefits of cloud compute is that it scales on-demand, enabling you to provision enough compute resources to process multiple child-runs of an automated machine learning experiment in parallel. You'll use the Azure Machine Learning compute cluster you created in an earlier lab (if it doesn't exist, it will be created). > **Important**: Change *your-compute-cluster* to the name of your compute cluster in the code below before running it! Cluster names must be globally unique names between 2 to 16 characters in length. Valid characters are letters, digits, and the - character. ``` from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException cluster_name = "your-compute-cluster" try: # Check for existing compute target training_cluster = ComputeTarget(workspace=ws, name=cluster_name) print('Found existing cluster, use it.') except ComputeTargetException: # If it doesn't already exist, create it try: compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS11_V2', max_nodes=2) training_cluster = ComputeTarget.create(ws, cluster_name, compute_config) training_cluster.wait_for_completion(show_output=True) except Exception as ex: print(ex) ``` ## Configure Automated Machine Learning Now you're ready to configure the automated machine learning experiment. To do this, you'll need an AutoML configuration that specifies options like the data to use, how many combinations to try, which metric to use when evaluating models, and so on. > **Note**: In this example, you'll restrict the experiment to 6 iterations to reduce the amount of time taken. In reality, you'd likely try many more iterations. ``` from azureml.train.automl import AutoMLConfig automl_config = AutoMLConfig(name='Automated ML Experiment', task='classification', compute_target=training_cluster, training_data = train_ds, validation_data = test_ds, label_column_name='Diabetic', iterations=6, primary_metric = 'AUC_weighted', max_concurrent_iterations=4, featurization='auto' ) print("Ready for Auto ML run.") ``` ## Run an Automated Machine Learning Experiment OK, you're ready to go. Let's run the automated machine learning experiment. > **Note**: This may take some time! ``` from azureml.core.experiment import Experiment from azureml.widgets import RunDetails print('Submitting Auto ML experiment...') automl_experiment = Experiment(ws, 'diabetes_automl') automl_run = automl_experiment.submit(automl_config) RunDetails(automl_run).show() automl_run.wait_for_completion(show_output=True) ``` ## Determine the Best Performing Model When the experiment has completed, view the output in the widget, and click the run that produced the best result to see its details. Then click the link to view the experiment details in the Azure portal and view the overall experiment details before viewing the details for the individual run that produced the best result. There's lots of information here about the performance of the model generated. Let's get the best run and the model that it produced. ``` best_run, fitted_model = automl_run.get_output() print(best_run) print(fitted_model) best_run_metrics = best_run.get_metrics() for metric_name in best_run_metrics: metric = best_run_metrics[metric_name] print(metric_name, metric) ``` Automated machine learning includes the option to try preprocessing the data, which is accomplished through the use of [Scikit-Learn transformation pipelines](https://scikit-learn.org/stable/modules/compose.html#combining-estimators) (not to be confused with Azure Machine Learning pipelines!). These produce models that include steps to transform the data before inferencing. You can view the steps in a model like this: ``` for step in fitted_model.named_steps: print(step) ``` Finally, having found the best performing model, you can register it. ``` from azureml.core import Model # Register model best_run.register_model(model_path='outputs/model.pkl', model_name='diabetes_model_automl', tags={'Training context':'Auto ML'}, properties={'AUC': best_run_metrics['AUC_weighted'], 'Accuracy': best_run_metrics['accuracy']}) # List registered models for model in Model.list(ws): print(model.name, 'version:', model.version) for tag_name in model.tags: tag = model.tags[tag_name] print ('\t',tag_name, ':', tag) for prop_name in model.properties: prop = model.properties[prop_name] print ('\t',prop_name, ':', prop) print('\n') ``` > **More Information**: For more information Automated Machine Learning, see the [Azure ML documentation](https://docs.microsoft.com/azure/machine-learning/how-to-configure-auto-train).
github_jupyter
# Tenor functions with Pytorch ### Torch up your tensor game The following 5 functions might empower you to navigate through your Deep Learning endeavours with Pytorch - torch.diag() - torch.inverse() - torch.randn() - torch.zeros_like() - torch.arange() ``` # Import torch and other required modules import torch ``` ## Function 1 - torch.diag() Given some tensor, the above method returns it's diagonal(s). The arguments to the function are as follows: ### torch.diag(input, diagonal=0, output=None) diagonal and output are optional paramenters. 1. If diagonal = 0, it is the main diagonal. (Principal diagonal) 2. If diagonal > 0, it is above the main diagonal. 3. If diagonal < 0, it is below the main diagonal. ``` # Example 1 - working scalar = torch.diag(torch.tensor([99])) print('diagonal of scalar: ', scalar, '\n') # returns scalar as is vector = torch.diag(torch.tensor([1,2,3,4])) # 1D tensor(Vector) print('diagonal of vector: \n',vector) # return square matrix with upper and lower # triangular sections imputed with 0's ``` The above returns diagonals for scalars (the value itself) and vectors (in the form of a square matrix) ``` # Example 2 - working matrix = torch.diag(torch.tensor([[1,2,3],[4,5,6], [7,8,9]])) # 3x3 matrix print('diagonal of matrix: ', matrix, '\n') # returns the diagonal as is mat1 = torch.diag(torch.tensor([[1,2,3],[4,5,6], [7,8,9]]), diagonal=1) print("mat1: ", mat1) # returns diagonal above the principal diagonal of the matrix ``` The first example upon running simply returns the principal diagonal(PD) of the matrix. The second example returns the diagonal above the PD of the matrix found the uppe triangular region. ``` # Example 3 - breaking (to illustrate when it breaks) tensor = torch.diag(torch.randn(2,3,32,32)) print("tensor: ", tensor) # tries to return diagonal of dim > 2 tensor but it isn't possible ``` Higher order tensors, i.e of dimensions above 2D aren't processed to return a diagonal as there can be numerous combinations of choosing one. Matrix decompositons are invaluable in DL and this method can be availed of in computing for diagonals. An example of this use case would be in SVD (Singular Value Decomposition). ## Function 2 - torch.inverse() torch.inverse(input, output=None) Takes the inverse of the square matrix input. Batches of 2D tensors to this function would return tensor composed of individual inverses. ``` # Example 1 - working tensor = torch.randn(3,3) torch.inverse(tensor) ``` Input should be in the form of a square matrix. ``` # Example 2 - working tensor = torch.randn(3,3,3) torch.inverse(tensor) ``` The output tensor is a composition of individual inverses of the square matrix within the input matrix. ``` # Example 3 - breaking (to illustrate when it breaks) tensor = torch.randn(2,1,3) torch.inverse(tensor) ``` Since the input tensor does not within itself contain batches of square matrices an error is raised for its non-invertibility (in this case). Theta = (X^(T)X)^(-1).(X^(T)y) - is the normal equation for to find the parameter value for the Linear Regression algorithm. The above torch.inverse() method can be used in its computation. ## Function 3 - torch.randn() One of the most sort after functions to initialize a tensor to values of the normal distribution. ``` # Example 1 - working scalar = torch.randn(1) print('scalar: ', scalar, '\n') vector = torch.randn(4) print('vector: ', vector) ``` Generates random values from the normal distribution and assignes it to the above 0 and 1 dimensional tensors. ``` # Example 2 - working matrix = torch.randn(3,4) print('matrix: ', matrix, '\n') tensor = torch.randn(2,3,4) print('tensor: ', tensor) ``` Generates random values from the normal distribution and assignes it to the above 2 and 3 dimensional tensors. ``` # Example 3 - breaking (to illustrate when it breaks) tensor = torch.randn(-1,0,0) print('tensor: ', tensor) ``` Specified dimensions given to the torch.randn() method have to be Natural Numbers, which is obvious. This method is handy when any tensor is to be initialized before performing any operations. Example of this would be to initialise the weights of the matrix of every layer of a neural network, randomly before performing backpropogation. ## Function 4 - torch.zeros_like() The above method takes in a tensor, and given that input's dimensionalty it creates a corressponding tensor of the same shape, but with zeros all over. ``` # Example 1 - working scal = torch.randn(1) scal_zero = torch.zeros_like(scal) print("zero_like for scalar: ", scal_zero, '\n') vec = torch.randn(4) vec_z = torch.zeros_like(vec) print("zero_like for vector: ", vec_z) ``` Corresponding zero tensors are produced with the given input tensor. ``` # Example 2 - working mat = torch.randn(2,3) mat_z = torch.zeros_like(mat) print("zero_like for matrix: ", mat_z, '\n') ten = torch.randn(2,3,4) ten_z = torch.zeros_like(ten) print("zero_like for 3D tensor: ", ten_z, '\n') ``` Explanation about example ``` # Example 3 - breaking (to illustrate when it breaks) ten_Z = torch.zeros_like(mat @ vec) ten_z ``` torch_zeros_like() is a pretty full proof method, only a nonsensical input will give rise to error. Handy way to initialize tensors to zeros with the demensions of another tensor. ## Function 5 - torch.arange() Returns a 1D tensor of the interval of [start, end) with the given step size ``` # Example 1 - working t = torch.arange(0, 5, 0.1) t ``` Returns a tensor with all the values within the range, given the step size. ``` # Example 2 - working tt = torch.arange(0, 5, 0.01) tt ``` Returns a 1D tensor with all the values in the range with a smaller step size. ``` # Example 3 - breaking (to illustrate when it breaks) t = torch.arange(0, 5, 0.0000000000000000000000000000000000001) t ``` Cannot accomodate for high precision like the example above. This function can be used to initiate a 1D tensor with alll values within an interval. ## Conclusion By no means were these 5 functions the keystones to your Deep Learning endevours. But I think we're ready to start looking at linear models for Machine Learning - given at least this much knowledge and an ability to perform other inbetween manipulations. ## Reference Links Provide links to your references and other interesting articles about tensors * Official documentation for `torch.Tensor`: https://pytorch.org/docs/stable/tensors.html * Check out this blog for more on Matrices: https://jhui.github.io/2017/01/05/Deep-learning-linear-algebra/ ``` !pip install jovian --upgrade --quiet import jovian jovian.commit(project='01-tensor-operations-4abc9', environment=None) ```
github_jupyter
# Specific examples of transitions data # 0. Import dependencies and inputs ``` %run ../../notebook_preamble_Transitions.ipy # Location to store transitions data outputs_folder = f'{useful_paths.data_dir}processed/transitions/specific_examples/' # File name to use for the specific examples file_name = 'Data_example' # First batch of transitions path_to_val_data = data_folder + 'restricted/validation/nesta_output_16Dec.csv' batch_results = pd.read_csv(path_to_val_data) ``` # 1. Prepare transitions data ## 1.0 Specify transitions ### Example 1: Generate transitions ``` # Example 1: Generate a collection of transitions (e.g. all transitions from hotel porter and hotel concierge) transitions_df = trans_utils.get_transitions(origin_ids=[732, 329], destination_ids='report') transitions_df = transitions_df[transitions_df.is_safe_desirable].reset_index(drop=True) transitions_df.info() ``` ### Example 2: Use the validation dataset ``` # Example 2: Add transition data using a pre-specified list of occupation pairs validation_data = pd.read_csv(useful_paths.data_dir + 'processed/validation/Transitions_to_validate_BATCH_1.csv') transition_pairs = [(row.origin_id, row.destination_id) for j, row in validation_data.iterrows()] validation_data.head(5) transition_pairs[0:5] transitions_df = trans_utils.get_transition_data(transition_pairs) transitions_df.head(5) ``` ## 1.1 Table of transitions ``` # Select only the desired columns transitions_table = transitions_df[[ 'origin_id', 'origin_label', 'destination_id', 'destination_label', 'similarity', 'W_essential_skills', 'W_optional_skills', 'W_activities', 'W_work_context', 'sim_category', 'is_viable', 'is_desirable', 'is_safe_desirable']] transitions_table.sample(5) ``` Notes: The column `similarity` stores the combined similarity measure, i.e. the average of the four different similarity measures described in the Mapping Career Causeways report. These are also provided in the columns `W_{x}`). Column `sim_category` indicates whether the combined similarity is above 0.4 ('highly viable') or only between 0.3 and 0.4 ('minimally viable'). The columns `is_viable`, `is_desirable`, `is_safe_desirable` should be clear (see the report for more details). ### Export transitions ``` transitions_table.to_csv(f'{outputs_folder}{file_name}_Transitions.csv', index=False) ``` ## 1.2 Table of occupational profiles ``` # Select all IDs involved in the transitions all_ids = set(transitions_table.origin_id.to_list()).union(set(transitions_table.destination_id.to_list())) # Occupational profiles occ_profiles = data.occ_report[data.occ_report.id.isin(all_ids)] occ_profiles.sample(5) ``` Please select the columns, which you find are the most relevant. For more information about the column data, please see [here](https://github.com/nestauk/mapping-career-causeways/tree/main/supplementary_online_data/transitions#number-of-transition-options-for-esco-occupations). ``` occ_profiles.info() ``` ### Export profiles ``` occ_profiles.to_csv(f'{outputs_folder}{file_name}_Occupation_profiles.csv', index=False) ``` ## 1.3 Skills matching data for specific transitions ``` # Choose a row of the transition table row = 0 # Get skills matches skills_matching = trans_utils.show_skills_overlap(transitions_table.loc[row].origin_id, transitions_table.loc[row].destination_id, skills_match='optional', verbose=True) # Export the skills matching table skills_matching.to_csv(f'{outputs_folder}{file_name}_Skills_match_{row}.csv', index=False) skills_matching # Extra: You may also want to get some reference data on the skills (links to the ESCO database) all_skills_ids = set(skills_matching.origin_skill_id.to_list()).union(set(skills_matching.destination_skill_id.to_list())) data.skills[data.skills.id.isin(all_skills_ids)] ``` ## 2. Data Sample export ``` transition_mean = batch_results.groupby('subject_ids')['feasibility_1-5'].mean() transitions = batch_results.reset_index().drop_duplicates('subject_ids').set_index('subject_ids') export_jobs = ['user interface developer', 'lottery cashier', 'community health worker', 'sales support assistant', 'travel agent', 'postman/postwoman', 'real estate surveyor', 'investment clerk', 'financial analyst', 'packaging production manager' ] sample_transitions = (transitions .reset_index() .set_index('origin_label') .loc[export_jobs] .reset_index() .set_index('subject_ids')) sample_transitions = sample_transitions.merge(transition_mean, left_index=True, right_index=True, how='inner', suffixes=('_raw', '_mean') ) sample_transitions = sample_transitions[sample_transitions['feasibility_1-5_mean'] > 2] with open(data_folder + 'restricted/validation/data_sample_ids.txt', 'w') as f: for l in [str(tuple(r)) for r in sample_transitions[['origin_id', 'destination_id']].to_numpy()]: f.write(l + '\n') from ast import literal_eval with open(data_folder + 'restricted/validation/data_sample_ids.txt', 'r') as f: sample_ids = f.read().splitlines() sample_ids = [literal_eval(l) for l in sample_ids] ``` ### 2.1 Sample Transitions ``` sample_transitions_df = trans_utils.get_transition_data(sample_ids) sample_transitions_df = sample_transitions_df.reset_index().rename(columns={'index': 'transition_id'}) sample_transitions_df ``` ### 2.2 Sample Job Profiles ``` # Select all IDs involved in the transitions all_ids = set(sample_transitions_df.origin_id.to_list()).union(set(sample_transitions_df.destination_id.to_list())) # Occupational profiles sample_occ_profiles = data.occ_report[data.occ_report.id.isin(all_ids)] sample_occ_profiles.sample(5) ``` ### 2.3 Sample Skills ``` rows = sample_transitions_df[['transition_id', 'origin_id', 'destination_id']].iterrows() skills_matches = [] for _, (i, origin_id, destination_id) in rows: skills_matching = trans_utils.show_skills_overlap(origin_id, destination_id, skills_match='optional', verbose=False) skills_matching['transition_id'] = i skills_matches.append(skills_matching) skills_matches = pd.concat(skills_matches, axis=0) skills_matches.head() # Extra: You may also want to get some reference data on the skills (links to the ESCO database) sample_skills_ids = (set(skills_matches.origin_skill_id.to_list()) .union(set(skills_matches.destination_skill_id.to_list()))) sample_skill_profiles = data.skills[data.skills.id.isin(sample_skills_ids)] sample_skill_profiles.head() ```
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Image captioning with visual attention <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tutorials/text/image_captioning"> <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/blob/master/site/en/tutorials/text/image_captioning.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/blob/master/site/en/tutorials/text/image_captioning.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/site/en/tutorials/text/image_captioning.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Given an image like the example below, our goal is to generate a caption such as "a surfer riding on a wave". ![Man Surfing](https://tensorflow.org/images/surf.jpg) *[Image Source](https://commons.wikimedia.org/wiki/Surfing#/media/File:Surfing_in_Hawaii.jpg); License: Public Domain* To accomplish this, you'll use an attention-based model, which enables us to see what parts of the image the model focuses on as it generates a caption. ![Prediction](https://tensorflow.org/images/imcap_prediction.png) The model architecture is similar to [Show, Attend and Tell: Neural Image Caption Generation with Visual Attention](https://arxiv.org/abs/1502.03044). This notebook is an end-to-end example. When you run the notebook, it downloads the [MS-COCO](http://cocodataset.org/#home) dataset, preprocesses and caches a subset of images using Inception V3, trains an encoder-decoder model, and generates captions on new images using the trained model. In this example, you will train a model on a relatively small amount of data—the first 30,000 captions for about 20,000 images (because there are multiple captions per image in the dataset). ``` import tensorflow as tf # You'll generate plots of attention in order to see which parts of an image # our model focuses on during captioning import matplotlib.pyplot as plt # Scikit-learn includes many helpful utilities from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import re import numpy as np import os import time import json from glob import glob from PIL import Image import pickle ``` ## Download and prepare the MS-COCO dataset You will use the [MS-COCO dataset](http://cocodataset.org/#home) to train our model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically. **Caution: large download ahead**. You'll use the training set, which is a 13GB file. ``` # Download caption annotation files annotation_folder = '/annotations/' if not os.path.exists(os.path.abspath('.') + annotation_folder): annotation_zip = tf.keras.utils.get_file('captions.zip', cache_subdir=os.path.abspath('.'), origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip', extract = True) annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json' os.remove(annotation_zip) # Download image files image_folder = '/train2014/' if not os.path.exists(os.path.abspath('.') + image_folder): image_zip = tf.keras.utils.get_file('train2014.zip', cache_subdir=os.path.abspath('.'), origin = 'http://images.cocodataset.org/zips/train2014.zip', extract = True) PATH = os.path.dirname(image_zip) + image_folder os.remove(image_zip) else: PATH = os.path.abspath('.') + image_folder ``` ## Optional: limit the size of the training set To speed up training for this tutorial, you'll use a subset of 30,000 captions and their corresponding images to train our model. Choosing to use more data would result in improved captioning quality. ``` # Read the json file with open(annotation_file, 'r') as f: annotations = json.load(f) # Store captions and image names in vectors all_captions = [] all_img_name_vector = [] for annot in annotations['annotations']: caption = '<start> ' + annot['caption'] + ' <end>' image_id = annot['image_id'] full_coco_image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (image_id) all_img_name_vector.append(full_coco_image_path) all_captions.append(caption) # Shuffle captions and image_names together # Set a random state train_captions, img_name_vector = shuffle(all_captions, all_img_name_vector, random_state=1) # Select the first 30000 captions from the shuffled set num_examples = 30000 train_captions = train_captions[:num_examples] img_name_vector = img_name_vector[:num_examples] len(train_captions), len(all_captions) ``` ## Preprocess the images using InceptionV3 Next, you will use InceptionV3 (which is pretrained on Imagenet) to classify each image. You will extract features from the last convolutional layer. First, you will convert the images into InceptionV3's expected format by: * Resizing the image to 299px by 299px * [Preprocess the images](https://cloud.google.com/tpu/docs/inception-v3-advanced#preprocessing_stage) using the [preprocess_input](https://www.tensorflow.org/api_docs/python/tf/keras/applications/inception_v3/preprocess_input) method to normalize the image so that it contains pixels in the range of -1 to 1, which matches the format of the images used to train InceptionV3. ``` def load_image(image_path): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, (299, 299)) img = tf.keras.applications.inception_v3.preprocess_input(img) return img, image_path ``` ## Initialize InceptionV3 and load the pretrained Imagenet weights Now you'll create a tf.keras model where the output layer is the last convolutional layer in the InceptionV3 architecture. The shape of the output of this layer is ```8x8x2048```. You use the last convolutional layer because you are using attention in this example. You don't perform this initialization during training because it could become a bottleneck. * You forward each image through the network and store the resulting vector in a dictionary (image_name --> feature_vector). * After all the images are passed through the network, you pickle the dictionary and save it to disk. ``` image_model = tf.keras.applications.InceptionV3(include_top=False, weights='imagenet') new_input = image_model.input hidden_layer = image_model.layers[-1].output image_features_extract_model = tf.keras.Model(new_input, hidden_layer) ``` ## Caching the features extracted from InceptionV3 You will pre-process each image with InceptionV3 and cache the output to disk. Caching the output in RAM would be faster but also memory intensive, requiring 8 \* 8 \* 2048 floats per image. At the time of writing, this exceeds the memory limitations of Colab (currently 12GB of memory). Performance could be improved with a more sophisticated caching strategy (for example, by sharding the images to reduce random access disk I/O), but that would require more code. The caching will take about 10 minutes to run in Colab with a GPU. If you'd like to see a progress bar, you can: 1. install [tqdm](https://github.com/tqdm/tqdm): `!pip install tqdm` 2. Import tqdm: `from tqdm import tqdm` 3. Change the following line: `for img, path in image_dataset:` to: `for img, path in tqdm(image_dataset):` ``` # Get unique images encode_train = sorted(set(img_name_vector)) # Feel free to change batch_size according to your system configuration image_dataset = tf.data.Dataset.from_tensor_slices(encode_train) image_dataset = image_dataset.map( load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16) for img, path in image_dataset: batch_features = image_features_extract_model(img) batch_features = tf.reshape(batch_features, (batch_features.shape[0], -1, batch_features.shape[3])) for bf, p in zip(batch_features, path): path_of_feature = p.numpy().decode("utf-8") np.save(path_of_feature, bf.numpy()) ``` ## Preprocess and tokenize the captions * First, you'll tokenize the captions (for example, by splitting on spaces). This gives us a vocabulary of all of the unique words in the data (for example, "surfing", "football", and so on). * Next, you'll limit the vocabulary size to the top 5,000 words (to save memory). You'll replace all other words with the token "UNK" (unknown). * You then create word-to-index and index-to-word mappings. * Finally, you pad all sequences to be the same length as the longest one. ``` # Find the maximum length of any caption in our dataset def calc_max_length(tensor): return max(len(t) for t in tensor) # Choose the top 5000 words from the vocabulary top_k = 5000 tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k, oov_token="<unk>", filters='!"#$%&()*+.,-/:;=?@[\]^_`{|}~ ') tokenizer.fit_on_texts(train_captions) train_seqs = tokenizer.texts_to_sequences(train_captions) tokenizer.word_index['<pad>'] = 0 tokenizer.index_word[0] = '<pad>' # Create the tokenized vectors train_seqs = tokenizer.texts_to_sequences(train_captions) # Pad each vector to the max_length of the captions # If you do not provide a max_length value, pad_sequences calculates it automatically cap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post') # Calculates the max_length, which is used to store the attention weights max_length = calc_max_length(train_seqs) ``` ## Split the data into training and testing ``` # Create training and validation sets using an 80-20 split img_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector, cap_vector, test_size=0.2, random_state=0) len(img_name_train), len(cap_train), len(img_name_val), len(cap_val) ``` ## Create a tf.data dataset for training Our images and captions are ready! Next, let's create a tf.data dataset to use for training our model. ``` # Feel free to change these parameters according to your system's configuration BATCH_SIZE = 64 BUFFER_SIZE = 1000 embedding_dim = 256 units = 512 vocab_size = top_k + 1 num_steps = len(img_name_train) // BATCH_SIZE # Shape of the vector extracted from InceptionV3 is (64, 2048) # These two variables represent that vector shape features_shape = 2048 attention_features_shape = 64 # Load the numpy files def map_func(img_name, cap): img_tensor = np.load(img_name.decode('utf-8')+'.npy') return img_tensor, cap dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train)) # Use map to load the numpy files in parallel dataset = dataset.map(lambda item1, item2: tf.numpy_function( map_func, [item1, item2], [tf.float32, tf.int32]), num_parallel_calls=tf.data.experimental.AUTOTUNE) # Shuffle and batch dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) ``` ## Model Fun fact: the decoder below is identical to the one in the example for [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb). The model architecture is inspired by the [Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) paper. * In this example, you extract the features from the lower convolutional layer of InceptionV3 giving us a vector of shape (8, 8, 2048). * You squash that to a shape of (64, 2048). * This vector is then passed through the CNN Encoder (which consists of a single Fully connected layer). * The RNN (here GRU) attends over the image to predict the next word. ``` class BahdanauAttention(tf.keras.Model): def __init__(self, units): super(BahdanauAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) def call(self, features, hidden): # features(CNN_encoder output) shape == (batch_size, 64, embedding_dim) # hidden shape == (batch_size, hidden_size) # hidden_with_time_axis shape == (batch_size, 1, hidden_size) hidden_with_time_axis = tf.expand_dims(hidden, 1) # score shape == (batch_size, 64, hidden_size) score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis)) # attention_weights shape == (batch_size, 64, 1) # you get 1 at the last axis because you are applying score to self.V attention_weights = tf.nn.softmax(self.V(score), axis=1) # context_vector shape after sum == (batch_size, hidden_size) context_vector = attention_weights * features context_vector = tf.reduce_sum(context_vector, axis=1) return context_vector, attention_weights class CNN_Encoder(tf.keras.Model): # Since you have already extracted the features and dumped it using pickle # This encoder passes those features through a Fully connected layer def __init__(self, embedding_dim): super(CNN_Encoder, self).__init__() # shape after fc == (batch_size, 64, embedding_dim) self.fc = tf.keras.layers.Dense(embedding_dim) def call(self, x): x = self.fc(x) x = tf.nn.relu(x) return x class RNN_Decoder(tf.keras.Model): def __init__(self, embedding_dim, units, vocab_size): super(RNN_Decoder, self).__init__() self.units = units self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.gru = tf.keras.layers.GRU(self.units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') self.fc1 = tf.keras.layers.Dense(self.units) self.fc2 = tf.keras.layers.Dense(vocab_size) self.attention = BahdanauAttention(self.units) def call(self, x, features, hidden): # defining attention as a separate model context_vector, attention_weights = self.attention(features, hidden) # x shape after passing through embedding == (batch_size, 1, embedding_dim) x = self.embedding(x) # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size) x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1) # passing the concatenated vector to the GRU output, state = self.gru(x) # shape == (batch_size, max_length, hidden_size) x = self.fc1(output) # x shape == (batch_size * max_length, hidden_size) x = tf.reshape(x, (-1, x.shape[2])) # output shape == (batch_size * max_length, vocab) x = self.fc2(x) return x, state, attention_weights def reset_state(self, batch_size): return tf.zeros((batch_size, self.units)) encoder = CNN_Encoder(embedding_dim) decoder = RNN_Decoder(embedding_dim, units, vocab_size) optimizer = tf.keras.optimizers.Adam() loss_object = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True, reduction='none') def loss_function(real, pred): mask = tf.math.logical_not(tf.math.equal(real, 0)) loss_ = loss_object(real, pred) mask = tf.cast(mask, dtype=loss_.dtype) loss_ *= mask return tf.reduce_mean(loss_) ``` ## Checkpoint ``` checkpoint_path = "./checkpoints/train" ckpt = tf.train.Checkpoint(encoder=encoder, decoder=decoder, optimizer = optimizer) ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5) start_epoch = 0 if ckpt_manager.latest_checkpoint: start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1]) # restoring the latest checkpoint in checkpoint_path ckpt.restore(ckpt_manager.latest_checkpoint) ``` ## Training * You extract the features stored in the respective `.npy` files and then pass those features through the encoder. * The encoder output, hidden state(initialized to 0) and the decoder input (which is the start token) is passed to the decoder. * The decoder returns the predictions and the decoder hidden state. * The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss. * Use teacher forcing to decide the next input to the decoder. * Teacher forcing is the technique where the target word is passed as the next input to the decoder. * The final step is to calculate the gradients and apply it to the optimizer and backpropagate. ``` # adding this in a separate cell because if you run the training cell # many times, the loss_plot array will be reset loss_plot = [] @tf.function def train_step(img_tensor, target): loss = 0 # initializing the hidden state for each batch # because the captions are not related from image to image hidden = decoder.reset_state(batch_size=target.shape[0]) dec_input = tf.expand_dims([tokenizer.word_index['<start>']] * target.shape[0], 1) with tf.GradientTape() as tape: features = encoder(img_tensor) for i in range(1, target.shape[1]): # passing the features through the decoder predictions, hidden, _ = decoder(dec_input, features, hidden) loss += loss_function(target[:, i], predictions) # using teacher forcing dec_input = tf.expand_dims(target[:, i], 1) total_loss = (loss / int(target.shape[1])) trainable_variables = encoder.trainable_variables + decoder.trainable_variables gradients = tape.gradient(loss, trainable_variables) optimizer.apply_gradients(zip(gradients, trainable_variables)) return loss, total_loss EPOCHS = 20 for epoch in range(start_epoch, EPOCHS): start = time.time() total_loss = 0 for (batch, (img_tensor, target)) in enumerate(dataset): batch_loss, t_loss = train_step(img_tensor, target) total_loss += t_loss if batch % 100 == 0: print ('Epoch {} Batch {} Loss {:.4f}'.format( epoch + 1, batch, batch_loss.numpy() / int(target.shape[1]))) # storing the epoch end loss value to plot later loss_plot.append(total_loss / num_steps) if epoch % 5 == 0: ckpt_manager.save() print ('Epoch {} Loss {:.6f}'.format(epoch + 1, total_loss/num_steps)) print ('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) plt.plot(loss_plot) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.show() ``` ## Caption! * The evaluate function is similar to the training loop, except you don't use teacher forcing here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output. * Stop predicting when the model predicts the end token. * And store the attention weights for every time step. ``` def evaluate(image): attention_plot = np.zeros((max_length, attention_features_shape)) hidden = decoder.reset_state(batch_size=1) temp_input = tf.expand_dims(load_image(image)[0], 0) img_tensor_val = image_features_extract_model(temp_input) img_tensor_val = tf.reshape(img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3])) features = encoder(img_tensor_val) dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0) result = [] for i in range(max_length): predictions, hidden, attention_weights = decoder(dec_input, features, hidden) attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy() predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy() result.append(tokenizer.index_word[predicted_id]) if tokenizer.index_word[predicted_id] == '<end>': return result, attention_plot dec_input = tf.expand_dims([predicted_id], 0) attention_plot = attention_plot[:len(result), :] return result, attention_plot def plot_attention(image, result, attention_plot): temp_image = np.array(Image.open(image)) fig = plt.figure(figsize=(10, 10)) len_result = len(result) for l in range(len_result): temp_att = np.resize(attention_plot[l], (8, 8)) ax = fig.add_subplot(len_result//2, len_result//2, l+1) ax.set_title(result[l]) img = ax.imshow(temp_image) ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent()) plt.tight_layout() plt.show() # captions on the validation set rid = np.random.randint(0, len(img_name_val)) image = img_name_val[rid] real_caption = ' '.join([tokenizer.index_word[i] for i in cap_val[rid] if i not in [0]]) result, attention_plot = evaluate(image) print ('Real Caption:', real_caption) print ('Prediction Caption:', ' '.join(result)) plot_attention(image, result, attention_plot) ``` ## Try it on your own images For fun, below we've provided a method you can use to caption your own images with the model we've just trained. Keep in mind, it was trained on a relatively small amount of data, and your images may be different from the training data (so be prepared for weird results!) ``` image_url = 'https://tensorflow.org/images/surf.jpg' image_extension = image_url[-4:] image_path = tf.keras.utils.get_file('image'+image_extension, origin=image_url) result, attention_plot = evaluate(image_path) print ('Prediction Caption:', ' '.join(result)) plot_attention(image_path, result, attention_plot) # opening the image Image.open(image_path) ``` # Next steps Congrats! You've just trained an image captioning model with attention. Next, take a look at this example [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb). It uses a similar architecture to translate between Spanish and English sentences. You can also experiment with training the code in this notebook on a different dataset.
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import datetime from datetime import datetime from sklearn.metrics import mean_squared_error %matplotlib inline plt.style.use('fivethirtyeight') #Used for replicating graph styles from fivethirtyeight.com from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from binance.client import Client api_key = "" secret_key="t" client = Client(api_key,secret_key) candles = client.get_klines(symbol='BTCUSDT',interval = Client.KLINE_INTERVAL_1MINUTE); len(candles) candles[499] #time-open-high-low-close-volume-close_time #Fetching closing prices from candlesticks data price = np.array([float(candles[i][4]) for i in range(500)]) #Fetching opening time from candlesticks data time = np.array([int(candles[i][0]) for i in range(500)]) #Converting time to HH:MM:SS format t = np.array([datetime.fromtimestamp(time[i]/1000).strftime('%H:%M:%S') for i in range(500)]) price.shape plt.figure(figsize=(8,5)) plt.xlabel("Time Step") plt.ylabel("Bitcoin Price $") plt.plot(price) #Putting this data into a dataframe timeframe = pd.DataFrame({'Time':t,'Price $BTC':price}) timeframe #minute by minute price price = price.reshape(500,1) from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(price[:374]) price = scaler.transform(price) #Putting the standardized data into dataframe according to input and target(output) columns for model training df = pd.DataFrame(price.reshape(100,5),columns = ['First','Second','Third','Fourth','Target']) df.head() #Split train and test data x_train = df.iloc[:74,:4] y_train = df.iloc[:74,-1] x_test = df.iloc[75:99,:4] y_test = df.iloc[75:99,-1] x_train = np.array(x_train) y_train = np.array(y_train) x_test = np.array(x_test) y_test = np.array(y_test) x_train = np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1)) x_test = np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1)) x_train.shape, x_test.shape #Calibrating and initializing the prediction model model = Sequential() model.add(LSTM(20,return_sequences=True,input_shape=(4,1))) model.add(LSTM(40,return_sequences=False)) model.add(Dense(1,activation='linear')) model.compile(loss='mse',optimizer='rmsprop') model.summary() model.fit(x_train,y_train,batch_size=5,epochs=100) y_pred = model.predict(x_test) #Plotting the prediction vs actual graph for scaled data plt.figure(figsize = [8,5]) plt.title('Model Fit') plt.xlabel('Time Step') plt.ylabel('Normalized Price') plt.plot(y_test,label = "True") plt.plot(y_pred,label="Prediction") plt.legend() plt.show() #Plotting the prediction vs actual graph for scaled data plt.figure(figsize = [8,5]) plt.title('Model Fit') plt.xlabel('Time Step') plt.ylabel('Price') plt.plot(scaler.inverse_transform(y_test),label = "True") plt.plot(scaler.inverse_transform(y_pred),label="Prediction") plt.legend() plt.show() testScore = np.sqrt(mean_squared_error(scaler.inverse_transform(y_test),scaler.inverse_transform(y_pred))) print('Test Score : %2f RMSE' % (testScore)) from sklearn.metrics import r2_score print('RSquared : ', '{:.2%}'.format(r2_score(y_test,y_pred))) model.save("Bitcoin_model.h5") ```
github_jupyter
<!--NOTEBOOK_HEADER--> *This notebook contains material from [cbe61622](https://jckantor.github.io/cbe61622); content is available [on Github](https://github.com/jckantor/cbe61622.git).* <!--NAVIGATION--> < [A.2 Downloading Python source files from github](https://jckantor.github.io/cbe61622/A.02-Downloading_Python_source_files_from_github.html) | [Contents](toc.html) | [A.4 Scheduling Real-Time Events with Simpy](https://jckantor.github.io/cbe61622/A.04-Scheduling-Real-Time-Events-with-Simpy.html) ><p><a href="https://colab.research.google.com/github/jckantor/cbe61622/blob/master/docs/A.03-Getting-Started-with-Pymata4.ipynb"> <img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open in Google Colaboratory"></a><p><a href="https://jckantor.github.io/cbe61622/A.03-Getting-Started-with-Pymata4.ipynb"> <img align="left" src="https://img.shields.io/badge/Github-Download-blue.svg" alt="Download" title="Download Notebook"></a> # A.3 Getting Started with Pymata4 [Pymata4](https://github.com/MrYsLab/pymata4) is a Python library that allows you to monitor and control Arduino hardware from a host computer. The library uses the Firmata protocol for communicating with the Arduino hardware. Pymata4 supports the StandardFirmata server included with the Arduino IDE, and also StandardFirmataWiFi, and an enhanced server FirmataExpress distributed with Pymata4. Pymata4 uses [concurrent Python threads](https://mryslab.github.io/pymata4/concurrency/) to manage interaction with the Arduino. The concurrency model enables development of performant and interactive Arduino applications using Python on a host computer. Changes in the status of an Arduino pin can be processed with callbacks. It's sibling, [pymata-express](https://github.com/MrYsLab/pymata-express), is available using the [Python asyncio package](https://docs.python.org/3/library/asyncio.html). Support for common $I^2C$ devices, including stepper motors, is included in FirmataExpress. Applications using unsupported $I^2C$ devices may require [modifications to the Firmata server sketch](https://www.instructables.com/Going-Beyond-StandardFirmata-Adding-New-Device-Sup/). Useful links: * [Pymata4 API documentation](http://htmlpreview.github.io/?https://raw.githubusercontent.com/MrYsLab/pymata4/master/html/pymata4/index.html) ## A.3.1 Hardware Setup and Software Installations The Arduino must be attached to the host by USB with either the StandardFirmata or Firmata-express sketch installed using the Arduino IDE. For use with WiFi, install StandardFirmataWiFi. The Python pymata4 package can be installed with pip. ``` !pip install pymata4 ``` ## A.3.2 Basic Usage pymata4.Pymata() board.shutdown() ``` from pymata4 import pymata4 # create a board instance board = pymata4.Pymata4() # remember to shutdown board.shutdown() ``` ## A.3.3 Blinker board.digital_write(pin, value) Pymata4 has two methods for writing a 1 or a 0 to a digital output. `digital_write(pin, value)` hides details of the Firmata protocol from the user. The user can refer to digital pins just as they would in standard Arduino coding. A second method, `digital_pin_write(pin, value)` allows writing to multiples at the same time, but requires the user to understand further details of the Firmata protocol. ``` from pymata4 import pymata4 import time LED_PIN = 13 board = pymata4.Pymata4() # set the pin mode board.set_pin_mode_digital_output(LED_PIN) for n in range(5): print("LED ON") board.digital_write(LED_PIN, 1) time.sleep(1) print("LED OFF") board.digital_write(LED_PIN, 0) time.sleep(1) board.shutdown() ``` ## A.3.4 Handling a Keyboard Interrupt Pymata4 sets up multiple concurrent processes upon opening connection to the Arduino hardware. If Python execution is interrupted, it isimportant to catch the interrupt and shutdown the board before exiting the code. Otherwise the Arduino may continue to stream data requiring the Arduino to be reset. ``` from pymata4 import pymata4 import time def blink(board, pin, N=20): board.set_pin_mode_digital_output(LED_PIN) for n in range(N): board.digital_write(LED_PIN, 1) time.sleep(0.5) board.digital_write(LED_PIN, 0) time.sleep(0.5) board.shutdown() LED_PIN = 13 board = pymata4.Pymata4() try: blink(board, LED_PIN) except KeyboardInterrupt: print("Operation interrupted. Shutting down board.") board.shutdown() ``` ## A.3.5 Getting Information about the Arduino [Firmata protocol](https://github.com/firmata/protocol/blob/master/protocol.md) ``` from pymata4 import pymata4 import time board = pymata4.Pymata4() print("Board Report") print(f"Firmware version: {board.get_firmware_version()}") print(f"Protocol version: {board.get_protocol_version()}") print(f"Pymata version: {board.get_pymata_version()}") def print_analog_map(board): analog_map = board.get_analog_map() for pin, apin in enumerate(analog_map): if apin < 127: print(f"Pin {pin:2d}: analog channel = {apin}") def print_pin_state_report(board): pin_modes = { 0x00: "INPUT", 0x01: "OUTPUT", 0x02: "ANALOG INPUT", 0x03: "PWM OUTPUT", 0x04: "SERVO OUTPUT", 0x06: "I2C", 0x08: "STEPPER", 0x0b: "PULLUP", 0x0c: "SONAR", 0x0d: "TONE", } analog_map = board.get_analog_map() for pin in range(len(analog_map)): state = board.get_pin_state(pin) print(f"Pin {pin:2d}: {pin_modes[state[1]]:>15s} = {state[2]}") print_pin_state_report(board) board.digital_write(13, 1) print_pin_state_report(board) print_analog_map(board) capability_report = board.get_capability_report() board.shutdown() # get capability report print("\nCapability Report") modes = { 0x00: "DIN", # digital input 0x01: "DO", # digital output 0x02: "AIN", # analog input 0x03: "PWM", # pwm output 0x04: "SRV", # servo output 0x05: "SFT", # shift 0x06: "I2C", # I2C 0x07: "WIR", # ONEWIRE 0x08: "STP", # STEPPER 0x09: "ENC", # ENCODER 0x0A: "SRL", # SERIAL 0x0B: "INP", # INPUT_PULLUP } pin_report = {} pin = 0 k = 0 while k < len(capability_report): pin_report[pin] = {} while capability_report[k] < 127: pin_report[pin][modes[capability_report[k]]] = capability_report[k+1] k += 2 k += 1 pin += 1 mode_set = set([mode for pin in pin_report.keys() for mode in pin_report[pin].keys()]) print(" " + "".join([f" {mode:>3s} " for mode in sorted(mode_set)])) for pin in pin_report.keys(): s = f"Pin {pin:2d}:" for mode in sorted(mode_set): s += f" {pin_report[pin][mode]:>3d} " if mode in pin_report[pin].keys() else " "*5 print(s) ``` ## A.3.6 Temperature Control Lab Shield ``` from pymata4 import pymata4 import time class tclab(): def __init__(self): self.board = pymata4.Pymata4() self.LED_PIN = 9 self.Q1_PIN = 3 self.Q2_PIN = 5 self.T1_PIN = 0 self.T2_PIN = 2 self.board.set_pin_mode_pwm_output(self.LED_PIN) self.board.set_pin_mode_pwm_output(self.Q1_PIN) self.board.set_pin_mode_pwm_output(self.Q2_PIN) self.board.set_pin_mode_analog_input(self.T1_PIN) self.board.set_pin_mode_analog_input(self.T2_PIN) self._Q1 = 0 self._Q2 = 0 time.sleep(0.1) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() return def close(self): self.Q1(0) self.Q2(0) self.board.shutdown() def read_temperature(self, pin): # firmata doesn't provide a means to use the 3.3 volt reference adc, ts = self.board.analog_read(pin) return round(adc*513/1024 - 50.0, 1) def Q1(self, val): val = int(255*max(0, min(100, val))/100) self.board.pwm_write(self.Q1_PIN, val) def Q2(self, val): val = int(255*max(0, min(100, val))/100) self.board.pwm_write(self.Q2_PIN, val) def T1(self): return self.read_temperature(self.T1_PIN) def T2(self): return self.read_temperature(self.T2_PIN) def LED(self, val): val = max(0, min(255, int(255*val/100))) self.board.pwm_write(self.LED_PIN, val) with tclab() as lab: lab.Q1(100) lab.Q2(100) for n in range(30): print(lab.T1(), lab.T2()) lab.LED(100) time.sleep(0.5) lab.LED(0) time.sleep(0.5) lab.Q1(0) lab.Q2(0) ``` <!--NAVIGATION--> < [A.2 Downloading Python source files from github](https://jckantor.github.io/cbe61622/A.02-Downloading_Python_source_files_from_github.html) | [Contents](toc.html) | [A.4 Scheduling Real-Time Events with Simpy](https://jckantor.github.io/cbe61622/A.04-Scheduling-Real-Time-Events-with-Simpy.html) ><p><a href="https://colab.research.google.com/github/jckantor/cbe61622/blob/master/docs/A.03-Getting-Started-with-Pymata4.ipynb"> <img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open in Google Colaboratory"></a><p><a href="https://jckantor.github.io/cbe61622/A.03-Getting-Started-with-Pymata4.ipynb"> <img align="left" src="https://img.shields.io/badge/Github-Download-blue.svg" alt="Download" title="Download Notebook"></a>
github_jupyter
# Tutorial 05: Creating Custom Networks This tutorial walks you through the process of generating custom networks. Networks define the network geometry of a task, as well as the constituents of the network, e.g. vehicles, traffic lights, etc... Various networks are available in Flow, depicting a diverse set of open and closed traffic networks such as ring roads, intersections, traffic light grids, straight highway merges, and more. In this tutorial, we will recreate the ring road network, seen in the figure below. <img src="img/ring_network.png"> In order to recreate this network, we will design a *network* class. This class creates the configuration files needed to produce a transportation network within the simulator. It also specifies the location of edge nodes in the network, as well as the positioning of vehicles at the start of a run. We begin by creating a class that inherits the methods of Flow's base network class. The separate methods are filled in in later sections. ``` # import Flow's base network class from flow.networks import Network # define the network class, and inherit properties from the base network class class myNetwork(Network): pass ``` The rest of the tutorial is organized as follows: sections 1 and 2 walk through the steps needed to specify custom traffic network geometry features and auxiliary features, respectively, while section 3 implements the new network in a simulation for visualization and testing purposes. ## 1. Specifying Traffic Network Features One of the core responsibilities of the network class is to to generate the necessary xml files needed to initialize a sumo instance. These xml files describe specific network features such as the position and directions of nodes and edges (see the figure above). Once the base network has been inherited, specifying these features becomes very systematic. All child classes are required to define at least the following three methods: * **specify_nodes**: specifies the attributes of nodes in the network * **specify_edges**: specifies the attributes of edges containing pairs on nodes in the network * **specify_routes**: specifies the routes vehicles can take starting from any edge Additionally, the following optional functions may also be defined: * **specify_types**: specifies the attributes of various edge types (if any exist) * **specify_connections**: specifies the attributes of connections. These attributes are used to describe how any specific node's incoming and outgoing edges/lane pairs are connected. If no connections are specified, sumo generates default connections. All of the functions mentioned above paragraph take in as input `net_params`, and output a list of dictionary elements, with each element providing the attributes of the component to be specified. This tutorial will cover the first three methods. For examples of `specify_types` and `specify_routes`, refer to source code located in `flow/networks/ring.py` and `flow/networks/bridge_toll.py`, respectively. ### 1.1 ADDITIONAL_NET_PARAMS The features used to parametrize the network are specified within the `NetParams` input, as discussed in tutorial 1. Specifically, for the sake of our network, the `additional_params` attribute within `NetParams` will be responsible for storing information on the radius, number of lanes, and speed limit within each lane, as seen in the figure above. Accordingly, for this problem, we define an `ADDITIONAL_NET_PARAMS` variable of the form: ``` ADDITIONAL_NET_PARAMS = { # radius of the circular components "radius_ring": 30, # number of lanes "lanes": 1, # speed limit for all edges "speed_limit": 30, # resolution of the curved portions "resolution": 40 } ``` All networks presented in Flow provide a unique `ADDITIONAL_NET_PARAMS` component containing the information needed to properly define the network parameters of the network. We assume that these values are always provided by the user, and accordingly can be called from `net_params`. For example, if we would like to call the "radius" parameter, we simply type: radius = net_params.additional_params["radius"] ### 1.2 specify_nodes The nodes of a network are the positions of a select few points in the network. These points are connected together using edges (see section 1.4). In order to specify the location of the nodes that will be placed in the network, the function `specify_nodes` is used. This method returns a list of dictionary elements, where each dictionary depicts the attributes of a single node. These node attributes include: * **id**: name of the node * **x**: x coordinate of the node * **y**: y coordinate of the node * other sumo-related attributes, see: http://sumo.dlr.de/wiki/Networks/Building_Networks_from_own_XML-descriptions#Node_Descriptions Refering to the figure at the top of this tutorial, we specify four nodes at the bottom (0,-r), top (0,r), left (-r,0), and right (0,r) of the ring. This is done as follows: ``` class myNetwork(myNetwork): # update my network class def specify_nodes(self, net_params): # one of the elements net_params will need is a "radius" value r = net_params.additional_params["radius"] # specify the name and position (x,y) of each node nodes = [{"id": "bottom", "x": 0, "y": -r}, {"id": "right", "x": r, "y": 0}, {"id": "top", "x": 0, "y": r}, {"id": "left", "x": -r, "y": 0}, {"id": "center", "x": 0, "y": 0}] return nodes ``` ### 1.3 specify_edges Once the nodes are specified, the nodes are linked together using directed edges. This done through the `specify_edges` method which, similar to `specify_nodes`, returns a list of dictionary elements, with each dictionary specifying the attributes of a single edge. The attributes include: * **id**: name of the edge * **from**: name of the node the edge starts from * **to**: the name of the node the edges ends at * **length**: length of the edge * **numLanes**: the number of lanes on the edge * **speed**: the speed limit for vehicles on the edge * other sumo-related attributes, see: http://sumo.dlr.de/wiki/Networks/Building_Networks_from_own_XML-descriptions#Edge_Descriptions. One useful additional attribute is **shape**, which specifies the shape of the edge connecting the two nodes. The shape consists of a series of subnodes (internal to sumo) that are connected together by straight lines to create a curved edge. If no shape is specified, the nodes are connected by a straight line. This attribute will be needed to create the circular arcs between the nodes in the system. We now create four arcs connected the nodes specified in section 1.2, with the direction of the edges directed counter-clockwise: ``` # some mathematical operations that may be used from numpy import pi, sin, cos, linspace class myNetwork(myNetwork): # update my network class def specify_edges(self, net_params): r = net_params.additional_params["radius"] edgelen = r * pi / 2 # this will let us control the number of lanes in the network lanes = net_params.additional_params["num_lanes"] # speed limit of vehicles in the network speed_limit = net_params.additional_params["speed_limit"] edges = [ { "id": "edge0", "numLanes": lanes, "speed": speed_limit, "from": "right", "to": "bottom", "length": edgelen, }, { "id": "edge1", "numLanes": lanes, "speed": speed_limit, "from": "top", "to": "left", "length": edgelen, }, { "id": "edge2", "numLanes": lanes, "speed": speed_limit, "from": "bottom", "to": "center", "length": edgelen, }, { "id": "edge3", "numLanes": lanes, "speed": speed_limit, "from": "center", "to": "top", "length": edgelen, }, { "id": "edge4", "numLanes": lanes, "speed": speed_limit, "from": "left", "to": "center", "length": edgelen, }, { "id": "edge5", "numLanes": lanes, "speed": speed_limit, "from": "center", "to": "right", "length": edgelen, } ] return edges ``` ### 1.4 specify_routes The routes are the sequence of edges vehicles traverse given their current position. For example, a vehicle beginning in the edge titled "edge0" (see section 1.3) must traverse, in sequence, the edges "edge0", "edge1", "edge2", and "edge3", before restarting its path. In order to specify the routes a vehicle may take, the function `specify_routes` is used. The routes in this method can be specified in one of three ways: **1. Single route per edge:** In this case of deterministic routes (as is the case in the ring road network), the routes can be specified as dictionary where the key element represents the starting edge and the element is a single list of edges the vehicle must traverse, with the first edge corresponding to the edge the vehicle begins on. Note that the edges must be connected for the route to be valid. For this network, the available routes under this setting can be defined as follows: ``` class myNetwork(myNetwork): # update my network class def specify_routes(self, net_params): rts = {"edge0": ["edge0", "edge2", "edge3", "edge1", "edge4", "edge5"], "edge1": ["edge1", "edge4", "edge5", "edge0", "edge2", "edge3"], "edge2": ["edge2", "edge3", "edge1", "edge4", "edge5", "edge0"], "edge3": ["edge3", "edge1", "edge4", "edge5", "edge0", "edge2"], "edge4": ["edge4", "edge5", "edge0", "edge2", "edge3", "edge1"], "edge5": ["edge5", "edge0", "edge2", "edge3", "edge1", "edge4"]} return rts ``` **2. Multiple routes per edge:** Alternatively, if the routes are meant to be stochastic, each element can consist of a list of (route, probability) tuples, where the first element in the tuple is one of the routes a vehicle can take from a specific starting edge, and the second element is the probability that vehicles will choose that route. Note that, in this case, the sum of probability values for each dictionary key must sum up to one. For example, modifying the code snippet we presented above, another valid way of representing the route in a more probabilistic setting is: ``` class myNetwork(myNetwork): # update my network class def specify_routes(self, net_params): rts = {"edge0": [(["edge0", "edge1", "edge2", "edge3"], 1)], "edge1": [(["edge1", "edge2", "edge3", "edge0"], 1)], "edge2": [(["edge2", "edge3", "edge0", "edge1"], 1)], "edge3": [(["edge3", "edge0", "edge1", "edge2"], 1)]} return rts ``` **3. Per-vehicle routes:** Finally, if you would like to assign a specific starting route to a vehicle with a specific ID, you can do so by adding a element into the dictionary whose key is the name of the vehicle and whose content is the list of edges the vehicle is meant to traverse as soon as it is introduced to the network. As an example, assume we have a vehicle named "human_0" in the network (as we will in the later sections), and it is initialized in the edge names "edge_0". Then, the route for this edge specifically can be added through the `specify_routes` method as follows: ``` class myNetwork(myNetwork): # update my network class def specify_routes(self, net_params): rts = {"edge0": ["edge0", "edge1", "edge2", "edge3"], "edge1": ["edge1", "edge2", "edge3", "edge0"], "edge2": ["edge2", "edge3", "edge0", "edge1"], "edge3": ["edge3", "edge0", "edge1", "edge2"], "human_0": ["edge0", "edge1", "edge2", "edge3"]} return rts ``` In all three cases, the routes are ultimately represented in the class in the form described under the multiple routes setting, i.e. >>> print(network.rts) { "edge0": [ (["edge0", "edge1", "edge2", "edge3"], 1) ], "edge1": [ (["edge1", "edge2", "edge3", "edge0"], 1) ], "edge2": [ (["edge2", "edge3", "edge0", "edge1"], 1) ], "edge3": [ (["edge3", "edge0", "edge1", "edge2"], 1) ], "human_0": [ (["edge0", "edge1", "edge2", "edge3"], 1) ] } where the vehicle-specific route is only included in the third case. ## 2. Specifying Auxiliary Network Features Other auxiliary methods exist within the base network class to help support vehicle state initialization and acquisition. Of these methods, the only required abstract method is: * **specify_edge_starts**: defines edge starts for road sections with respect to some global reference Other optional abstract methods within the base network class include: * **specify_internal_edge_starts**: defines the edge starts for internal edge nodes caused by finite length connections between road section * **specify_intersection_edge_starts**: defines edge starts for intersections with respect to some global reference frame. Only needed by environments with intersections. * **gen_custom_start_pos**: used to generate a user defined set of starting positions for vehicles in the network ### 2.2 Specifying the Starting Position of Edges All of the above functions starting with "specify" receive no inputs, and return a list of tuples in which the first element of the tuple is the name of the edge/intersection/internal_link, and the second value is the distance of the link from some global reference, i.e. [(link_0, pos_0), (link_1, pos_1), ...]. The data specified in `specify_edge_starts` is used to provide a "global" sense of the location of vehicles, in one dimension. This is done either through the `get_x_by_id` method within an environment, or the `get_absolute_position` method in the `Vehicles` object within an environment. The `specify_internal_edge_starts` allows us to do the same to junctions/internal links when they are also located within the network (this is not the case for the ring road). In section 1, we created a network with 4 edges named: "edge0", "edge1", "edge2", and "edge3". We assume that the edge titled "edge0" is the origin, and accordingly the position of the edge start of "edge0" is 0. The next edge, "edge1", begins a quarter of the length of the network from the starting point of edge "edge0", and accordingly the position of its edge start is radius * pi/2. This process continues for each of the edges. We can then define the starting position of the edges as follows: ``` # import some math functions we may use from numpy import pi class myNetwork(myNetwork): # update my network class def specify_edge_starts(self): r = self.net_params.additional_params["radius"] edgestarts = [("edge0", 0), ("edge1", 1.414*r), ("edge2", 1.414*r), ("edge3", r), ("edge4", 2*r), ("edge5", r)] return edgestarts ``` ## 3. Testing the New Network In this section, we run a new sumo simulation using our newly generated network class. For information on running sumo experiments, see `tutorial01_sumo.ipynb`. We begin by defining some of the components needed to run a sumo experiment. ``` from flow.core.params import VehicleParams from flow.controllers import IDMController, ContinuousRouter from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams vehicles = VehicleParams() vehicles.add(veh_id="human", acceleration_controller=(IDMController, {}), routing_controller=(ContinuousRouter, {}), num_vehicles=22) sim_params = SumoParams(sim_step=0.1, render=True) initial_config = InitialConfig(bunching=40) ``` For visualizing purposes, we use the environment `AccelEnv`, as it works on any given network. ``` from flow.envs.ring.accel import AccelEnv, ADDITIONAL_ENV_PARAMS env_params = EnvParams(additional_params=ADDITIONAL_ENV_PARAMS) ``` Next, using the `ADDITIONAL_NET_PARAMS` component see created in section 1.1, we prepare the `NetParams` component. ``` additional_net_params = ADDITIONAL_NET_PARAMS.copy() net_params = NetParams(additional_params=additional_net_params) ``` We are ready now to create and run our network. Using the newly defined network classes, we create a network object and feed it into a `Experiment` simulation. Finally, we are able to visually confirm that are network has been properly generated. ``` from flow.core.experiment import Experiment from flow.networks import FigureEightNetwork flow_params = dict( exp_tag='test_network', env_name=AccelEnv, network=FigureEightNetwork, simulator='traci', sim=sim_params, env=env_params, net=net_params, veh=vehicles, initial=initial_config, ) # number of time steps flow_params['env'].horizon = 1500 exp = Experiment(flow_params) # run the sumo simulation _ = exp.run(1) ```
github_jupyter
TSG033 - Show BDC SQL status ============================ Steps ----- ### Common functions Define helper functions used in this notebook. ``` # Define `run` function for transient fault handling, hyperlinked suggestions, and scrolling updates on Windows import sys import os import re import json import platform import shlex import shutil import datetime from subprocess import Popen, PIPE from IPython.display import Markdown retry_hints = {} # Output in stderr known to be transient, therefore automatically retry error_hints = {} # Output in stderr where a known SOP/TSG exists which will be HINTed for further help install_hint = {} # The SOP to help install the executable if it cannot be found first_run = True rules = None debug_logging = False def run(cmd, return_output=False, no_output=False, retry_count=0, base64_decode=False, return_as_json=False): """Run shell command, stream stdout, print stderr and optionally return output NOTES: 1. Commands that need this kind of ' quoting on Windows e.g.: kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='data-pool')].metadata.name} Need to actually pass in as '"': kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='"'data-pool'"')].metadata.name} The ' quote approach, although correct when pasting into Windows cmd, will hang at the line: `iter(p.stdout.readline, b'')` The shlex.split call does the right thing for each platform, just use the '"' pattern for a ' """ MAX_RETRIES = 5 output = "" retry = False global first_run global rules if first_run: first_run = False rules = load_rules() # When running `azdata sql query` on Windows, replace any \n in """ strings, with " ", otherwise we see: # # ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string or buffer length (0) (SQLExecDirectW)') # if platform.system() == "Windows" and cmd.startswith("azdata sql query"): cmd = cmd.replace("\n", " ") # shlex.split is required on bash and for Windows paths with spaces # cmd_actual = shlex.split(cmd) # Store this (i.e. kubectl, python etc.) to support binary context aware error_hints and retries # user_provided_exe_name = cmd_actual[0].lower() # When running python, use the python in the ADS sandbox ({sys.executable}) # if cmd.startswith("python "): cmd_actual[0] = cmd_actual[0].replace("python", sys.executable) # On Mac, when ADS is not launched from terminal, LC_ALL may not be set, which causes pip installs to fail # with: # # UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4969: ordinal not in range(128) # # Setting it to a default value of "en_US.UTF-8" enables pip install to complete # if platform.system() == "Darwin" and "LC_ALL" not in os.environ: os.environ["LC_ALL"] = "en_US.UTF-8" # When running `kubectl`, if AZDATA_OPENSHIFT is set, use `oc` # if cmd.startswith("kubectl ") and "AZDATA_OPENSHIFT" in os.environ: cmd_actual[0] = cmd_actual[0].replace("kubectl", "oc") # To aid supportability, determine which binary file will actually be executed on the machine # which_binary = None # Special case for CURL on Windows. The version of CURL in Windows System32 does not work to # get JWT tokens, it returns "(56) Failure when receiving data from the peer". If another instance # of CURL exists on the machine use that one. (Unfortunately the curl.exe in System32 is almost # always the first curl.exe in the path, and it can't be uninstalled from System32, so here we # look for the 2nd installation of CURL in the path) if platform.system() == "Windows" and cmd.startswith("curl "): path = os.getenv('PATH') for p in path.split(os.path.pathsep): p = os.path.join(p, "curl.exe") if os.path.exists(p) and os.access(p, os.X_OK): if p.lower().find("system32") == -1: cmd_actual[0] = p which_binary = p break # Find the path based location (shutil.which) of the executable that will be run (and display it to aid supportability), this # seems to be required for .msi installs of azdata.cmd/az.cmd. (otherwise Popen returns FileNotFound) # # NOTE: Bash needs cmd to be the list of the space separated values hence shlex.split. # if which_binary == None: which_binary = shutil.which(cmd_actual[0]) # Display an install HINT, so the user can click on a SOP to install the missing binary # if which_binary == None: if user_provided_exe_name in install_hint and install_hint[user_provided_exe_name] is not None: display(Markdown(f'HINT: Use [{install_hint[user_provided_exe_name][0]}]({install_hint[user_provided_exe_name][1]}) to resolve this issue.')) raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") else: cmd_actual[0] = which_binary start_time = datetime.datetime.now().replace(microsecond=0) print(f"START: {cmd} @ {start_time} ({datetime.datetime.utcnow().replace(microsecond=0)} UTC)") print(f" using: {which_binary} ({platform.system()} {platform.release()} on {platform.machine()})") print(f" cwd: {os.getcwd()}") # Command-line tools such as CURL and AZDATA HDFS commands output # scrolling progress bars, which causes Jupyter to hang forever, to # workaround this, use no_output=True # # Work around a infinite hang when a notebook generates a non-zero return code, break out, and do not wait # wait = True try: if no_output: p = Popen(cmd_actual) else: p = Popen(cmd_actual, stdout=PIPE, stderr=PIPE, bufsize=1) with p.stdout: for line in iter(p.stdout.readline, b''): line = line.decode() if return_output: output = output + line else: if cmd.startswith("azdata notebook run"): # Hyperlink the .ipynb file regex = re.compile(' "(.*)"\: "(.*)"') match = regex.match(line) if match: if match.group(1).find("HTML") != -1: display(Markdown(f' - "{match.group(1)}": "{match.group(2)}"')) else: display(Markdown(f' - "{match.group(1)}": "[{match.group(2)}]({match.group(2)})"')) wait = False break # otherwise infinite hang, have not worked out why yet. else: print(line, end='') if rules is not None: apply_expert_rules(line) if wait: p.wait() except FileNotFoundError as e: if install_hint is not None: display(Markdown(f'HINT: Use {install_hint} to resolve this issue.')) raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") from e exit_code_workaround = 0 # WORKAROUND: azdata hangs on exception from notebook on p.wait() if not no_output: for line in iter(p.stderr.readline, b''): try: line_decoded = line.decode() except UnicodeDecodeError: # NOTE: Sometimes we get characters back that cannot be decoded(), e.g. # # \xa0 # # For example see this in the response from `az group create`: # # ERROR: Get Token request returned http error: 400 and server # response: {"error":"invalid_grant",# "error_description":"AADSTS700082: # The refresh token has expired due to inactivity.\xa0The token was # issued on 2018-10-25T23:35:11.9832872Z # # which generates the exception: # # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 179: invalid start byte # print("WARNING: Unable to decode stderr line, printing raw bytes:") print(line) line_decoded = "" pass else: # azdata emits a single empty line to stderr when doing an hdfs cp, don't # print this empty "ERR:" as it confuses. # if line_decoded == "": continue print(f"STDERR: {line_decoded}", end='') if line_decoded.startswith("An exception has occurred") or line_decoded.startswith("ERROR: An error occurred while executing the following cell"): exit_code_workaround = 1 # inject HINTs to next TSG/SOP based on output in stderr # if user_provided_exe_name in error_hints: for error_hint in error_hints[user_provided_exe_name]: if line_decoded.find(error_hint[0]) != -1: display(Markdown(f'HINT: Use [{error_hint[1]}]({error_hint[2]}) to resolve this issue.')) # apply expert rules (to run follow-on notebooks), based on output # if rules is not None: apply_expert_rules(line_decoded) # Verify if a transient error, if so automatically retry (recursive) # if user_provided_exe_name in retry_hints: for retry_hint in retry_hints[user_provided_exe_name]: if line_decoded.find(retry_hint) != -1: if retry_count < MAX_RETRIES: print(f"RETRY: {retry_count} (due to: {retry_hint})") retry_count = retry_count + 1 output = run(cmd, return_output=return_output, retry_count=retry_count) if return_output: if base64_decode: import base64 return base64.b64decode(output).decode('utf-8') else: return output elapsed = datetime.datetime.now().replace(microsecond=0) - start_time # WORKAROUND: We avoid infinite hang above in the `azdata notebook run` failure case, by inferring success (from stdout output), so # don't wait here, if success known above # if wait: if p.returncode != 0: raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(p.returncode)}.\n') else: if exit_code_workaround !=0 : raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(exit_code_workaround)}.\n') print(f'\nSUCCESS: {elapsed}s elapsed.\n') if return_output: if base64_decode: import base64 return base64.b64decode(output).decode('utf-8') else: return output def load_json(filename): """Load a json file from disk and return the contents""" with open(filename, encoding="utf8") as json_file: return json.load(json_file) def load_rules(): """Load any 'expert rules' from the metadata of this notebook (.ipynb) that should be applied to the stderr of the running executable""" # Load this notebook as json to get access to the expert rules in the notebook metadata. # try: j = load_json("tsg033-azdata-bdc-sql-status.ipynb") except: pass # If the user has renamed the book, we can't load ourself. NOTE: Is there a way in Jupyter, to know your own filename? else: if "metadata" in j and \ "azdata" in j["metadata"] and \ "expert" in j["metadata"]["azdata"] and \ "expanded_rules" in j["metadata"]["azdata"]["expert"]: rules = j["metadata"]["azdata"]["expert"]["expanded_rules"] rules.sort() # Sort rules, so they run in priority order (the [0] element). Lowest value first. # print (f"EXPERT: There are {len(rules)} rules to evaluate.") return rules def apply_expert_rules(line): """Determine if the stderr line passed in, matches the regular expressions for any of the 'expert rules', if so inject a 'HINT' to the follow-on SOP/TSG to run""" global rules for rule in rules: notebook = rule[1] cell_type = rule[2] output_type = rule[3] # i.e. stream or error output_type_name = rule[4] # i.e. ename or name output_type_value = rule[5] # i.e. SystemExit or stdout details_name = rule[6] # i.e. evalue or text expression = rule[7].replace("\\*", "*") # Something escaped *, and put a \ in front of it! if debug_logging: print(f"EXPERT: If rule '{expression}' satisfied', run '{notebook}'.") if re.match(expression, line, re.DOTALL): if debug_logging: print("EXPERT: MATCH: name = value: '{0}' = '{1}' matched expression '{2}', therefore HINT '{4}'".format(output_type_name, output_type_value, expression, notebook)) match_found = True display(Markdown(f'HINT: Use [{notebook}]({notebook}) to resolve this issue.')) print('Common functions defined successfully.') # Hints for binary (transient fault) retry, (known) error and install guide # retry_hints = {'azdata': ['Endpoint sql-server-master does not exist', 'Endpoint livy does not exist', 'Failed to get state for cluster', 'Endpoint webhdfs does not exist', 'Adaptive Server is unavailable or does not exist', 'Error: Address already in use', 'Login timeout expired (0) (SQLDriverConnect)']} error_hints = {'azdata': [['The token is expired', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Reason: Unauthorized', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Max retries exceeded with url: /api/v1/bdc/endpoints', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Look at the controller logs for more details', 'TSG027 - Observe cluster deployment', '../diagnose/tsg027-observe-bdc-create.ipynb'], ['provided port is already allocated', 'TSG062 - Get tail of all previous container logs for pods in BDC namespace', '../log-files/tsg062-tail-bdc-previous-container-logs.ipynb'], ['Create cluster failed since the existing namespace', 'SOP061 - Delete a big data cluster', '../install/sop061-delete-bdc.ipynb'], ['Failed to complete kube config setup', 'TSG067 - Failed to complete kube config setup', '../repair/tsg067-failed-to-complete-kube-config-setup.ipynb'], ['Error processing command: "ApiError', 'TSG110 - Azdata returns ApiError', '../repair/tsg110-azdata-returns-apierror.ipynb'], ['Error processing command: "ControllerError', 'TSG036 - Controller logs', '../log-analyzers/tsg036-get-controller-logs.ipynb'], ['ERROR: 500', 'TSG046 - Knox gateway logs', '../log-analyzers/tsg046-get-knox-logs.ipynb'], ['Data source name not found and no default driver specified', 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ["Can't open lib 'ODBC Driver 17 for SQL Server", 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ['Control plane upgrade failed. Failed to upgrade controller.', 'TSG108 - View the controller upgrade config map', '../diagnose/tsg108-controller-failed-to-upgrade.ipynb'], ["[Errno 2] No such file or directory: '..\\\\", 'TSG053 - ADS Provided Books must be saved before use', '../repair/tsg053-save-book-first.ipynb'], ["NameError: name 'azdata_login_secret_name' is not defined", 'SOP013 - Create secret for azdata login (inside cluster)', '../common/sop013-create-secret-for-azdata-login.ipynb'], ['ERROR: No credentials were supplied, or the credentials were unavailable or inaccessible.', "TSG124 - 'No credentials were supplied' error from azdata login", '../repair/tsg124-no-credentials-were-supplied.ipynb']]} install_hint = {'azdata': ['SOP063 - Install azdata CLI (using package manager)', '../install/sop063-packman-install-azdata.ipynb']} ``` ### Use azdata to show the big data cluster sql status ``` run('azdata bdc sql status show') print('Notebook execution complete.') ```
github_jupyter
# Predicting Marketing Efforts: SEO Advertising, Brand Advertising, and Retailer Support Let's look at predicting the average Brand Advertising Efforts and Search Engine Optimization Efforts This helps us make more accurate decisions in BSG and identify if we'll hit the shareholder expectations for the period. ``` #let's grab a few packages for stats import matplotlib.pyplot as plt import numpy as np import pandas as pd #Let's set some variables that we'll change each round #Change this year to the year being predicted (i.e. if you're predicting year 16, enter '16') predictionYear = 17 #Load the dataset from our bsg_prices_actual - Sheet1.csv df = pd.read_csv('bsg_marketing_actual - Sheet1.csv') df ``` ## Functions 1. Slope Intercept 2. Print Slope as Formula 3. Hypothetical Slope and Intercept from our data 4. Print the Predicted Year using Hypothetical Slope and Intercept ``` #1. Slope Intercept Function #Function to find the slope intercept of a first degree polynomial def getSlope(x,y): #pass in the x value, y value, and a string for printing slope, intercept = np.polyfit(x,y,1).round(decimals = 4) #compute the slope return slope, intercept #2. Print Slope as Formulas #Function to print the slope def printSlope(x,y,string): slope, intercept = np.polyfit(x,y,1).round(decimals = 4) printed_string = string + '= ' + str(slope) + 'x + ' + str(intercept) return printed_string #3. Hypothetical Slope and Intercept from our data x_theor = np.array([10,predictionYear]) #set x_theor as it will be used in all our Linear Models def getYTheor(slope, x_theor, intercept): #pass in the slope, x_theor, and intercept y_theor = slope * x_theor + intercept return y_theor #4. Print Predicted Year using Hypothetical Slope and Intercept def printPrediction(slope, intercept, string): prediction = 'Year ' + str(predictionYear) + ' ' + string +' predicted price: ' + str(slope * predictionYear + intercept) return prediction ``` ### Find Slope Intercept for each segment ``` # variable assignments x = np.array(df['YEAR']) y_na_seo = np.array(df['NA_SEO']) y_na_advertising = np.array(df['NA_ADVERTISING']) y_na_retailsup = np.array(df['NA_RETAIL_SUPPORT']) y_eu_seo = np.array(df['EU_SEO']) y_eu_advertising = np.array(df['EU_ADVERTISING']) y_eu_retailsup = np.array(df['EU_RETAIL_SUPPORT']) y_ap_seo = np.array(df['AP_SEO']) y_ap_advertising = np.array(df['AP_ADVERTISING']) y_ap_retailsup = np.array(df['AP_RETAIL_SUPPORT']) y_la_seo = np.array(df['LA_SEO']) y_la_advertising = np.array(df['LA_ADVERTISING']) y_la_retailsup = np.array(df['LA_RETAIL_SUPPORT']) #print the slope in y=mx+b form print(printSlope(x,y_na_seo,'NA SEO')) print(printSlope(x,y_na_advertising,'NA Advertising')) print(printSlope(x,y_na_retailsup,'NA Retailer Support')) print(printSlope(x,y_eu_seo,'EU SEO')) print(printSlope(x,y_eu_advertising,'EU Advertising')) print(printSlope(x,y_eu_retailsup,'EU Retailer Support')) print(printSlope(x,y_ap_seo,'AP SEO')) print(printSlope(x,y_ap_advertising,'AP Advertising')) print(printSlope(x,y_ap_retailsup,'AP Retailer Support')) print(printSlope(x,y_la_seo,'LA SEO')) print(printSlope(x,y_la_advertising,'LA Advertising')) print(printSlope(x,y_la_retailsup,'LA Retailer Support')) ``` ### North America SEO, Advertising, and Retailer Support Predictions * SEO: Search Engine Optimization Advertising 000s dollars * Advertising: Wholesale Brand Advertising 000s dollars * Retailer Support: dollars per outlet ``` #grab the slope and intercepts for NA na_seo_slope, na_seo_intercept = getSlope(x,y_na_seo) na_advertising_slope,na_advertising_intercept = getSlope(x,y_na_advertising) na_retailsup_slope, na_retailsup_intercept = getSlope(x,y_na_retailsup) #set the y theoretical for NA seo_y_theor = getYTheor(na_seo_slope, x_theor, na_seo_intercept) advertising_y_theor = getYTheor(na_advertising_slope,x_theor,na_advertising_intercept) retailsup_y_theor = getYTheor(na_retailsup_slope, x_theor, na_retailsup_intercept) #print the predicted price print(printPrediction(na_seo_slope, na_seo_intercept, 'SEO')) print(printPrediction(na_advertising_slope, na_advertising_intercept, 'Brand Advertising')) print(printPrediction(na_retailsup_slope, na_retailsup_intercept, 'Retailer Support')) #plot the anscombe data and theoretical lines _ = plt.plot(x,y_na_seo,marker='.', linestyle='none') _ = plt.plot(x_theor,seo_y_theor) _ = plt.plot(x,y_na_advertising,marker='.', linestyle='none') _ = plt.plot(x_theor,advertising_y_theor) _ = plt.plot(x,y_na_retailsup,marker='.', linestyle='none') _ = plt.plot(x_theor,retailsup_y_theor) #label the axes plt.xlabel('Year') plt.ylabel('Advertising Dollars') plt.title('North America') plt.show() ``` ### Europe Africa SEO, Advertising, and Retailer Support Predictions * SEO: Search Engine Optimization Advertising 000s dollars * Advertising: Wholesale Brand Advertising 000s dollars * Retailer Support: dollars per outlet ``` #grab the slope and intercepts for EU eu_seo_slope, eu_seo_intercept = getSlope(x,y_eu_seo) eu_advertising_slope, eu_advertising_intercept = getSlope(x,y_eu_advertising) eu_retailsup_slope, eu_retailsup_intercept = getSlope(x,y_eu_retailsup) #set the y theoretical for EU seo_y_theor = getYTheor(eu_seo_slope, x_theor, eu_seo_intercept) advertising_y_theor = getYTheor(eu_advertising_slope,x_theor,eu_advertising_intercept) retailsup_y_theor = getYTheor(eu_retailsup_slope, x_theor, eu_retailsup_intercept) #print the predicted price print(printPrediction(eu_seo_slope, eu_seo_intercept, 'SEO')) print(printPrediction(eu_advertising_slope, eu_advertising_intercept, 'Brand Advertising')) print(printPrediction(eu_retailsup_slope, eu_retailsup_intercept, 'Retailer Support')) #plot the anscombe data and theoretical lines _ = plt.plot(x,y_eu_seo,marker='.', linestyle='none') _ = plt.plot(x_theor,seo_y_theor) _ = plt.plot(x,y_eu_advertising,marker='.', linestyle='none') _ = plt.plot(x_theor,advertising_y_theor) _ = plt.plot(x,y_eu_retailsup,marker='.', linestyle='none') _ = plt.plot(x_theor,retailsup_y_theor) #label the axes plt.xlabel('Year') plt.ylabel('Advertising Dollars') plt.title('Europe Africa') plt.show() ``` ### Asia Pacific SEO, Advertising, and Retailer Support Predictions * SEO: Search Engine Optimization Advertising 000s dollars * Advertising: Wholesale Brand Advertising 000s dollars * Retailer Support: dollars per outlet ``` #grab the slope and intercepts for AP ap_seo_slope, ap_seo_intercept = getSlope(x,y_ap_seo) ap_advertising_slope, ap_advertising_intercept = getSlope(x,y_ap_advertising) ap_retailsup_slope, ap_retailsup_intercept = getSlope(x,y_ap_retailsup) #set the y theoretical for AP seo_y_theor = getYTheor(ap_seo_slope, x_theor, ap_seo_intercept) advertising_y_theor = getYTheor(ap_advertising_slope,x_theor,ap_advertising_intercept) retailsup_y_theor = getYTheor(ap_retailsup_slope, x_theor, ap_retailsup_intercept) #print the predicted price print(printPrediction(ap_seo_slope, ap_seo_intercept, 'SEO')) print(printPrediction(ap_advertising_slope, ap_advertising_intercept, 'Brand Advertising')) print(printPrediction(ap_retailsup_slope, ap_retailsup_intercept, 'Retailer Support')) #plot the anscombe data and theoretical lines _ = plt.plot(x,y_ap_seo,marker='.', linestyle='none') _ = plt.plot(x_theor,seo_y_theor) _ = plt.plot(x,y_ap_advertising,marker='.', linestyle='none') _ = plt.plot(x_theor,advertising_y_theor) _ = plt.plot(x,y_ap_retailsup,marker='.', linestyle='none') _ = plt.plot(x_theor,retailsup_y_theor) #label the axes plt.xlabel('Year') plt.ylabel('Advertising Dollars') plt.title('Asia Pacific') plt.show() ``` ### Latin America SEO, Advertising, and Retailer Support Predictions * SEO: Search Engine Optimization Advertising 000s dollars * Advertising: Wholesale Brand Advertising 000s dollars * Retailer Support: dollars per outlet ``` #grab the slope and intercepts for LA la_seo_slope, la_seo_intercept = getSlope(x,y_la_seo) la_advertising_slope, la_advertising_intercept = getSlope(x,y_la_advertising) la_retailsup_slope, la_retailsup_intercept = getSlope(x,y_la_retailsup) #set the y theoretical for LA seo_y_theor = getYTheor(la_seo_slope, x_theor, la_seo_intercept) advertising_y_theor = getYTheor(la_advertising_slope,x_theor,la_advertising_intercept) retailsup_y_theor = getYTheor(la_retailsup_slope, x_theor, la_retailsup_intercept) #print the predicted price print(printPrediction(la_seo_slope, la_seo_intercept, 'SEO')) print(printPrediction(la_advertising_slope, la_advertising_intercept, 'Brand Advertising')) print(printPrediction(la_retailsup_slope, la_retailsup_intercept, 'Retailer Support')) #plot the anscombe data and theoretical lines _ = plt.plot(x,y_la_seo,marker='.', linestyle='none') _ = plt.plot(x_theor,seo_y_theor) _ = plt.plot(x,y_la_advertising,marker='.', linestyle='none') _ = plt.plot(x_theor,advertising_y_theor) _ = plt.plot(x,y_la_retailsup,marker='.', linestyle='none') _ = plt.plot(x_theor,retailsup_y_theor) #label the axes plt.xlabel('Year') plt.ylabel('Advertising Dollars') plt.title('Latin America') plt.show() ```
github_jupyter
### Een parser-generator voor de wordgrammar In de ETCBC-data wordt een morphologische analyse-annotatie gebruikt, die per project kan worden gedefinieerd in een `word_grammar`-definitiebestand. Per project moet er eerst een annotatieparser worden gegenereerd aan de hand van het `word-grammar`-bestand. Dat gebeurt in de `WordGrammar` class in `wrdgrm.py`, die afhankelijk is van de parser-generator in de `wgr.py` en `yapps-runtime.py` modules. De parser-generator is gegenereerd met Yapps2 (zie de website: http://theory.stanford.edu/~amitp/yapps/ en https://github.com/smurfix/yapps). Om een `WordGrammar`-object te maken zijn een `word_grammar`-bestand en een `lexicon`-bestand vereist. Vervolgens kunnen woorden geanalyseerd worden met de method `WordGrammar.analyze(word)`. ``` # eerst modules importeren import os from wrdgrm import WordGrammar ``` hulpfunctie ``` def filepath(rel_path): return os.path.realpath(os.path.join(os.getcwd(), rel_path)) # bestandslocaties lexicon_file = filepath("../../data/blc/syrlex") word_grammar_file = filepath("../../data/blc/syrwgr") an_file = filepath("../../data/blc/Laws.an") # dan kan de wordgrammar worden geïnitialiseerd wg = WordGrammar(word_grammar_file, lexicon_file) ``` De method `analyze()` retourneert een `Word`-object met de analyse. ``` # wrdgrm.Word object wg.analyze(">TR/&WT=~>") # voorbeeld word = wg.analyze(">TR/&WT=~>") print( "{:15}".format("Morphemes:"), tuple((m.mt.ident, (m.p, m.s, m.a)) for m in word.morphemes), ) print("{:15}".format("Functions:"), word.functions) print("{:15}".format("Lexicon:"), word.lex) print("{:15}".format("Lexeme:"), word.lexeme) print("{:15}".format("Annotated word:"), word.word) print("{:15}".format("Meta form:"), word.meta_form) print("{:15}".format("Surface form:"), word.surface_form) print("{:15}".format("Paradigmatic form:"), word.paradigmatic_form) ``` Naast verschillende `string`-weergaven van het geanalyseerde woord bevat het `Word`-object drie `tuples`: `morphemes`, `functions` en `lex`, met daarin de belangrijkste analyses. De eerste, `morphemes`, bevat een tuple met alle gevonden morfemen, elk als een ~~tuple met drie strings~~ `Morpheme` object met vier attributen: `mt`, een namedtuple met informatie over het morfeemtype; `p`, de paradigmatische vorm (zoals die in het lexicon staat); `s`, de oppervlaktevorm (zoals die in de tekst staat); en `a`, de geannoteerde vorm met meta-karakters. De tweede, `functions`, bevat de grammaticale functies van het woord, zoals die in de `wordgrammar` gedefinieerd zijn: `ps: "person"`, `nu: "number"`, `gn: "gender"`, `ls: "lexical set"`, `sp: "part of speech"`, `st: "state"`, `vo: "voice"`, `vs: "verbal stem"`, `vt: "verbal tense"`. Een veld met de waarde `False` geeft aan dat deze functie niet van toepassing is op dit woord, een veld met waarde `None` geeft aan dat de waarde niet is vastgesteld. De derde, `lex`, bevat het lemma zoals dat in het lexicon staat, met als eerste het woord-id, en vervolgens de annotaties. Behalve standaard-waarden voor de grammaticale functies bevat het lexicon een `gl`-veld voor ieder woord (gloss), en soms een `de`-veld (derived form). (In één resp. twee gevallen komen ook de velden `cs` en `ln` voor, waarvan de betekenis mij niet duidelijk is.) ``` # De method `dmp_str` genereert een string die overeenkomt met die in .dmp-bestanden. # Hieronder een voorbeeld hoe die gebruikt kan worden om een .dmp-bestand te genereren. # Voor een eenvoudiger manier, zie de AnParser notebook. def dump_anfile(name, an_file): with open(an_file) as f: for line in f: verse, s, a = line.split() # verse, surface form, analyzed form for an_word in a.split("-"): word = wg.analyze(an_word) yield word.dmp_str(name, verse) for i, line in zip(range(20), dump_anfile("Laws", an_file)): # for line in dump_anfile('Laws', an_file): print(line) print("...") ``` Om te controleren dat de output correct is heb ik bovenstaande output vergeleken met de bestaande .dmp-bestanden. Omdat de volgorde van de waarden willekeurig lijkt te zijn - of in ieder geval niet in alle gevallen gelijk - moeten alle waarden gesorteerd worden voor ze vergeleken kunnen worden, een eenvoudige diff volstaat niet. Onderstaand script ~~bevestigt dat bovenstaande output, op de volgorde na, een exacte weergave is van de bestaande .dmp-bestanden~~ toont aan dat zowel de an-file als de word_grammar zijn aangepast sinds de .dmp-bestanden zijn gegenereerd: (verschillen: woorden met vpm=dp zijn nu correct als vo=pas geanalyseerd, en van `]>](NKJ[` in 15,12 en `]M]SKN[/JN` in 19.12 zijn de annotaties gewijzigd) ``` dmp_file = filepath("../../data/blc/Laws.dmp") dmp_gen = dump_anfile("BLC", an_file) with open(dmp_file) as f_dmp: for line1, line2 in zip(f_dmp, dmp_gen): for f1, f2 in zip(line1.strip().split("\t"), line2.split("\t")): f1s, f2s = (",".join(sorted(f.split(","))) for f in (f1, f2)) if f1s != f2s: print(f"{line1}!=\n{line2}") ```
github_jupyter
最初に必要なライブラリを読み込みます。 ``` from sympy import * from sympy.physics.quantum import * from sympy.physics.quantum.qubit import Qubit, QubitBra, measure_all, measure_all_oneshot from sympy.physics.quantum.gate import H,X,Y,Z,S,T,CPHASE,CNOT,SWAP,UGate,CGateS,gate_simp from sympy.physics.quantum.gate import IdentityGate as _I from sympy.physics.quantum.qft import * from sympy.printing.dot import dotprint init_printing() %matplotlib inline import matplotlib.pyplot as plt from sympy.physics.quantum.circuitplot import CircuitPlot,labeller, Mz,CreateOneQubitGate ``` ## (狭義の)量子プログラミングの手順 1. 計算に必要な量子ビット(量子レジスタ)を準備して、その値を初期化する 2. 量子計算をユニタリ行列(ゲート演算子)で記述する 3. ユニタリ行列を量子ビットに作用する 4. 測定する #### (1の例)計算に必要な量子ビット(量子レジスタ)を準備して、その値を初期化する ``` # 全て 0 の3量子ビットを準備 Qubit('000') ``` #### (2の例)量子計算をユニタリ行列(ゲート演算子)で記述する ``` # 基本的なユニタリ演算子 pprint(represent(X(0),nqubits=1)) pprint(represent(Y(0),nqubits=1)) pprint(represent(Z(0),nqubits=1)) pprint(represent(H(0),nqubits=1)) pprint(represent(S(0),nqubits=1)) pprint(represent(S(0)**(-1),nqubits=1)) pprint(represent(T(0),nqubits=1)) pprint(represent(T(0)**(-1),nqubits=1)) pprint(represent(CNOT(1,0),nqubits=2)) ``` #### (3の例)ユニタリ行列を量子ビットに作用する ``` # ユニタリ行列を量子ビットに作用するには、qapply() を使います。 hadamard3 = H(2)*H(1)*H(0) qapply(hadamard3*Qubit('000')) ``` #### (4の例)測定する ``` # 測定は、qapply() した量子状態に対して、measure_all_oneshot() で確率的な結果を得ます。 for i in range(10): pprint(measure_all_oneshot(qapply(hadamard3*Qubit('000')))) # SymPyの量子シミュレーターでは、内部で量子状態を厳密に計算して、すべての状態を保持しています。 # そのため。measure_all() では、全ての量子状態の確率を得ることができます。 measure_all(qapply(hadamard3*Qubit('000'))) ``` ## 【練習問題】いつもの説明資料の量子回路をプログラミング手順にそって計算しましょう。 ![計算例](quantum_calc_sample.png) ``` ### 1. 計算に必要な量子ビット(量子レジスタ)を準備して、その値を初期化する ## 2量子ビットを 0 で初期化してください。 Qubit('00') ### 2. 量子計算をユニタリ行列(ゲート演算子)で記述する ## Hadamard のテンソル積 の行列表現を表示してください。 represent(H(1)*H(0),nqubits=2) ## CNOT を Hadamard で挟んだゲート操作 の行列表現を表示してください。 represent(H(0)*CNOT(1,0)*H(0),nqubits=2) ### 3. ユニタリ行列を量子ビットに作用する ## Hadamard のテンソル積 を `Qubit('00')` に作用してください。 qapply(H(1)*H(0)*Qubit('00')) ## 次に、CNOT を Hadamard で挟んだゲート操作 を 前の状態に作用してください。 qapply(H(0)*CNOT(1,0)*H(0)*H(1)*H(0)*Qubit('00')) ### 4. 測定する ## measure_all() を使って、それぞれの状態が測定される確率を表示してください。 measure_all(qapply(H(0)*CNOT(1,0)*H(0)*H(1)*H(0)*Qubit('00'))) ``` ## 【課題1】グローバーのアルゴリズム <strong> 問1) 1. 次の「問1の初期状態」 quest_state を入力として、この量子状態に $\lvert 111 \rangle $ が含まれるか  グローバーのアルゴリズムを使って調べてください。 2. 上の条件で、この量子状態に $\lvert 101 \rangle $ が含まれるかをグローバーのアルゴリズムを  使って調べる考察をします。(うまくいかない例を見ます)    ・プログラムを作り、実際は、$\lvert 101 \rangle $ が高確率で検出されることを調べてください。  ・なぜ、初期状態に含まれていない状態が検出されるか理由を考えましょう。(解答は口頭でよい)     問2) 1. 下の「問2の初期状態」quest2_state を入力として、問1と同様、  $\lvert 111 \rangle $ と $\lvert 101 \rangle $ の状態にの検知について グローバーのアルゴリズムを適用して、  その状況を考察してください。     </strong> **以降、【課題1】問1−1)の回答欄:** ``` # 問1の初期状態 quest_state = CNOT(1,0)*CNOT(2,1)*H(2)*H(0)*Qubit('000') CircuitPlot(quest_state,nqubits=3) # 計算した初期状態を init_state とする init_state = qapply(quest_state) init_state # 以降で役立ちそうな関数を定義します。 def CCX(c1,c2,t): return CGateS((c1,c2),X(t)) def hadamard(s,n): h = H(s) for i in range(s+1,n+s): h = H(i)*h return h def CCZ(c1,c2,t): return (H(t)*CCX(c1,c2,t)*H(t)) # CCZ演算子を定義します。 def DOp(n): return (Qubit('0'*n)*QubitBra('0'*n)*2-_I(0)) # ゲート操作で計算するには、上記コメントのような演算になります。 h_3 = hadamard(0,3) d_3 = h_3 * DOp(3) * h_3 # 平均値周りの反転操作 # represent(d_3,nqubits=3) # | 111 > の検索する量子回路を作成する。 mark_7 = CCZ(1,2,0) grover_7 = gate_simp(d_3*mark_7*d_3*mark_7) state1_7 = qapply(d_3*mark_7*init_state) pprint(state1_7) qapply(d_3*mark_7*state1_7) # 上で作った量子回路を初期状態と作用させて measure_all_oneshot() で何回か試行して、結果をみる。 for i in range(10): pprint(measure_all_oneshot(qapply(grover_7*init_state))) ``` **以降、【課題1】問1−2)の回答欄:** ``` # | 101 > の検索する量子回路を作成する。 mark_5 = X(1)*CCZ(1,2,0)*X(1) grover_5 = gate_simp(d_3*mark_5*d_3*mark_5) state1_5 = qapply(d_3*mark_5*init_state) pprint(state1_5) qapply(d_3*mark_5*state1_5) # 上で作った量子回路を初期状態と作用させて measure_all() でかく状態の確率をみて、考察する。 measure_all(qapply(grover_5*init_state)) ``` **以降、【課題1】問2−1)の回答欄:** ``` # 問2の初期状態 quest2_state = CNOT(2,1)*H(2)*X(2)*CNOT(2,1)*CNOT(2,0)*H(2)*X(2)*Qubit('000') CircuitPlot(quest2_state,nqubits=3) # 問2の回答欄(1) init2_state = qapply(quest2_state) init2_state # 問2の回答欄(2) for i in range(10): pprint(measure_all_oneshot(qapply(grover_7*init2_state))) # 問2の回答欄(3) measure_all(qapply(grover_5*init2_state)) ``` ## 【課題2】量子フーリエ変換 <strong> 問1) 1. 3量子ビットを対象にした、量子フーリエ変換を行います。  |000>, |001>, ..., |110>, |111> の全ての状態のそれぞれの QFT の結果を出してください。      ヒント)sympy.physics.quantum.qft の QFT 関数を使います。 2. QFT(0,3) の量子回路図を CircuitPlot() で作図してください。     問2) 1. 3量子ビットを対象にした、量子フーリエ変換を基本的な量子ゲートだけで表してください。   $\sqrt{T}$ゲートである Rk(n,4) は利用してもよい。    ・演算をテンソル積で表してください。  ・(この場合の量子回路図は、うまく描けません。)     </strong> **以降、【課題2】問1−1)の回答欄:** ``` ## QFT(0,3) の行列表現を表示してください。 qft3=QFT(0,3) represent(qft3,nqubits=3) # |000> を量子フーリエ変換してください。 qapply(qft3*Qubit('000')) # |001> を量子フーリエ変換してください。 qapply(qft3*Qubit('001')) # |010> を量子フーリエ変換してください。 qapply(qft3*Qubit('010')) # |011> を量子フーリエ変換してください。 qapply(qft3*Qubit('011')) # |100> を量子フーリエ変換してください。 qapply(qft3*Qubit('100')) # |101> を量子フーリエ変換してください。 qapply(qft3*Qubit('101')) # |110> を量子フーリエ変換してください。 qapply(qft3*Qubit('110')) # |111> を量子フーリエ変換してください。 qapply(qft3*Qubit('111')) ``` **以降、【課題2】問1−2)の回答欄:** ``` ### QFT(0,3) は、SymPy ではひと塊りのまとまったオペレータとして定義されています。 ### 基本ゲートを知るためには、decompose() を使います。 QFT(0,3).decompose() # QFT(0,3) の量子回路図を CircuitPlot() で作図してください。 CircuitPlot(QFT(0,3).decompose(), nqubits=3) # decompose() した上記の回路を改めて、定義しなおします。 qft3_decomp = SWAP(0,2)*H(0)*CGateS((0,),S(1))*H(1)*CGateS((0,),T(2))*CGateS((1,),S(2))*H(2) qft3_decomp # 上記で定義しなおした QFT の量子回路図を CircuitPlot() で作図します。 # QFT(0,3).decompose() の量子回路図と比較してください。 CircuitPlot(qft3_decomp,nqubits=3) ``` **以降、【課題2】問2−1)の解答欄:** (ヒント)$c_{g}$ をグローバル位相として、Z軸回転 $ R_{z\theta} = c_{g} X \cdot R_{z\theta/2}^{\dagger} \cdot X \cdot R_{z\theta/2} $ と表せることを使います。 ``` # S = c・X・T†・X・T であることを示します。 pprint(represent(S(0),nqubits=1)) represent(exp(I*pi/4)*X(0)*T(0)**(-1)*X(0)*T(0),nqubits=1) # T = c・X・sqrt(T)†・X・sqrt(T) であることを示します。 pprint(represent(T(0),nqubits=1)) represent(exp(I*pi/8)*X(0)*Rk(0,4)**(-1)*X(0)*Rk(0,4),nqubits=1) # qft3_decomp = SWAP(0,2)*H(0)*CGateS((0,),S(1))*H(1)*CGateS((0,),T(2))*CGateS((1,),S(2))*H(2) # qft3_decomp を見ながら、制御Sゲートを置き換えて、qft3_decomp2 へ代入します。 qft3_decomp2 = SWAP(0,2)*H(0)*CNOT(0,1)*T(1)**(-1)*CNOT(0,1)*T(1)*H(1)*CGateS((0,),T(2))*CNOT(1,2)*T(2)**(-1)*CNOT(1,2)*T(2)*H(2) qft3_decomp2 # qft3_decomp2 = SWAP(0,2)*H(0)*CNOT(0,1)*T(1)**(-1)*CNOT(0,1)*T(1)*H(1)*CGateS((0,),T(2))*CNOT(1,2)*T(2)**(-1)*CNOT(1,2)*T(2)*H(2) # qft3_decomp を見ながら、制御Tゲートを置き換えて、qft3_decomp3 へ代入します。 qft3_decomp3 = SWAP(0,2)*H(0)*CNOT(0,1)*T(1)**(-1)*CNOT(0,1)*T(1)*H(1)*CNOT(0,2)*Rk(2,4)**(-1)*CNOT(0,2)*Rk(2,4)*CNOT(1,2)*T(2)**(-1)*CNOT(1,2)*T(2)*H(2) qft3_decomp3 # |000> の量子フーリエ変換の結果をみます。 ### ゲート操作が少し複雑になるため、SymPyがうまく判断できません。 ### represent()で計算します。解答例では、結果が縦ベクトルで行数が長くなるのを嫌い、transpose()します。 # (解答例)transpose(represent(qft3_decomp2*Qubit('000'), nqubits=3)) transpose(represent(qft3_decomp2*Qubit('000'), nqubits=3)) # |001> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/4) をかけると同じになります。 exp(I*pi/4)*transpose(represent(qft3_decomp2*Qubit('001'), nqubits=3)) # |010> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/4) をかけると同じになります。 exp(I*pi/4)*transpose(represent(qft3_decomp2*Qubit('010'), nqubits=3)) # |011> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/2) をかけると同じになります。 exp(I*pi/2)*transpose(represent(qft3_decomp2*Qubit('011'), nqubits=3)) # |100> の量子フーリエ変換の結果をみます。 transpose(represent(qft3_decomp2*Qubit('100'), nqubits=3)) # |101> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/4) をかけると同じになります。 exp(I*pi/4)*transpose(represent(qft3_decomp2*Qubit('101'), nqubits=3)) # |110> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/4) をかけると同じになります。 exp(I*pi/4)*transpose(represent(qft3_decomp2*Qubit('110'), nqubits=3)) # |111> の量子フーリエ変換の結果をみます。 ### グローバル位相 exp(I*pi/2) をかけると同じになります。 exp(I*pi/2)*transpose(represent(qft3_decomp2*Qubit('111'), nqubits=3)) ```
github_jupyter
``` import numpy as np import torch import math import matplotlib import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import GPyOpt import GPy import os import matplotlib as mpl import matplotlib.tri as tri import ternary import pickle import datetime from collections import Counter import matplotlib.ticker as ticker import pyDOE import random from sklearn import preprocessing from scipy.stats import norm from sklearn.ensemble import RandomForestRegressor import matplotlib.font_manager as font_manager import copy from scipy.interpolate import splrep from scipy.interpolate import interp1d ``` # Load materials dataset ``` # go to directory where datasets reside # load a dataset # dataset names = ['Crossed barrel', 'Perovskite', 'AgNP', 'P3HT', 'AutoAM'] dataset_name = 'pool_bo_datasets/coe_opt' raw_dataset = pd.read_csv(dataset_name + '_dataset_with_outliers.csv') feature_name = list(raw_dataset.columns)[:-1] objective_name = list(raw_dataset.columns)[-1] ``` # Processing ``` ds = copy.deepcopy(raw_dataset) # only P3HT/CNT, Crossed barrel, AutoAM need this line; Perovskite and AgNP do not need this line. ds[objective_name] = -raw_dataset[objective_name].values ds_grouped = ds.groupby(feature_name)[objective_name].agg(lambda x: x.unique().mean()) ds_grouped = (ds_grouped.to_frame()).reset_index() # pool size # total number of data in set N = len(ds_grouped) print(N) nsteps = N # number of top candidates, currently using top 5% of total dataset size n_top = int(math.ceil(nsteps * 0.1)) print(n_top) # the top candidates and their indicies top_indices = list(ds_grouped.sort_values(objective_name).head(n_top).index) ``` # Load calculation results from framework ``` # Load ensemble calculation results from framework # for 50 ensembles, they take some time to run collection result = np.load('pool_bo_coe_rf_lcb2_top010_with_outliers.npy', allow_pickle = True) collection result = collection result[3] print(collection result) ``` # Random baseline ``` def P_rand(nn): x_random = np.arange(nn) M = n_top N = nn P = np.array([None for i in x_random]) E = np.array([None for i in x_random]) A = np.array([None for i in x_random]) cA = np.array([None for i in x_random]) P[0] = M / N E[0] = M / N A[0] = M / N cA[0] = A[0] for i in x_random[1:]: P[i] = (M - E[i-1]) / (N - i) E[i] = np.sum(P[:(i+1)]) j = 0 A_i = P[i] while j < i: A_i *= (1 - P[j]) j+=1 A[i] = A_i cA[i] = np.sum(A[:(i+1)]) return E / M, cA ``` # Aggregation of performance ``` seed_list = [5782, 5776, 9975, 4569, 8020, 363, 9656, 992, 348, 6048, 4114, 7476, 4892, 9710, 9854, 5243, 2906, 5963, 3035, 5122, 9758, 4327, 4921, 6179, 1718, 441, 9326, 2153, 5079, 8192, 3646, 4413, 3910, 5370, 3070, 7130, 1589, 1668, 9842, 5275, 5468, 3677, 7183, 2773, 1309, 5516, 3572, 9312, 7390, 4433, 3686, 1981, 555, 8677, 3126, 5163, 9418, 3007, 4564, 5572, 1401, 5657, 9658, 2124, 6902, 4783, 8493, 4442, 7613, 5674, 6830, 4757, 6877, 9311, 6709, 582, 6770, 2555, 3269, 76, 7820, 8358, 7116, 9156, 3638, 529, 7482, 8503, 4735, 8910, 5588, 3726, 1115, 9644, 4702, 1966, 4006, 738, 575, 8393] def aggregation_(seed, n_runs, n_fold): assert math.fmod(n_runs, n_fold) == 0 fold_size = int(n_runs / n_fold) random.seed(seed) index_runs = list(np.arange(n_runs)) agg_list = [] i = 0 while i < n_fold: index_i = random.sample(index_runs, fold_size) for j in index_i: index_runs.remove(j) agg_list.append(index_i) i += 1 # print(agg_list) return agg_list def avg_(x): # nsteps n_eval = len(x[0]) # fold n_fold = 5 # rows = # of ensembles = 50 n_runs = len(x) assert math.fmod(n_runs, n_fold) == 0 fold_size = int(n_runs / n_fold) # # of seeds n_sets = len(seed_list) l_index_list = [] for i in np.arange(n_sets): s = aggregation_(seed_list[i], n_runs, n_fold) l_index_list.extend(s) # rows in l_index_list assert len(l_index_list) == n_sets * n_fold l_avg_runs = [] for i in np.arange(len(l_index_list)): avg_run = np.zeros(n_eval) for j in l_index_list[i]: avg_run += np.array(x[j]) avg_run = avg_run/fold_size l_avg_runs.append(avg_run) assert n_eval == len(l_avg_runs[0]) assert n_sets * n_fold == len(l_avg_runs) mean_ = [None for i in np.arange(n_eval)] std_ = [None for i in np.arange(n_eval)] median_ = [None for i in np.arange(n_eval)] low_q = [None for i in np.arange(n_eval)] high_q = [None for i in np.arange(n_eval)] # 5th, 95th percentile, mean, median are all accessible for i in np.arange(len(l_avg_runs[0])): i_column = [] for j in np.arange(len(l_avg_runs)): i_column.append(l_avg_runs[j][i]) i_column = np.array(i_column) mean_[i] = np.mean(i_column) median_[i] = np.median(i_column) std_[i] = np.std(i_column) low_q[i] = np.quantile(i_column, 0.05, out=None, overwrite_input=False, interpolation='linear') high_q[i] = np.quantile(i_column, 0.95, out=None, overwrite_input=False, interpolation='linear') return np.array(median_), np.array(low_q), np.array(high_q), np.array(mean_), np.array(std_) ``` # Top% ``` def TopPercent(x_top_count, n_top, N): x_ = [[] for i in np.arange(len(x_top_count))] for i in np.arange(len(x_top_count)): for j in np.arange(N): if j < len(x_top_count[i]): x_[i].append(x_top_count[i][j] / n_top) else: x_[i].append(1) return x_ # Aggregating the performance TopPercent_result = avg_(TopPercent(collection result, n_top, N)) print(TopPercent_result) fig = plt.figure(figsize=(12,12)) ax0 = fig.add_subplot(111) ax0.plot(np.arange(N)+1, P_rand(N)[0],'--',color='black',label='random baseline', linewidth=3.5) ax0.plot(np.arange(N) + 1, np.round(TopPercent_result[0].astype(np.double) / 0.005, 0) * 0.005, label = 'RF', color = '#006d2c', linewidth=3) ax0.fill_between(np.arange(N) + 1, np.round(TopPercent_result[1].astype(np.double) / 0.005, 0) * 0.005, np.round(TopPercent_result[2].astype(np.double) / 0.005, 0) * 0.005, color = '#006d2c', alpha=0.2) # the rest are for visualization purposes, please adjust for different needs font = font_manager.FontProperties(family='Arial', size = 26, style='normal') leg = ax0.legend(prop = font, borderaxespad = 0, labelspacing = 0.3, handlelength = 1.2, handletextpad = 0.3, frameon=False, loc = (0, 0.81)) for line in leg.get_lines(): line.set_linewidth(4) ax0.set_ylabel("Top%", fontname="Arial", fontsize=30, rotation='vertical') plt.hlines(0.8, 0, 480, colors='k', linestyles='--', alpha = 0.2) ax0.set_xscale('log') ax0.set_xlabel('learning cycle $i$', fontsize=30, fontname = 'Arial') ax0.xaxis.set_tick_params(labelsize=30) ax0.yaxis.set_tick_params(labelsize=30) ax0.spines['right'].set_visible(False) ax0.spines['top'].set_visible(False) saveas = 'S_fig_BO' plt.savefig(saveas+'.pdf') plt.savefig(saveas+'.svg') plt.savefig(saveas+'.png', dpi=300) ```
github_jupyter
## Introduction to Pandas Pandas is a newer package built on top of NumPy, and provides an efficient implementation of a DataFrame . DataFrame s are essentially multidimen‐ sional arrays with attached row and column labels, and often with heterogeneous types and/or missing data. As well as offering a convenient storage interface for labeled data, Pandas implements a number of powerful data operations familiar to users of both database frameworks and spreadsheet programs. As we saw, NumPy’s ndarray data structure provides essential features for the type of clean, well-organized data typically seen in numerical computing tasks. While it serves this purpose very well, its limitations become clear when we need more flexi‐ bility (attaching labels to data, working with missing data, etc.) and when attempting operations that do not map well to element-wise broadcasting (groupings, pivots, etc.), each of which is an important piece of analyzing the less structured data avail‐ able in many forms in the world around us. Pandas, and in particular its Series and DataFrame objects, builds on the NumPy array structure and provides efficient access to these sorts of “data munging” tasks that occupy much of a data scientist’s time. ``` import pandas as pd pd.__version__ import numpy as np import pandas as pd ``` #### The Pandas Series Object A Pandas Series is a one-dimensional array of indexed data. ``` data = pd.Series([0.25, 0.5, 0.75, 1.0]) data ``` The Series wraps both a sequence of values and a sequence of indices, which we can access with the values and index attributes. ``` data.values data.index ``` Like with a NumPy array, data can be accessed by the associated index via the familiar Python square-bracket notation ``` data[1] data[1:3] ``` It may look like the Series object is basically inter‐ changeable with a one-dimensional NumPy array. The essential difference is the pres‐ ence of the index: while the NumPy array has an implicitly defined integer index used to access the values, the Pandas Series has an explicitly defined index associated with the values. This explicit index definition gives the Series object additional capabilities. For example, the index need not be an integer, but can consist of values of any desired type. ``` ## Syntax - pd.Series(data, index=index) data = pd.Series([0.25, 0.5, 0.75, 1.0],index=['a', 'b', 'c', 'd']) data data['b'] ``` Pandas Series a bit like a specialization of a Python dictionary. A dictionary is a structure that maps arbitrary keys to a set of arbitrary values, and a Series is a structure that maps typed keys to a set of typed values. This typing is important: just as the type-specific compiled code behind a NumPy array makes it more efficient than a Python list for certain operations, the type information of a Pandas Series makes it much more efficient than Python dictionaries for certain operations. We can make the Series as dictionary analogy even more clear by constructing a Series object directly from a Python dictionary ``` population_dict = {'California': 38332521, 'Texas': 26448193, 'New York': 19651127, 'Florida': 19552860, 'Illinois': 12882135} population = pd.Series(population_dict) population population['California'] ``` Unlike a dictionary, though, the Series also supports array-style operations such as slicing ``` population['California':'Illinois'] # population_dict['California':'Illinois'] ``` In constructing Series objects, data can be a list, NumPy array or dictionary. ``` pd.Series([2, 4, 6]) pd.Series(5, index=[100, 200, 300]) pd.Series(5) pd.Series({2:'a', 1:'b', 3:'c'}) pd.Series({2:'a', 1:'b', 3:'c'}, index=[3, 2]) ``` ### The Pandas DataFrame Object The next fundamental structure in Pandas is the DataFrame . The DataFrame can be thought of either as a generalization of a NumPy array, or as a specialization of a Python dictionary. #### DataFrame as a generalized NumPy array If a Series is an analog of a one-dimensional array with flexible indices, a DataFrame is an analog of a two-dimensional array with both flexible row indices and flexible column names. ``` area_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297, 'Florida': 170312, 'Illinois': 149995} area = pd.Series(area_dict) area states = pd.DataFrame({'population': population,'area': area}) states ``` Like the Series object, the DataFrame has an index attribute that gives access to the index labels ``` states.index ``` Additionally, the DataFrame has a columns attribute, which is an Index object holding the column labels ``` states.columns ``` Thus the DataFrame can be thought of as a generalization of a two-dimensional NumPy array, where both the rows and columns have a generalized index for access‐ ing the data. #### DataFrame as specialized dictionary A dictionary maps a key to a value, a DataFrame maps a column name to a Series of column data. ``` states['area'] ``` Notice the potential point of confusion here: in a two-dimensional NumPy array, data[0] will return the first row. For a DataFrame , data['col0'] will return the first column. Because of this, it is probably better to think about DataFrame s as generalized dictionaries rather than generalized arrays, though both ways of looking at the situa‐ tion can be useful. We can construct DataFrame objects in a variety of ways. Some of them are :- ##### From a single Series object A DataFrame is a collection of Series objects, and a single- column DataFrame can be constructed from a single Series ``` pd.DataFrame(population, columns=['population']) ``` ##### From a list of dict Any list of dictionaries can be made into a DataFrame . We’ll use a simple list comprehension to create some data ``` data = [{'a': i, 'b': 2 * i} for i in range(3)] print(data) pd.DataFrame(data) ``` Even if some keys in the dictionary are missing, Pandas will fill them in with NaN (i.e., “not a number”) values ``` pd.DataFrame([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}]) ``` ##### From a dictionary of Series objects ``` pd.DataFrame({'population': population,'area': area}) ``` ##### From a two-dimensional NumPy array Given a two-dimensional array of data, we can create a DataFrame with any specified column and index names. If omitted, an integer index will be used for each ``` pd.DataFrame(np.random.rand(3, 2),columns=['x', 'y'],index=['a', 'b', 'c']) ``` ##### From a NumPy structured array ``` A = np.zeros(3, dtype=[('A', 'i8'), ('B', 'f8')]) A pd.DataFrame(A) ``` ### The Pandas Index Object We have seen here that both the Series and DataFrame objects contain an explicit index that lets you reference and modify data. This Index object is an interesting structure in itself, and it can be thought of either as an immutable array (a mutable object can be changed after it is created, and an immutable object can’t.) or as an ordered set (technically a multiset, as Index objects may contain repeated values). ``` ind = pd.Index([2, 3, 5, 7, 11]) ind ``` The Index object in many ways operates like an array. For example, we can use stan‐ dard Python indexing notation to retrieve values or slices ``` ind[1] ind[::2] print(ind.size, ind.shape, ind.ndim, ind.dtype) ``` One difference between Index objects and NumPy arrays is that indices are immutable—that is, they cannot be modified via the normal means ``` # ind[1] = 0 ``` This immutability makes it safer to share indices between multiple DataFrame s and arrays, without the potential for side effects from inadvertent index modification. ### Data Selection in Series A Series object acts in many ways like a one- dimensional NumPy array, and in many ways like a standard Python dictionary. Like a dictionary, the Series object provides a mapping from a collection of keys to a collection of values ``` import pandas as pd data = pd.Series([0.25, 0.5, 0.75, 1.0], index=['a', 'b', 'c', 'd']) data data['b'] 'a' in data data.keys() list(data.items()) ``` Series objects can even be modified with a dictionary-like syntax. Just as you can extend a dictionary by assigning to a new key, you can extend a Series by assigning to a new index value ``` data['e'] = 1.25 data # slicing by explicit index data['a':'c'] # slicing by implicit integer index data[0:2] ``` Notice that when slicing with an explicit index (i.e., data['a':'c'] ), the final index is included in the slice, while when you’re slicing with an implicit index (i.e., data[0:2] ), the final index is excluded from the slice. ``` # masking data[(data > 0.3) & (data < 0.8)] # fancy indexing data[['a', 'e']] ``` These slicing and indexing conventions can be a source of confusion. For example, if your Series has an explicit integer index, an indexing operation such as data[1] will use the explicit indices, while a slicing operation like data[1:3] will use the implicit Python-style index. ``` data = pd.Series(['a', 'b', 'c'], index=[1, 3, 5]) data # explicit index when indexing data[1] # implicit index when slicing data[1:3] ``` Because of this potential confusion in the case of integer indexes, Pandas provides some special indexer attributes that explicitly expose certain indexing schemes. First, the loc attribute allows indexing and slicing that always references the explicit index ``` data.loc[1] data.loc[1:3] # try # data.loc[2] ``` The iloc attribute allows indexing and slicing that always references the implicit Python-style index ``` data.iloc[1] data.iloc[1:3] data.iloc[2] #try # data.iloc[5] ``` ### Data Selection in DataFrame A DataFrame acts in many ways like a two-dimensional or structured array, and in other ways like a dictionary of Series structures sharing the same index ##### DataFrame as a dictionary ``` area = pd.Series({'California': 423967, 'Texas': 695662,'New York': 141297, 'Florida': 170312,'Illinois': 149995}) pop = pd.Series({'California': 38332521, 'Texas': 26448193,'New York': 19651127, 'Florida': 19552860,'Illinois': 12882135}) data = pd.DataFrame({'area':area, 'pop':pop}) data data['area'] data.area data.area is data['area'] ``` Though this is a useful shorthand, keep in mind that it does not work for all cases! For example, if the column names are not strings, or if the column names conflict with methods of the DataFrame , this attribute-style access is not possible. For example, the DataFrame has a pop() method, so data.pop will point to this rather than the "pop" column ``` data.pop is data['pop'] data['pop'] data.pop ``` Like with the Series objects, this dictionary-style syntax can also be used to modify the object, in this case to add a new column ``` data['density'] = data['pop'] / data['area'] data ``` This shows a preview of the straightforward syntax of element-by-element arithmetic between Series objects ##### DataFrame as two-dimensional array ``` data.values ``` We can see this is familiar array-like. Hence we can do array like operatin on dataframe itself. For example, we can transpose the full DataFrame to swap rows and columns ``` data.T data.T.values[0] data['area'] ``` When it comes to indexing of DataFrame objects, however, it is clear that the dictionary-style indexing of columns precludes our ability to simply treat it as a NumPy array.Thus for array-style indexing, Pandas again uses the loc , iloc. Using the iloc indexer, we can index the underlying array as if it is a simple NumPy array (using the implicit Python-style index), but the DataFrame index and column labels are maintained in the result ``` data.iloc[:3, :2] # data data.loc[:'Illinois', :'pop'] ``` In the loc indexer we can combine masking and fancy indexing ``` data.loc[data.density > 100, ['pop', 'density']] ``` Any of these indexing conventions may also be used to set or modify values ``` data.iloc[0, 2] = 90 data ``` #### Ufuncs: Index Preservation Because Pandas is designed to work with NumPy, any NumPy ufunc will work on Pandas Series and DataFrame objects. ``` import pandas as pd import numpy as np rng = np.random.RandomState(42) ser = pd.Series(rng.randint(0, 10, 4)) ser df = pd.DataFrame(rng.randint(0, 10, (3, 4)), columns=['A', 'B', 'C', 'D']) df ``` If we apply a NumPy ufunc on either of these objects, the result will be another Pan‐ das object with the indices preserved ``` np.exp(ser) np.sin(df * np.pi / 4) ``` ##### Index alignment in Series ``` A = pd.Series([2, 4, 6], index=[0, 1, 2]) B = pd.Series([1, 3, 5], index=[1, 2, 3]) A + B ``` Any item for which one or the other does not have an entry is marked with NaN , or “Not a Number,” which is how Pandas marks missing data If using NaN values is not the desired behavior, modify the fill value using appropriate object methods in place of the operators ``` A.add(B, fill_value=0) ``` ##### Index alignment in DataFrame A similar type of alignment takes place for both columns and indices when you are performing operations on DataFrame ``` A = pd.DataFrame(rng.randint(0, 20, (2, 2)),columns=list('AB')) A list("AB") B = pd.DataFrame(rng.randint(0, 10, (3, 3)),columns=list('BAC')) B A + B ``` Notice that indices are aligned correctly irrespective of their order in the two objects, and indices in the result are sorted. ``` fill = A.stack().mean() print(fill) A.add(B, fill_value=fill) A.stack() A.stack() #try A.shape A.ndim A.stack().shape # A.stack().ndim # A.stack().mean() ``` Operations between a DataFrame and a Series are similar to operations between a two-dimensional and one-dimensional NumPy array. ``` A = rng.randint(10, size=(3, 4)) A A[0] A - A[0] ``` According to NumPy’s broadcasting rules subtraction between a two-dimensional array and one of its rows is applied row-wise. In Pandas, the convention similarly operates row-wise by default ``` df = pd.DataFrame(A, columns=list('QRST')) df df - df.iloc[0] df.subtract(df['R'], axis=0) df.loc[0] df.subtract(df.loc[0],axis = 1) halfrow = df.iloc[0, ::2] halfrow df - halfrow ``` This preservation and alignment of indices and columns means that operations on data in Pandas will always maintain the data context, which prevents the types of silly errors that might come up when you are working with heterogeneous and/or mis‐ aligned data in raw NumPy arrays. ### Handling Missing Data The difference between data found in many tutorials and data in the real world is that real-world data is rarely clean and homogeneous. In particular, many interesting datasets will have some amount of data missing. To make matters even more complicated, different data sources may indicate missing data in different ways. Pandas uses the special floating- point NaN value, and the Python None objects for missing data None is a Python object, hence it cannot be used in any arbitrary NumPy/Pandas array, but only in arrays with data type 'object' ``` import numpy as np import pandas as pd vals1 = np.array([1, None, 3, 4]) vals1 ``` This dtype=object means that the best common type representation NumPy could infer for the contents of the array is that they are Python objects. The other missing data representation, NaN (acronym for Not a Number), is different; it is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation ``` vals2 = np.array([1, np.nan, 3, 4]) vals2.dtype 1 + np.nan 0 * np.nan vals2.sum(), vals2.min(), vals2.max() np.nansum(vals2), np.nanmin(vals2), np.nanmax(vals2) ``` Keep in mind that NaN is specifically a floating-point value; there is no equivalent NaN value for integers, strings, or other types. ##### NaN and None in Pandas ``` pd.Series([1, np.nan, 2, None]) ``` NaN and None both have their place, and Pandas is built to handle the two of them nearly interchangeably, converting between them where appropriate. If we set a value in an integer array to np.nan , Pandas will automatically be upcast to a floating-point type to accommodate the NA ``` x = pd.Series(range(2), dtype=int) x x[0] = None x ``` Notice that in addition to casting the integer array to floating point, Pandas automati‐ cally converts the None to a NaN value #### Operating on Null Values Pandas treats None and NaN as essentially interchangeable for indi‐ cating missing or null values. To facilitate this convention, there are several useful methods for detecting, removing, and replacing null values in Pandas data structures. Pandas data structures have two useful methods for detecting null data: isnull() and notnull() . Either one will return a Boolean mask over the data. ``` data = pd.Series([1, np.nan, 'hello', None]) data.isnull() data[data.notnull()] data.notnull() ``` The isnull() and notnull() methods produce similar Boolean results for Data Frames. ##### Dropping null values In addition to the masking used before, there are the convenience methods, dropna() (which removes NA values) and fillna() (which fills in NA values). For a Series , the result is straightforward ``` data.dropna() ``` For a DataFrame , there are more options. Consider the following DataFrame ``` df = pd.DataFrame([[1,np.nan, 2],[2,3,5],[np.nan, 4,6]]) df ``` We cannot drop single values from a DataFrame ; we can only drop full rows or full columns. Depending on the application, you might want one or the other, so dropna() gives a number of options for a DataFrame . By default, dropna() will drop all rows in which any null value is present ``` df.dropna() ``` Alternatively, you can drop NA values along a different axis; axis=1 drops all col‐ umns containing a null value ``` df.dropna(axis='columns') ``` But this drops some good data as well; you might rather be interested in dropping rows or columns with all NA values, or a majority of NA values. This can be specified through the how or thresh parameters, which allow fine control of the number of nulls to allow through. The default is how='any' , such that any row or column (depending on the axis key‐ word) containing a null value will be dropped. You can also specify how='all' , which will only drop rows/columns that are all null values: ``` df[3] = np.nan df df.dropna(axis='columns', how='all') ``` For finer-grained control, the thresh parameter lets you specify a minimum number of non-null values for the row/column to be kept ``` df.dropna(axis='rows', thresh=2) ``` Here the first and last row have been dropped, because they contain only two non- null values. ##### Filling null values Sometimes rather than dropping NA values, you’d rather replace them with a valid value. ``` data = pd.Series([1, np.nan, 2, None, 3], index=list('abcde')) data data.fillna(0) # forward-fill data.fillna(method='ffill') # back-fill data.fillna(method='bfill') ``` For DataFrames, the options are similar, but we can also specify an axis along which the fills take place ``` df = pd.DataFrame([[1,np.nan, 2],[2,3,5],[np.nan, 4,6]]) df df.fillna(method='ffill', axis=1) df.fillna(method='ffill', axis=0) ``` ### Hierarchical Indexing It is useful to go beyond 1D and 2D array and store higher-dimensional data—that is, data indexed by more than one or two keys. ``` import pandas as pd import numpy as np index = [('California', 2000), ('California', 2010),('New York', 2000), ('New York', 2010),('Texas', 2000), ('Texas', 2010)] index = pd.MultiIndex.from_tuples(index) index populations = [33871648, 37253956,18976457, 19378102,20851820, 25145561] pop = pd.Series(populations, index=index) pop pop[:, 2010] ``` The unstack() method will quickly convert a multiply- indexed Series into a conventionally indexed DataFrame ``` pop_df = pop.unstack() pop_df pop_df.stack() pop_df = pd.DataFrame({'total': pop,'under18': [9267089, 9284094,4687374, 4318033,5906301, 6879014]}) pop_df f_u18 = pop_df['under18'] / pop_df['total'] f_u18.unstack() # print(type(f_u18)) # f_u18.stack() ``` This allows us to easily and quickly manipulate and explore even high-dimensional data. The most straightforward way to construct a multiply indexed Series or DataFrame is to simply pass a list of two or more index arrays to the constructor. ``` df = pd.DataFrame(np.random.rand(4, 2),index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],columns=['data1', 'data2']) df ``` Similarly, if you pass a dictionary with appropriate tuples as keys, Pandas will auto‐ matically recognize this and use a MultiIndex by default ``` data = {('California', 2000): 33871648, ('California', 2010): 37253956, ('Texas', 2000): 20851820, ('Texas', 2010): 25145561, ('New York', 2000): 18976457, ('New York', 2010): 19378102} pd.Series(data) ``` For more flexibility in how the index is constructed, you can instead use the class method constructors available in the pd.MultiIndex . ``` pd.MultiIndex.from_arrays([['a', 'a', 'b', 'b'], [1, 2, 1, 2]]) pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2)]) pd.MultiIndex.from_product([['a', 'b'], [1, 2]]) pd.MultiIndex(levels=[['a', 'b'], [1, 2]],labels=[[0, 0, 1, 1], [0, 1, 0, 1]]) pop.index.names = ['state', 'year'] pop ``` In a DataFrame , the rows and columns are completely symmetric, and just as the rows can have multiple levels of indices, the columns can have multiple levels as well. ``` # hierarchical indices and columns index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],names=['year', 'visit']) columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']], names=['subject', 'type']) index columns # mock some data data = np.round(np.random.randn(4, 6), 1) print(data) data[:, ::2] *= 10 data data += 37 data # create the DataFrame health_data = pd.DataFrame(data, index=index, columns=columns) health_data ``` This is fundamentally four-dimensional data, where the dimensions are the subject, the measurement type, the year, and the visit number. With this in place we can, for example, index the top-level column by the person’s name and get a full Data Frame containing just that person’s information ``` health_data['Guido'] ``` For complicated records containing multiple labeled measurements across multiple times for many subjects (people, countries, cities, etc.), use of hierarchical rows and columns can be extremely convenient! ##### Indexing and Slicing a MultiIndex Consider the multiply indexed Series of state populations ``` pop pop['California', 2000] pop['California'] pop.loc['California':'New York'] pop[:, 2000] pop[pop > 22000000] pop[['California', 'Texas']] ``` A multiply indexed DataFrame behaves in a similar manner. ``` health_data health_data['Guido', 'HR'] health_data.iloc[:2, :2] health_data.loc[:, ('Bob', 'HR')] ``` ##### Rearranging Multi-Indices One of the keys to working with multiply indexed data is knowing how to effectively transform the data. There are a number of operations that will preserve all the infor‐ mation in the dataset, but rearrange it for the purposes of various computations. ``` index = pd.MultiIndex.from_product([['a', 'c', 'b'], [1, 2]]) data = pd.Series(np.random.rand(6), index=index) data.index.names = ['char', 'int'] data index data = data.sort_index() data pop.unstack(level=0) pop.unstack(level=1) pop.unstack().stack() ``` Another way to rearrange hierarchical data is to turn the index labels into columns; this can be accomplished with the reset_index method ``` pop_flat = pop.reset_index(name='population') pop_flat pop_flat.set_index(['state', 'year']) ``` ##### Data Aggregations on Multi-Indices ``` health_data #to average out the measurements in the two visits each year data_mean = health_data.mean(level='year') data_mean data_mean.mean(axis=1, level='type') ``` ### Combining Datasets: Concat and Append Some of the most interesting studies of data come from combining different data sources. These operations can involve anything from very straightforward concatena‐ tion of two different datasets, to more complicated database-style joins and merges that correctly handle any overlaps between the datasets. Series and DataFrame s are built with this type of operation in mind, and Pandas includes functions and methods that make this sort of data wrangling fast and straightforward. ``` import pandas as pd import numpy as np def make_df(cols, ind): """Quickly make a DataFrame""" data = {c: [str(c) + str(i) for i in ind]for c in cols} return pd.DataFrame(data, ind) # example DataFrame make_df('ABC', range(3)) ``` Concatenation of Series and DataFrame objects is very similar to concatenation of NumPy arrays ``` x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] np.concatenate([x, y, z]) x = [[1, 2], [3, 4]] np.concatenate([x, x], axis=1) ``` Pandas has a function, pd.concat() , which has a similar syntax to np.concatenate but contains a number of options ``` # Signature in Pandas v0.18 # pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, # keys=None, levels=None, names=None, verify_integrity=False, # copy=True) ``` pd.concat() can be used for a simple concatenation of Series or DataFrame objects, just as np.concatenate() can be used for simple concatenations of arrays ``` ser1 = pd.Series(['A', 'B', 'C'], index=[1, 3, 4]) ser2 = pd.Series(['D', 'E', 'F'], index=[2, 5, 6]) pd.concat([ser1, ser2]) df1 = make_df('AB', [1, 2]) df2 = make_df('AB', [3, 4]) print(df1) print("\n") print(df2) print("\n") print(pd.concat([df1, df2])) ``` One important difference between np.concatenate and pd.concat is that Pandas concatenation preserves indices, even if the result will have duplicate indices! ``` x = make_df('AB', [0, 1]) y = make_df('AB', [2, 3]) x y y.index = x.index # make duplicate indices! print(pd.concat([x, y])) ``` Notice the repeated indices in the result. While this is valid within DataFrame s, the outcome is often undesirable. pd.concat() gives us a few ways to handle it.If you’d like to simply verify that the indices in the result of pd.concat() do not overlap, you can specify the verify_integrity flag. With this set to True , the concatenation will raise an exception if there are duplicate indices. ``` try: pd.concat([x, y], verify_integrity=True) except ValueError as e: print("ValueError:", e) ``` Sometimes the index itself does not matter, and you would prefer it to simply be ignored. You can specify this option using the ignore_index flag. ``` print(pd.concat([x, y], ignore_index=True)) ``` Another alternative is to use the keys option to specify a label for the data sources; the result will be a hierarchically indexed series containing the data ``` print(pd.concat([x, y], keys=['x', 'y'])) df5 = make_df('ABC', [1, 2]) df6 = make_df('BCD', [3, 4]) print(df5) print("\n") print(df6) print("\n") print(pd.concat([df5, df6],sort = True)) ``` By default, the entries for which no data is available are filled with NA values. To change this, we can specify one of several options for the join and join_axes param‐ eters of the concatenate function. By default, the join is a union of the input columns ( join='outer' ), but we can change this to an intersection of the columns using join='inner' ``` print(pd.concat([df5, df6], join='inner')) ``` Because direct array concatenation is so common, Series and DataFrame objects have an append method that can accomplish the same thing in fewer keystrokes.Rather than calling pd.concat([df1, df2]) , you can simply call df1.append(df2) ``` print(df1.append(df2)) ``` Keep in mind that unlike the append() and extend() methods of Python lists, the append() method in Pandas does not modify the original object—instead, it creates a new object with the combined data. It also is not a very efficient method, because it involves creation of a new index and data buffer. Thus, if you plan to do multiple append operations, it is generally better to build a list of DataFrame s and pass them all at once to the concat() function. #### Merge and Join One essential feature offered by Pandas is its high-performance, in-memory join and merge operations.The pd.merge() function implements a number of types of joins: the one-to-one, many-to-one, and many-to-many joins. All three types of joins are accessed via an identical call to the pd.merge() interface; the type of join performed depends on the form of the input data. ##### One-to-one joins Perhaps the simplest type of merge expression is the one-to-one join, which is in many ways very similar to the column-wise concatenation ``` df1 = pd.DataFrame({'employee': ['Bob', 'Jake', 'Lisa', 'Sue'],'group': ['Accounting', 'Engineering', 'Engineering', 'HR']}) df2 = pd.DataFrame({'employee': ['Lisa', 'Bob', 'Jake', 'Sue'],'hire_date': [2004, 2008, 2012, 2014]}) df1 df2 df3 = pd.merge(df1, df2) df3 ``` The pd.merge() function recognizes that each DataFrame has an “employee” column, and automatically joins using this column as a key. The result of the merge is a new DataFrame that combines the information from the two inputs. Notice that the order of entries in each column is not necessarily maintained: in this case, the order of the “employee” column differs between df1 and df2 , and the pd.merge() function cor‐ rectly accounts for this. Additionally, keep in mind that the merge in general discards the index, except in the special case of merges by index ##### Many-to-one joins Many-to-one joins are joins in which one of the two key columns contains duplicate entries. For the many-to-one case, the resulting DataFrame will preserve those dupli‐ cate entries as appropriate. ``` df4 = pd.DataFrame({'group': ['Accounting', 'Engineering', 'HR'],'supervisor': ['Carly', 'Guido', 'Steve']}) print(df4) print(pd.merge(df3, df4)) ``` The resulting DataFrame has an additional column with the “supervisor” information, where the information is repeated in one or more locations as required by the inputs. ##### Many-to-many joins Many-to-many joins are a bit confusing conceptually, but are nevertheless well defined. If the key column in both the left and right array contains duplicates, then the result is a many-to-many merge. ``` df5 = pd.DataFrame({'group': ['Accounting', 'Accounting','Engineering', 'Engineering', 'HR', 'HR'],'skills': ['math', 'spreadsheets', 'coding', 'linux','spreadsheets', 'organization']}) print(df1) print(df5) print(pd.merge(df1, df5)) ``` These three types of joins can be used with other Pandas tools to implement a wide array of functionality. ##### Specification of the Merge Key Most simply, you can explicitly specify the name of the key column using the on key‐ word, which takes a column name or a list of column names: ``` print(df1) print(df2) print(pd.merge(df1, df2, on='employee')) ``` This option works only if both the left and right DataFrame s have the specified col‐ umn name. At times you may wish to merge two datasets with different column names; for exam‐ ple, we may have a dataset in which the employee name is labeled as “name” rather than “employee”. In this case, we can use the left_on and right_on keywords to specify the two column names: ``` df3 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],'salary': [70000, 80000, 120000, 90000]}) print(df3) print(df1) pd.merge(df1, df3, left_on="employee", right_on="name") ``` The result has a redundant column that we can drop if desired—for example, by using the drop() method of DataFrame s ``` pd.merge(df1, df3, left_on="employee", right_on="name").drop('name', axis=1) ``` Sometimes, rather than merging on a column, you would instead like to merge on an index. ``` df1a = df1.set_index('employee') df1a df2a = df2.set_index('employee') df2a ``` the index as the key for merging by specifying the left_index and/or right_index flags in pd.merge() ``` pd.merge(df1a, df2a, left_index=True, right_index=True) ``` For convenience, DataFrame s implement the join() method, which performs a merge that defaults to joining on indices ``` df1a.join(df2a) pd.merge(df1a, df3, left_index=True, right_on='name') df6 = pd.DataFrame({'name': ['Peter', 'Paul', 'Mary'],'food': ['pizza', 'burger', 'sandwich']},columns=['name', 'food']) df7 = pd.DataFrame({'name': ['Mary', 'Joseph'],'drink': ['coke', 'pepsi']},columns=['name', 'drink']) df6 df7 pd.merge(df6, df7) pd.merge(df6, df7, how='inner') pd.merge(df6, df7, how='outer') pd.merge(df6, df7, how='left') pd.merge(df6, df7, how='right') ``` Finally, you may end up in a case where your two input DataFrame s have conflicting column names ``` df8 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],'rank': [1, 2, 3, 4]}) df9 = pd.DataFrame({'name': ['Bob', 'Jake', 'Lisa', 'Sue'],'rank': [3, 1, 4, 2]}) pd.merge(df8, df9, on="name") pd.merge(df8, df9, on="name", suffixes=["_L", "_R"]) # read data from csv pop = pd.read_csv('state-population.cs.v') areas = pd.read_csv('state-areas.csv') abbrevs = pd.read_csv('state-abbrevs.csv') ``` ### Aggregation and Grouping An essential piece of analysis of large data is efficient summarization: computing aggregations like sum() , mean() , median() , min() , and max() , in which a single num‐ ber gives insight into the nature of a potentially large dataset. ``` df = pd.DataFrame({'A': rng.rand(5),'B': rng.rand(5)}) df df.mean() df.mean(axis='columns') import seaborn as sns planets = sns.load_dataset('planets') planets.shape planets.head() planets.dropna().describe() ``` This can be a useful way to begin understanding the overall properties of a dataset. ### GroupBy: Split, Apply, Combine Simple aggregations can give you a flavor of your dataset, but often we would prefer to aggregate conditionally on some label or index: this is implemented in the so- called groupby operation. • The split step involves breaking up and grouping a DataFrame depending on the value of the specified key. • The apply step involves computing some function, usually an aggregate, transfor‐ mation, or filtering, within the individual groups. • The combine step merges the results of these operations into an output array. ``` df = pd.DataFrame({'key': ['A', 'B', 'C', 'A', 'B', 'C'],'data': range(6)}, columns=['key', 'data']) df df.groupby('key') ``` Notice that what is returned is not a set of DataFrame s, but a DataFrameGroupBy object. This object is where the magic is: you can think of it as a special view of the DataFrame , which is poised to dig into the groups but does no actual computation until the aggregation is applied. This “lazy evaluation” approach means that common aggregates can be implemented very efficiently in a way that is almost transparent to the user. To produce a result, we can apply an aggregate to this DataFrameGroupBy object, which will perform the appropriate apply/combine steps to produce the desired result ``` df.groupby('key').sum() planets.groupby('method')['orbital_period'].median() planets["method"].value_counts() planets.columns planets.groupby('method')['year'].describe() rng = np.random.RandomState(0) df = pd.DataFrame({'key': ['A', 'B', 'C', 'A', 'B', 'C'],'data1': range(6),'data2': rng.randint(0, 10, 6)},columns = ['key', 'data1', 'data2']) df ``` The aggregate() method allows for even more flexibility, it can take a string, a function, or a list thereof, and compute all the aggregates at once. ``` df.groupby('key').aggregate(['min', np.median, max]) df.groupby('key').aggregate({'data1': 'min','data2': 'max'}) ``` Filtering. A filtering operation allows you to drop data based on the group properties. ``` def filter_func(x): return x['data2'].std() > 4 print(df.groupby('key')) print(df.groupby('key').std()) print(df.groupby('key').filter(filter_func)) filter_func(df) filter_func(df.groupby('key')) ``` Transformation. While aggregation must return a reduced version of the data, trans‐ formation can return some transformed version of the full data to recombine. For such a transformation, the output is the same shape as the input. ``` df.groupby('key').transform(lambda x: x - x.mean()) ``` The apply() method. The apply() method lets you apply an arbitrary function to the group results. The function should take a DataFrame , and return either a Pandas object (e.g., DataFrame , Series ) or a scalar; the combine operation will be tailored to the type of output returned. ``` def norm_by_data2(x): # x is a DataFrame of group values x['data1'] /= x['data2'].sum() return x print(df) print(df.groupby('key').apply(norm_by_data2)) ``` ### Pivot Tables The GroupBy abstraction lets us explore relationships within a data‐ set. A pivot table is a similar operation that is commonly seen in spreadsheets and other programs that operate on tabular data. The pivot table takes simple column- wise data as input, and groups the entries into a two-dimensional table that provides a multidimensional summarization of the data. ``` import numpy as np import pandas as pd import seaborn as sns titanic = sns.load_dataset('titanic') titanic.head() titanic.groupby('sex')[['survived']].mean() ``` This is useful, but we might like to go one step deeper and look at survival by both sex and, say, class. ``` titanic.groupby(['sex', 'class'])['survived'].aggregate('mean').unstack() ``` This gives us a better idea of how both gender and class affected survival, but the code is starting to look a bit garbled. ``` titanic.pivot_table('survived', index='sex', columns='class') # DataFrame.pivot_table(data, values=None, index=None, columns=None, # aggfunc='mean', fill_value=None, margins=False, # dropna=True, margins_name='All') ``` At times it’s useful to compute totals along each grouping. ``` titanic.pivot_table('survived', index='sex', columns='class', margins=True) ``` ### Working with Time Series ``` from datetime import datetime datetime(year=2015, month=7, day=4) from dateutil import parser date = parser.parse("4th of July, 2015") date import numpy as np date = np.array('2015-07-04', dtype=np.datetime64) date date + np.arange(12) ``` Pandas can construct a DatetimeIndex that can be used to index data in a Series or DataFrame ``` import pandas as pd date = pd.to_datetime("4th of July, 2015") date date + pd.to_timedelta(np.arange(12), 'D') index = pd.DatetimeIndex(['2014-07-04', '2014-08-04','2015-07-04', '2015-08-04']) data = pd.Series([0, 1, 2, 3], index=index) data data['2014-07-04':'2015-07-04'] data['2015'] dates = pd.to_datetime([datetime(2015, 7, 3), '4th of July, 2015','2015-Jul-6', '07-07-2015', '20150708']) dates pd.date_range('2015-07-03', '2015-07-10') pd.date_range('2015-07-03', periods=8) pd.date_range('2015-07-03', periods=8, freq='H') ```
github_jupyter
# Project 2: Continuous Control ### Test 2 - PPO model <sub>Uirá Caiado. October 15, 2018<sub> #### Abstract _In this notebook, I will use the Unity ML-Agents environment to train a PPO model for the second project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893)._ ## 1. What we are going to test We begin by checking if the necessary packages are presented. If the code cell below returns an error, please check if you have all the packages required in the README of this project. ``` %load_ext version_information %version_information numpy, unityagents, torch, matplotlib, pandas, statsmodels ``` Now, let's define some meta variables to use in this notebook ``` import os fig_prefix = 'figures/2018-10-14-' data_prefix = '../data/2018-10-14-' s_currentpath = os.getcwd() ``` Finally, let's import some of the necessary packages for this experiment. ``` import sys import os import eda sys.path.append("../") # include the root directory as the main import pandas as pd import numpy as np ``` ## 2. Exploring the Environment The environment used for this project is the Reacher environment, from [Unity](https://youtu.be/heVMs3t9qSk). Bellow, we are going to start this environment. ``` from drlnd import make, PPO, PPO_PARAMS env = make() ``` Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the brain we will be controlling from Python. ``` # get the default brain env.brain_name brain = env.brain ``` In this environment, a double-jointed arm can move to target locations. A reward of `+0.1` is provided for each step that the agent's hand is in the goal location. Thus, the goal of your agent is to maintain its position at the target location for as many time steps as possible. The observation space consists of `33` variables corresponding to position, rotation, velocity, and angular velocities of the arm. Each action is a vector with four numbers, corresponding to torque applicable to two joints. Every entry in the action vector must be a number between `-1` and `1`. Let's check some information about the environment below. ``` # reset the environment states = env.reset() # number of agents print('Number of agents:', env.num_agents) # size of each action print('Size of each action:', env.action_size) # examine the state space state_size = states.shape[1] print('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size)) print('The state for the first agent looks like:', states[0]) ``` ## 3. Training the Agent Let's use the Python API to control the agent and receive feedback from the environment.The idea is to make the agent use its experience to gradually choose better actions when interacting with the environment. First, lest's check the agent's parameters. ``` print(PPO_PARAMS) ``` Now, we are going to train the agent for 1000 episodes or until it reaches an average score of 30 over the last 100 episodes and over the 20 agents. ``` from collections import deque import pickle import torch from drlnd import Trajectory episodes = 4000 rand_seed = 0 scores = [] scores_std = [] scores_avg = [] scores_window = deque(maxlen=100) agent = PPO(env.state_size, env.action_size, env.num_agents, rand_seed) %%time from collections import deque import pickle import torch from drlnd import Trajectory episodes = 4000 rand_seed = 0 scores = [] scores_std = [] scores_avg = [] scores_window = deque(maxlen=100) agent = PPO(env.state_size, env.action_size, env.num_agents, rand_seed) SOLVED = False print('\nNN ARCHITECURES:') print(agent.policy.actor_body) print(agent.policy.critic_body) print('\nTRAINING:') na = np.array([x.data for x in PPO_PARAMS]).flatten() d_params = dict([(na[y].strip(), float(na[y+1]))for y in range(0, len(na), 2)]) eps = d_params['EPSILON'] beta = d_params['BETA'] for episode in range(episodes): states = env.reset() trject = Trajectory() for i in range(1000): actions, log_probs, values = agent.act(states) # pdb.set_trace() next_states, rewards, dones = env.step(actions) trject.add(states, rewards, log_probs, actions, values, dones) states = next_states if np.any(dones): break agent.step(trject, eps, beta) eps *= 0.999 beta *= 0.995 scores.append(trject.score) scores_window.append(trject.score) scores_avg.append(np.mean(scores_window)) scores_std.append(np.std(scores_window)) s_msg = '\rEpisode {}\tAverage Score: {:.2f}\tσ: {:.2f}\tScore: {:.2f}' print(s_msg.format(episode, np.mean(scores_window), np.std(scores_window), trject.score), end="") if episode % 10 == 0: print(s_msg.format(episode, np.mean(scores_window), np.std(scores_window), trject.score)) if np.mean(scores_window) >= 30.: SOLVED = True s_msg = '\n\nEnvironment solved in {:d} episodes!\tAverage ' s_msg += 'Score: {:.2f}\tσ: {:.2f}' print(s_msg.format(episode, np.mean(scores_window), np.std(scores_window))) # save the models s_aux = '%scheckpoint-%s.%s.pth' s_policy_path = s_aux % (data_prefix, agent.__name__, 'policy') torch.save(agent.policy.state_dict(), s_policy_path) break # save data to use later if not SOLVED: s_msg = '\n\nEnvironment not solved =/' print(s_msg.format(episode, np.mean(scores_window), np.std(scores_window))) print('\n') d_data = {'episodes': episode, 'scores': scores, 'scores_std': scores_std, 'scores_avg': scores_avg, 'scores_window': scores_window} pickle.dump(d_data, open('%ssim-data-%s.data' % (data_prefix, agent.__name__), 'wb')) ``` ## 4. Results The agent using the PPO agent was able to solve the Reacher environment in 309 episodes of 1000 steps, each. ``` import pickle d_data = pickle.load(open('%ssim-data-%s.data' % (data_prefix, agent.__name__), 'rb')) s_msg = 'Environment solved in {:d} episodes!\tAverage Score: {:.2f} +- {:.2f}' print(s_msg.format(d_data['episodes'], np.mean(d_data['scores_window']), np.std(d_data['scores_window']))) ``` Now, let's plot the rewards per episode. In the right panel, we will plot the rolling average score over 100 episodes $\pm$ its standard deviation, as well as the goal of this project (30+ on average over the last 100 episodes). ``` import matplotlib.pyplot as plt import seaborn as sns import numpy as np %matplotlib inline #recover data na_raw = np.array(d_data['scores']) na_mu = np.array(d_data['scores_avg']) na_sigma = np.array(d_data['scores_std']) # plot the scores f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True) # plot the sores by episode ax1.plot(np.arange(len(na_raw)), na_raw) ax1.set_xlim(0, len(na_raw)+1) ax1.set_ylabel('Score') ax1.set_xlabel('Episode #') ax1.set_title('raw scores') # plot the average of these scores # ax2.axhline(y=30., xmin=0.0, xmax=1.0, color='r', linestyle='--', linewidth=0.7, alpha=0.9) ax2.plot(np.arange(len(na_mu)), na_mu) ax2.fill_between(np.arange(len(na_mu)), na_mu+na_sigma, na_mu-na_sigma, facecolor='gray', alpha=0.1) ax2.set_ylabel('Average Score') ax2.set_xlabel('Episode #') ax2.set_title('learning curve') f.tight_layout() f.savefig(fig_prefix + '%s-learning-curve.jpg' % agent.__name__, format='jpg') env.close() ``` ## 5. Conclusion The PPO agent was not able to solve the environment.
github_jupyter
# The Laplace Transform *This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Communications Engineering, Universität Rostock. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Inverse Transform So far only the [(forward) Laplace transform](definition.ipynb) has been introduced. The Laplace transform features also an [inverse transform](https://en.wikipedia.org/wiki/Inverse_Laplace_transform). The inverse Laplace transform maps a complex-valued Laplace transform $X(s) \in \mathbb{C}$ with complex-valued independent variable $s \in \mathbb{C}$ into the complex-valued signal $x(t) \in \mathbb{C}$ with real-valued independent variable $t \in \mathbb{R}$. It can be shown that the inverse Laplace transform $x(t) = \mathcal{L}^{-1} \{ X(s) \}$ is uniquely determined for most practically relevant signals. This section discusses two different techniques for the computation of the inverse Laplace transform. ### Integral Formula Using results from complex analysis, the inverse Laplace transform is given by the following complex line integral \begin{equation} x(t) = \frac{1}{2 \pi j} \int_{\sigma - j \infty}^{\sigma + j \infty} X(s) \, e^{s t} \; ds \end{equation} where $X(s) = \mathcal{L} \{ x(t) \}$ is assumed to be analytic in its simply connected region of convergence (ROC). The notation $\sigma \mp j \infty$ for the lower/upper integration limit denotes an arbitrary integration path which lies in the ROC and ranges from $\Im \{s\} = - \infty$ to $\Im \{s\} = + \infty$. The integration path can be chosen parallel to the imaginary axis but also all other paths in the ROC are possible. This results from [Cauchy's integral theorem](https://en.wikipedia.org/wiki/Cauchy's_integral_theorem). Two equivalent paths are shown in the following illustration ![Possible integration paths for the inverse Laplace transform](integration_paths.png) where the blue line indicates the integration path and the gray area the ROC. ### Rational Laplace Transforms Computing the inverse Laplace transform by above integral formula can be challenging. The [Cauchy residue theorem](https://en.wikipedia.org/wiki/Residue_theorem) provides a practically tractable solution for Laplace transforms $X(s) = \mathcal{L} \{ x(t) \}$ which are given as rational functions. It states that the value of a line integral of an holomorphic function over a closed contour is given by summing up its [residues](https://en.wikipedia.org/wiki/Residue_theorem). The residue is the value of the line integral for a path enclosing a singularity. Consequently, the inverse Laplace transform of a rational Laplace transform can be computed by summing up the individual contributions from its poles. This procedure is detailed in the following. #### Basic Procedure A rational Laplace transform $X(s)$ can be written in terms of its numerator and denominator polynomial \begin{equation} X(s) = \frac{\sum_{m=0}^{M} \beta_m s^m}{\sum_{n=0}^{N} \alpha_n s^n} \end{equation} where $M$, $N$ denote the order of the numerator and denominator polynomial and $\beta_m$, $\alpha_n$ their coefficients, respectively. It is assumed that $\alpha_N \neq 0$ and that $M \leq N$. If $M > N$, $X(s)$ can be decomposed by [polynomial division](https://en.wikipedia.org/wiki/Polynomial_long_division) into a sum of powers of $s$ and a rational function fulfilling $M \leq N$. Now a [partial fraction decomposition](https://en.wikipedia.org/wiki/Partial_fraction_decomposition) of $X(s)$ is performed resulting in \begin{equation} X(s) = A_0 + \sum_{\mu = 1}^{L} \sum_{\nu = 1}^{R_\mu} \frac{A_{\mu \nu}}{(s - s_{\infty \mu})^\nu} \end{equation} where $s_{\infty \mu}$ denotes the $\mu$-th unique pole of $X(s)$, $R_\mu$ its degree and $L$ the total number of different poles $\mu = 1 \dots L$. Using the known Laplace transforms (cf. [example for the modulation theorem](theorems.ipynb#Modulation-Theorem) or [table of selected transforms](table_theorems_transforms.ipynb#Selected-Transforms)) \begin{equation} \mathcal{L} \{ t^n e^{-s_0 t} \epsilon(t) \} = \frac{n!}{(s + s_0)^{n+1}} \qquad \text{for } \Re \{ s \} > \Re \{ - s_0 \} \end{equation} and $\mathcal{L} \{ \delta(t) \} = 1$, together with the linearity of the Laplace transform yields a generic result for the inverse Laplace transform $x(t) = \mathcal{L}^{-1} \{ X(s) \}$ of a right-sided signal \begin{equation} x(t) = A_0 \cdot \delta(t) + \epsilon(t) \sum_{\mu = 1}^{L} e^{s_{\infty \mu} t} \sum_{\nu = 1}^{R_\mu} \frac{A_{\mu \nu} \, t^{\mu - 1}}{(\nu -1)!} \end{equation} It remains to compute the coefficients $A_0$ and $A_{\mu \nu}$ of the partial fraction decomposition. The constant coefficient $A_0$ is given as \begin{equation} A_0 = \lim_{s \to \infty} X(s) \end{equation} For a pole $s_{\infty \mu}$ with degree $R_\mu = 1$, the coefficient $A_{\mu 1}$ reads \begin{equation} A_{\mu 1} = \lim_{s \to s_{\infty \mu}} \left( X(s) \cdot (s - s_{\infty \mu}) \right) \end{equation} For a pole $s_{\infty \mu}$ of degree $R_\mu > 1$, the coefficients $A_{\mu \nu}$ are given as \begin{equation} A_{\mu \nu} = \frac{1}{(R_\mu - \nu)!} \lim_{s \to s_{\infty \mu}} \frac{d^{R_\mu - \nu}}{d s^{R_\mu - \nu}} \left( X(s) \cdot (s - s_{\infty \mu})^{R_\mu} \right) \end{equation} #### Example - Inverse transform of a rational Laplace transform The inverse transform $x(t) = \mathcal{L}^{-1} \{ X(s) \}$ of \begin{equation} X(s) = \frac{1}{(s+1) (s+2)^2} \qquad \text{for } \Re \{s \} > -1 \end{equation} is computed using the procedure outline above. First the function $X(s)$ is defined in `SymPy` ``` import sympy as sym sym.init_printing() s = sym.symbols('s', complex=True) t = sym.symbols('t', real=True) X = 1/((s+1)*(s+2)**2) X ``` Since $X(s)$ has two real-values poles, $x_{\infty 1} = -1$ with degree $R_1 = 1$ and $x_{\infty 2} = -2$ with degree $R_2 = 2$, the following partial fraction decomposition is chosen as ansatz in accordance with above given formula ``` A0, A11, A21, A22 = sym.symbols('A_0 A_{11} A_{21} A_{22}', real=True) Xp = A0 + A11/(s+1) + A21/(s+2) + A22/(s+2)**2 Xp ``` The four real-valued constants $A_0$, $A_{11}$, $A_{21}$ and $A_{22}$ of the partial fraction decomposition will be determined later. First a look is taken at the inverse Laplace transforms of the individual summands composed from the constant and the individual poles. For the constant we get ``` x0 = sym.inverse_laplace_transform(Xp.args[0], s, t) x0 ``` For the first pole $s_{\infty 1}$ with degree zero we get ``` x1 = sym.inverse_laplace_transform(Xp.args[1], s, t) x1 ``` For the second pole $s_{\infty 2}$ with degree two we get two contributions ``` x2 = sym.inverse_laplace_transform(Xp.args[2], s, t) x2 x3 = sym.inverse_laplace_transform(Xp.args[3], s, t) x3 ``` The inverse Laplace transform of $X(s)$ is now composed from the superposition of the four individual parts ``` x = x0 + x1 + x2 + x3 x ``` For the final solution the four coefficients are determined using the given limit formulas for the coefficients of a partial fraction decomposition ``` coeffs = {A0: sym.limit(X, s, sym.oo)} coeffs.update({A11: sym.limit(X*(s+1), s, -1)}) coeffs.update({A21: sym.limit(sym.diff(X*(s+2)**2, s), s, -2)}) coeffs.update({A22: sym.limit(X*(s+2)**2, s, -2)}) coeffs ``` Substitution into the inverse Laplace transform yields the final solution $x(t) = \mathcal{L}^{-1}\{ X(s) \}$ ``` x = x.subs(coeffs) x ``` The solution is plotted for illustration ``` sym.plot(x, (t, -1, 10), ylabel=r'$x(t)$'); ``` **Exercise** * Derive the inverse Laplace transform of $X(s)$ by manual calculation. #### Classification of Poles Above procedure allows to compute the inverse Laplace transform $x(t) = \mathcal{L}^{-1} \{ X(s) \}$ of a rational Laplace transform $X(s)$ in a systematic way. It is well suited for an algorithmic realization. However, for manual calculus it may be more efficient to classify the poles with respect to their location in the $s$-plane and their symmetries. The classification can then be used to formulate a modified partial fraction decomposition which limits the need for later algebraic simplification of the inverse Laplace transform. Three classes of poles are typically considered | Type | Pole-Zero Diagramm | $X(s)$ | $x(t) = \mathcal{L}^{-1} \{ X(s) \} \qquad \qquad$ | |---|:---:|:---:|:---:| | Single complex pole | ![Single pole](single_pole.png) | $\frac{n!}{(s + s_0)^{n+1}}$ | $t^n e^{-s_0 t} \epsilon(t)$ | | Conjugated imaginary poles | ![Conjugated imaginary poles](conjugated_imaginary_poles.png) | $\frac{A s + B}{s^2 + \omega_0^2}$ | $\begin{cases} \sin(\omega_0 t) \epsilon(t) \\ \cos(\omega_0 t) \epsilon(t) \end{cases}$ | | Conjugated complex poles | ![](conjugated_complex_poles.png) | $\frac{A s + B}{(s + \sigma_0)^2 + \omega_0^2}$ | $\begin{cases} e^{-\sigma_0 t} \sin(\omega_0 t) \epsilon(t) \\ e^{-\sigma_0 t} \cos(\omega_0 t) \epsilon(t) \end{cases}$ | where $s_0 \in \mathbb{C}$ and $\omega_0, \sigma_0 \in \mathbb{R}$. The expansion coefficients $A, B \in \mathbb{R}$ can be derived by comparison of coefficients. Whether $x(t)$ contains a sine or cosine depends on the coefficient $A$. If $A \neq 0$ then $x(t)$ contains a cosine (cf. [table of selected transforms](table_theorems_transforms.ipynb#Selected-Transforms)). #### Example - Inverse transform of a rational Laplace transform with symmetric poles The inverse transform $x(t) = \mathcal{L}^{-1} \{ X(s) \}$ of \begin{equation} X(s) = \frac{2 s^2 + 14 s + 124}{s^3 + 8 s^2 + 46 s + 68} \qquad \text{for } \Re \{s \} > -2 \end{equation} is computed. First the function $X(s)$ is defined in `SymPy` ``` X = (2*s**2 + 14*s + 124)/(s**3 + 8 * s**2 + 46*s + 68) X ``` The poles of $X(s)$ are derived by computing the roots of the denominator polynomial ``` poles = sym.roots(sym.denom(X)) poles ``` The result is a real-valued pole and a conjugate complex pair of poles. According to above introduced classification of poles, the following ansatz is chosen for the partial fraction decomposition of the Laplace transform \begin{equation} X_p(s) = \frac{A}{s + 2} + \frac{B s + C}{s^2 + 6s + 34} \end{equation} The coefficients $A, B, C \in \mathbb{R}$ are derived by equating coefficients with $X(s)$ ``` A, B, C = sym.symbols('A B C', real=True) Xp = A / (s+2) + (B*s + C)/(s**2 + 6*s + 34) coeffs = sym.solve(sym.Eq(X, Xp), (A, B, C)) coeffs ``` Introducing the coefficients into $X_p(s)$ yields ``` Xp = Xp.subs(coeffs) Xp ``` The first fraction belongs to the complex conjugate poles. Applying [completion of the square](https://en.wikipedia.org/wiki/Completing_the_square) to the denominator, its inverse can be identified in the [table of Laplace transforms](table_theorems_transforms.ipynb#Transforms) as exponentially decaying cosine signal. Performing the inverse Laplace transform with `SymPy` yields ``` x1 = sym.inverse_laplace_transform(Xp.args[1], s, t) x1 ``` The second fraction belongs to a real-valued pole of first degree. Its inverse Laplace transform can be looked-up directly in the [table of Laplace transforms](table_theorems_transforms.ipynb#Transforms) as exponentially decaying signal. Performing the inverse Laplace transform again with `SymPy` yields ``` x2 = sym.inverse_laplace_transform(Xp.args[0], s, t) x2 ``` The inverse Laplace transform of $X(s)$ is given by summing up these two parts ``` x = x1 + x2 x ``` The resulting signal is plotted for illustration ``` sym.plot(x, (t, -0.1, 4), xlabel='$t$', ylabel='$x(t)$'); ``` The same result can be derived directly from $X(s)$ by using the inverse Laplace transform of `SymPy` ``` sym.inverse_laplace_transform(X, s, t).simplify() ``` **Exercise** * Derive the inverse Laplace transform of $X(s)$ by manual calculation. **Copyright** This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Continuous- and Discrete-Time Signals and Systems - Theory and Computational Examples*.
github_jupyter
``` %matplotlib inline %config InlineBackend.figure_formats = {'png', 'retina'} data_key = pd.read_csv('key.csv') data_key = data_key[data_key['station_nbr'] != 5] data_weather = pd.read_csv('weather.csv') data_weather = data_weather[data_weather['station_nbr'] != 5] ## Station 5번 제거한 나머지 data_train = pd.read_csv('train.csv') df = pd.merge(data_weather, data_key) station_nbr = df['station_nbr'] df.drop('station_nbr', axis=1, inplace=True) df['station_nbr'] = station_nbr df = pd.merge(df, data_train) # Station 5번을 뺀 나머지 Merge 완성 # 'M'과 '-'을 np.nan으로 값을 변경하기 전에, ' T'값을 먼저 snowfall=0.05, preciptotal = 0.005로 변경하자 df['snowfall'][df['snowfall'] == ' T'] = 0.05 df['preciptotal'][df['preciptotal'] == ' T'] = 0.005 df['snowfall'][df['snowfall'] == ' T'], df['preciptotal'][df['preciptotal'] == ' T'] # T 값 변경 완료. 이제, 19개 Station 별로 정리하기 (5번 Station 생략) df['snowfall'][df['snowfall'] == ' T'] = 0.05 df['preciptotal'][df['preciptotal'] == ' T'] = 0.005 # T 값 변경 완료. 이제, 19개 Station 별로 정리하기 (5번 Station 생략) df_s_1 = df[df['station_nbr'] == 1]; df_s_8 = df[df['station_nbr'] == 8]; df_s_15 = df[df['station_nbr'] == 15] df_s_2 = df[df['station_nbr'] == 2]; df_s_9 = df[df['station_nbr'] == 9]; df_s_16 = df[df['station_nbr'] == 16] df_s_3 = df[df['station_nbr'] == 3]; df_s_10 = df[df['station_nbr'] == 10]; df_s_17 = df[df['station_nbr'] == 17] df_s_4 = df[df['station_nbr'] == 4]; df_s_11 = df[df['station_nbr'] == 11]; df_s_18 = df[df['station_nbr'] == 18] df_s_5 = df[df['station_nbr'] == 5]; df_s_12 = df[df['station_nbr'] == 12]; df_s_19 = df[df['station_nbr'] == 19] df_s_6 = df[df['station_nbr'] == 6]; df_s_13 = df[df['station_nbr'] == 13]; df_s_20 = df[df['station_nbr'] == 20] df_s_7 = df[df['station_nbr'] == 7]; df_s_14 = df[df['station_nbr'] == 14] # Each Station depart 의 M값을 np.nan으로 변경 df_s_1_depart = df_s_1['depart'].copy(); df_s_1_depart = pd.to_numeric(df_s_1_depart, errors = 'coerce') df_s_2_depart = df_s_2['depart'].copy(); df_s_2_depart = pd.to_numeric(df_s_2_depart, errors = 'coerce') df_s_3_depart = df_s_3['depart'].copy(); df_s_3_depart = pd.to_numeric(df_s_3_depart, errors = 'coerce') df_s_4_depart = df_s_4['depart'].copy(); df_s_4_depart = pd.to_numeric(df_s_4_depart, errors = 'coerce') df_s_5_depart = df_s_5['depart'].copy(); df_s_5_depart = pd.to_numeric(df_s_5_depart, errors = 'coerce') df_s_6_depart = df_s_6['depart'].copy(); df_s_6_depart = pd.to_numeric(df_s_6_depart, errors = 'coerce') df_s_7_depart = df_s_7['depart'].copy(); df_s_7_depart = pd.to_numeric(df_s_7_depart, errors = 'coerce') df_s_8_depart = df_s_8['depart'].copy(); df_s_8_depart = pd.to_numeric(df_s_8_depart, errors = 'coerce') df_s_9_depart = df_s_9['depart'].copy(); df_s_9_depart = pd.to_numeric(df_s_9_depart, errors = 'coerce') df_s_10_depart = df_s_10['depart'].copy(); df_s_10_depart = pd.to_numeric(df_s_10_depart, errors = 'coerce') df_s_11_depart = df_s_11['depart'].copy(); df_s_11_depart = pd.to_numeric(df_s_11_depart, errors = 'coerce') df_s_12_depart = df_s_12['depart'].copy(); df_s_12_depart = pd.to_numeric(df_s_12_depart, errors = 'coerce') df_s_13_depart = df_s_13['depart'].copy(); df_s_13_depart = pd.to_numeric(df_s_13_depart, errors = 'coerce') df_s_14_depart = df_s_14['depart'].copy(); df_s_14_depart = pd.to_numeric(df_s_14_depart, errors = 'coerce') df_s_15_depart = df_s_15['depart'].copy(); df_s_15_depart = pd.to_numeric(df_s_15_depart, errors = 'coerce') df_s_16_depart = df_s_16['depart'].copy(); df_s_16_depart = pd.to_numeric(df_s_16_depart, errors = 'coerce') df_s_17_depart = df_s_17['depart'].copy(); df_s_17_depart = pd.to_numeric(df_s_17_depart, errors = 'coerce') df_s_18_depart = df_s_18['depart'].copy(); df_s_18_depart = pd.to_numeric(df_s_18_depart, errors = 'coerce') df_s_19_depart = df_s_19['depart'].copy(); df_s_19_depart = pd.to_numeric(df_s_19_depart, errors = 'coerce') df_s_20_depart = df_s_20['depart'].copy(); df_s_20_depart = pd.to_numeric(df_s_20_depart, errors = 'coerce') # 각 각의 Station의 Nan 값에, 위에서 구한 각각 station의 평균 값을 넣어서 NaN 값 뺏을 때와 비교할 것. df_s_1_depart_with_mean = df_s_1_depart.copy(); df_s_1_depart_with_mean[df_s_1_depart_with_mean.isnull()] = df_s_1_depart.mean() df_s_2_depart_with_mean = df_s_2_depart.copy(); df_s_2_depart_with_mean[df_s_2_depart_with_mean.isnull()] = df_s_2_depart.mean() df_s_3_depart_with_mean = df_s_3_depart.copy(); df_s_3_depart_with_mean[df_s_3_depart_with_mean.isnull()] = df_s_3_depart.mean() df_s_4_depart_with_mean = df_s_4_depart.copy(); df_s_4_depart_with_mean[df_s_4_depart_with_mean.isnull()] = df_s_4_depart.mean() df_s_5_depart_with_mean = df_s_5_depart.copy(); df_s_5_depart_with_mean[df_s_5_depart_with_mean.isnull()] = df_s_5_depart.mean() df_s_6_depart_with_mean = df_s_6_depart.copy(); df_s_6_depart_with_mean[df_s_6_depart_with_mean.isnull()] = df_s_6_depart.mean() df_s_7_depart_with_mean = df_s_7_depart.copy(); df_s_7_depart_with_mean[df_s_7_depart_with_mean.isnull()] = df_s_7_depart.mean() df_s_8_depart_with_mean = df_s_8_depart.copy(); df_s_8_depart_with_mean[df_s_8_depart_with_mean.isnull()] = df_s_8_depart.mean() df_s_9_depart_with_mean = df_s_9_depart.copy(); df_s_9_depart_with_mean[df_s_9_depart_with_mean.isnull()] = df_s_9_depart.mean() df_s_10_depart_with_mean = df_s_10_depart.copy(); df_s_10_depart_with_mean[df_s_10_depart_with_mean.isnull()] = df_s_10_depart.mean() df_s_11_depart_with_mean = df_s_11_depart.copy(); df_s_11_depart_with_mean[df_s_11_depart_with_mean.isnull()] = df_s_11_depart.mean() df_s_12_depart_with_mean = df_s_12_depart.copy(); df_s_12_depart_with_mean[df_s_12_depart_with_mean.isnull()] = df_s_12_depart.mean() df_s_13_depart_with_mean = df_s_13_depart.copy(); df_s_13_depart_with_mean[df_s_13_depart_with_mean.isnull()] = df_s_13_depart.mean() df_s_14_depart_with_mean = df_s_14_depart.copy(); df_s_14_depart_with_mean[df_s_14_depart_with_mean.isnull()] = df_s_14_depart.mean() df_s_15_depart_with_mean = df_s_15_depart.copy(); df_s_15_depart_with_mean[df_s_15_depart_with_mean.isnull()] = df_s_15_depart.mean() df_s_16_depart_with_mean = df_s_16_depart.copy(); df_s_16_depart_with_mean[df_s_16_depart_with_mean.isnull()] = df_s_16_depart.mean() df_s_17_depart_with_mean = df_s_17_depart.copy(); df_s_17_depart_with_mean[df_s_17_depart_with_mean.isnull()] = df_s_17_depart.mean() df_s_18_depart_with_mean = df_s_18_depart.copy(); df_s_18_depart_with_mean[df_s_18_depart_with_mean.isnull()] = df_s_18_depart.mean() df_s_19_depart_with_mean = df_s_19_depart.copy(); df_s_19_depart_with_mean[df_s_19_depart_with_mean.isnull()] = df_s_19_depart.mean() df_s_20_depart_with_mean = df_s_20_depart.copy(); df_s_20_depart_with_mean[df_s_20_depart_with_mean.isnull()] = df_s_20_depart.mean() # 각 각의 Station 별로 depart의 값이 np.nan일 때, 즉, missing value를 뺏을 때의 전체 mean 값을 나타낸다. print('#station1_without_nan_mean:', round(df_s_1_depart.mean(),4), '#station1_without_nan_std:', round(df_s_1_depart.std(),4)); print('#station2_without_nan_mean:', round(df_s_2_depart.mean(),4), '#station2_without_nan_std:', round(df_s_2_depart.std(),4)); print('#station3_without_nan_mean:', round(df_s_3_depart.mean(),4), '#station3_without_nan_std:', round(df_s_3_depart.std(),4)); print('#station4_without_nan_mean:', round(df_s_4_depart.mean(),4), '#station4_without_nan_std:', round(df_s_4_depart.std(),4)); print('#station5_without_nan_mean:', round(df_s_5_depart.mean(),4), '#station5_without_nan_std:', round(df_s_5_depart.std(),4)); print('#station6_without_nan_mean:', round(df_s_6_depart.mean(),4), '#station6_without_nan_std:', round(df_s_6_depart.std(),4)); print('#station7_without_nan_mean:', round(df_s_7_depart.mean(),4), '#station7_without_nan_std:', round(df_s_7_depart.std(),4)); print('#station8_without_nan_mean:', round(df_s_8_depart.mean(),4), '#station8_without_nan_std:', round(df_s_8_depart.std(),4)); print('#station9_without_nan_mean:', round(df_s_9_depart.mean(),4), '#station9_without_nan_std:', round(df_s_9_depart.std(),4)); print('#station10_without_nan_mean:', round(df_s_10_depart.mean(),4), '#station10_without_nan_std:', round(df_s_10_depart.std(),4)); print('#station11_without_nan_mean:', round(df_s_11_depart.mean(),4), '#station11_without_nan_std:', round(df_s_11_depart.std(),4)); print('#station12_without_nan_mean:', round(df_s_12_depart.mean(),4), '#station12_without_nan_std:', round(df_s_12_depart.std(),4)); print('#station13_without_nan_mean:', round(df_s_13_depart.mean(),4), '#station13_without_nan_std:', round(df_s_13_depart.std(),4)); print('#station14_without_nan_mean:', round(df_s_14_depart.mean(),4), '#station14_without_nan_std:', round(df_s_14_depart.std(),4)); print('#station15_without_nan_mean:', round(df_s_15_depart.mean(),4), '#station15_without_nan_std:', round(df_s_15_depart.std(),4)); print('#station16_without_nan_mean:', round(df_s_16_depart.mean(),4), '#station16_without_nan_std:', round(df_s_16_depart.std(),4)); print('#station17_without_nan_mean:', round(df_s_17_depart.mean(),4), '#station17_without_nan_std:', round(df_s_17_depart.std(),4)); print('#station18_without_nan_mean:', round(df_s_18_depart.mean(),4), '#station18_without_nan_std:', round(df_s_18_depart.std(),4)); print('#station19_without_nan_mean:', round(df_s_19_depart.mean(),4), '#station19_without_nan_std:', round(df_s_19_depart.std(),4)); print('#station20_without_nan_mean:', round(df_s_20_depart.mean(),4), '#station20_without_nan_std:', round(df_s_20_depart.std(),4)); print('stat1_nan_as_mean:',round(df_s_1_depart_with_mean.mean(),4),'#stat1_nan_as_std:', round(df_s_1_depart_with_mean.std(),4)); print('stat2_nan_as_mean:',round(df_s_2_depart_with_mean.mean(),4),'#stat2_nan_as_std:', round(df_s_2_depart_with_mean.std(),4)); print('stat3_nan_as_mean:',round(df_s_3_depart_with_mean.mean(),4),'#stat3_nan_as_std:', round(df_s_3_depart_with_mean.std(),4)); print('stat4_nan_as_mean:',round(df_s_4_depart_with_mean.mean(),4),'#stat4_nan_as_std:', round(df_s_4_depart_with_mean.std(),4)); print('stat5_nan_as_mean:',round(df_s_5_depart_with_mean.mean(),4),'#stat5_nan_as_std:', round(df_s_5_depart_with_mean.std(),4)); print('stat6_nan_as_mean:',round(df_s_6_depart_with_mean.mean(),4),'#stat6_nan_as_std:', round(df_s_6_depart_with_mean.std(),4)); print('stat7_nan_as_mean:',round(df_s_7_depart_with_mean.mean(),4),'#stat7_nan_as_std:', round(df_s_7_depart_with_mean.std(),4)); print('stat8_nan_as_mean:',round(df_s_8_depart_with_mean.mean(),4),'#stat8_nan_as_std:', round(df_s_8_depart_with_mean.std(),4)); print('stat9_nan_as_mean:',round(df_s_9_depart_with_mean.mean(),4),'#stat9_nan_as_std:', round(df_s_9_depart_with_mean.std(),4)); print('stat10_nan_as_mean:',round(df_s_10_depart_with_mean.mean(),4),'#stat10_nan_as_std:', round(df_s_10_depart_with_mean.std(),4)); print('stat11_nan_as_mean:',round(df_s_11_depart_with_mean.mean(),4),'#stat11_nan_as_std:', round(df_s_11_depart_with_mean.std(),4)); print('stat12_nan_as_mean:',round(df_s_12_depart_with_mean.mean(),4),'#stat12_nan_as_std:', round(df_s_12_depart_with_mean.std(),4)); print('stat13_nan_as_mean:',round(df_s_13_depart_with_mean.mean(),4),'#stat13_nan_as_std:', round(df_s_13_depart_with_mean.std(),4)); print('stat14_nan_as_mean:',round(df_s_14_depart_with_mean.mean(),4),'#stat14_nan_as_std:', round(df_s_14_depart_with_mean.std(),4)); print('stat15_nan_as_mean:',round(df_s_15_depart_with_mean.mean(),4),'#stat15_nan_as_std:', round(df_s_15_depart_with_mean.std(),4)); print('stat16_nan_as_mean:',round(df_s_16_depart_with_mean.mean(),4),'#stat16_nan_as_std:', round(df_s_16_depart_with_mean.std(),4)); print('stat17_nan_as_mean:',round(df_s_17_depart_with_mean.mean(),4),'#stat17_nan_as_std:', round(df_s_17_depart_with_mean.std(),4)); print('stat18_nan_as_mean:',round(df_s_18_depart_with_mean.mean(),4),'#stat18_nan_as_std:', round(df_s_18_depart_with_mean.std(),4)); print('stat19_nan_as_mean:',round(df_s_19_depart_with_mean.mean(),4),'#stat19_nan_as_std:', round(df_s_19_depart_with_mean.std(),4)); print('stat20_nan_as_mean:',round(df_s_20_depart_with_mean.mean(),4),'#stat20_nan_as_std:', round(df_s_20_depart_with_mean.std(),4)); y1 = np.array([df_s_1_depart.mean(), df_s_2_depart.mean(), df_s_3_depart.mean(), df_s_4_depart.mean(), df_s_5_depart.mean(), df_s_6_depart.mean(), df_s_7_depart.mean(), df_s_8_depart.mean(), df_s_9_depart.mean(), df_s_10_depart.mean(), df_s_11_depart.mean(), df_s_12_depart.mean(), df_s_13_depart.mean(), df_s_14_depart.mean(), df_s_15_depart.mean(), df_s_16_depart.mean(), df_s_17_depart.mean(), df_s_18_depart.mean(), df_s_19_depart.mean(), df_s_20_depart.mean()]) y2 = np.array([df_s_1_depart_with_mean.mean(), df_s_2_depart_with_mean.mean(), df_s_3_depart_with_mean.mean(), df_s_4_depart_with_mean.mean() ,df_s_5_depart_with_mean.mean(), df_s_6_depart_with_mean.mean(), df_s_7_depart_with_mean.mean(), df_s_8_depart_with_mean.mean() ,df_s_9_depart_with_mean.mean(), df_s_10_depart_with_mean.mean(), df_s_11_depart_with_mean.mean(), df_s_12_depart_with_mean.mean() ,df_s_13_depart_with_mean.mean(), df_s_14_depart_with_mean.mean(), df_s_15_depart_with_mean.mean(), df_s_16_depart_with_mean.mean() ,df_s_17_depart_with_mean.mean(),df_s_18_depart_with_mean.mean(),df_s_19_depart_with_mean.mean(),df_s_20_depart_with_mean.mean()]) plt.figure(figsize=(10,5)) plt.plot() x = range(1, 21) plt.xlabel('Station Number') plt.ylabel('depart') plt.bar(x, y1, color='y') plt.bar(x, y2, color='r') plt.show() #### depart 에서는 # 이 Graph가 나타내는 바는, y1과 y2가 차이가 거의 없다는 것. 그래프에는 r color와 y color이 있는데, 하나만 보인다는 것은 # 우리가 그래프에서 눈으로 보이지 않는 정도의 차이가 나온다는 것이다, 즉 차이가 극히 작다고 판단 할 수 있다. # Missing Values를 np.nan으로 바꾸고, 거기서 Mean 값을 구하여 np.nan에 대입하여도, # 따라서, 여기서는 Missing Value에 Mean값을 적용하여 회귀 분석에 적용 할 수있다고 판단된다. plt.figure(figsize=(12,6)) xticks = range(1,21) plt.plot(xticks, y1, 'ro-', label='stations_without_nan_mean') plt.plot(xticks, y2, 'bd:', label='stations_nan_as_mean') plt.legend(loc=0) plt.show() y3 = np.array([df_s_1_depart.std(), df_s_2_depart.std(), df_s_3_depart.std(), df_s_4_depart.std(), df_s_5_depart.std(), df_s_6_depart.std(), df_s_7_depart.std(), df_s_8_depart.std(), df_s_9_depart.std(), df_s_10_depart.std(), df_s_11_depart.std(), df_s_12_depart.std(), df_s_13_depart.std(), df_s_14_depart.std(), df_s_15_depart.std(), df_s_16_depart.std(), df_s_17_depart.std(), df_s_18_depart.std(), df_s_19_depart.std(), df_s_20_depart.std()]) y4 = np.array([df_s_1_depart_with_mean.std(), df_s_2_depart_with_mean.std(), df_s_3_depart_with_mean.std(), df_s_4_depart_with_mean.std() ,df_s_5_depart_with_mean.std(), df_s_6_depart_with_mean.std(), df_s_7_depart_with_mean.std(), df_s_8_depart_with_mean.std() ,df_s_9_depart_with_mean.std(), df_s_10_depart_with_mean.std(), df_s_11_depart_with_mean.std(), df_s_12_depart_with_mean.std() ,df_s_13_depart_with_mean.std(), df_s_14_depart_with_mean.std(), df_s_15_depart_with_mean.std(), df_s_16_depart_with_mean.std() ,df_s_17_depart_with_mean.std(),df_s_18_depart_with_mean.std(),df_s_19_depart_with_mean.std(),df_s_20_depart_with_mean.std()]) plt.figure(figsize=(10,5)) plt.plot() x = range(1, 21) plt.xlabel('Station Number') plt.ylabel('depart') plt.bar(x, y3, color='r') plt.bar(x, y4, color='g') plt.show() plt.figure(figsize=(12,6)) xticks = range(1,21) plt.plot(xticks, y3, 'ro-', label='stations_without_nan_std') plt.plot(xticks, y4, 'bd:', label='stations_nan_as_std') plt.legend(loc=0) plt.show() ```
github_jupyter
# ElasticSearch DSL Librería de alto nivel que ayuda a escribir y ejecutar consultas en Elastic. Proporciona una API más idiomática y pythonica para manipular y componer consultas. Proporciona una capa para trabajar con los documentos, definiendo el mapping, rescatar, actualizar, guardar documentos, usando orientación a objetos. ### Conexión con nuestro cluster. Tenemos una forma cómoda de conectarnos, tan solo indicando una lista de dominios o ips, de los nodos de nuestro cluster. Permite configurar muchas opciones de la capa de transporte, incluidos certificados ssl. ``` from elasticsearch_dsl import connections connections.create_connection(hosts=['elasticsearch']) ``` La api de Elasticsearch DSL, permite comprobar el estado de nuestro cluster. ``` # Consultamos el estado de nuestro cluster, (red, yellow, green). connections.get_connection().cluster.health()['status'] ``` ### Uso de Mapping De forma opcional, podemos definir un mapping elasticsearch, desde una clase python. Esto tiene multiples ventajas. 1. Fijar nosotros mismos la naturaleza de la información que vamos a almacenar en el indice. 2. Trabajar con los documentos de este indice, haciendo uso de los atributos y los métodos de la clase, pudiendo hacer programación orientada a objetos. 3. Definir nosotros mismos el "analyzer" que se debe aplicar. 4. Definir de forma programática, opciones de la configuración del índice. En este caso usamos el analizador "snowball", para ver más [https://snowballstem.org/](https://snowballstem.org/). Para conocer todos los [built_in_analyzers](https://www.elastic.co/guide/en/elasticsearch/guide/master/analysis-intro.html#_built_in_analyzers) podemos consultar la referencia. ``` from datetime import datetime from elasticsearch_dsl import Document, Date, Integer, Keyword, Text from elasticsearch_dsl.connections import connections class Article(Document): title = Text(analyzer='snowball', fields={'raw': Keyword()}) body = Text(analyzer='snowball') tags = Keyword() published_from = Date() words = Integer() url = Keyword() class Index: name = 'blog' settings = { "number_of_shards": 2, } def save(self, ** kwargs): self.words = len(self.body.split()) return super(Article, self).save(** kwargs) def is_published(self): return datetime.now() >= self.published_from import elasticsearch.exceptions as elasticexceptions from elasticsearch_dsl import Index # Instanciar un objeto referente al índice. index = Index("blog") try: # En caso de existir previamente, obligamos a borrarlo. index.delete() except elasticexceptions.NotFoundError: pass # Ejecutamos la creación del índice, con el mapping definido. Article.init() ``` Una vez creado el indice, ya podemos empezar a crear documentos. Creamos manualmente una serie de objetos de tipo de Articulo. ``` article1 = Article(title='Docketiza tu aplicación', tags=['devops', 'virtualizacion', 'docker']) article1.body = '''Hoy día quizá escuches frecuentemente términos como Devops, Virtualización y por supuesto Cloud. En las siguientes lineas hablaremos sobre ellas y además para hacer la cosa más divertida presentar una aplicación real de todos estos conceptos.Virtualización es un concepto muy amplio y tiene diferentes aplicaciones según el nivel donde se dé, ya hemos hablado en otra ocasión de Copicloud, donde la virtualización llega al extremo, convirtiéndose en un “cloud”.Hoy nos centraremos en otro nivel de virtualización, destinado tanto a desarrolladores como a administradores de sistemas, es por ello que os presento la herramienta Docker. Por ser actualmente una de las herramientas preferidas en el mundillo Devops. ''' article1.published_from = datetime.now() article1.url = "http://blog.intelligenia.com/2016/06/docketiza-tu-aplicacion.html" article1.save() article2 = Article(title='Consumiendo websocket desde el bar', tags=['websocket', 'http', 'services']) article2.body = ''' No podemos negar que Internet está creciendo, tanto en número de usuario, como en número de servicios que ofrece, así como en número de dispositivos que están conectados. Esto hace que las necesidades también sean mayores y las aplicaciones se adapten a cada una de ellas.Hoy día, estamos acostumbrados a trabajar con aplicaciones cada vez más dinámicas. Donde el proceso de comunicación sea cada vez más transparente al usuario, de forma que no se perciba el constante diálogo con el servidor web. Estamos cada vez más familiarizados con aplicaciones que nos muestran información en tiempo real, ya sea el estado de la bolsa o el tiempo meteorológico de nuestra zona, aplicaciones que nos muestran notificaciones y se actualiza nuestra bandeja de correo electrónico, así como chats donde podemos conversar con otros usuarios.Una tecnología reciente que permite tener una comunicación bidireccional y persistente entre nuestras aplicaciones web y el servidor web, recibe el nombre de Websocket.''' article2.published_from = datetime.now() article1.url = "http://blog.intelligenia.com/2016/12/consumiendo-websocket-desde-el-bar.html" article2.save() article3 = Article(title='APIS fantásticas y dónde encontrarlas', tags=['graphql', 'rest', 'soap']) article3.body = ''' Es una realidad que el incremento en la oferta de APIS públicas se ha disparado en los últimos años. En las siguientes líneas vamos a tratar de adentrarnos en esta tecnología, conocer los motivos de dicho crecimiento, así como ver algunas de las APIS más interesantes que tenemos a nuestro alcance y podemos probar.Si no estás familiarizado con la terminología quizá no te diga mucho las siglas "API", para comenzar te puedo decir que se refieren a la traducción inglesa de "interfaz de programación de aplicaciones". Muy resumidamente podemos decir que las APIS, es una de las formas más importantes con las que contamos para conectar unas aplicaciones con otras, ya sean aplicaciones propias o de terceros. Con las APIS logramos que unos sistemas puedan acceder a funcionalidad o información que se encuentra en otros sistemas.Anteriormente en en la entrada "Cómo crear una API RESTful con Django REST-framework", se explica de una forma muy interesante cómo implementar y exponer una API RESTful usando tecnología Django y se comentan muchos conceptos relacionados. Por ello si te interesa el tema te recomiendo que lo visitéis.En esta ocasión vamos a tratar el tema desde un punto de vista diferente. Viendo la utilidad que nos plantea servirnos de APIs de terceros para ampliar la funcionalidad de nuestras propias aplicaciones o sistemas.''' article3.published_from = datetime.now() article3.url = "http://blog.intelligenia.com/2017/10/apis-fantasticas-y-donde-encontrarlas.html" article3.save() ``` Podemos crear una búsqueda básica. ``` from utils import json_print search = Article.search().query("match", body="Django") #search = search.highlight_options(order='score') #search = search.highlight('body') json_print(search.to_dict()) response = search.execute() print() result = [print(f"{hit.title} {hit.words}") for hit in search] #for hit in response: # for fragment in hit.meta.highlight.body: # print(fragment) ``` Tambien podemos aplicar filtros y ordenaciones ``` search = Article.search().filter('terms', tags=['docker']).sort('-words') json_print(search.to_dict()) print() response = search.execute() result = [print(f"{hit.title} {hit.words}") for hit in search] from elasticsearch_dsl import Q import json q = Q("match", tags='python') | Q("match", tags='rest') search = Article.search().query(q) json_print(search.to_dict()) print() response = search.execute() result = [print(f"{hit.title} {hit.words}") for hit in search] from elasticsearch_dsl import Q import json q = Q("match", tags='graphql') & Q("match", tags='soap') search = Article.search().query(q) json_print(search.to_dict()) print() response = search.execute() result = [print(f"{hit.title} {hit.words}") for hit in search] from elasticsearch_dsl import Q import json q = ~Q("match", tags='python') & ~Q("match", tags='websocket') search = Article.search().query(q) json_print(search.to_dict()) print() response = search.execute() result = [print(f"{hit.title} {hit.tags}") for hit in search] q='tags:python OR tags:websocket' search = Article.search().query("query_string", query=q) json_print(search.to_dict()) response = search.execute() result = [print(f"{hit.title} {hit.tags}") for hit in search] ``` ## Ejemplo Titanic. ``` from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, Boolean, Float import elasticsearch.exceptions as elasticexceptions from elasticsearch_dsl import Index import os csv_path=f"{os.getcwd()}/data/titanic.csv" class TitanicPassenger(Document): passengerid = Keyword() survived = Integer() pclass = Integer() name = Text(analyzer='snowball') sex = Keyword() age = Integer() sibsp = Integer() parch = Integer() ticket = Keyword() fare = Float() embarked = Keyword() class Index: name = 'titanic' settings = { "number_of_shards": 2, "blocks":{'read_only_allow_delete': None} } def reset_titanic(): index = Index("titanic") try: index.delete() except elasticexceptions.NotFoundError: pass TitanicPassenger.init() import pandas as pd df = pd.read_csv(csv_path, sep='\t') df.head(20) from elasticsearch import helpers, Elasticsearch import csv es = Elasticsearch("elasticsearch:9200") reset_titanic() def indexing_titanic(): with open(csv_path) as f: reader = csv.reader(f, delimiter="\t") next(reader) for row in reader: TitanicPassenger(passengerid=row[0], survived=row[1], pclass=row[2], name=row[3], sex=row[4], age=row[5], sibsp=row[6], parch=row[7], ticket=row[8], fare=row[9], cabin=row[10], embarked=row[11]).save() %timeit indexing_titanic() from elasticsearch import helpers, Elasticsearch import csv es = Elasticsearch("elasticsearch:9200") reset_titanic() def load_data(): data = [] with open(csv_path) as f: reader = csv.reader(f, delimiter="\t") next(reader) for i, row in enumerate(reader): yield { "_index": "titanic", "_id": row[0], "_source":{ "passengerid": row[0], "survived":row[1], "pclass":row[2], "name":row[3], "sex":row[4], "age":row[5], "sibsp":row[6], "parch":row[7], "ticket":row[8], "fare":row[9], "embarked":row[11] } } %timeit helpers.bulk(es, load_data()) ``` ### Comparativa de parrallel bulk indexing y sreaming bulk indexing. ``` from elasticsearch import Elasticsearch from elasticsearch import helpers def test_streaming_bulk(): actions = [] for i in range(0, 100000): actions.append({'_index': 'test_index', '_type': 'test', 'x': i}) helpers.bulk(es, actions, False) def test_parallel_bulk(): actions = [] for i in range(0, 100000): actions.append({'_index': 'test_index', '_type': 'test', 'x': i}) parallel_bulk(es, actions) def parallel_bulk(client, actions, stats_only=False, **kwargs): success, failed = 0, 0 # list of errors to be collected is not stats_only errors = [] for ok, item in helpers.parallel_bulk(client, actions, **kwargs): # print ok, item # go through request-reponse pairs and detect failures if not ok: if not stats_only: errors.append(item) failed += 1 else: success += 1 return success, failed if stats_only else errors %timeit test_streaming_bulk() %timeit test_parallel_bulk() search = TitanicPassenger.search().query("match", name="Meo") response = search.execute() result = [print(f"{hit.passengerid}) {hit.name}") for hit in search] from elasticsearch_dsl import A s = TitanicPassenger.search() a = A('terms', field='survived') s.aggs.bucket('title_terms', a) print(s.to_dict()) t = s.execute() for vo in t.aggregations.title_terms.buckets: print(vo) ``` ## Opensciencegrid example ``` from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, A # https://gracc.opensciencegrid.org/q/gracc.osg.summary/_search gracc=Elasticsearch('https://gracc.opensciencegrid.org/q',timeout=120) # Last year start='now-360d' end='now' # GRACC summary index i='gracc.osg.summary' search = Search(using=gracc, index=i).filter("range",EndTime={'gte':start,'lte':end}) count = search.count() # Numero de elementos de la agregación. print(count) json_print(search.to_dict()) a = A('terms', field='OIM_Organization') search.aggs.bucket('organization_terms', a) t = search.execute() # Normalizamos datos para pinter grafica. from pandas.io.json import json_normalize df = json_normalize(t.to_dict()['aggregations']['organization_terms']['buckets']) df.head() %matplotlib inline df.plot.barh(x='key',y='doc_count') import matplotlib.pyplot as plt organization_array = [] count_array = [] for vo in t.aggregations.organization_terms.buckets: organization_array.append(vo['key']) count_array.append(vo['doc_count']) fig1, ax1 = plt.subplots() ax1.pie(count_array, labels=organization_array, shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show() ```
github_jupyter
## ResFPN Classifier Tutorial - Flower Photos by *Ming Ming Zhang* ``` import tensorflow as tf print('TF Version:', tf.__version__) #print('GPUs:', len(tf.config.list_physical_devices('GPU'))) import numpy as np import matplotlib.pyplot as plt import os, sys # python files directory PY_DIR = #'directory/to/python/files' sys.path.append(PY_DIR) import resnet_fpn ``` ## Data Info ``` # dataset directory DATASET_DIR = #'directory/to/covidx' TRAIN_NUM_IMGS = {} print('-----Training Set Info-----') for class_name in os.listdir(DATASET_DIR): if class_name == 'LICENSE.txt': continue imgs_list = os.listdir(os.path.join(DATASET_DIR, class_name)) num_imgs = len(imgs_list) TRAIN_NUM_IMGS[class_name] = num_imgs print('%s: %d images' % (class_name, num_imgs)) ``` ### TF Dataset ``` IMAGE_SIZE = (256, 256) BATCH_SIZE = 32 train_ds = tf.keras.preprocessing.image_dataset_from_directory( directory=DATASET_DIR, labels='inferred', label_mode='int', class_names=None, color_mode='rgb', batch_size=BATCH_SIZE, image_size=IMAGE_SIZE, shuffle=True, seed=123, validation_split=0.1, subset='training' ) for x_train_batch, y_train_batch in train_ds.take(1): print(x_train_batch.shape, y_train_batch.shape) CLASS_NAMES = train_ds.class_names print('classes:', CLASS_NAMES) NUM_CLASSES = len(CLASS_NAMES) val_ds = tf.keras.preprocessing.image_dataset_from_directory( directory=DATASET_DIR, labels='inferred', label_mode='int', class_names=None, color_mode='rgb', batch_size=BATCH_SIZE, image_size=IMAGE_SIZE, shuffle=True, seed=123, validation_split=0.1, subset='validation' ) for x_val_batch, y_val_batch in val_ds.take(1): print(x_val_batch.shape, y_val_batch.shape) train_ds = train_ds.cache().shuffle(1000).prefetch(1) val_ds = val_ds.cache().prefetch(1) ``` #### Visualization ``` plt.figure(figsize=(10, 10)) for x_train_batch, y_train_batch in train_ds.take(1): for i in range(9): plt.subplot(3, 3, i+1) plt.imshow(tf.cast(x_train_batch[i], tf.int32)) plt.title(CLASS_NAMES[y_train_batch[i]]) plt.axis('off') ``` ### ResFPN Classifiers #### Without Pretrained ResNet Weights ``` ResFPN = resnet_fpn.ResFPN_Classifier( image_shape=IMAGE_SIZE + (3,), num_classes=NUM_CLASSES, num_filters=256, architecture='resnet50', augmentation=True, checkpoint_path=None, resnet_weights_path=None) ResFPN.train( train_dataset=train_ds, val_dataset=val_ds, params={'lr':0.001, 'l2':0.3, 'epochs':5}, loss_type='ce', save_weights=False) ResFPN.plot() top_idxes, ensemble_acc = ResFPN.select_top(val_ds, top=3) ensemble_class_ids, metrics, f1_score = ResFPN.predict( val_ds, CLASS_NAMES, display_metrics=True, top_idxes=top_idxes) ``` #### With Pretrained ResNet Weights ``` filepath = #'path\to\pretrained_resnet_weights.h5' pretrain_ResFPN = resnet_fpn.ResFPN_Classifier( image_shape=IMAGE_SIZE + (3,), num_classes=NUM_CLASSES, num_filters=256, architecture='resnet50', augmentation=True, checkpoint_path=None, resnet_weights_path=filepath) pretrain_ResFPN.train( train_dataset=train_ds, val_dataset=val_ds, params={'lr':0.001, 'l2':0.3, 'epochs':5}, loss_type='ce', save_weights=False) pretrain_ResFPN.plot() top_idxes, val_acc = pretrain_ResFPN.select_top(val_ds, top=3) ensemble_class_ids, metrics, f1_score = pretrain_ResFPN.predict( val_ds, CLASS_NAMES, display_metrics=True, top_idxes=top_idxes) ```
github_jupyter
# **BentoML Example: Image Segmentation with PaddleHub** **BentoML makes moving trained ML models to production easy:** * Package models trained with any ML framework and reproduce them for model serving in production * **Deploy anywhere** for online API serving or offline batch serving * High-Performance API model server with adaptive micro-batching support * Central hub for managing models and deployment process via Web UI and APIs * Modular and flexible design making it adaptable to your infrastrcuture BentoML is a framework for serving, managing, and deploying machine learning models. It is aiming to bridge the gap between Data Science and DevOps, and enable teams to deliver prediction services in a fast, repeatable, and scalable way. Before reading this example project, be sure to check out the [Getting started guide](https://github.com/bentoml/BentoML/blob/master/guides/quick-start/bentoml-quick-start-guide.ipynb) to learn about the basic concepts in BentoML. This notebook demonstrates how to use BentoML to turn a Paddlehub module into a docker image containing a REST API server serving this model, how to use your ML service built with BentoML as a CLI tool, and how to distribute it a pypi package. This example notebook is based on the [Python quick guide from PaddleHub](https://github.com/PaddlePaddle/PaddleHub/blob/release/v2.0/docs/docs_en/quick_experience/python_use_hub_en.md). ``` %reload_ext autoreload %autoreload 2 %matplotlib inline !pip3 install -q bentoml paddlepaddle paddlehub !hub install deeplabv3p_xception65_humanseg ``` ## Prepare Input Data ``` !wget https://paddlehub.bj.bcebos.com/resources/test_image.jpg ``` ## Create BentoService with PaddleHub Module Instantiation ``` %%writefile paddlehub_service.py import paddlehub as hub import bentoml from bentoml import env, artifacts, api, BentoService import imageio from bentoml.adapters import ImageInput @env(infer_pip_packages=True) class PaddleHubService(bentoml.BentoService): def __init__(self): super(PaddleHubService, self).__init__() self.module = hub.Module(name="deeplabv3p_xception65_humanseg") @api(input=ImageInput(), batch=True) def predict(self, images): results = self.module.segmentation(images=images, visualization=True) return [result['data'] for result in results] # Import the custom BentoService defined above from paddlehub_service import PaddleHubService import numpy as np import cv2 # Pack it with required artifacts bento_svc = PaddleHubService() # Predict with the initialized module image = cv2.imread("test_image.jpg") images = [image] segmentation_results = bento_svc.predict(images) ``` ### Visualizing the result ``` # View the segmentation mask layer from matplotlib import pyplot as plt for result in segmentation_results: plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() # Get the segmented image of the original image for result, original in zip(segmentation_results, images): result = cv2.cvtColor(result, cv2.COLOR_GRAY2RGB) original_mod = cv2.cvtColor(original, cv2.COLOR_RGB2RGBA) mask = result / 255 *_, alpha = cv2.split(mask) mask = cv2.merge((mask, alpha)) segmented_image = (original_mod * mask).clip(0, 255).astype(np.uint8) plt.imshow(cv2.cvtColor(segmented_image, cv2.COLOR_BGRA2RGBA)) plt.axis('off') plt.show() ``` ### Start dev server for testing ``` # Start a dev model server bento_svc.start_dev_server() !curl -i \ -F image=@test_image.jpg \ localhost:5000/predict # Stop the dev model server bento_svc.stop_dev_server() ``` ### Save the BentoService for deployment ``` saved_path = bento_svc.save() ``` ## REST API Model Serving ``` !bentoml serve PaddleHubService:latest ``` If you are running this notebook from Google Colab, you can start the dev server with --run-with-ngrok option, to gain acccess to the API endpoint via a public endpoint managed by ngrok: ``` !bentoml serve PaddleHubService:latest --run-with-ngrok ``` ## Make request to the REST server *After navigating to the location of this notebook, copy and paste the following code to your terminal and run it to make request* ``` curl -i \ --header "Content-Type: image/jpeg" \ --request POST \ --data-binary @test_image.jpg \ localhost:5000/predict ``` ## Launch inference job from CLI ``` !bentoml run PaddleHubService:latest predict --input-file test_image.jpg ``` ## Containerize model server with Docker One common way of distributing this model API server for production deployment, is via Docker containers. And BentoML provides a convenient way to do that. Note that docker is **not available in Google Colab**. You will need to download and run this notebook locally to try out this containerization with docker feature. If you already have docker configured, simply run the follow command to product a docker container serving the PaddeHub prediction service created above: ``` !bentoml containerize PaddleHubService:latest !docker run --rm -p 5000:5000 PaddleHubService:latest ``` # **Deployment Options** If you are at a small team with limited engineering or DevOps resources, try out automated deployment with BentoML CLI, currently supporting AWS Lambda, AWS SageMaker, and Azure Functions: * [AWS Lambda Deployment Guide](https://docs.bentoml.org/en/latest/deployment/aws_lambda.html) * [AWS SageMaker Deployment Guide](https://docs.bentoml.org/en/latest/deployment/aws_sagemaker.html) * [Azure Functions Deployment Guide](https://docs.bentoml.org/en/latest/deployment/azure_functions.html) If the cloud platform you are working with is not on the list above, try out these step-by-step guide on manually deploying BentoML packaged model to cloud platforms: * [AWS ECS Deployment](https://docs.bentoml.org/en/latest/deployment/aws_ecs.html) * [Google Cloud Run Deployment](https://docs.bentoml.org/en/latest/deployment/google_cloud_run.html) * [Azure container instance Deployment](https://docs.bentoml.org/en/latest/deployment/azure_container_instance.html) * [Heroku Deployment](https://docs.bentoml.org/en/latest/deployment/heroku.html) Lastly, if you have a DevOps or ML Engineering team who's operating a Kubernetes or OpenShift cluster, use the following guides as references for implementating your deployment strategy: * [Kubernetes Deployment](https://docs.bentoml.org/en/latest/deployment/kubernetes.html) * [Knative Deployment](https://docs.bentoml.org/en/latest/deployment/knative.html) * [Kubeflow Deployment](https://docs.bentoml.org/en/latest/deployment/kubeflow.html) * [KFServing Deployment](https://docs.bentoml.org/en/latest/deployment/kfserving.html) * [Clipper.ai Deployment Guide](https://docs.bentoml.org/en/latest/deployment/clipper.html)
github_jupyter
# Hyperparameter tuning ## Spark <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Apache_Spark_logo.svg/1280px-Apache_Spark_logo.svg.png" width="400"> # Load data and feature engineering ``` import numpy as np import datetime import findspark findspark.init() from pyspark.sql import SparkSession import pyspark.sql.functions as F import pyspark.sql.types as T spark = SparkSession.builder.getOrCreate() taxi = spark.read.csv('s3://nyc-tlc/trip data/yellow_tripdata_2019-01.csv', header=True, inferSchema=True, timestampFormat='yyyy-MM-dd HH:mm:ss', ).sample(fraction=0.1, withReplacement=False) taxi = taxi.withColumn('pickup_weekday', F.dayofweek(taxi.tpep_pickup_datetime).cast(T.DoubleType())) taxi = taxi.withColumn('pickup_weekofyear', F.weekofyear(taxi.tpep_pickup_datetime).cast(T.DoubleType())) taxi = taxi.withColumn('pickup_hour', F.hour(taxi.tpep_pickup_datetime).cast(T.DoubleType())) taxi = taxi.withColumn('pickup_minute', F.minute(taxi.tpep_pickup_datetime).cast(T.DoubleType())) taxi = taxi.withColumn('pickup_year_seconds', (F.unix_timestamp(taxi.tpep_pickup_datetime) - F.unix_timestamp( F.lit(datetime.datetime(2019, 1, 1, 0, 0, 0)))).cast(T.DoubleType())) taxi = taxi.withColumn('pickup_week_hour', ((taxi.pickup_weekday * 24) + taxi.pickup_hour).cast(T.DoubleType())) taxi = taxi.withColumn('passenger_count', F.coalesce(taxi.passenger_count, F.lit(-1)).cast(T.DoubleType())) taxi = taxi.fillna({'VendorID': 'missing', 'RatecodeID': 'missing', 'store_and_fwd_flag': 'missing' }) # Spark ML expects a "label" column for the dependent variable taxi = taxi.withColumn('label', taxi.total_amount) taxi.cache() ``` # Run grid search ``` from pyspark.ml.regression import LinearRegression from pyspark.ml.tuning import CrossValidator, ParamGridBuilder from pyspark.ml.evaluation import RegressionEvaluator from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler, StandardScaler from pyspark.ml.pipeline import Pipeline numeric_feat = ['pickup_weekday', 'pickup_weekofyear', 'pickup_hour', 'pickup_minute', 'pickup_year_seconds', 'pickup_week_hour', 'passenger_count'] categorical_feat = ['VendorID', 'RatecodeID', 'store_and_fwd_flag', 'PULocationID', 'DOLocationID'] features = numeric_feat + categorical_feat y_col = 'total_amount' indexers = [ StringIndexer( inputCol=c, outputCol=f'{c}_idx', handleInvalid='keep') for c in categorical_feat ] encoders = [ OneHotEncoder( inputCol=f'{c}_idx', outputCol=f'{c}_onehot', ) for c in categorical_feat ] num_assembler = VectorAssembler( inputCols=numeric_feat, outputCol='num_features', ) scaler = StandardScaler(inputCol='num_features', outputCol='num_features_scaled') assembler = VectorAssembler( inputCols=[f'{c}_onehot' for c in categorical_feat] + ['num_features_scaled'], outputCol='features', ) lr = LinearRegression(standardization=False, maxIter=100) pipeline = Pipeline( stages=indexers + encoders + [num_assembler, scaler, assembler, lr]) grid = ( ParamGridBuilder() .addGrid(lr.elasticNetParam, np.arange(0, 1.01, 0.01)) .addGrid(lr.regParam, [0, 0.5, 1, 2]) .build() ) crossval = CrossValidator(estimator=pipeline, estimatorParamMaps=grid, evaluator=RegressionEvaluator(), numFolds=3) ``` ## 3 nodes ``` %%time fitted = crossval.fit(taxi) ``` ## Scale up to 10 nodes (how depends on where Spark cluster is running, need to restart kernal and run all cells) ``` %%time fitted = crossval.fit(taxi) ``` ## Scale up to 20 nodes (how depends on where Spark cluster is running, need to restart kernal and run all cells) ``` %%time fitted = crossval.fit(taxi) ```
github_jupyter
<a href="https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/manual_setup.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # T81-558: Applications of Deep Neural Networks **Manual Python Setup** * Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). # Software Installation This class is technically oriented. A successful student needs to be able to compile and execute Python code that makes use of TensorFlow for deep learning. There are two options for you to accomplish this: * Install Python, TensorFlow and some IDE (Jupyter, TensorFlow, and others) * Use Google CoLab in the cloud ## Installing Python and TensorFlow It is possible to install and run Python/TensorFlow entirely from your computer, without the need for Google CoLab. Running TensorFlow locally does require some software configuration and installation. If you are not confortable with software installation, just use Google CoLab. These instructions show you how to install TensorFlow for both CPU and GPU. Many of the examples in this class will achieve considerable performance improvement from a GPU. The first step is to install Python 3.7. As of August 2019, this is the latest version of Python 3. I recommend using the Miniconda (Anaconda) release of Python, as it already includes many of the data science related packages that are needed by this class. Anaconda directly supports Windows, Mac, and Linux. Miniconda is the minimal set of features from the extensive Anaconda Python distribution. Download Miniconda from the following URL: * [Miniconda](https://docs.conda.io/en/latest/miniconda.html) First, lets install Jupyter, which is the editor you will use in this course. ``` conda install -y jupyter ``` We will actually launch Jupyter later. You must make sure that TensorFlow has the version of Python that it is compatible with. The best way to accomplish this is with an Anaconda environment. Each environment that you create can have its own Python version, drivers, and Python libraries. I suggest that you create an environment to hold the Python instance for this class. Use the following command to create your environment. I am calling the environment **tensorflow**, you can name yours whatever you like. ``` conda create --name tensorflow python=3.7 ``` To enter this environment, you must use the following command: ``` conda activate tensorflow ``` For now, lets add Jupyter support to your new environment. ``` conda install nb_conda ``` We will now install TensorFlow. We will make use of conda for this installation. Unfortunately, different platforms are at different versions of TensorFlow. Currently (July 2020), the following versions are supported. * Google CoLab: 2.3 * Windows: 2.1 * Linux: 2.2 * Mac: 2.0 The examples in this course has been tested on all of these versions. The next two sections describe how to install TensorFlow for either a CPU or GPU. To use GPU, you must have a [compatible NVIDIA GPU](https://developer.nvidia.com/cuda-gpus). ## Install TensorFlow for CPU Only The following command installs TensorFlow for CPU support. Even if you have a GPU, it will not be used. ``` conda install -c anaconda tensorflow ``` ## Install TensorFlow for GPU and CPU The following command installs TensorFlow for GPU support. All of the complex driver installations should be handled by this command. ``` conda install -c anaconda tensorflow-gpu ``` ## Install Additional Libraries for ML There are several additional libraries that you will need for this course. This command will install them. Make sure you are still in your **tensorflow** environment. ``` conda env update --file tools.yml ``` The [tools.yml](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/tools.yml) file is located in the root directory for this GitHub repository. ## Register your Environment The following command registers your **tensorflow** environment. Again, make sure you "conda activate" your new **tensorflow** environment. ``` python -m ipykernel install --user --name tensorflow --display-name "Python 3.7 (tensorflow)" ``` ## Testing your Environment You can now start Jupyter notebook. Use the following command. ``` jupyter notebook ``` You can now run the following code to check that you have the versions expected. ``` # What version of Python do you have? import sys import tensorflow.keras import pandas as pd import sklearn as sk import tensorflow as tf print(f"Tensor Flow Version: {tf.__version__}") print(f"Keras Version: {tensorflow.keras.__version__}") print() print(f"Python {sys.version}") print(f"Pandas {pd.__version__}") print(f"Scikit-Learn {sk.__version__}") gpu = len(tf.config.list_physical_devices('GPU'))>0 print("GPU is", "available" if gpu else "NOT AVAILABLE") ```
github_jupyter
``` from os import listdir from keras.models import model_from_json from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from nltk.translate.bleu_score import sentence_bleu from tqdm import tqdm import numpy as np import h5py as h5py from compiler.classes.Compiler import * # Read a file and return a string def load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return text def load_data(data_dir): text = [] images = [] # Load all the files and order them all_filenames = listdir(data_dir) all_filenames.sort() for filename in (all_filenames)[-2:]: if filename[-3:] == "npz": # Load the images already prepared in arrays image = np.load(data_dir+filename) images.append(image['features']) else: # Load the boostrap tokens and rap them in a start and end tag syntax = '<START> ' + load_doc(data_dir+filename) + ' <END>' # Seperate all the words with a single space syntax = ' '.join(syntax.split()) # Add a space after each comma syntax = syntax.replace(',', ' ,') text.append(syntax) images = np.array(images, dtype=float) return images, text # Initialize the function to create the vocabulary tokenizer = Tokenizer(filters='', split=" ", lower=False) # Create the vocabulary tokenizer.fit_on_texts([load_doc('resources/bootstrap.vocab')]) dir_name = '../../../../eval/' train_features, texts = load_data(dir_name) #load model and weights json_file = open('../../../../model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("../../../../weights.hdf5") print("Loaded model from disk") # map an integer to a word def word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return None print(word_for_id(17, tokenizer)) # generate a description for an image def generate_desc(model, tokenizer, photo, max_length): photo = np.array([photo]) # seed the generation process in_text = '<START> ' # iterate over the whole length of the sequence print('\nPrediction---->\n\n<START> ', end='') for i in range(150): # integer encode input sequence sequence = tokenizer.texts_to_sequences([in_text])[0] # pad input sequence = pad_sequences([sequence], maxlen=max_length) # predict next word yhat = loaded_model.predict([photo, sequence], verbose=0) # convert probability to integer yhat = np.argmax(yhat) # map integer to word word = word_for_id(yhat, tokenizer) # stop if we cannot map the word if word is None: break # append as input for generating the next word in_text += word + ' ' # stop if we predict the end of the sequence print(word + ' ', end='') if word == '<END>': break return in_text max_length = 48 # evaluate the skill of the model def evaluate_model(model, descriptions, photos, tokenizer, max_length): actual, predicted = list(), list() # step over the whole set for i in range(len(texts)): yhat = generate_desc(model, tokenizer, photos[i], max_length) # store actual and predicted print('\n\nReal---->\n\n' + texts[i]) actual.append([texts[i].split()]) predicted.append(yhat.split()) # calculate BLEU score bleu = corpus_bleu(actual, predicted) return bleu, actual, predicted bleu, actual, predicted = evaluate_model(loaded_model, texts, train_features, tokenizer, max_length) #Compile the tokens into HTML and css dsl_path = "compiler/assets/web-dsl-mapping.json" compiler = Compiler(dsl_path) compiled_website = compiler.compile(predicted[0], 'index.html') print(compiled_website ) print(bleu) ```
github_jupyter
<a href="https://colab.research.google.com/github/pachterlab/CBP_2021/blob/main/notebooks/VMHNeurons/kimetal_smartseq_predictions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import requests import os from tqdm import tnrange, tqdm_notebook def download_file(doi,ext): url = 'https://api.datacite.org/dois/'+doi+'/media' r = requests.get(url).json() netcdf_url = r['data'][0]['attributes']['url'] r = requests.get(netcdf_url,stream=True) #Set file name fname = doi.split('/')[-1]+ext #Download file with progress bar if r.status_code == 403: print("File Unavailable") if 'content-length' not in r.headers: print("Did not get file") else: with open(fname, 'wb') as f: total_length = int(r.headers.get('content-length')) pbar = tnrange(int(total_length/1024), unit="B") for chunk in r.iter_content(chunk_size=1024): if chunk: pbar.update() f.write(chunk) return fname #SMART-seq VMH data #metadata.csv download_file('10.22002/D1.2067','.gz') #smartseq.mtx (log counts) download_file('10.22002/D1.2071','.gz') #smartseq.mtx (raw counts) download_file('10.22002/D1.2070','.gz') #gene names download_file('10.22002/D1.2068','.gz') os.system("gunzip *.gz") os.system("mv D1.2067 metadata.csv") os.system("mv D1.2071 smartseq.mtx") os.system("mv D1.2070 smartseqCount.mtx") os.system("mv D1.2068 gene_names.npy") !git clone https://github.com/pachterlab/CBP_2021.git !pwd !git clone https://github.com/joeytab/netAE.git !pip3 install --quiet torch !pip3 install --quiet anndata !pip3 install --quiet matplotlib !pip3 install --quiet scikit-learn !pip3 install --quiet torchsummary !pip install --quiet scanpy==1.7.0rc1 !pip3 install --quiet umap-learn==0.5.1 !pip3 install --quiet scvi-tools==0.11.0 %cd /content/CBP_2021/scripts ``` ## **Install Packages** ``` import anndata import pandas as pd import numpy as np from MCML import MCML #Now has continuous label addition import random import scvi from sklearn.decomposition import TruncatedSVD from sklearn.manifold import TSNE import matplotlib.pyplot as plt from sklearn.neighbors import NeighborhoodComponentsAnalysis, NearestNeighbors from sklearn.metrics import pairwise_distances from sklearn.metrics import accuracy_score from sklearn.preprocessing import scale import torch import time import scanpy as sc import seaborn as sns import umap from scipy import stats import scipy.io as sio sns.set_style('white') ``` ## **Import Data** ``` plt.rcParams["font.family"] = "sans-serif" plt.rcParams['axes.linewidth'] = 0.1 state = 42 ndims = 2 data_path = '../..' pcs = 50 n_latent = 50 count_mat = sio.mmread(data_path+'/smartseq.mtx') count_mat.shape raw_count_mat = sio.mmread(data_path+'/smartseqCount.mtx') raw_count_mat.shape #Center and scale data scaled_mat = scale(count_mat) meta = pd.read_csv(data_path+'/metadata.csv',index_col = 0) meta.head() clusters = np.unique(meta['smartseq_cluster'].values) map_dict = {} for i, c in enumerate(clusters): map_dict[c] = i new_labs = [map_dict[c] for c in meta['smartseq_cluster'].values] adata = anndata.AnnData(count_mat, obs = meta) adata.X = np.nan_to_num(adata.X) adata2 = anndata.AnnData(raw_count_mat, obs = meta) adata2.X = np.nan_to_num(adata2.X) def knn_infer(embd_space, labeled_idx, labeled_lab, unlabeled_idx,n_neighbors=50): """ Predicts the labels of unlabeled data in the embedded space with KNN. Parameters ---------- embd_space : ndarray (n_samples, embedding_dim) Each sample is described by the features in the embedded space. Contains all samples, both labeled and unlabeled. labeled_idx : list Indices of the labeled samples (used for training the classifier). labeled_lab : ndarray (n_labeled_samples) Labels of the labeled samples. unlabeled_idx : list Indices of the unlabeled samples. Returns ------- pred_lab : ndarray (n_unlabeled_samples) Inferred labels of the unlabeled samples. """ # obtain labeled data and unlabled data from indices labeled_samp = embd_space[labeled_idx, :] unlabeled_samp = embd_space[unlabeled_idx, :] from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=n_neighbors) knn.fit(labeled_samp, labeled_lab) pred_lab = knn.predict(unlabeled_samp) return pred_lab ``` ### **Test Cell Type Prediction Capabilities for Multiple Benchmarks** Also test accuracy for sex labels ``` lab1 = list(meta.smartseq_cluster) lab2 = list(meta.sex_label) lab3 = list(meta.medical_cond_label) lab4 = list(meta.smartseq_cluster_id) allLabs = np.array([lab1]) allLabs2 = np.array([lab1,lab2]) nanLabs = np.array([[np.nan]*len(lab1)]) #Shuffled labels for over-fitting check shuff_lab1 = random.sample(lab1, len(lab1)) shuff_lab2 = random.sample(lab2, len(lab2)) shuff_allLabs = np.array([shuff_lab1,shuff_lab2]) clus_colors = list(pd.unique(meta.smartseq_cluster_color)) sex_colors = ['#abacb7','#F8C471'] ``` First test 2D space predictions (t-SNE, UMAP, UMAP-Supervised) ``` ndims = 2 acc_score_2D = [] for i in range(3): reducer = umap.UMAP(n_components = ndims) tsne = TSNE(n_components = ndims) tsvd = TruncatedSVD(n_components=pcs) x_pca = tsvd.fit_transform(scaled_mat) pcaUMAP = reducer.fit_transform(x_pca) pcaTSNE = tsne.fit_transform(x_pca) #Partially labeled UMAP labels = np.array([lab4]).copy().astype(np.int8) train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) #0.7 for training fraction #Set 30% to no label (nan) unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = -1 pcaUMAPLab = reducer.fit_transform(x_pca,y=labels[0]) preds = knn_infer(pcaUMAPLab, train_inds, adata.obs.smartseq_cluster_id.values[train_inds], unlab_inds) acc = accuracy_score(adata.obs.smartseq_cluster_id.values[unlab_inds], preds) acc_score_2D.append(acc) preds = knn_infer(pcaUMAP, train_inds, adata.obs.smartseq_cluster_id.values[train_inds], unlab_inds) acc = accuracy_score(adata.obs.smartseq_cluster_id.values[unlab_inds], preds) acc_score_2D.append(acc) preds = knn_infer(pcaTSNE, train_inds, adata.obs.smartseq_cluster_id.values[train_inds], unlab_inds) acc = accuracy_score(adata.obs.smartseq_cluster_id.values[unlab_inds], preds) acc_score_2D.append(acc) print(acc_score_2D) from tqdm import tqdm #Need to intialize to stop tqdm errors tqdm(disable=True, total=0) # LDVAE accuracy scores scvi.data.setup_anndata(adata2, labels_key='smartseq_cluster_id') acc_score = [] acc_score2 = [] for i in range(3): vae = scvi.model.LinearSCVI(adata2,n_latent=n_latent) vae.train(train_size = 0.7) #train_size = 0.7 latent_ldvae = vae.get_latent_representation() lab_idx = vae.train_indices unlabeled_idx = [] for i in range(len(adata2)): if i not in lab_idx: unlabeled_idx.append(i) preds = knn_infer(np.array(latent_ldvae), list(lab_idx), adata2.obs.smartseq_cluster_id.values[lab_idx], unlabeled_idx) acc = accuracy_score(adata2.obs.smartseq_cluster_id.values[unlabeled_idx], preds) acc_score.append(acc) preds2 = knn_infer(np.array(latent_ldvae), list(lab_idx), adata2.obs.sex_label.values[lab_idx], unlabeled_idx) acc2 = accuracy_score(adata2.obs.sex_label.values[unlabeled_idx], preds2) acc_score2.append(acc2) print(acc_score) print(acc_score2) print(acc_score) print(acc_score2) # SCANVI accuracy scores scvi.data.setup_anndata(adata2, labels_key='smartseq_cluster_id') acc_score_scanvi = [] acc_score_scanvi2 = [] for i in range(3): vae = scvi.model.SCANVI(adata2, np.nan,n_latent=n_latent) vae.train(train_size = 0.7) latent_scanvi = vae.get_latent_representation() lab_idx = vae.train_indices unlabeled_idx = [] for i in range(len(adata2)): if i not in lab_idx: unlabeled_idx.append(i) preds = knn_infer(np.array(latent_scanvi), list(lab_idx),adata2.obs.smartseq_cluster_id.values[lab_idx], unlabeled_idx) acc = accuracy_score(adata2.obs.smartseq_cluster_id.values[unlabeled_idx], preds) acc_score_scanvi.append(acc) preds2 = knn_infer(np.array(latent_scanvi), list(lab_idx), adata2.obs.sex_label.values[lab_idx], unlabeled_idx) acc2 = accuracy_score(adata2.obs.sex_label.values[unlabeled_idx], preds2) acc_score_scanvi2.append(acc2) print(acc_score_scanvi) print(acc_score_scanvi2) print(acc_score_scanvi) print(acc_score_scanvi2) ``` Get labels for MCML Runs ``` # Reconstruction loss only acc_scoreR = [] acc_scoreR2 = [] for i in range(3): ncaR = MCML(n_latent = n_latent, epochs = 100) ncaR2 = MCML(n_latent = n_latent, epochs = 100) labels = np.array([lab1]).copy() train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) #0.7 for training fraction #Set 30% to no label (nan) unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan #2 labels labels2 = allLabs2.copy() labels2 = allLabs2[:, unlab_inds] = np.nan lossesR, latentR = ncaR.fit(scaled_mat,nanLabs,fracNCA = 0, silent = True,ret_loss = True) #labels toc = time.perf_counter() unlabeled_idx = [] for i in range(len(adata)): if i not in train_inds: unlabeled_idx.append(i) preds = knn_infer(latentR, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds) acc_scoreR.append(acc) preds2 = knn_infer(latentR, train_inds, adata.obs.sex_label.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.sex_label.values[unlabeled_idx], preds2) acc_scoreR2.append(acc2) # print(f"nnNCA fit in {toc - tic:0.4f} seconds") print(acc_scoreR) print(acc_scoreR2) ``` PCA 50D ``` # Reconstruction loss only acc_scorePCA = [] acc_scorePCA2 = [] for i in range(3): tsvd = TruncatedSVD(n_components=pcs) x_pca = tsvd.fit_transform(scaled_mat) labels = np.array([lab1]) train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan unlabeled_idx = [] for i in range(len(adata)): if i not in train_inds: unlabeled_idx.append(i) preds = knn_infer(x_pca, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds) acc_scorePCA.append(acc) preds2 = knn_infer(x_pca, train_inds, adata.obs.sex_label.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.sex_label.values[unlabeled_idx], preds2) acc_scorePCA2.append(acc2) # print(f"nnNCA fit in {toc - tic:0.4f} seconds") print(acc_scorePCA) print(acc_scorePCA2) ``` Check train/test 'overfitting' ``` nca = MCML(n_latent = n_latent, epochs = 100) labels = np.array([lab1]).copy() train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) #0.7 unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan lossesTrain, lossesTest = nca.trainTest(scaled_mat,labels, fracNCA = 1, silent = True) fig, axs = plt.subplots(1, lossesTrain.shape[1],figsize=(8,4)) for i in range(lossesTrain.shape[1]): axs[i].plot(lossesTrain[:,i],label=str(i)) axs[i].plot(lossesTest[:,i],label=str(i)) plt.legend() plt.show() ``` NCA MCML Below ``` # NCA loss only acc_scoreNCA = [] acc_scoreNCA2 = [] acc_scoreNCA3 = [] for i in range(1): #3 nca = MCML(n_latent = n_latent, epochs = 100) ncaR2 = MCML(n_latent = n_latent, epochs = 100) labels = np.array([lab1]).copy() train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) #0.7 unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan #2 labels labels2 = allLabs2.copy() labels2[:, unlab_inds] = np.nan losses, latent = nca.fit(scaled_mat,labels,fracNCA = 1, silent = True,ret_loss = True) losses2, latent2 = ncaR2.fit(scaled_mat,labels2,fracNCA = 1, silent = True,ret_loss = True) toc = time.perf_counter() unlabeled_idx = [] for i in range(len(adata)): if i not in train_inds: unlabeled_idx.append(i) preds = knn_infer(latent, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds) acc_scoreNCA.append(acc) preds2 = knn_infer(latent2, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds2) acc_scoreNCA2.append(acc2) preds2 = knn_infer(latent2, train_inds, adata.obs.sex_label.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.sex_label.values[unlabeled_idx], preds2) acc_scoreNCA3.append(acc2) # print(f"nnNCA fit in {toc - tic:0.4f} seconds") print(acc_scoreNCA) print(acc_scoreNCA2) print(acc_scoreNCA3) # fracNCA = 0.5 acc_scoreBoth = [] acc_scoreBoth2 = [] acc_scoreBoth3 = [] for i in range(3): #3 nca = MCML(n_latent = n_latent, epochs = 100) ncaR2 = MCML(n_latent = n_latent, epochs = 100) labels = np.array([lab1]).copy() train_inds = np.random.choice(len(scaled_mat), size = int(0.7*len(scaled_mat)),replace=False) #0.7 unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan #2 labels labels2 = allLabs2.copy() labels2[:, unlab_inds] = np.nan losses, latent = nca.fit(scaled_mat,labels,fracNCA = 0.3, silent = True,ret_loss = True) losses2, latent2 = ncaR2.fit(scaled_mat,labels2,fracNCA = 0.3, silent = True,ret_loss = True) toc = time.perf_counter() unlabeled_idx = [] for i in range(len(adata)): if i not in train_inds: unlabeled_idx.append(i) preds = knn_infer(latent, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds) acc_scoreBoth.append(acc) preds2 = knn_infer(latent2, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds2) acc_scoreBoth2.append(acc2) preds2 = knn_infer(latent2, train_inds, adata.obs.sex_label.values[train_inds], unlabeled_idx) acc2 = accuracy_score(adata.obs.sex_label.values[unlabeled_idx], preds2) acc_scoreBoth3.append(acc2) # print(f"nnNCA fit in {toc - tic:0.4f} seconds") print(acc_scoreBoth) print(acc_scoreBoth2) print(acc_scoreBoth3) fig, axs = plt.subplots(1, losses2.shape[1],figsize=(8,4)) for i in range(losses2.shape[1]): axs[i].plot(losses2[:,i],label=str(i)) plt.legend() plt.show() fig, axs = plt.subplots(1, losses.shape[1],figsize=(8,4)) for i in range(losses.shape[1]): axs[i].plot(losses[:,i],label=str(i)) plt.legend() plt.show() losses2 ``` ### **netAE Comparisons** ``` labs = np.zeros((adata.n_obs, 3)) labs[:, 0] = np.arange(len(adata)) labs[:, 1] = new_labs # 1st index is cluster # 2nd index is the cell_type, all undefined %cd /content/ data_netAE = np.concatenate((labs, adata.X), axis = 1) np.save("./dataset_matched.npy", data_netAE) # gene_names = genes["gene_name"].values.astype(str) # np.save("gene_names.npy", gene_names) from netAE import data dataset = data.Data(".") dataset.dataset.shape ! python3 /content/netAE/run.py #Same indices used by netAE labeled_index = [92, 30, 151, 223, 83, 75, 57, 32, 84, 20, 816, 43, 1, 48, 15, 101, 10, 13, 21, 82, 73, 49, 66, 79, 17, 29, 2, 0, 23, 38, 31, 5, 77, 35, 61, 58, 18, 26, 87, 28, 70, 47, 39, 27, 65, 7, 69, 80, 25, 12, 90, 391, 325, 573, 417, 365, 579, 302, 486, 602, 544, 627, 338, 841, 532, 336, 559, 381, 293, 310, 555, 976, 400, 264, 306, 584, 276, 523, 268, 551, 269, 594, 485, 33, 322, 612, 1028, 589, 497, 16, 439, 624, 385, 394, 471, 498, 651, 516, 451, 459, 605, 366, 531, 311, 1009, 484, 615, 354, 626, 475, 501, 613, 461, 890, 865, 509, 424, 512, 411, 347, 4, 591, 405, 634, 145, 309, 650, 625, 298, 543, 379, 496, 633, 1078, 646, 464, 403, 244, 610, 19, 356, 1092, 645, 517, 488, 323, 572, 421, 378, 63, 638, 502, 436, 510, 6, 788, 482, 853, 300, 467, 632, 331, 533, 278, 800, 519, 616, 528, 524, 226, 569, 319, 308, 328, 360, 397, 807, 455, 534, 294, 925, 321, 406, 428, 656, 609, 136, 908, 430, 55, 542, 447, 324, 393, 40, 489, 474, 571, 563, 1980, 814, 515, 601, 631, 577, 1046, 1086, 431, 355, 636, 500, 1071, 557, 376, 628, 297, 462, 811, 468, 289, 1977, 644, 469, 649, 363, 478, 481, 273, 858, 608, 422, 479, 505, 314, 427, 333, 606, 878, 274, 923, 408, 538, 470, 326, 1132, 549, 380, 487, 450, 412, 279, 932, 440, 545, 514, 582, 320, 399, 513, 617, 446, 511, 14, 284, 564, 635, 598, 270, 305, 404, 565, 806, 492, 280, 445, 477, 59, 472, 292, 444, 452, 283, 415, 614, 583, 586, 463, 508, 335, 595, 535, 353, 454, 236, 423, 53, 382, 888, 60, 550, 939, 332, 318, 437, 587, 296, 597, 599, 561, 494, 655, 623, 364, 522, 554, 604, 352, 54, 64, 568, 465, 611, 590, 301, 603, 621, 56, 849, 553, 162, 567, 315, 833, 850, 495, 619, 330, 466, 371, 575, 407, 37, 640, 637, 443, 945, 829, 946, 930, 926, 877, 827, 866, 934, 871, 921, 1003, 1012, 846, 840, 824, 1018, 2736, 1978, 855, 912, 961, 1020, 847, 891, 962, 935, 896, 1017, 859, 958, 844, 918, 346, 999, 795, 789, 1011, 951, 851, 970, 911, 803, 998, 808, 174, 940, 801, 813, 920, 981, 874, 792, 836, 812, 787, 815, 933, 842, 978, 937, 826, 968, 886, 857, 822, 916, 989, 1014, 882, 854, 2768, 956, 910, 810, 805, 1021, 994, 873, 828, 903, 703, 1005, 973, 986, 1284, 1004, 894, 953, 852, 898, 975, 861, 831, 897, 938, 1102, 821, 992, 839, 944, 988, 1308, 1010, 889, 834, 802, 980, 880, 837, 2683, 799, 862, 887, 965, 1006, 985, 825, 1998, 2061, 1053, 2050, 2016, 1949, 1954, 2067, 1911, 1950, 342, 1925, 1964, 1923, 2028, 2046, 2059, 2081, 1063, 1317, 373, 2014, 2002, 1944, 2074, 1969, 1057, 1066, 1979, 1972, 1048, 1113, 2042, 892, 1951, 2008, 1968, 2020, 1896, 1958, 1912, 2069, 1976, 341, 2048, 1956, 1957, 2043, 2060, 2019, 1920, 327, 1962, 1147, 1112, 2064, 1986, 2049, 2006, 2038, 1926, 1150, 1952, 2053, 868, 362, 1907, 2027, 1052, 1319, 1062, 2055, 1069, 334, 1999, 1981, 1140, 2070, 2025, 1044, 2041, 1136, 2073, 1153, 1937, 1995, 1918, 1910, 2079, 2035, 1906, 1930, 1967, 2004, 1984, 2034, 2063, 1922, 2047, 1868, 1943, 1924, 1946, 2078, 1975, 1050, 2021, 1953, 1941, 864, 369, 1914, 1067, 2052, 1933, 339, 1982, 1963, 2062, 1994, 2056, 1064, 2066, 1125, 1530, 2057, 1931, 2032, 2037, 1928, 2040, 2026, 1065, 1929, 2072, 1060, 1991, 2080, 1936, 1051, 156, 123, 180, 221, 258, 158, 229, 139, 200, 1960, 214, 188, 192, 172, 169, 249, 147, 251, 116, 166, 138, 98, 135, 242, 233, 155, 204, 1123, 248, 210, 126, 304, 901, 194, 252, 201, 128, 3595, 95, 142, 103, 99, 261, 199, 197, 243, 187, 108, 262, 182, 111, 141, 94, 206, 106, 150, 115, 193, 3522, 125, 100, 133, 114, 195, 140, 160, 218, 227, 149, 121, 1913, 241, 265, 165, 146, 1945, 216, 186, 113, 230, 196, 102, 157, 127, 255, 177, 97, 189, 263, 238, 208, 224, 171, 215, 144, 175, 234, 153, 130, 173, 205, 1942, 120, 219, 137, 209, 240, 250, 260, 168, 132, 107, 1993, 163, 212, 134, 2076, 105, 154, 167, 246, 256, 3603, 3530, 3541, 3657, 3566, 3567, 3692, 3582, 3561, 3624, 3486, 3678, 3685, 3687, 3674, 3495, 3570, 3517, 3698, 3520, 3596, 3612, 3610, 3502, 3515, 3598, 3498, 3592, 3673, 3680, 3568, 3511, 3491, 3588, 3654, 3663, 3626, 3591, 3474, 3510, 3574, 3581, 3523, 3514, 3538, 3481, 3645, 3682, 3583, 3664, 3543, 254, 3627, 3672, 3532, 3606, 3609, 3578, 3662, 3544, 3628, 3652, 3509, 3607, 3650, 3648, 3477, 3473, 3549, 3669, 3480, 3475, 3526, 3565, 3490, 3602, 3497, 3573, 3504, 3131, 3649, 3679, 3513, 3659, 3572, 3636, 3483, 3632, 3512, 3589, 3516, 3660, 3555, 3693, 3536, 3529, 3577, 3622, 3525, 3548, 3593, 3620, 3499, 3651, 3681, 3540, 3675, 3521, 3560, 3542, 3579, 3562, 3696, 3697, 3638, 3488, 3585, 3634, 3569, 3559, 3479, 3476, 3533, 3503, 3665, 3551, 3472, 3684, 3639, 3518, 3618, 3629, 3623, 3700, 3686, 3653, 3546, 3667, 3613, 3641, 3501, 3547, 3655, 3689, 3496, 3600, 3694, 3554, 3489, 3647, 3587, 674, 708, 737, 964, 707, 863, 699, 658, 668, 661, 775, 758, 762, 709, 870, 717, 693, 679, 722, 750, 676, 701, 764, 907, 368, 735, 702, 745, 746, 357, 666, 667, 697, 669, 748, 780, 694, 771, 723, 767, 731, 751, 724, 664, 766, 692, 909, 885, 681, 691, 720, 732, 396, 744, 695, 690, 361, 358, 716, 663, 725, 686, 350, 785, 743, 670, 791, 895, 769, 696, 736, 784, 683, 902, 773, 738, 755, 753, 662, 848, 763, 685, 659, 711, 714, 687, 959, 761, 706, 718, 786, 677, 675, 872, 869, 392, 757, 688, 742, 678, 689, 712, 778, 329, 779, 734, 749, 754, 1300, 2475, 375, 2388, 2321, 2024, 1302, 2474, 2425, 1313, 2460, 2382, 2452, 2463, 2466, 1289, 1318, 2308, 993, 2374, 1297, 1610, 2449, 2643, 1338, 2017, 1258, 2482, 1303, 2411, 372, 2291, 2472, 1283, 2297, 2423, 2428, 2445, 2430, 1334, 1293, 969, 1320, 2446, 2337, 2343, 2481, 1311, 1333, 2426, 2346, 1285, 2453, 2418, 776, 2387, 2442, 1295, 2290, 1287, 1296, 2415, 2310, 2359, 349, 2473, 1272, 351, 984, 2476, 2368, 2335, 2469, 2383, 1305, 1516, 1117, 1175, 1262, 1278, 1279, 1165, 1033, 1264, 1128, 1274, 1249, 1235, 1130, 1718, 1166, 1101, 1167, 1270, 1162, 1075, 1241, 1126, 1186, 1168, 1133, 1230, 2454, 1618, 3341, 1120, 1244, 1176, 1216, 1263, 3237, 1169, 1068, 1219, 1111, 1267, 398, 1161, 1254, 1256, 1259, 1231, 1619, 1118, 1232, 1280, 1072, 1220, 1218, 1199, 1204, 1277, 1237, 1243, 1144, 1188, 1173, 1119, 1644, 1106, 1149, 1154, 1100, 1192, 1201, 1251, 3316, 1238, 1185, 1208, 1268, 1137, 1131, 1214, 1127, 1081, 1159, 1138, 3336, 1194, 1250, 384, 1228, 1233, 1171, 1098, 390, 1247, 1080, 1143, 3308, 1184, 1190, 2516, 2563, 2553, 2569, 2595, 2590, 2600, 460, 2493, 2612, 2629, 2638, 2542, 2547, 2549, 2618, 414, 416, 2576, 2571, 2518, 2521, 2613, 2599, 2531, 2568, 2508, 2598, 2514, 448, 2523, 2634, 2533, 449, 2574, 2610, 2502, 2564, 3013, 2573, 2492, 2592, 2022, 453, 2821, 2058, 995, 990, 1180, 1476, 2819, 2324, 941, 530, 2681, 540, 2045, 1504, 2323, 1376, 1155, 1027, 3080, 3130, 2143, 996, 950, 3109, 768, 3211, 2280, 700, 947, 3045, 1037, 1030, 3230, 3182, 3197, 3196, 3086, 1026, 927, 1034, 1031, 1025, 1038, 1079, 1121, 3210, 1040, 3038, 3192, 1024, 3223, 952, 3078, 2742, 2781, 2694, 2716, 2702, 2686, 2756, 954, 2777, 2759, 2766, 2678, 2693, 2760, 2763, 2748, 2696, 2755, 966, 2722, 948, 3016, 2780, 2740, 2719, 2745, 2701, 2754, 2720, 2951, 2729, 2731, 2769, 2787, 2724, 2726, 2758, 2709, 2715, 2785, 2682, 2757, 2691, 2718, 2786, 2767, 2707, 2689, 997, 2749, 3002, 2690, 2974, 2970, 2700, 2706, 2979, 2770, 2746, 2685, 2684, 2778, 2730, 2695, 2413, 2713, 2703, 2762, 2735, 798, 2788, 2679, 928, 2773, 2150, 2962, 2739, 2728, 3018, 2743, 2697, 2752, 2712, 2727, 2783, 2089, 2088, 2113, 2130, 2101, 2092, 2110, 2175, 2127, 2155, 2139, 2170, 2141, 2179, 2082, 2119, 2105, 2087, 2123, 2129, 2107, 2135, 2108, 2174, 2172, 2145, 2148, 3050, 2091, 2151, 2083, 2160, 2171, 2311, 2095, 2479, 2085, 2398, 2096, 2104, 2116, 2293, 3187, 2164, 2165, 2178, 2109, 2134, 2813, 919, 2153, 2356, 2084, 2097, 2699, 2112, 2115, 2120, 2094, 2154, 2126, 2169, 2103, 2790, 2818, 2837, 2827, 2848, 2195, 2917, 2934, 2986, 2792, 2817, 2896, 2269, 2855, 2277, 2880, 2847, 2836, 2795, 2823, 2938, 2889, 3015, 2138, 2826, 2251, 2888, 2858, 2132, 2250, 2926, 2918, 2271, 2884, 3001, 2932, 2879, 2987, 2854, 2894, 2235, 2925, 2928, 2798, 2811, 2893, 2872, 2152, 2940, 2820, 2809, 2137, 2136, 2886, 2232, 2920, 2805, 2106, 2910, 2825, 2919, 2907, 2891, 2877, 3268, 2822, 2869, 2909, 2802, 2912, 2873, 2885, 2857, 2209, 3003, 2897, 2804, 2177, 2841, 2845, 2916, 3005, 2901, 2833, 2849, 2927, 2793, 2791, 2936, 2933, 2146, 2892, 2807, 2794, 2922, 2843, 2915, 955, 2866, 2875, 2881, 2824, 2883, 2447, 2405, 3439, 2240, 2432, 2274, 2238, 2444, 2279, 2477, 2286, 2403, 2535, 2131, 3464, 2503, 2276, 2417, 2622, 2298, 2566, 2596, 2602, 2603, 2189, 2632, 2494, 3426, 2336, 2371, 2386, 2212, 2604, 2244, 2354, 2325, 2436, 2220, 2252, 2435, 2234, 2264, 2621, 2262, 2379, 2353, 2366, 2465, 2114, 2307, 2431, 2299, 2289, 2201, 2205, 2219, 2190, 2320, 2246, 2501, 2223, 2419, 3207, 2582, 2263, 2532, 2303, 2313, 2192, 2266, 2215, 2319, 2488, 2499, 2344, 2214, 2397, 2424, 2221, 2186, 2239, 2422, 2627, 2196, 2295, 2268, 2360, 2333, 2412, 2218, 2247, 2315, 2548, 2273, 2318, 2102, 2462, 2392, 2440, 3422, 2624, 2572, 2249, 3446, 2302, 2451, 2551, 2369, 2585, 2623, 2203, 2272, 2329, 2649, 2558, 2433, 2437, 2283, 2429, 2224, 2515, 2347, 2616, 2339, 2188, 2260, 2349, 2322, 2506, 2225, 2637, 2275, 2534, 2377, 2384, 2464, 2467, 2421, 2305, 2380, 2390, 2233, 2561, 3036, 2478, 2228, 2181, 2455, 2396, 2284, 2557, 2443, 2207, 2552, 2401, 2528, 2182, 2194, 2507, 2345, 2361, 2187, 2580, 2614, 2202, 2191, 2306, 2402, 2222, 2285, 2237, 2441, 2253, 2180, 2243, 2483, 2519, 2597, 2459, 2578, 2206, 2471, 2267, 2198, 2278, 2497, 2389, 2608, 2332, 2316, 2439, 2365, 2304, 2505, 2480, 2236, 2241, 2589, 2254, 2342, 2529, 2294, 2400, 2512, 2406, 2555, 2185, 2217, 2211, 2434, 2399, 2199, 1073, 1087, 1108, 1105, 1076, 1058, 1083, 1142, 1152, 1094, 1115, 1139, 1122, 1061, 1109, 1074, 1134, 1082, 1088, 1124, 1085, 1740, 1898, 1798, 1859, 1743, 1885, 1890, 1861, 1897, 1843, 1205, 1889, 1748, 1871, 1755, 1255, 1894, 1741, 1865, 1832, 1816, 1802, 1851, 1615, 1769, 1880, 1344, 1791, 1886, 1795, 1768, 1736, 1224, 1867, 1790, 1806, 1882, 1845, 1181, 1829, 1774, 1746, 1900, 1197, 1797, 1833, 1786, 1815, 1817, 1110, 1756, 1846, 1849, 2504, 1762, 1878, 1887, 1847, 1793, 1735, 1765, 1737, 1808, 1873, 1191, 1179, 1792, 1883, 1196, 1183, 1751, 1841, 1223, 1825, 1269, 1904, 1731, 1156, 1836, 1856, 1739, 1875, 1813, 1854, 1198, 1870, 1738, 1807, 1742, 1780, 1819, 1760, 1754, 1799, 1826, 1750, 1773, 1814, 1864, 1394, 1866, 1893, 1764, 1877, 1747, 1785, 1767, 1804, 1787, 2550, 2567, 1821, 1215, 1810, 1852, 1794, 1784, 1195, 1187, 1757, 1730, 1888, 1776, 1178, 1830, 1803, 1892, 1744, 1837, 1899, 1879, 2636, 1850, 1869, 1771, 1872, 1891, 1520, 1772, 1903, 1265, 1823, 2538, 1779, 1217, 1862, 1812, 3239, 3250, 3328, 3251, 1276, 3298, 3327, 3339, 3243, 3276, 3272, 3286, 3292, 1174, 3345, 3249, 3264, 3023, 3275, 3257, 1172, 3347, 3271, 3296, 3269, 3288, 3252, 3262, 3324, 3256, 3302, 3343, 3320, 3318, 3246, 1212, 3329, 3321, 3310, 3287, 3342, 3255, 3261, 3314, 3283, 3241, 3325, 3306, 1206, 3338, 3247, 3274, 3242, 3248, 3319, 3258, 3317, 1095, 3303, 3322, 3279, 3281, 3305, 3334, 3224, 1164, 1246, 3340, 3295, 3285, 3332, 3299, 3253, 3267, 3395, 3392, 3386, 3403, 3405, 3459, 3385, 3414, 3364, 3391, 3462, 3346, 3351, 3354, 3417, 3421, 3365, 3457, 1273, 3450, 1275, 3419, 3416, 3368, 3371, 3373, 3425, 3381, 3469, 3361, 3468, 3445, 3406, 3438, 3382, 3350, 3418, 3443, 3360, 3409, 3404, 3456, 3412, 3353, 1389, 1509, 1382, 1550, 1359, 1365, 1383, 1560, 1573, 1405, 1393, 1440, 1569, 1372, 1499, 1990, 1575, 1288, 1361, 1384, 1561, 1445, 1497, 1535, 1456, 1987, 1360, 1409, 1589, 1584, 1471, 1331, 1403, 1424, 1536, 1414, 1578, 1562, 1378, 1466, 1556, 1438, 1489, 1375, 1459, 1321, 1363, 1766, 1312, 1522, 1349, 1367, 1475, 1527, 1398, 1558, 1391, 1301, 1653, 1496, 1455, 1352, 1422, 1567, 1464, 1364, 1473, 1423, 1540, 1553, 1525, 1434, 1437, 1396, 1420, 1539, 1345, 1485, 1416, 1537, 1511, 1447, 1460, 1298, 1444, 1492, 1315, 1373, 1446, 1433, 1425, 1478, 1427, 1646, 1544, 1563, 1415, 1508, 1395, 1487, 1493, 1299, 1528, 1417, 1564, 1495, 1316, 1307, 1432, 1379, 1451, 1598, 1429, 1481, 1347, 2011, 1324, 1354, 1421, 1290, 1501, 1579, 1436, 1362, 1555, 1402, 1532, 1348, 1529, 1336, 1671, 1965, 1443, 1505, 1435, 1612, 1385, 1548, 1397, 1463, 1428, 1498, 1513, 1310, 1358, 1353, 1340, 1327, 1449, 1547, 1309, 1483, 1531, 1369, 2068, 1523, 1477, 1512, 1426, 1482, 1514, 1648, 1400, 1480, 1500, 1570, 1552, 1467, 1533, 1545, 1351, 1401, 1551, 1691, 1346, 1453, 2001, 1408, 2010, 1543, 1590, 1616, 1622, 1659, 1721, 1519, 1625, 1713, 1631, 1592, 1697, 1680, 1582, 1649, 1585, 1665, 1627, 1729, 1596, 1620, 1617, 1673, 1684, 1368, 1677, 1580, 1700, 1651, 1335, 1577, 1674, 1613, 1583, 1719, 1663, 1706, 1641, 1652, 1688, 2409, 1568, 1685, 1587, 1599, 1716, 1704, 1724, 1666, 1609, 1366, 1350, 1675, 1541, 1699, 1604, 1328, 1632, 1624, 1698, 1672, 1661, 1702, 1640, 1709, 1621, 1693, 1720, 1601, 1692, 1660, 1678, 1650, 1521, 1710, 1683, 1603, 1507, 1635, 1638, 1695, 1728, 1679, 1630, 1642, 1574, 1594, 1591, 1714, 1726, 1412, 1607, 1595, 1701, 1636, 1694, 1304, 1657, 1662, 1667, 1623, 1669, 1502, 2647, 2674, 2797, 2981, 2948, 2605, 2856, 2996, 2976, 2651, 2671, 2963, 2640, 3040, 2642, 3007, 2956, 2815, 2655, 3011, 2968, 2969, 2966, 2527, 2800, 2639, 2935, 2953, 2498, 2631, 2905, 2670, 2641, 2949, 2942, 2985, 2984, 2992, 2874, 2947, 2628, 2967, 3012, 2959, 2657, 2667, 2829, 2814, 2540, 2960, 2672, 2666, 2524, 2510, 2994, 2626, 2867, 2662, 2490, 2955, 2676, 2983, 2853, 2876, 2941, 2903, 2673, 2988, 2971, 2659, 2871, 2975, 2929, 2950, 3009, 2607, 2993, 2964, 2661, 2601, 2831, 2838, 3008, 3017, 3019, 2812, 2859, 2999, 2652, 2648, 2997, 2995, 2537, 2958, 2664, 2946, 2654, 2665, 2834, 2978, 2213, 2900, 2924, 2954, 2943, 3032, 3027, 2692, 3134, 3150, 3035, 3094, 3120, 3075, 3047, 3204, 3191, 3135, 3093, 2668, 3240, 3082, 3068, 3026, 3124, 3034, 3143, 3219, 3073, 3311, 3208, 3146, 3152, 3114, 3176, 3149, 3337, 3218, 3309, 3092, 3101, 3181, 3122, 3057, 3209, 3174, 3021, 3069, 3059, 3072, 3097, 3227, 3159, 3169, 3178, 3140, 3194, 3085, 3335, 3132, 3331, 2410, 3102, 3277, 3020, 3064, 3312, 3171, 3148, 3236, 3087, 3062, 3041, 3044, 3039, 3119, 3049, 3025, 3216, 3221, 3133, 3053, 3156, 3128, 3104, 3189, 3028, 3116, 3202, 3184, 3162, 3056, 3037, 3063, 3043, 3144, 3079, 3061, 3076, 3195, 3095, 3220, 3190, 3106, 3300, 3200, 3074, 3088, 3212, 3107, 3051, 3198, 3168, 3030, 3058, 3052, 3060, 3081, 3180, 3139, 3165, 3175, 3126, 3167, 3066, 3233, 3113, 3225, 3022, 3173, 3089, 3142, 3217, 3029, 3222, 3138, 3215, 3070, 3103, 3136, 3213, 3436, 3411, 3448, 3235, 3429, 3380, 3393, 3379, 3428, 3460, 3401, 3447, 3232, 3355, 3228, 3352, 3388, 3394, 3357, 3466, 3110, 3458, 3111, 3434, 3431, 3359, 3362, 3366, 3430, 3461, 3423, 3376, 3390, 3455, 3432, 3410, 3453, 3377, 3229, 3433, 3454, 3349, 3415, 3407, 3465, 3500, 3646, 3644, 3616, 3666, 3507, 3531, 3642, 3643, 3727, 3750, 3753, 3823, 3795, 3714, 3768, 3835, 3819, 3729, 3747, 3808, 3721, 3849, 3723, 3840, 3802, 3759, 3732, 3844, 3813, 3814, 3811, 3706, 3754, 3720, 3787, 3799, 3703, 3719, 3783, 3746, 3722, 3796, 3789, 3827, 3826, 3831, 3775, 3794, 3717, 3812, 3845, 3805, 3734, 3744, 3760, 3758, 3709, 3806, 3748, 3743, 3705, 3704, 3833, 3716, 3773, 3739, 3702, 3801, 3752, 3825, 3767, 3776, 3788, 3782, 3749, 3828, 3815, 3736, 3774, 3818, 3786, 3797, 3842, 3715, 3832, 3809, 3738, 3713, 3762, 3765, 3841, 3847, 3848, 3757, 3769, 3838, 3730, 3728, 3836, 3834, 3708, 3804, 3741, 3793, 3731, 3742, 3763, 3821, 3691, 3780, 3785, 3800, 3790] netAE_embedded = np.load("./output/netVDCA_embd_space_cortex_full_0.npy") netAE_trained = np.load("./output/netVDCA_trained_cortex_full_0.pt") labeled_idx = labeled_index unlabeled_idx = [] for i in range(len(dataset.dataset)): if i not in labeled_idx: unlabeled_idx.append(i) lab_full = dataset.dataset[:, 1].astype(int) labeled_data = data_netAE[labeled_idx, :] labeled_lab = lab_full[labeled_idx] unlabeled_data = data_netAE[unlabeled_idx, :] unlabeled_lab = lab_full[unlabeled_idx] labeled_lab2 = adata.obs.sex_label.values[labeled_idx] unlabeled_lab2 = adata.obs.sex_label.values[unlabeled_idx] # import scipy.stats as st knn_netAE = knn_infer(netAE_embedded, labeled_idx, labeled_lab, unlabeled_idx) netAE_score = accuracy_score(unlabeled_lab, knn_netAE) knn_netAE2 = knn_infer(netAE_embedded, labeled_idx, labeled_lab2, unlabeled_idx) netAE_score2 = accuracy_score(adata.obs.sex_label.values[unlabeled_idx], knn_netAE2) print(netAE_score) print(netAE_score2) ``` ### **Save Analysis Output** ``` vals = pd.DataFrame() vals['Accuracy'] = acc_score + acc_score_scanvi + acc_scoreR + acc_scoreNCA + acc_scoreBoth + acc_score2 + acc_score_scanvi2 + acc_scoreR2 + acc_scoreNCA3 + acc_scoreBoth3 + acc_scoreNCA2 + acc_scoreBoth2 + acc_scorePCA + acc_scorePCA2 #+ netAE_score + netAE_score2 vals['Embed'] = ['LDVAE']*3 + ['SCANVI']*3 + ['Recon MCML']*3 + ['NCA 100% MCML']*1 + ['NCA-Recon MCML']*3 +['LDVAE']*3 + ['SCANVI']*3 + ['Recon MCML']*3 + ['NCA 100% MCML']*1 + ['NCA-Recon MCML']*3 + ['NCA 100% MCML']*1 + ['NCA-Recon MCML']*3 + ['PCA 50D']*3 + ['PCA 50D']*3 #+ ['netAE']*2 vals['Label'] = ['CellType1']*13 + ['Gender2']*13 + ['CellType2']*4 +['CellType1']*3 + ['Gender2']*3 #+ ['CellType1'] #+ ['Gender2'] vals from google.colab import files vals.to_csv('allSmartSeqPreds.csv') files.download('allSmartSeqPreds.csv') netAEvals = pd.DataFrame() netAEvals['Accuracy'] = [netAE_score] + [netAE_score2] netAEvals['Embed'] = ['netAE']*2 netAEvals['Label'] = ['CellType1'] + ['Gender2'] netAEvals from google.colab import files netAEvals.to_csv('netAESmartSeqPreds.csv') files.download('netAESmartSeqPreds.csv') ``` ### **Prediction Accuracy With Lower Percentages of Labeled Data** ``` #fracNCA = 0.3 acc_scoreBoth = [] percs = [0.7,0.6,0.5,0.4,0.3,0.2,0.1] for p in percs: nca = MCML(n_latent = n_latent, epochs = 100) ncaR2 = MCML(n_latent = n_latent, epochs = 100) labels = np.array([lab1]) train_inds = np.random.choice(len(scaled_mat), size = int(p*len(scaled_mat)),replace=False) unlab_inds = [i for i in range(len(adata)) if i not in train_inds] labels[:, unlab_inds] = np.nan #2 labels labels2 = allLabs2 labels2[:, unlab_inds] = np.nan losses, latent = nca.fit(scaled_mat,labels,fracNCA = 0.3, silent = True,ret_loss = True) toc = time.perf_counter() unlabeled_idx = [] for i in range(len(adata)): if i not in train_inds: unlabeled_idx.append(i) preds = knn_infer(latent, train_inds, adata.obs.smartseq_cluster.values[train_inds], unlabeled_idx) acc = accuracy_score(adata.obs.smartseq_cluster.values[unlabeled_idx], preds) acc_scoreBoth.append(acc) # print(f"nnNCA fit in {toc - tic:0.4f} seconds") lowPercsSmartSeq = pd.DataFrame() lowPercsSmartSeq['Accuracy'] = acc_scoreBoth lowPercsSmartSeq['Percent'] = percs lowPercsSmartSeq from google.colab import files lowPercsSmartSeq.to_csv('lowPercsSmartSeqPreds.csv') files.download('lowPercsSmartSeqPreds.csv') ```
github_jupyter
# Ax Service API with RayTune on PyTorch CNN Ax integrates easily with different scheduling frameworks and distributed training frameworks. In this example, Ax-driven optimization is executed in a distributed fashion using [RayTune](https://ray.readthedocs.io/en/latest/tune.html). RayTune is a scalable framework for hyperparameter tuning that provides many state-of-the-art hyperparameter tuning algorithms and seamlessly scales from laptop to distributed cluster with fault tolerance. RayTune leverages [Ray](https://ray.readthedocs.io/)'s Actor API to provide asynchronous parallel and distributed execution. Ray 'Actors' are a simple and clean abstraction for replicating your Python classes across multiple workers and nodes. Each hyperparameter evaluation is asynchronously executed on a separate Ray actor and reports intermediate training progress back to RayTune. Upon reporting, RayTune then uses this information to performs actions such as early termination, re-prioritization, or checkpointing. ``` import logging from ray import tune from ray.tune import track from ray.tune.suggest.ax import AxSearch logger = logging.getLogger(tune.__name__) logger.setLevel(level=logging.CRITICAL) # Reduce the number of Ray warnings that are not relevant here. import torch import numpy as np from ax.plot.contour import plot_contour from ax.plot.trace import optimization_trace_single_method from ax.service.ax_client import AxClient from ax.utils.notebook.plotting import render, init_notebook_plotting from ax.utils.tutorials.cnn_utils import load_mnist, train, evaluate init_notebook_plotting() ``` ## 1. Initialize client We specify `enforce_sequential_optimization` as False, because Ray runs many trials in parallel. With the sequential optimization enforcement, `AxClient` would expect the first few trials to be completed with data before generating more trials. When high parallelism is not required, it is best to enforce sequential optimization, as it allows for achieving optimal results in fewer (but sequential) trials. In cases where parallelism is important, such as with distributed training using Ray, we choose to forego minimizing resource utilization and run more trials in parallel. ``` ax = AxClient(enforce_sequential_optimization=False) ``` ## 2. Set up experiment Here we set up the search space and specify the objective; refer to the Ax API tutorials for more detail. ``` ax.create_experiment( name="mnist_experiment", parameters=[ {"name": "lr", "type": "range", "bounds": [1e-6, 0.4], "log_scale": True}, {"name": "momentum", "type": "range", "bounds": [0.0, 1.0]}, ], objective_name="mean_accuracy", ) ``` ## 3. Define how to evaluate trials Since we use the Ax Service API here, we evaluate the parameterizations that Ax suggests, using RayTune. The evaluation function follows its usual pattern, taking in a parameterization and outputting an objective value. For detail on evaluation functions, see [Trial Evaluation](https://ax.dev/docs/runner.html). ``` def train_evaluate(parameterization): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_loader, valid_loader, test_loader = load_mnist(data_path='~/.data') net = train(train_loader=train_loader, parameters=parameterization, dtype=torch.float, device=device) track.log( mean_accuracy=evaluate( net=net, data_loader=valid_loader, dtype=torch.float, device=device, ) ) ``` ## 4. Run optimization Execute the Ax optimization and trial evaluation in RayTune using [AxSearch algorithm](https://ray.readthedocs.io/en/latest/tune-searchalg.html#ax-search): ``` tune.run( train_evaluate, num_samples=30, search_alg=AxSearch(ax), # Note that the argument here is the `AxClient`. verbose=0, # Set this level to 1 to see status updates and to 2 to also see trial results. # To use GPU, specify: resources_per_trial={"gpu": 1}. ) ``` ## 5. Retrieve the optimization results ``` best_parameters, values = ax.get_best_parameters() best_parameters means, covariances = values means ``` ## 6. Plot the response surface and optimization trace ``` render( plot_contour( model=ax.generation_strategy.model, param_x='lr', param_y='momentum', metric_name='mean_accuracy' ) ) # `plot_single_method` expects a 2-d array of means, because it expects to average means from multiple # optimization runs, so we wrap out best objectives array in another array. best_objectives = np.array([[trial.objective_mean * 100 for trial in ax.experiment.trials.values()]]) best_objective_plot = optimization_trace_single_method( y=np.maximum.accumulate(best_objectives, axis=1), title="Model performance vs. # of iterations", ylabel="Accuracy", ) render(best_objective_plot) ```
github_jupyter
``` #code is used from these 3 repositories, have a look at them on GitHub or access the files from colab !git clone https://github.com/PeterWang512/FALdetector !git clone https://github.com/NVIDIA/flownet2-pytorch.git !git clone https://github.com/Kwanss/PCLNet #import necessary modules and append paths import random import os import csv import pickle import cv2 from PIL import Image import matplotlib.pyplot as plt import sys sys.path.append("/content/FALdetector/networks/") sys.path.append("/content/FALdetector/") from drn_seg import DRNSeg import torch from torch.autograd import Variable from torch.nn import Linear, ReLU, CrossEntropyLoss,BCELoss, Sequential, Conv2d, MaxPool2d, Module, Softmax, BatchNorm2d, Dropout from torch.optim import Adam, SGD sys.path.append("/content/flownet2-pytorch/") import losses from losses import MultiScale,EPE sys.path.append("/content/PCLNet/Losses/") sys.path.append("/content/PCLNet/models/") from utils.tools import * from utils.visualize import * import pandas as pd import numpy as np import torch.nn as nn # for reading and displaying images from skimage.io import imread # for creating validation set from sklearn.model_selection import train_test_split # for evaluating the model from sklearn.metrics import accuracy_score from tqdm import tqdm from skimage.transform import rescale, resize, downscale_local_mean from skimage import data, color from torchsummary import summary from skimage.util import random_noise from skimage.transform import rotate from google.colab import drive drive.mount('/content/gdrive') !ln -s /content/gdrive/My\ Drive/ /mydrive #!ls /mydrive !unzip /mydrive/nofakes/flow_pred_data/modified.zip -d modif !unzip /mydrive/nofakes/flow_pred_data/reference.zip -d ref !unzip /mydrive/nofakes/flow_pred_data/local_weight.zip -d weights pathM =r"/content/modif" path =r"/content/ref" import random #if you guys can come up with a more efficient way to do this go ahead. height, width = 400, 400 #variable to control how many training examples to import train_size = 3 batch_size = train_size filenames = [] #Redo this part.... it doesnt import training images in order, I have printed out the filenames imported for convenience # 23/01/21 added augmentation, convert PNG to JPG, and read files in order def createTrain(path, n_images): arr=[] count = 0 for root, dirs, files in os.walk(path, topdown=True): for name in files: #make sure to change to correct image format .jpg or .png etc... #print(count) if '.png' in name: #print(name) img = Image.open(r"" + path + "/" + str(name)) img.save(r"" + path + "/" + str(name) + ".jpg") if '.jpg' in name: #print(name) img = Image.open(r"" + path + "/" + str(name)) filenames.append(path + "/" + str(name)) #keep image dimensions at 400 for now, the following is image interpolation img_height, img_width = img.size #for the case where we don't shrink img = img.resize( (width, height)) arr.append(np.array(img)) count+=1 if count>=train_size: break return np.array(arr,dtype =np.uint8) X_ref=createTrain(path,train_size) X_mod = createTrain(pathM,train_size) print("the filenames are",filenames) shape = X_ref.shape print(shape) plt.imshow(X_ref[0]) print(X_ref[0]) flow_arr =[] #calcOptical gives an error if I input all training data at once (doesnt seem very efficient atm) for i in range(shape[0]): flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(X_ref[i],cv2.COLOR_BGR2GRAY), cv2.cvtColor(X_mod[i],cv2.COLOR_BGR2GRAY), None, 0.5, 3, 15, 3, 5, 1.2, 0) print(flow.shape) print(np.max(flow)) flow_arr.append(flow) print(X_mod.shape) flow_arr = np.array(flow_arr) mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1]) print(mag) print(mag.shape) path = "tester_before_train.png" tester = save_heatmap_cv(X_mod[0], mag, path) #print(flow) print("flow arr has shape",flow_arr.shape) #the code below is pretty similar to how the binary classifier is trained with a few changes #since the output shape is (2,height,width) for the vector field ``` **Discretize the flow fields** ``` categorical_flow =[] dic ={} inv_dic={} counter =0 #create a placeholder for the (u,v)->class pairs, hashmap is the easiest as its O(1) lookup time for the values #Note when obtaining flow values from classes it takes O(n) time to look up each one, not very efficient so #maybe re-do this part so that the hashmap key-value pairs are {class_pairs:(u,v)} #max and minimum allowed flow values max_f =5 min_f=-5 #fill up hashmap with values for i in range(min_f,max_f+1): for j in range(min_f,max_f+1): dic[i,j]=counter inv_dic[counter]=[i,j] counter+=1 dimens= flow_arr.shape #categorise the flow into distinct values print("CATEGORISING FLOW...") for flows in flow_arr: temp_flow =np.zeros((dimens[1],dimens[2])) for i in range(dimens[1]): for j in range(dimens[2]): value = flows[i][j] #makes sure we are not going over the max and min values if (value[1]>max_f or value[1]<min_f or value[0]>max_f or value[0]<min_f): continue temp_flow[i][j]=dic[int(value[0]),int(value[1])] categorical_flow.append(temp_flow) #convert into numpy array categorical_flow = np.array(categorical_flow) #Sanity check to make sure shapes add up #print(categorical_flow.shape) #print(categorical_flow[0][100]) print(torch.cuda.get_device_name(0)) #check if GPU is available cuda0 = torch.device('cuda:0') if torch.cuda.is_available(): device = 'cuda:{}'.format("0") else: device = 'cpu' temp = torch.randn(1, 3, 200, 200) temp = temp.cuda() #just add a tanh activation onto it perPix_model = DRNSeg(len(dic)).to(device) summary(perPix_model, (3, height, width)) !ls /content/weights/local_weight #perPix_model.load_pretrained(r"/content/weights/local_weight/local.pth") perPix_model.to(device) ``` **Training the Classifier** ``` #changed crossentropy to MSE since cross entropy needs classes, we arent doing classification #other losses might work much better from torch.utils.data import TensorDataset, DataLoader optimizer = Adam(perPix_model.parameters(),lr=0.07) criterion =torch.nn.MSELoss() criterion_classif = nn.CrossEntropyLoss() import torchvision.transforms as transforms tf = transforms.Compose([transforms.ToTensor()]) shape = X_mod.shape #criterion = MultiScale(model) if torch.cuda.is_available(): perPix_model =perPix_model.cuda() criterion = criterion.cuda() criterion_classif=criterion_classif.cuda() #convert to torch format train_x = X_mod print("train_x has shape",train_x.shape) train_x_orig=X_ref train_x = train_x.transpose(0,3,1,2) train_x_orig = train_x_orig.transpose(0,3,1,2) print("new train_x shape ius ",train_x.shape) train_x = torch.from_numpy(train_x) #train_x_orig = torch.from_numpy(train_x_orig).float() # converting the target into torch format train_y=flow_arr cat_shape = categorical_flow.shape print("categorical shape is",cat_shape) categorical_label=torch.from_numpy(categorical_flow) train_y = train_y.transpose(0,3,1,2) print("train_y has shape: ",train_y.shape) train_y = torch.from_numpy(train_y).float() print("xtrain shape",train_x.shape) print("y shape",categorical_label.shape) #MAIN CHANGE, dataloader so that batches can be trained, use batch size of 1 and then multiple pictures can be trained import math batch_loader_size = 3 my_dataset_categ = TensorDataset(train_x, categorical_label) # create your datset b_size = batch_loader_size my_dataloader_cat = DataLoader(my_dataset_categ,batch_size=b_size) #here is the batch version of the classification training function. Might be nice to add a counter to keep track of the epochs def batch_train_classif(epoch): correct =0 #epoch = 0 #iterate over batches for idx,(x_t,y_t) in enumerate(my_dataloader_cat): #epoch += 1 perPix_model.train() tr_loss = 0 if epoch%10 == 0: print("Batch n° : " + str(idx)) print("No of examples in batch : " + str(x_t.shape[0])) # getting the training set x_train, y_categorical = Variable(x_t), Variable(y_t) # converting the data into GPU format if torch.cuda.is_available(): x_train = x_train.cuda() y_categorical = y_categorical.cuda() optimizer.zero_grad() # prediction for training and validation set output_train = perPix_model(x_train.float()) #print("y has shape",y_categorical.shape) label_output = torch.argmax(output_train,dim=1) Loss = criterion_classif(output_train, y_categorical.long()) #print(label_output) #print("label output has shape",label_output.shape) correct = (label_output==y_categorical).sum().float()/(height*width*b_size) total = train_size #print(Loss) train_losses.append(Loss) # computing the updated weights of all the model parameters Loss.backward() optimizer.step() tr_loss = Loss.item() if epoch%10 == 0: # printing the validation loss print('Epoch : ',epoch+1, "for Batch:",idx, '\t', 'loss :',Loss.item(),"accuracy: ",correct.item()) #Check for existing checkpoint in content/, train additional epochs if found n_epochs_to_train = 100 train_losses =[] correct =0 #same parameters the FAL paper have used optimizer = Adam(perPix_model.parameters(),lr=0.0001,betas =(0.9,0.999)) checkpoint_path = r"checkpoint.pt" if os.path.exists(checkpoint_path): checkpoint = torch.load(checkpoint_path) perPix_model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) checkpoint_epoch = checkpoint['checkpoint_epoch'] train_losses = checkpoint['train_losses'] print("checkpoint loaded") print("checkpoint epoch:" + str(checkpoint_epoch)) else: checkpoint_epoch=0 print("No existing checkpoint found") for i in range(n_epochs_to_train): batch_train_classif(i) print("In this run, another "+str(n_epochs_to_train)+" epochs were trained") print("Total epochs model has been trained upon:" + str(checkpoint_epoch+n_epochs_to_train)) #Will overwrite existing checkpoints torch.save({ 'checkpoint_epoch': checkpoint_epoch+n_epochs_to_train, 'model_state_dict': perPix_model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'train_losses': train_losses }, checkpoint_path) print(checkpoint_epoch+n_epochs_to_train) ``` **plots the training loss** ``` print(len(train_losses)) iter = np.linspace(0,len(train_losses),len(train_losses)) plt.plot(iter,train_losses) plt.show() ``` **Training the regression, skip these blocks for now** ``` pretrained_dict = perPix_model.state_dict() modelR = DRNSeg(2) model_dict=modelR.state_dict() # filter out unnecessary keys pretrained_dict = {k: v for k, v in pretrained_dict.items() if (k in model_dict) and (model_dict[k].shape == pretrained_dict[k].shape)} model_dict.update(pretrained_dict) modelR.load_state_dict(model_dict) device = torch.device(cuda0) modelR.to(device) #the function below is very messy atm, im just happy that it works, it needs to be cleaned up though #it just converts and reshapes tensors to numpy arrays and vica versa during training for the recreational loss #creates the recreation loss, unwarps image and compares with the original image b_size=1 my_dataset_reg = TensorDataset(train_x,train_y) # create your datset my_dataloader_reg = DataLoader(my_dataset_reg,batch_size=b_size) loss = nn.MSELoss() def train_regress(epoch): for idx,(x_t,y_t) in enumerate(my_dataloader_reg): modelR.train() tr_loss = 0 # getting the training set x_train, y_train = Variable(x_t), Variable(y_t) x_train_orig=Variable(torch.from_numpy(train_x_orig)) # converting the data into GPU format if torch.cuda.is_available(): x_train = x_train.cuda() y_train = y_train.cuda() x_train_orig=x_train_orig.cuda() optimizer.zero_grad() output_train = modelR(x_train.float()).float() total = train_size MS_loss_train =loss(output_train, y_train.float()) loss_train=MS_loss_train train_losses.append(loss_train) # computing the updated weights of all the model parameters loss_train.backward() optimizer.step() tr_loss = loss_train.item() if epoch%10 == 0: # printing the validation loss print('Epoch : ',epoch+1, "for Batch:",idx, '\t', 'loss :',tr_loss) print("\n") n_epochs = 150 train_losses =[] correct =0 #same parameters the FAL paper have used optimizer = Adam(modelR.parameters(),lr=0.001,betas =(0.9,0.999)) for epoch in range(n_epochs): train_regress(epoch) from FALdetector.utils.visualize import * #function to def get_heatmap_cv(img, magn, max_flow_mag): min_flow_mag = 5 cv_magn = np.clip( 255 * (magn - min_flow_mag) / (max_flow_mag - min_flow_mag), a_min=0, a_max=255).astype(np.uint8) if img.dtype != np.uint8: img = (255 * img).astype(np.uint8) heatmap_img = cv2.applyColorMap(cv_magn, cv2.COLORMAP_MAGMA) heatmap_img = heatmap_img[..., ::-1] h, w = magn.shape img_alpha = np.ones((h, w), dtype=np.double)[:, :, None] heatmap_alpha = np.clip( magn / max_flow_mag, a_min=0, a_max=1)[:, :, None]**.7 heatmap_alpha[heatmap_alpha < .2]**.5 pm_hm = heatmap_img * heatmap_alpha pm_img = img * img_alpha cv_out = pm_hm + pm_img * (1 - heatmap_alpha) cv_out = np.clip(cv_out, a_min=0, a_max=255).astype(np.uint8) return cv_out def save_heatmap_cv(img, magn, path, max_flow_mag=2): cv_out = get_heatmap_cv(img, magn, max_flow_mag) out = Image.fromarray(cv_out) plt.imshow(out) plt.show() out.save(path, quality=95) return out from utils.tools import * from utils.visualize import * #quick sanity check again #print(flow.shape) #print(pic.size) ``` **uses training image to predict the flow field** ``` test_ref = X_ref[1] test_mod = X_mod[1] print(test_mod.shape) def load_data(img_path, device): face = Image.open(img_path).convert('RGB') face = face.resize((400,400)) face_tens = tf(face).to(device) return face_tens, face pathM ="/content/modif/ref_001.jpg" pathR ="/content/ref/ref_001.jpg" imgR, modified = load_data(r""+pathM, device) imgR_ref, reference = load_data(r""+pathR, device) test_ref= np.array(Image.open(r""+pathR).resize( (width, height))) test_mod= np.array(Image.open(r""+pathM).resize( (width, height))) plt.imshow(test_mod) plt.show() ground_flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(test_ref,cv2.COLOR_BGR2GRAY), cv2.cvtColor(test_mod,cv2.COLOR_BGR2GRAY),None, 0.5, 3, 4, 2, 3, 1.2, 0) image = np.array([test_mod]) shapes = image.shape print(shapes) image = np.transpose(image,(0,3,1,2)) print(image.shape) image_tensor = torch.from_numpy(image) image_tensor= Variable(image_tensor) # converting the data into GPU format if torch.cuda.is_available(): image_tensor = image_tensor.cuda() #ground_flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(test_ref,cv2.COLOR_BGR2GRAY), cv2.cvtColor(test_mod,cv2.COLOR_BGR2GRAY),None, 0.5, 3, 4, 2, 3, 1.2, 0) with torch.no_grad(): flow = perPix_model(image_tensor.float()).cpu().numpy() flow = np.argmax(flow,1) print("perpixel original shape",flow.shape) flow =flow[0] #print(flow.shape) #print(flow) real_flow = np.zeros((2,400,400)) temp =0 for i in range(shapes[1]): for j in range(shapes[2]): real_flow[:,i,j]=inv_dic[int(flow[i][j])] #print(real_flow.shape) np.set_printoptions(edgeitems=3) #print(real_flow) real_flow = np.transpose(real_flow, (1, 2, 0)) flow_reg = modelR(imgR.unsqueeze(0))[0].cpu().numpy() print(flow_reg.shape) print(flow_reg) flow_reg = np.transpose(flow_reg, (1, 2, 0)) print(flow_reg.shape) w, h, _ = real_flow.shape flow = flow_resize(flow_reg, modified.size) flow_categ = flow_resize(real_flow, modified.size) plt.imshow(modified) modified_np = np.array(modified) plt.show() mag, ang = cv2.cartToPolar(flow[:,:,1], flow[:,:,0]) mag_c, ang = cv2.cartToPolar(flow_categ[:,:,0], flow_categ[:,:,1]) path = "tester.png" tester =get_heatmap_cv(modified_np,mag,max_flow_mag=5) plt.title("Predicted modification") plt.imshow(tester) plt.show() tester2 =get_heatmap_cv(modified_np,mag_c,max_flow_mag=5) plt.title("Predicted modification categorical") plt.imshow(tester2) ``` **plots the ground truth heatmap on the image** ``` mag, ang = cv2.cartToPolar(ground_flow[...,0], ground_flow[...,1]) #print(mag.shape) real = get_heatmap_cv(np.array(reference),mag,max_flow_mag=12) plt.title("Ground truth modification") plt.imshow(real) model_path = r"model.pt" torch.save(model.state_dict(), model_path) ```
github_jupyter
## Data Centric ML Development using Snowflake and Amazon SageMaker This notebook guides you through a Data Centric machine learning (ML) development process using Snowflake and Amazon SageMaker. We demonstrate the use case through a credit-risk analysis use case. **What you will learn:** * How to use the Snowflake connector for Amazon SageMaker DataWrangler. * How to train a model using a AWS Marketplace algorithm, Autogluon. * How to enrich your ML dataset with data from the Snowflake Data Marketplace. * How to iterate on your model design and data prep flows with the provided tools. * How to deploy a production scoring pipeline. **How to run it:** This notebook was designed for Amazon SageMaker Studio, and to run on the Snowflake kernel that has been customized for this workshop. CloudFormation [templates](https://github.com/dylan-tong-aws/snowflake-sagemaker-workshops) have been provided for you to setup the workshop environment including the creation of the Snowflake SageMaker kernel. Refer to this [DockerFile](https://github.com/aws-samples/amazon-sagemaker-kernel-builder/blob/main/kernels/snowflake/Dockerfile) if you like to know what dependencies are baked into the kernel. The kernel is created and integrated using the [Amazon SageMaker Studio Kernel Builder solution](https://github.com/aws-samples/amazon-sagemaker-kernel-builder) **Have feedback?** <br> Contact: [Dylan Tong](mailto:dylatong@amazon.com) --- ### Pre-requisites 1. **Setup Environment** using the provided CloudFormation [templates](https://github.com/dylan-tong-aws/snowflake-sagemaker-workshops). You can use the following launch button if you haven't completed this step yet. <a href="https://console.aws.amazon.com/cloudformation/home?region=region#/stacks/new?stackName=snowflake-sagemaker-credit-risk-workshop&templateURL=https://snowflake-corp-se-workshop.s3.us-west-1.amazonaws.com/VHOL_Snowflake_Data_Wrangler/V2/cft/workshop-setup-no-studio.yml"/> ![Existing SageMaker Studio Environment](./images/deploy-to-aws.png) The button above will launch a CloudFormation template that creates IAM permissions, a Snowflake [Storage Integration](https://docs.snowflake.com/en/sql-reference/sql/create-storage-integration.html), and a custom Amazon SageMaker Studio Kernel that pre-installs libraries like the Snowflake Python Connector. The template automates a lot of functionality to simplify this workshop. You need to relog into Amazon SageMaker Studio to see the "snowflake-workshop" kernel. If you are running this lab with an existing Amazon SageMaker Studio environment, you should ensure that you're running the **latest versions of Amazon SageMaker Studio and DataWrangler**. This involves restarting the applications to force an upgrade. Follow the instructions provided in the **[documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tasks-update.html)**. 2. Run the following cells to import the required libraries and set the global variables. Make sure that your notebook is running in the "snowflake-workshop" kernel environment. If you made changes to the CFT also copy the name of the S3 bucket that will be used by SageMaker. <img src="./images/snowflake-kernel.png" align="left" width="70%"/> ``` import pandas as pd from IPython.display import Markdown as md import boto3 import sagemaker from sagemaker.s3 import S3Uploader from sagemaker import get_execution_role from sagemaker import AlgorithmEstimator, get_execution_role import utils.algo import utils.dw from workflow.pipeline import BlueprintFactory from utils.trust import ModelInspector sess = sagemaker.Session() role = get_execution_role() region = boto3.session.Session().region_name account_id = boto3.client('sts').get_caller_identity().get('Account') bucket = f"snowflake-sagemaker-{region}-{account_id}" ``` ### Step 1: Configure Permissions --- #### 1.1 Provide Access to [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) Later in this lab, you will need to provide database credentials. We need to provide your Amazon SageMaker Studio environment permission to access AWS Secrets Manager so that the credentials are stored securely. We do this by **attaching the [SecretsManagerReadWrite](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/SecretsManagerReadWrite$jsonEditor) managed policy** to your Amazon SageMaker Studio's execution role. The authentication method used in this lab requires your Amazon SageMaker environment to have access to [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/). If you provisioned this Amazon SageMaker Studio environment using the provided CloudFormation templates, this step has already been done for you. If not, run the following cell to generate a direct link to the IAM role and attach the managed policy. Your execution role should look like the following: <img src="./images/secret-manager-policy.png" align="left" width="65%"/> ``` rolename = get_execution_role().split("/")[-1] exec_role_url = f"https://console.aws.amazon.com/iam/home?#/roles/{rolename}" md(f"IAM console redirect: {exec_role_url}") ``` ### Step 2: Build your Data Prep Flow --- Next, we'll use the Snowflake connector for Data Wrangler to access our data and describe a pipeline that prepares our data for machine learning (ML) training. #### 2.1 Create a new Data Wrangler Flow <img src="./images/create-data-flow.png" width=30% align="left" img/> --- #### 2.2. Create a Snowflake Connection Select Snowflake from the data source dropdown. </br> <img src="./images/create-snowflake-connection.png" width=75% align="left" img/> Configure the connection with information about your account and storage integration. </br> Use the Storage Integration name identified in the Snowflake worksheet. You can use the Snowflake username and password, or you can use the AWS Secret that was created by the Snowflake Storage Integration CloudFormation Template. Copy the Secret ARN to paste in from the [Secrets Manager Console](https://console.aws.amazon.com/secretsmanager/home). </br> <img src="./images/configure-snowflake-connection.png" width=45% align="left" img/> --- #### 2.3 Explore your Snowflake Data 1. Select your data warehouse, database and schema. Warehouse - ML_WH; Database - ML_LENDER_DATA, Schema - ML_DATA 2. Run SELECT * FROM ML_LENDER_DATA.ML_DATA.LOAN_DATA_ML. The data set will be sampled by default. This data set consists of a year of loan data derived from [LendingClub](https://www.lendingclub.com/) data. It has been augmented with unemployment rate data provided by [Knoema](https://knoema.com/) from the [Snowflake Data Marketplace](https://www.snowflake.com/data-marketplace/). In this lab, we will demonstrate the data centric approach to improving machine learning model by showing how data from the Snowflake Marketplace can improve prediction performance. <img src="./images/query-and-explore-snowflake.png" width=80% align="left" img/> --- #### 2.4 Refine your Features With a bit of intuition and experience, you should be able to quickly spot some data columns that are unlikely to be good features. For instance, **LOAN_ID** is the unique identifier, and intuitively, we know that it has no meaningful correlation with loan defaults. On the other hand, **LOAN_AMNT** (*loan amount*) and **GRADE**, has potential. Large loans might bear greater risk. Similarly, we expect Grade F loans be riskier than Grade A ones. Thus, the former would help predict defaults. The machine learning algorithms can learn from these patterns and build a model that can predict the risk of defaults. **Run** the following query to acquire a filtered list of potential features. Next, click the **Import** button and name your training dataset. Note: - You also have the alternative option to drop columns as part of your DataWrangler data prep flow. - We're using Snowflake's sampling functionality to create a train/test set split. This query generates a repeatable 80% sampling of our data. **SELECT** </br> >LOAN_ID, </br> LOAN_AMNT, </br> FUNDED_AMNT, </br> TERM, </br> INT_RATE, </br> INSTALLMENT, </br> GRADE, </br> SUB_GRADE, </br> EMP_LENGTH, </br> HOME_OWNERSHIP, </br> ANNUAL_INC, </br> VERIFICATION_STATUS, </br> PYMNT_PLAN, </br> PURPOSE, </br> ZIP_SCODE, </br> DTI, </br> DELINQ_2YRS, </br> EARLIEST_CR_LINE, </br> INQ_LAST_6MON, </br> MNTHS_SINCE_LAST_DELINQ, </br> MNTHS_SINCE_LAST_RECORD, </br> OPEN_ACC, </br> PUB_REC, </br> REVOL_BAL, </br> REVOL_UTIL, </br> TOTAL_ACC, </br> INITIAL_LIST_STATUS, </br> MTHS_SINCE_LAST_MAJOR_DEROG, </br> POLICY_CODE, </br> LOAN_DEFAULT, </br> ISSUE_MONTH </br> **FROM** ML_LENDER_DATA.ML_DATA.LOAN_DATA_ML </br> sample block (80) REPEATABLE(100) --- #### 2.5 Profile your Data Data profiling and analysis is often a good place to start before you begin building your data preparation flow. Follow the steps illustrated by the video to create a histogram to analyze the distribution of loan defaults. **LOAN_DEFAULT** is the feature to plot. ![Loan Default Distribution](./images/create-histogram.gif) Typical of loan default data, the dataset is skew. There are less default cases than successful ones. Our analysis helps us confirm that the skew is manageable. An AutoML algorithm will apply the appropriate mitigation techniques for us. --- #### 2.6 Apply Feature Transforms There are features that require transformations before the data can be trained. Later on, you will use an AutoML algorithm to train a model. The algorithm automates a great deal of feature engineering. Nonetheless, there is some data preparation that cannot be automated. We will go through the exercise of using SageMaker DataWrangler to transform the **INT_RATE** column. First, select the tail of the flow and select **Add transform**. </br> </br> <img src=./images/create-transform.png width="60%" align="left"/> **INT_RATE** is an example of column that requires human input to properly process. This column is stored as a string type. ML algorithms only on numerical data. AutoML algorithms typically provide automation. They will detect string type columns and convert them accordingly. However, generally, they will assume that this column is categorical and apply [one-hot encoding](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-transform.html#data-wrangler-transform-cat-encode). This is the incorrect transformation and will render this feature useless. Instead, this feature should be treated as a continuous numerical feature. **TERM**, on the other hand, is seemingly similar but it could be left as a string. The dataset consists of 36 and 60 month terms. If you leave it as is, an AutoML algorithm will automically one-hot encode this column. Use the **"Search and Edit"** transform to remove the "%" sign from **INT_RATE** so that we can convert the column into numerical values. </br> <img src=./images/ft-search-replace.png width="70%" align="left"/> </br> Next, use the **"Parse column as type"** to convert the data column from **String** to **Float**. <img src=./images/ft-parse-type.png width="70%" align="left"/> --- The **VERIFICATION_STATUS** column has a minor data quality issue. This feature is effectively a boolean, but the verified status is represented as two values. This transformation requires custom logic. In such cases, we can run a custom script using a **Custom Transform**. Copy the following PySpark script: from pyspark.sql.functions import udf from pyspark.sql.types import LongType def categories(status) : if not status : return None elif status == "not verified" : return 0 elif status == "VERIFIED - income": return 1 elif status == "VERIFIED - income source": return 1 else : return None bucket_udf = udf(categories, LongType()) df = df.withColumn("VERIFIED", bucket_udf("VERIFICATION_STATUS")) Apply the script by creating a **Custom Transform** as shown below: <img src=./images/ft-custom-transform.png width="65%" align="left"/> Since we created a new column we need to delete the source. Select **Manage columns** and apply the following settings: **Transform:** Drop column </br> **Column to Drop:** VERIFICATION_STATUS </br> <img src=./images/drop-column-vstatus.png width="65%" align="left"/> --- Finally, drop the **LOAN_ID** column. This is a unique identifier for each loan. It will only add noise to the training data. Select **Manage columns** and apply the following settings: **Transform:** Drop column </br> **Column to Drop:** LOAN_ID </br> <img src="images/ft-drop-loanid.png" width="35%" align="left"/> --- Click on **"back to data flow"**. You should see the five transforms steps at the tail of your data prep flow. <img src=./images/flow-w-transforms.png width="65%" align="left"/> --- #### 2.7 Data Validation It is best practice to perform data validation before model training. DataWrangler provides useful reports to faciliate data bias and target leakage analysis. Our use case, loan default prediction, has legal and ethical risk considerations. For instance, [data bias](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-analyses.html#data-wrangler-bias-report) can result in models that could put certain demographics at a disadvantage. For instance, a loan default model could unfairly reject a disproportionate number of minority group loan applications without merit as a consequence of training on flawed data. You also want to avoid [target leakage](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-analyses.html#data-wrangler-analysis-target-leakage). Target leakage occurs when you accidently train a model with features that are not available in production. As a consequence, you end up with a deceptively effective model in development that causes problems in production. You can mitigate production issues by performing target leakage analysis. Create a Target Leakage report as demonstrated by the video below. Use the following settings: - **Max features:** 30 - **Problem Type:** Classification - **Target:** LOAN_DEFAULT ![Target Leakage Report](./images/target-leakage-report.gif) The report indicates that there is no target leakage risk. It does detect some potentially redundant features. The AutoML algorithm that you will use will mitigate redundant features. As an optional exercise, you can run experiments and determine whether these potentially redundant features effect model performance. <img src=./images/target-leakage-results.png width="65%" align="left"/> --- Create a Bias Report as demonstrated by the following video. Use the following settings: - **Select the column your model predicts (target):** LOAN_DEFAULT - **Is your predicted column a value or threshold?:** Value - **Predicted value(s):** 0;1 - **Select the column to analyze for bias:** ZIPS_CODE - **Is your column a value or threshold?:** Value - **Column value(s) to analyze for bias:** 200xx;207xx;206xx;900xx;100xx;941xx ![Bias Report](./images/create-bias-report.gif) Our data does not have any obvious sensitive attributes like gender and race. However, it does contain zip codes. It's possible that we have a flawed dataset with an abnormal number of loan defaults in minority communities. This might not represent the actual distribution. Regardless, this situation could create a model that is biased against minorities resulting in legal risk. The report does not reveal any salient data bias issues. <img src=./images/bias-report-results.png width="65%" align="left"/> --- ### Step 3: Prototype your Model Amazon SageMaker provides a broad range of remote training services that can help you scale your ML experimentation, training and tuning process. But before you commit to a long running process, it maybe desireable to explore different combinations of candidate features and be able to rapidly iterate on a few prototypes. #### 3.1 Create a Quick Model Report Amazon Data Wrangler provides a **[Quick Model](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-analyses.html#data-wrangler-quick-model)** report which can serve as a prototyping mechanism. The report will sample your dataset, process your flow and generates a Random Forest Model. The report provides model and feature importance scores to help you assess: * What features are most impactful? * Does your data have enough predictive signals to produce a practical model? * Are your changes to your dataset leading to improvements? Navigate to the Analysis panal from the tail end of your flow—as you did in the previous section. Configure your report: * **Analysis type:** Quick Model * **Analysis name:** Quick Test * **Label:** LOAN_DEFAULT It will take about 5 minutes to generate a report like the following: <img src="./images/quick-model-iter1.png" width="65%" align="left"/> Take note of the feature importance ranking in the bar chart. This gives you an *approximation* of which features have strong predictive signals. The F1 score of <span style="color:yellow">**0.691**</span> is not great. However, you can expect better results with a complete training and tuning process. The score tells you that your dataset has potential to produce a practical model. --- ### Step 4: Iterate, Experiment and Improve You can improve your model's performance through further feature engineering and improvements to your dataset. Next, you will do just that by enriching your dataset with data obtained from the Snowflake's Data Marketplace. In the following sections, we'll be modifying our existing flow. In practice, you should version control your .flow files first through the [Git integration](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html) #### Step 4.1 Explore and Extract Candidate Features from the Data Marketplace Add a new data source to your existing flow. Select the **Import** sub tab and click on the Snowflake icon. Run the following query to extract the unemployment rate data that you obtained from the [Snowflake Data Marketplace](https://www.snowflake.com/data-marketplace/). **SELECT** >UNEMPLOYMENT_RATE, </br> LOAN_ID </br> **FROM** ML_LENDER_DATA.ML_DATA.UNEMPLOYMENT_DATA --- #### Step 4.2 Augment your Dataset Next, you're going to merge the two datasets. There are many ways to do this. You could have perform this entirely using Snowflake. In this lab, you'll learn how to perform this merge through DataWrangler. This method provides you with a visualization of the modified flow and the change can be version control within your Git repository. First, **Delete** the last transformation from the original flow, so that we have **LOAN_ID** available in the original dataset. ![Delete Step](./images/delete-step.gif) Next, replicate the steps in the following video to merge the unemployment rate feature into your dataset. 1. Click on the end of the original flow and select the **Join** operator. 2. Select the other flow. 3. Select **Left Outer** as the **Join Type**. 4. Select **LOAN_ID** for both the **Left** and **Right** join keys. ![Join Datasets](./images/join-and-enrich-flow.gif) Finally, discard the join keys. Same as before, use the **Manage columns** transform to drop columns. 1. Select the Join node and **Add transform**. 2. Drop the columns, **LOAN_ID_0** and **LOAN_ID_1**. <img src="./images/ft-drop-loanid0.png" width="35%" align="left"/> <img src="./images/ft-drop-loanid1.png" width="35%" align="left"/> --- #### Step 4.3 Re-validate your Dataset You should re-validate your dataset since it has been modified. The Target Leakage report calculates the correlation between your features and the target variable. In effect, it provides you with an idea of how likely your new feature will improve your model. The report should present the new feature, **UNEMPLOYMENT_RATE**, as the feature with the highest predictive potential. <img src="./images/target-leakage-report-w-unemployment.png" /> --- #### Step 4.4 Evaluate your Dataset Modifications Next, we're going to evaluate whether our new feature is beneficial. We will use the Quick Model report again to get a quick assessment. Note that in practice, you might want to be more thorough and fully train and tune a model on some your dataset iterations so that you have a reliable baseline. For the sake of demonstration, we use the Quick Model report exclusively. Create a new **Quick Model** report to assess the impact of your modifications. The results should be similiar to the following: <img src="./images/quick-model-iter2.png" width="65%" align="left"/> A couple of key takeaways: * UNEMPLOYMENT_RATE is clearly ranked as the most important feature. * The F1 score increased to <span style="color:lightgreen">**0.784**</span> from 0.691. This tells us that we are likely heading in the right direction. We added a feature that generated noteable improvements to the "quick model" and the new feature had the greatest impact. --- ### Step 5: Generate your Dataset We are now ready to fully train and tune a model. First, we need to generate our datasets by executing the data flow that we've created. #### 5.1 Export Your Data Flow DataWrangler supports multiple ways to [export](https://docs.aws.amazon.com/sagemaker/latest/dg/data-wrangler-data-export.html) the flow for execution. In this lab, you will select the option that generates a notebook that can be run to execute the flow as a [SageMaker Processing](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html) job. This is the simplest option. The other options offer capabilities that you might value in production deployments. Follow steps as demonstrated in the following video. ![Export Script](./images/data-flow-export.gif) --- #### 5.2 Execute the Data Flow * Follow the steps outlined in the **generated notebook**. * **Run the cells and wait for the processing job to complete**. * Copy the output S3 URI of the processed dataset. The S3 URI will look similar to: *s3://(YOUR BUCKET)/export-flow-23-23-17-34-6a8a80ec/output/data-wrangler-flow-processing-23-23-17-34-6a8a80ec*. Set the variable **PREP_DATA_S3** in the following cell to that S3 URI. ``` PREP_DATA_S3 = "s3://sagemaker-eu-west-2-407247006381/export-flow-27-22-43-24-b21b61bd/output/data-wrangler-flow-processing-27-22-43-24-b21b61bd" ``` --- ### Step 6: Train Your Model #### 6.1 Subscribe to AutoGluon in the AWS Marketplace Next, you are going to subscribe to the AutoGluon Marketplace algorithm. This provides your account access to a SageMaker compatible container for running AutoGluon. This Marketplace algorithm is managed by AWS and doesn't have additonal software costs. Marketplace algorithms are similar to SageMaker built-in algorithms. Once subscribed, you can run the algorithm to train and serve models with "low-to-no-code". Follow these steps to subscribe to the AWS Marketplace AutoGluon algorithm: 1. Click **[this URL](https://aws.amazon.com/marketplace/pp/Amazon-Web-Services-AutoGluon-Tabular/prodview-n4zf5pmjt7ism)** to navigate to the AutoGluon product page. 2. Select the orange "Continue to Subscribe" button. 3. Run the helper function below to identify the AWS resource ID (ARN) of your AutoGluon Marketplace algorithm. ``` AUTOGLUON_PRODUCT = "autogluon-tabular-v3-5-cb7001bd0e8243b50adc3338deb44a48" algorithm_arn = utils.algo.get_algorithm_arn(region, AUTOGLUON_PRODUCT) print("The Tabular AutoGluon ARN in your region is {}.".format(algorithm_arn)) ``` Next, we'll configure our algorithm for remote training (Note: you can configure and launch the job using the AWS console as an alternative to the SDK). 1. **Hyperparamters**: AutoML algorithms like AutoGluon are designed to automate hyperparameter tuning using hyperparamter search algorithms like Bayesian Optimization. Thus, setting hyperparameters are optional. However, you can override the defaults. We'll use the default configurations in this lab, so we only need to identify the name of the target label column. The other configurations are commented out and serve as examples. 2. **Infrastructure**: We're using SageMaker's remote training service, so we need to specify the infrastructure to allocate. Since we're using a Marketplace product, we need to be aware of the subset of supported instances. 3. **Data**: lastly, we need to identify the location of our training data. ``` hyperparameters = { "init_args":{ "label": "LOAN_DEFAULT" } } data_uri = utils.dw.get_data_uri(PREP_DATA_S3) compatible_training_instance_type='ml.m5.4xlarge' s3_input_train = sagemaker.inputs.TrainingInput(s3_data=data_uri, content_type='csv') autogluon_model = AlgorithmEstimator(algorithm_arn=algorithm_arn, role=role, instance_count=1, instance_type=compatible_training_instance_type, sagemaker_session=sess, base_job_name='autogluon', hyperparameters=hyperparameters, train_volume_size=100) ``` Executing the next cell will launch the remote training job. ``` autogluon_model.fit({'training': s3_input_train}) ``` --- Review the output generated by the training job. The top performing model generated by Autogluon should, again, be the WeightedEnsemble. Your model's AUC score on the validation set should be in the vicinity of <span style="color:lightgreen">**0.89817**</span>. If you had created a baseline model with the previous dataset version, you would have obtained an AUC score around 0.843707. Thus, the data enrichment yielded significant improvements over the baseline. --- ### Step 7: Deploy You can serve your predictions in a couple of ways. You could deploy the model as a [real-time hosted endpoint](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-deployment.html) on SageMaker and integrate it with Snowflake as an [External Function](https://docs.snowflake.com/en/sql-reference/external-functions-creating-aws.html). This will enable you to query your predictions in real-time and minimize data staleness. Alternatively, you can pre-calculate your predictions as a transient batch process. In the following section, you will use [Batch Transform](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html) to do just that. When your use case allows you to pre-calculate predictions, Batch Transform is a good option. Batch Transform design to scale-out and is optimized for throughput while the real-time endpoints are designed for low latency. Generally, Batch Transform is the cost efficient option as you are only charged for the resources used by the transient batch job. You should run your Batch Transform job as part of an automated workflow in production. In the following sections we are going to deploy our model as a batch inference pipeline. The pipeline is designed to consume data from Snowflake, process it using our DataWrangler flow and then pre-calculate predictions using our trained model and Batch Transform. --- #### Step 7.1 Modify your Data Prepartion flow for Inference You are going to use your model to generate predictions and a credit risk score on unseen data. You can re-use your data preparation flow, but you will need to update your data source. * Make a copy of your flow file. In practice, you should also commit this to version control. * Assign **INFERENCE_FLOW_NAME** with the name of your *.flow* file and run the following cell. ``` INFERENCE_FLOW_NAME = "inference_flow_loan.flow" ``` Next edit the query for your loan origination data source. We will use the 20% data sample that we held out for the purpose of demonstration. The query is as follows. **SELECT** </br> &nbsp; L1.LOAN_ID, </br> &nbsp; L1.LOAN_AMNT, </br> &nbsp; L1.FUNDED_AMNT, </br> &nbsp; L1.TERM, </br> &nbsp; L1.INT_RATE, </br> &nbsp; L1.INSTALLMENT, </br> &nbsp; L1.GRADE, </br> &nbsp; L1.SUB_GRADE, </br> &nbsp; L1.EMP_LENGTH, </br> &nbsp; L1.HOME_OWNERSHIP, </br> &nbsp; L1.ANNUAL_INC, </br> &nbsp; L1.VERIFICATION_STATUS, </br> &nbsp; L1.PYMNT_PLAN, </br> &nbsp; L1.PURPOSE, </br> &nbsp; L1.ZIP_SCODE, </br> &nbsp; L1.DTI, </br> &nbsp; L1.DELINQ_2YRS, </br> &nbsp; L1.EARLIEST_CR_LINE, </br> &nbsp; L1.INQ_LAST_6MON, </br> &nbsp; L1.MNTHS_SINCE_LAST_DELINQ, </br> &nbsp; L1.MNTHS_SINCE_LAST_RECORD, </br> &nbsp; L1.OPEN_ACC, </br> &nbsp; L1.PUB_REC, </br> &nbsp; L1.REVOL_BAL, </br> &nbsp; L1.REVOL_UTIL, </br> &nbsp; L1.TOTAL_ACC, </br> &nbsp; L1.INITIAL_LIST_STATUS, </br> &nbsp; L1.MTHS_SINCE_LAST_MAJOR_DEROG, </br> &nbsp; L1.POLICY_CODE, </br> &nbsp; L1.LOAN_DEFAULT, </br> &nbsp; L1.ISSUE_MONTH </br> **FROM** ML_LENDER_DATA.ML_DATA.LOAN_DATA_ML **AS** L1 </br> &nbsp;**LEFT OUTER JOIN** </br> &nbsp;(**SELECT** * FROM ML_LENDER_DATA.ML_DATA.LOAN_DATA_ML **sample block (80) REPEATABLE(100)**) **AS** L2 </br> &nbsp;**ON** L1.LOAN_ID = L2.LOAN_ID </br> **WHERE** L2.LOAN_ID **IS NULL** </br> The following video demonstrates how to modify your query. ![Edit Query](./images/flow-edit-query.gif) ### Step 7.2 Re-export and Re-factor your Flow as a Pipeline Your goal is to deploy a credit-risk scoring pipeline into production. DataWrangler provides the option to deploy your flow as an Amazon SageMaker Pipeline to facilitate this: <img src="./images/export-flow-as-pipeline.png" width="40%" align="left"/> In practice, you will need to refactor the exported script. This has been done for you, so all you need to do is find locate the export node-id. Each step in your data flow is a unique node and the export script is dependent on the node that you select for export. The node id should look like the image below. Copy your node id, assign **FLOW_NODE_ID** to this value and run the following cell. <img src="./images/export-node-id.png" width="60%" align="left"/> ``` FLOW_NODE_ID = "69f2fb1a-2043-41d9-b2fa-5ec328a027e9.default" ``` Run the following cell if you like to view the refactored script. The exported pipeline script has been refactored such that it runs a Batch Transform job after the data preparation processing job to generate the credit-risk scores. ``` !pygmentize "./workflow/pipeline.py" ``` Run the following cell to execute your batch scoring pipeline. ``` batch_output_prefix = "batch/out" batch_s3_output_uri = f"s3://{bucket}/{batch_output_prefix}" config = { "dw_output_name" : FLOW_NODE_ID, "dw_instance_count" : 1, "dw_instance_type" : "ml.m5.4xlarge", "dw_flow_filepath" : "", "dw_flow_filename" : INFERENCE_FLOW_NAME, "dw_volume_size_in_gb" : 30, "dw_output_content_type" : "CSV", "dw_enable_network_isolation" : False, "dw_source_bucket" : bucket, "batch_instance_type" : "ml.c5.2xlarge", "batch_instance_count" : 1, "batch_s3_output_uri" : batch_s3_output_uri, "wf_instance_type" : "ml.m5.4xlarge", "wf_instance_count" : 1, "sm_estimator" : autogluon_model, } bpf = BlueprintFactory(config) pipeline = bpf.get_batch_pipeline() execution = pipeline.start() execution.wait() ``` --- You can monitor the status of your pipeline from Amazon SageMaker Studio. The following video demonstrates how to do this. ![Pipeline Status](./images/pipeline-status.gif) The credit-risk prediction data is small enough for us to load into a local pandas dataframe. Run the following cell to preview the results. ``` threshold = 0.5 output_uri = utils.dw.get_data_uri(batch_s3_output_uri) results = pd.read_csv(output_uri, header=None, names=["label","probas"]) results[["p_default"]] = pd.DataFrame(results["probas"].str[1:-1].str.split(",", expand=True)[1].astype(float)) results["predictions"] = (results["p_default"] > threshold).astype(int) cols = ["label","predictions","p_default"] results_file = "results.csv" results_prefix = "results" results.to_csv(path_or_buf=results_file, columns = cols, index=False) S3Uploader.upload(results_file, f"s3://{bucket}/{results_prefix}") results[cols] ``` We used our hold-out test set to generate the scores. Let's evaluate our model performance with the provided utilities. ``` inspector_params = { "workspace": bucket, "drivers":{ "db": boto3.client("s3"), "dsmlp": boto3.client("sagemaker"), }, "prefixes": { "results_path": results_prefix, "bias_path": None, "xai_path": None, }, "results-config":{ "gt_index": 0, "pred_index": 2, } } inspector = ModelInspector.get_inspector(inspector_params) %matplotlib inline inspector.display_interactive_cm() ``` --- Lastly, we're going to use the Snowflake Python connector to load our predictions into Snowflake to drive credit-risk analysis. This is only practical for smaller data sets. For larger data sets the Snowflake [COPY](https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html) command can be used to load data directly from S3. In practice, the process of loading the predictions from S3 into Snowflake should be part of your production scoring pipeline. Snowflake provides a service called [Snowpipe](https://docs.snowflake.com/en/user-guide/data-load-snowpipe-intro.html) that autoamtically can load data from S3 to Snowflake and will automatically scale based on the data volume, with no manamgement required. We already used the AWS Secrets Manager to store your Snowflake credentials. Go to the [Secrets Manager Console](https://console.aws.amazon.com/secretsmanager/home). Select the Snowflake Secret and copy the Secret Name i.e. <span style="color:lightgreen">**SnowflakeSecret-P4qyGUyk67hj**</span> in the cell below. ``` secret_name = "SnowflakeSecret-MJOPTIss7CX4" import base64 from botocore.exceptions import ClientError import json def get_secret(): # Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region ) # In this sample we only handle the specific exceptions for the 'GetSecretValue' API. # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html # We rethrow the exception by default. try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: if e.response['Error']['Code'] == 'DecryptionFailureException': # Secrets Manager can't decrypt the protected secret text using the provided KMS key. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InternalServiceErrorException': # An error occurred on the server side. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InvalidParameterException': # You provided an invalid value for a parameter. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InvalidRequestException': # You provided a parameter value that is not valid for the current state of the resource. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'ResourceNotFoundException': # We can't find the resource that you asked for. # Deal with the exception here, and/or rethrow at your discretion. raise e else: # Decrypts secret using the associated KMS CMK. # Depending on whether the secret is a string or binary, one of these fields will be populated. if 'SecretString' in get_secret_value_response: secret = get_secret_value_response['SecretString'] else: decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary']) return json.loads(secret) # Your code goes here. import snowflake.connector # Connecting to Snowflake using the default authenticator # Get credentials from Secrets Manager snowcreds = get_secret() ctx = snowflake.connector.connect( user=snowcreds["username"], password=snowcreds["password"], account=snowcreds["accountid"], warehouse='ML_WH', database='ML_LENDER_DATA', schema='ML_DATA' ) from snowflake.connector.pandas_tools import write_pandas # Write the predictions to the table named "ML_RESULTS". success, nchunks, nrows, _ = write_pandas(ctx, results[cols], 'ML_RESULTS', quote_identifiers=False) display(nrows) ``` #### Clean up Congratulations! You've completed the lab. You can delete the active resources created for the lab by deleting the CloudFormation templates. Also check for any S3 buckets that were created, empty them and delete the buckets. Follow the steps in Snowflake Worksheet (SQL Script) to delete all Snowflake resources that were created.
github_jupyter
**[Pandas Home Page](https://www.kaggle.com/learn/pandas)** --- # Introduction Run the following cell to load your data and some utility functions. ``` from learntools.core import binder; binder.bind(globals()) from learntools.pandas.renaming_and_combining import * print("Setup complete.") import pandas as pd reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0) ``` # Exercises View the first several lines of your data by running the cell below: ``` reviews.head() ``` ## 1. `region_1` and `region_2` are pretty uninformative names for locale columns in the dataset. Create a copy of `reviews` with these columns renamed to `region` and `locale`, respectively. ``` renamed = reviews.rename(columns={'region_1': 'region', 'region_2': 'locale'}) # check your answer q1.check() # q1.hint() # q1.solution() ``` <hr/> ## 2. Set the index name in the dataset to `wines`. ``` reindexed = reviews.rename_axis('wines', axis='rows') # check your answer q2.check() # q2.hint() # q2.solution() ``` <hr/> ## 3. The [Things on Reddit](https://www.kaggle.com/residentmario/things-on-reddit/data) dataset includes product links from a selection of top-ranked forums ("subreddits") on reddit.com. Run the cell below to load a dataframe of products mentioned on the */r/gaming* subreddit and another dataframe for products mentioned on the *r//movies* subreddit. ``` gaming_products = pd.read_csv("../input/things-on-reddit/top-things/top-things/reddits/g/gaming.csv") gaming_products['subreddit'] = "r/gaming" movie_products = pd.read_csv("../input/things-on-reddit/top-things/top-things/reddits/m/movies.csv") movie_products['subreddit'] = "r/movies" ``` Create a `DataFrame` of products mentioned on *either* subreddit. ``` combined_products = pd.concat([gaming_products, movie_products]) # check your answer q3.check() # q3.hint() # q3.solution() ``` <hr/> ## 4. The [Powerlifting Database](https://www.kaggle.com/open-powerlifting/powerlifting-database) dataset on Kaggle includes one CSV table for powerlifting meets and a separate one for powerlifting competitors. Run the cell below to load these datasets into dataframes: ``` powerlifting_meets = pd.read_csv("../input/powerlifting-database/meets.csv") powerlifting_competitors = pd.read_csv("../input/powerlifting-database/openpowerlifting.csv") ``` Both tables include references to a `MeetID`, a unique key for each meet (competition) included in the database. Using this, generate a dataset combining the two tables into one. ``` col1 = powerlifting_meets.columns.tolist() col2 = powerlifting_competitors.columns.tolist() [i for i in col1 if i in col2] left = powerlifting_meets.set_index('MeetID') right = powerlifting_competitors.set_index('MeetID') powerlifting_combined = left.join(right) # check your answer q4.check() # q4.hint() # q4.solution() ``` # Congratulations! You've finished the Pandas micro-course. Many data scientists feel efficiency with Pandas is the most useful and practical skill they have, because it allows you to progress quickly in any project you have. If you'd like to apply your new skills to examining geospatial data, you're encouraged to check out our **[Geospatial Analysis](https://www.kaggle.com/learn/geospatial-analysis)** micro-course. You can also take advantage of your Pandas skills by entering a **[Kaggle Competition](https://www.kaggle.com/competitions)** or by answering a question you find interesting using **[Kaggle Datasets](https://www.kaggle.com/datasets)**. --- **[Pandas Home Page](https://www.kaggle.com/learn/pandas)** *Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum) to chat with other Learners.*
github_jupyter
# Shifting Previous Week Stats to Predict Current Week Performance Author: Aidan O'Connor Date: 15 June 2021 In this notebook, I'll take previous week stats and shift them to current week predictions. ``` # Import pandas for data manipulation and sqlite3 for stored data access import pandas as pd import sqlite3 # Create a database connection conn = sqlite3.connect('../../fixtures/database/cloudy_with_a_chance_of_football.db') cursorObj = conn.cursor() # Read in Defense stats and Red Zone stats defense = pd.read_csv('../../fixtures/cleaned_data/fantasyDefenseScores.csv') redzone = pd.read_csv('../../fixtures/cleaned_data/red_zone_stats.csv') # Read in stats data grouped and ordered by PlayerID and week_id stats = pd.read_sql_query( """ SELECT PlayerID,new_week_id from stats_regular GROUP BY PlayerID, new_week_id ORDER BY PlayerID, new_week_id; """ ,conn ).drop_duplicates() # Split defense into 2019 and 2020 dataframes defense_2019 = defense[defense['Season'] == 2019] defense_2020 = defense[defense['Season'] == 2020] # Split redzone into 2019 and 2020 dataframes redzone_2019 = redzone[redzone['Season'] == 2019] redzone_2020 = redzone[redzone['Season'] == 2020] def_red_frames = [defense_2019,defense_2020,redzone_2019,redzone_2020] for n in def_red_frames: #n['PlayerID_x'] = n.PlayerID #n.set_index('PlayerID_x', inplace = True) n = n.sort_values(by = ['PlayerID','Week'], ascending = True, inplace = True) # Create year and week columns to help order the data, then sort by both stats['year'] = [n[0:4] for n in stats['week_id']] stats['week'] = [int(n[-1]) if len(n) == 6 else int(n[-2:]) for n in stats['week_id']] stats = stats.sort_values(by = ['PlayerID','week']) # Create 2 subordinate dataframes to ensure no data overlap stats_2019 = stats[['PlayerID','week']][stats['year'] == '2019'] stats_2020 = stats[['PlayerID','week']][stats['year'] == '2020'] # Make a list of dataframes to apply this next function to frames_to_shift = [stats_2019,stats_2020] def stat_shifter(dataframe): """ Shifts previous week stats to help predict current week performance Different from pandas shift, takes into account unique player ID Input: dataframe with PlayerID and week columns """ new_week_id_list = [] for n in range(0,len(dataframe) - 1): if dataframe['PlayerID'].iloc[n] == dataframe['PlayerID'].iloc[n+1]: new_week_id_list.append(dataframe['week'].iloc[n+1]) else: new_week_id_list.append(0) new_week_id_list.append(0) dataframe['new_week_id_list'] = new_week_id_list return dataframe # Apply the stat_shifter function to the dataframes for n in frames_to_shift: n = stat_shifter(n) # Apply the stat_shifter function to the redzone and defense dataframes for n in [defense_2019,defense_2020,redzone_2019,redzone_2020]: n = n.rename({'Week':'week'}, axis = 'columns') n = stat_shifter(n) # Append 2020 dataframe to 2019 dataframe for all three sets of dataframes merged_redzone = redzone_2019.append(redzone_2020) merged_defense = defense_2019.append(defense_2020) merged_stats = stats_2019.append(stats_2020) # Create a week_id and new_week_id column for each subordinate dataframe stats_2019['week_id'] = '2019_' + stats_2019['week'].astype(str) stats_2019['new_week_id'] = '2019_' + stats_2019['new_week_id_list'].astype(str) stats_2020['week_id'] = '2020_' + stats_2020['week'].astype(str) stats_2020['new_week_id'] = '2020_' + stats_2020['new_week_id_list'].astype(str) # Read in stats data df = pd.read_csv('../../fixtures/cleaned_data/fantasyPlayerScores.csv') # Merge the shifted stats columns and the overall stats table, dropping 2018 # from the merged dataframe merged_df = pd.merge( df, merged_stats.drop(['week','new_week_id_list'], axis = 'columns'), how = 'left', left_on = ['PlayerID','week_id'], right_on = ['PlayerID','week_id'] ) merged_df = merged_df[merged_df['Season'] != 2018].drop('week_id', axis = 'columns') # Drop the old stats table... cursorObj.execute("DROP TABLE stats_regular") # ...and add in the new one, then check to make sure it stuck merged_df.to_sql('stats_regular', con = conn, index = False, if_exists = 'append' ) cursorObj.execute('SELECT name from sqlite_master where type = "table"') print(cursorObj.fetchall()) merged_redzone.to_sql('redzone_stats', con = conn, index = False, if_exists = 'append' ) merged_defense.to_sql('defense_stats', con = conn, index = False, if_exists = 'append' ) cursorObj.execute('SELECT name from sqlite_master where type = "table"') print(cursorObj.fetchall()) # Close the database connection conn.close() ```
github_jupyter
# Obsessed with Boba? Analyzing Bubble Tea Shops in NYC Using the Yelp Fusion API Exploratory Data Analysis ``` # # imports for Google Colab Sessions # !apt install gdal-bin python-gdal python3-gdal # # Install rtree - Geopandas requirment # !apt install python3-rtree # # Install Geopandas # !pip install git+git://github.com/geopandas/geopandas.git # # Install descartes - Geopandas requirment # !pip install descartes import pandas as pd import numpy as np import geopandas as gpd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set(color_codes=True) # google colab path to data url = 'https://raw.githubusercontent.com/mebauer/boba-nyc/master/teabook/boba-nyc.csv' df = pd.read_csv(url) # # local path to data # df = pd.read_csv('boba-nyc.csv') df.head() # preview last five rows df.tail() rows, columns = df.shape print('number of rows: {}\nnumber of columns: {}'.format(rows, columns)) # review concise summary of data df.info() # identifiying number of nulls and percentage of total per column ser1 = df.isnull().sum().sort_values(ascending=False) ser2 = round((df.isnull().sum().sort_values(ascending=False) / len(df)) * 100, 2) pd.concat([ser1.rename('null_count'), ser2.rename('null_perc')], axis=1) # descriptive statistics of numeric columns df.describe() # descriptive statistics of string/object columns df.describe(include=['O']).T # confirm that unique id is actually unique print('id is unique: {}'.format(df['id'].is_unique)) df.head() # identify number of unique bubble tea shop entries names_counts = df['name'].value_counts().reset_index() names_counts = names_counts.rename(columns={'index':'name', 'name':'counts'}) print('number of unique bubble tea shops: {}'.format(len(names_counts))) # save file name_counts_file_path = '../teaapp/name_counts.csv' names_counts.to_csv(name_counts_file_path) # view dataframe names_counts df['name'].value_counts().reset_index(drop=False) names_counts = df['name'].value_counts().reset_index(drop=False) names_counts = names_counts.rename(columns={'index':'names', 'name':'counts'}) fig, ax = plt.subplots(figsize=(8, 6)) sns.barplot(x='counts', y="names", data=names_counts.head(10), ax=ax) plt.title('Number of bubble tea shops by business in nyc', fontsize=15) plt.tight_layout() review_count_df = df.groupby(by='name')['review_count'].mean().sort_values(ascending=False) review_count_df = round(review_count_df, 2) review_count_df = review_count_df.reset_index() review_count_df.head() fig, ax = plt.subplots(figsize=(8, 6)) sns.barplot(x="review_count", y="name", data=review_count_df.head(20), ax=ax) plt.title('Average number of reviews per business in nyc', fontsize=15) plt.tight_layout() most_reviewed = df.sort_values(by='review_count', ascending=False).head(20) most_reviewed.head() fig, ax = plt.subplots(figsize=(8, 6)) sns.barplot(x="review_count", y="alias", data=most_reviewed, ax=ax) plt.title('Most reviews per business location in nyc', fontsize=15) plt.tight_layout() df['rating'].describe() fig, ax = plt.subplots(figsize=(8, 6)) sns.countplot(data=df, x="rating") plt.title('Count of Yelp ratings per business location in nyc', fontsize=15) plt.tight_layout() price_df = df['price'].dropna().value_counts() price_df = price_df.reset_index() price_df.columns = ['price', 'counts'] price_df price_df['price'] = price_df['price'].str.count('\\$') price_df fig, ax = plt.subplots(figsize=(8, 6)) sns.barplot(y="counts", x="price", data=price_df, ax=ax) plt.title('Yelp price level (1 = $) per business location in NYC', fontsize=15) plt.tight_layout() url = 'https://data.cityofnewyork.us/api/geospatial/cpf4-rkhq?method=export&format=Shapefile' neighborhoods = gpd.read_file(url) neighborhoods.head() neighborhoods.crs neighborhoods = neighborhoods.to_crs('EPSG:4326') neighborhoods.crs df.head() gdf = gpd.GeoDataFrame(df, crs=4326, geometry=gpd.points_from_xy(df.longitude, df.latitude)) gdf.head() join_df = gpd.sjoin(gdf, neighborhoods, op='intersects') join_df.head() join_df = join_df.groupby(by=['ntaname', 'shape_area'])['id'].count().sort_values(ascending=False) join_df = join_df.reset_index() join_df = join_df.rename(columns={'id':'counts'}) join_df['counts_squaremile'] = join_df['counts'] / (join_df['shape_area'] / 27878400) join_df.head() fig, ax = plt.subplots(figsize=(10, 6)) data = join_df.sort_values(by='counts', ascending=False).head(20) sns.barplot(x="counts", y="ntaname", data=data, ax=ax) plt.title('Most bubble tea locations per neighborhood in NYC', fontsize=15) plt.ylabel('neighborhood') plt.xlabel('count') plt.tight_layout() plt.savefig('busineses-per-neighborhood.png', dpi=200) fig, ax = plt.subplots(figsize=(10, 6)) data = join_df.sort_values(by='counts_squaremile', ascending=False).head(20) sns.barplot(x="counts_squaremile", y="ntaname", data=data, ax=ax) plt.suptitle('Most bubble tea locations per square mile by neighborhood in NYC', fontsize=15, y=.96, x=.60) plt.ylabel('neighborhood') plt.xlabel('count per square mile') plt.tight_layout() plt.savefig('busineses-per-neighborhood.png', dpi=200) ```
github_jupyter
# Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. **Notation**: - Superscript $[l]$ denotes an object of the $l^{th}$ layer. - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters. - Superscript $(i)$ denotes an object from the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example input. - Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer. - $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$. - $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$. We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started! ## 1 - Packages Let's first import all the packages that you will need during this assignment. - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python. - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python. - np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. ``` import numpy as np import h5py import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ``` ## 2 - Outline of the Assignment You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed: - Convolution functions, including: - Zero Padding - Convolve window - Convolution forward - Convolution backward (optional) - Pooling functions, including: - Pooling forward - Create mask - Distribute value - Pooling backward (optional) This notebook will ask you to implement these functions from scratch in `numpy`. In the next notebook, you will use the TensorFlow equivalents of these functions to build the following model: <img src="images/model.png" style="width:800px;height:300px;"> **Note** that for every forward function, there is its corresponding backward equivalent. Hence, at every step of your forward module you will store some parameters in a cache. These parameters are used to compute gradients during backpropagation. ## 3 - Convolutional Neural Networks Although programming frameworks make convolutions easy to use, they remain one of the hardest concepts to understand in Deep Learning. A convolution layer transforms an input volume into an output volume of different size, as shown below. <img src="images/conv_nn.png" style="width:350px;height:200px;"> In this part, you will build every step of the convolution layer. You will first implement two helper functions: one for zero padding and the other for computing the convolution function itself. ### 3.1 - Zero-Padding Zero-padding adds zeros around the border of an image: <img src="images/PAD.png" style="width:600px;height:400px;"> <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Zero-Padding**<br> Image (3 channels, RGB) with a padding of 2. </center></caption> The main benefits of padding are the following: - It allows you to use a CONV layer without necessarily shrinking the height and width of the volumes. This is important for building deeper networks, since otherwise the height/width would shrink as you go to deeper layers. An important special case is the "same" convolution, in which the height/width is exactly preserved after one layer. - It helps us keep more of the information at the border of an image. Without padding, very few values at the next layer would be affected by pixels as the edges of an image. **Exercise**: Implement the following function, which pads all the images of a batch of examples X with zeros. [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html). Note if you want to pad the array "a" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do: ```python a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..)) ``` ``` # GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- integer, amount of padding around each image on vertical and horizontal dimensions Returns: X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C) """ ### START CODE HERE ### (≈ 1 line) X_pad = np.pad(X, ((0,0), (pad,pad), (pad,pad), (0,0)), 'constant', constant_values = (0,0)) ### END CODE HERE ### return X_pad np.random.seed(1) x = np.random.randn(4, 3, 3, 2) x_pad = zero_pad(x, 2) print ("x.shape =", x.shape) print ("x_pad.shape =", x_pad.shape) print ("x[1,1] =", x[1,1]) print ("x_pad[1,1] =", x_pad[1,1]) fig, axarr = plt.subplots(1, 2) axarr[0].set_title('x') axarr[0].imshow(x[0,:,:,0]) axarr[1].set_title('x_pad') axarr[1].imshow(x_pad[0,:,:,0]) ``` **Expected Output**: <table> <tr> <td> **x.shape**: </td> <td> (4, 3, 3, 2) </td> </tr> <tr> <td> **x_pad.shape**: </td> <td> (4, 7, 7, 2) </td> </tr> <tr> <td> **x[1,1]**: </td> <td> [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] </td> </tr> <tr> <td> **x_pad[1,1]**: </td> <td> [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] </td> </tr> </table> ### 3.2 - Single step of convolution In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: - Takes an input volume - Applies a filter at every position of the input - Outputs another volume (usually of different size) <img src="images/Convolution_schematic.gif" style="width:500px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : **Convolution operation**<br> with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) </center></caption> In a computer vision application, each value in the matrix on the left corresponds to a single pixel value, and we convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up and adding a bias. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output. Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation. **Exercise**: Implement conv_single_step(). [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html). ``` # GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev) b -- Bias parameters contained in a window - matrix of shape (1, 1, 1) Returns: Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data """ ### START CODE HERE ### (≈ 2 lines of code) # Element-wise product between a_slice and W. Do not add the bias yet. s = np.multiply(a_slice_prev,W) # Sum over all entries of the volume s. Z = np.sum(s) # Add bias b to Z. Cast b to a float() so that Z results in a scalar value. Z = Z + b ### END CODE HERE ### return Z np.random.seed(1) a_slice_prev = np.random.randn(4, 4, 3) W = np.random.randn(4, 4, 3) b = np.random.randn(1, 1, 1) Z = conv_single_step(a_slice_prev, W, b) print("Z =", Z) ``` **Expected Output**: <table> <tr> <td> **Z** </td> <td> -6.99908945068 </td> </tr> </table> ### 3.3 - Convolutional Neural Networks - Forward pass In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume: <center> <video width="620" height="440" src="images/conv_kiank.mp4" type="video/mp4" controls> </video> </center> **Exercise**: Implement the function below to convolve the filters W on an input activation A_prev. This function takes as input A_prev, the activations output by the previous layer (for a batch of m inputs), F filters/weights denoted by W, and a bias vector denoted by b, where each filter has its own (single) bias. Finally you also have access to the hyperparameters dictionary which contains the stride and the padding. **Hint**: 1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do: ```python a_slice_prev = a_prev[0:2,0:2,:] ``` This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define. 2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find how each of the corner can be defined using h, w, f and s in the code below. <img src="images/vert_horiz_kiank.png" style="width:400px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)** <br> This figure shows only a single channel. </center></caption> **Reminder**: The formulas relating the output shape of the convolution to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_C = \text{number of filters used in the convolution}$$ For this exercise, we won't worry about vectorization, and will just implement everything with for-loops. ``` # GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): """ Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy array of shape (f, f, n_C_prev, n_C) b -- Biases, numpy array of shape (1, 1, 1, n_C) hparameters -- python dictionary containing "stride" and "pad" Returns: Z -- conv output, numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward() function """ ### START CODE HERE ### # Retrieve dimensions from A_prev's shape (≈1 line) (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (≈1 line) (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" (≈2 lines) stride = hparameters['stride'] pad = hparameters['pad'] # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines) n_H = int((n_H_prev - f + 2 * pad) / stride) + 1 n_W = int((n_W_prev - f + 2 * pad) / stride) + 1 # Initialize the output volume Z with zeros. (≈1 line) Z = np.zeros((m, n_H, n_W, n_C)) # Create A_prev_pad by padding A_prev A_prev_pad = zero_pad(A_prev, pad) for i in range(m): # loop over the batch of training examples a_prev_pad = A_prev_pad[i, :, :, :] # Select ith training example's padded activation for h in range(n_H): # loop over vertical axis of the output volume for w in range(n_W): # loop over horizontal axis of the output volume for c in range(n_C): # loop over channels (= #filters) of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = stride * h vert_end = vert_start + f horiz_start = stride * w horiz_end = horiz_start + f # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line) a_slice_prev = a_prev_pad[vert_start : vert_end, horiz_start : horiz_end, :] # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line) Z[i, h, w, c] = conv_single_step(a_slice_prev, W[:, :, :, c], b[:, :, :, c]) ### END CODE HERE ### # Making sure your output shape is correct assert(Z.shape == (m, n_H, n_W, n_C)) # Save information in "cache" for the backprop cache = (A_prev, W, b, hparameters) return Z, cache np.random.seed(1) A_prev = np.random.randn(10,4,4,3) W = np.random.randn(2,2,3,8) b = np.random.randn(1,1,1,8) hparameters = {"pad" : 2, "stride": 2} Z, cache_conv = conv_forward(A_prev, W, b, hparameters) print("Z's mean =", np.mean(Z)) print("Z[3,2,1] =", Z[3,2,1]) print("cache_conv[0][1][2][3] =", cache_conv[0][1][2][3]) ``` **Expected Output**: <table> <tr> <td> **Z's mean** </td> <td> 0.0489952035289 </td> </tr> <tr> <td> **Z[3,2,1]** </td> <td> [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437 5.18531798 8.75898442] </td> </tr> <tr> <td> **cache_conv[0][1][2][3]** </td> <td> [-0.20075807 0.18656139 0.41005165] </td> </tr> </table> Finally, CONV layer should also contain an activation, in which case we would add the following line of code: ```python # Convolve the window to get back one output neuron Z[i, h, w, c] = ... # Apply activation A[i, h, w, c] = activation(Z[i, h, w, c]) ``` You don't need to do it here. ## 4 - Pooling layer The pooling (POOL) layer reduces the height and width of the input. It helps reduce computation, as well as helps make feature detectors more invariant to its position in the input. The two types of pooling layers are: - Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output. - Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output. <table> <td> <img src="images/max_pool1.png" style="width:500px;height:300px;"> <td> <td> <img src="images/a_pool.png" style="width:500px;height:300px;"> <td> </table> These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size $f$. This specifies the height and width of the fxf window you would compute a max or average over. ### 4.1 - Forward Pooling Now, you are going to implement MAX-POOL and AVG-POOL, in the same function. **Exercise**: Implement the forward pass of the pooling layer. Follow the hints in the comments below. **Reminder**: As there's no padding, the formulas binding the output shape of the pooling to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f}{stride} \rfloor +1 $$ $$ n_C = n_{C_{prev}}$$ ``` # GRADED FUNCTION: pool_forward def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C) cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters """ # Retrieve dimensions from the input shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve hyperparameters from "hparameters" f = hparameters["f"] stride = hparameters["stride"] # Define the dimensions of the output n_H = int(1 + (n_H_prev - f) / stride) n_W = int(1 + (n_W_prev - f) / stride) n_C = n_C_prev # Initialize output matrix A A = np.zeros((m, n_H, n_W, n_C)) ### START CODE HERE ### for i in range(m): # loop over the training examples for h in range(n_H): # loop on the vertical axis of the output volume for w in range(n_W): # loop on the horizontal axis of the output volume for c in range (n_C): # loop over the channels of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = stride * h vert_end = vert_start + f horiz_start = stride * w horiz_end = horiz_start + f # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line) a_prev_slice = A_prev[i, vert_start : vert_end, horiz_start : horiz_end, c] # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean. if mode == "max": A[i, h, w, c] = np.max(a_prev_slice) elif mode == "average": A[i, h, w, c] = np.mean(a_prev_slice) ### END CODE HERE ### # Store the input and hparameters in "cache" for pool_backward() cache = (A_prev, hparameters) # Making sure your output shape is correct assert(A.shape == (m, n_H, n_W, n_C)) return A, cache np.random.seed(1) A_prev = np.random.randn(2, 4, 4, 3) hparameters = {"stride" : 2, "f": 3} A, cache = pool_forward(A_prev, hparameters) print("mode = max") print("A =", A) print() A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mode = average") print("A =", A) ``` **Expected Output:** <table> <tr> <td> A = </td> <td> [[[[ 1.74481176 0.86540763 1.13376944]]] [[[ 1.13162939 1.51981682 2.18557541]]]] </td> </tr> <tr> <td> A = </td> <td> [[[[ 0.02105773 -0.20328806 -0.40389855]]] [[[-0.22154621 0.51716526 0.48155844]]]] </td> </tr> </table> Congratulations! You have now implemented the forward passes of all the layers of a convolutional network. The remainer of this notebook is optional, and will not be graded. ## 5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED) In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers don't need to bother with the details of the backward pass. The backward pass for convolutional networks is complicated. If you wish however, you can work through this optional portion of the notebook to get a sense of what backprop in a convolutional network looks like. When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial and we did not derive them in lecture, but we briefly presented them below. ### 5.1 - Convolutional layer backward pass Let's start by implementing the backward pass for a CONV layer. #### 5.1.1 - Computing dA: This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example: $$ dA += \sum _{h=0} ^{n_H} \sum_{w=0} ^{n_W} W_c \times dZ_{hw} \tag{1}$$ Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, we multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, we are just adding the gradients of all the a_slices. In code, inside the appropriate for-loops, this formula translates into: ```python da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c] ``` #### 5.1.2 - Computing dW: This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss: $$ dW_c += \sum _{h=0} ^{n_H} \sum_{w=0} ^ {n_W} a_{slice} \times dZ_{hw} \tag{2}$$ Where $a_{slice}$ corresponds to the slice which was used to generate the acitivation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$. In code, inside the appropriate for-loops, this formula translates into: ```python dW[:,:,:,c] += a_slice * dZ[i, h, w, c] ``` #### 5.1.3 - Computing db: This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$: $$ db = \sum_h \sum_w dZ_{hw} \tag{3}$$ As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost. In code, inside the appropriate for-loops, this formula translates into: ```python db[:,:,:,c] += dZ[i, h, w, c] ``` **Exercise**: Implement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above. ``` def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv_forward() Returns: dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev), numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) dW -- gradient of the cost with respect to the weights of the conv layer (W) numpy array of shape (f, f, n_C_prev, n_C) db -- gradient of the cost with respect to the biases of the conv layer (b) numpy array of shape (1, 1, 1, n_C) """ ### START CODE HERE ### # Retrieve information from "cache" (A_prev, W, b, hparameters) = cache # Retrieve dimensions from A_prev's shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" stride = hparameters['stride'] pad = hparameters['pad'] # Retrieve dimensions from dZ's shape (m, n_H, n_W, n_C) = dZ.shape # Initialize dA_prev, dW, db with the correct shapes dA_prev = np.zeros((m, n_H_prev, n_W_prev, n_C_prev)) dW = np.zeros((f, f, n_C_prev, n_C)) db = np.zeros((1, 1, 1, n_C)) # Pad A_prev and dA_prev A_prev_pad = zero_pad(A_prev, pad) dA_prev_pad = zero_pad(dA_prev, pad) for i in range(m): # loop over the training examples # select ith training example from A_prev_pad and dA_prev_pad a_prev_pad = A_prev_pad[i, :, :, :] da_prev_pad = dA_prev_pad[i, :, :, :] for h in range(n_H): # loop over vertical axis of the output volume for w in range(n_W): # loop over horizontal axis of the output volume for c in range(n_C): # loop over the channels of the output volume # Find the corners of the current "slice" vert_start = stride * h vert_end = vert_start + f horiz_start = stride * w horiz_end = horiz_start + f # Use the corners to define the slice from a_prev_pad a_slice = A_prev_pad[i, vert_start : vert_end, horiz_start : horiz_end, :] # Update gradients for the window and the filter's parameters using the code formulas given above da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:, :, :, c] * dZ[i, h, w, c] dW[:,:,:,c] += a_slice * dZ[i, h, w, c] db[:,:,:,c] += dZ[i, h, w, c] # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :]) dA_prev[i, :, :, :] = da_prev_pad[pad : -pad, pad : -pad, :] ### END CODE HERE ### # Making sure your output shape is correct assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev)) return dA_prev, dW, db np.random.seed(1) dA, dW, db = conv_backward(Z, cache_conv) print("dA_mean =", np.mean(dA)) print("dW_mean =", np.mean(dW)) print("db_mean =", np.mean(db)) ``` ** Expected Output: ** <table> <tr> <td> **dA_mean** </td> <td> 1.45243777754 </td> </tr> <tr> <td> **dW_mean** </td> <td> 1.72699145831 </td> </tr> <tr> <td> **db_mean** </td> <td> 7.83923256462 </td> </tr> </table> ## 5.2 Pooling layer - backward pass Next, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer. ### 5.2.1 Max pooling - backward pass Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following: $$ X = \begin{bmatrix} 1 && 3 \\ 4 && 2 \end{bmatrix} \quad \rightarrow \quad M =\begin{bmatrix} 0 && 0 \\ 1 && 0 \end{bmatrix}\tag{4}$$ As you can see, this function creates a "mask" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling will be similar to this but using a different mask. **Exercise**: Implement `create_mask_from_window()`. This function will be helpful for pooling backward. Hints: - [np.max()]() may be helpful. It computes the maximum of an array. - If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that: ``` A[i,j] = True if X[i,j] = x A[i,j] = False if X[i,j] != x ``` - Here, you don't need to consider cases where there are several maxima in a matrix. ``` def create_mask_from_window(x): """ Creates a mask from an input matrix x, to identify the max entry of x. Arguments: x -- Array of shape (f, f) Returns: mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x. """ ### START CODE HERE ### (≈1 line) mask = None ### END CODE HERE ### return mask np.random.seed(1) x = np.random.randn(2,3) mask = create_mask_from_window(x) print('x = ', x) print("mask = ", mask) ``` **Expected Output:** <table> <tr> <td> **x =** </td> <td> [[ 1.62434536 -0.61175641 -0.52817175] <br> [-1.07296862 0.86540763 -2.3015387 ]] </td> </tr> <tr> <td> **mask =** </td> <td> [[ True False False] <br> [False False False]] </td> </tr> </table> Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will "propagate" the gradient back to this particular input value that had influenced the cost. ### 5.2.2 - Average pooling - backward pass In max pooling, for each input window, all the "influence" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this. For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like: $$ dZ = 1 \quad \rightarrow \quad dZ =\begin{bmatrix} 1/4 && 1/4 \\ 1/4 && 1/4 \end{bmatrix}\tag{5}$$ This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average. **Exercise**: Implement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html) ``` def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we distributed the value of dz """ ### START CODE HERE ### # Retrieve dimensions from shape (≈1 line) (n_H, n_W) = None # Compute the value to distribute on the matrix (≈1 line) average = None # Create a matrix where every entry is the "average" value (≈1 line) a = None ### END CODE HERE ### return a a = distribute_value(2, (2,2)) print('distributed value =', a) ``` **Expected Output**: <table> <tr> <td> distributed_value = </td> <td> [[ 0.5 0.5] <br\> [ 0.5 0.5]] </td> </tr> </table> ### 5.2.3 Putting it together: Pooling backward You now have everything you need to compute backward propagation on a pooling layer. **Exercise**: Implement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dZ. ``` def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev """ ### START CODE HERE ### # Retrieve information from cache (≈1 line) (A_prev, hparameters) = None # Retrieve hyperparameters from "hparameters" (≈2 lines) stride = None f = None # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines) m, n_H_prev, n_W_prev, n_C_prev = None m, n_H, n_W, n_C = None # Initialize dA_prev with zeros (≈1 line) dA_prev = None for i in range(None): # loop over the training examples # select training example from A_prev (≈1 line) a_prev = None for h in range(None): # loop on the vertical axis for w in range(None): # loop on the horizontal axis for c in range(None): # loop over the channels (depth) # Find the corners of the current "slice" (≈4 lines) vert_start = None vert_end = None horiz_start = None horiz_end = None # Compute the backward propagation in both modes. if mode == "max": # Use the corners and "c" to define the current slice from a_prev (≈1 line) a_prev_slice = None # Create the mask from a_prev_slice (≈1 line) mask = None # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None elif mode == "average": # Get the value a from dA (≈1 line) da = None # Define the shape of the filter as fxf (≈1 line) shape = None # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += None ### END CODE ### # Making sure your output shape is correct assert(dA_prev.shape == A_prev.shape) return dA_prev np.random.seed(1) A_prev = np.random.randn(5, 5, 3, 2) hparameters = {"stride" : 1, "f": 2} A, cache = pool_forward(A_prev, hparameters) dA = np.random.randn(5, 4, 2, 2) dA_prev = pool_backward(dA, cache, mode = "max") print("mode = max") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) print() dA_prev = pool_backward(dA, cache, mode = "average") print("mode = average") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) ``` **Expected Output**: mode = max: <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0. 0. ] <br> [ 5.05844394 -1.68282702] <br> [ 0. 0. ]] </td> </tr> </table> mode = average <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0.08485462 0.2787552 ] <br> [ 1.26461098 -0.25749373] <br> [ 1.17975636 -0.53624893]] </td> </tr> </table> ### Congratulations ! Congratulation on completing this assignment. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next assignment you will implement a ConvNet using TensorFlow.
github_jupyter
<a href="https://colab.research.google.com/github/GiselaCS/Mujeres_Digitales/blob/main/KNN_(Ejemplo_1).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Cargamos todas las librerías necesarias. Utilizaremos la clase KNeighborsClassifier, para poder usar el algoritmo KNN para problemas de clasificación. ``` import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.neighbors import KNeighborsClassifier ``` Primero crearemos unos datos de prueba, de los que sabemos la categoría y creamos un punto nuevo, del que no sabemos su género y visualizamos todos los puntos. ``` data = {'Masa': [50, 80, 90, 45, 60], 'Altura': [1.48, 1.82, 1.85, 1.55, 1.60], 'Genero': ['m', 'h', 'h', 'm', 'm']} data # Individuo nuevo punto_nuevo = {'Masa': [70], 'Altura': [1.82]} ``` Convertimos a dataframe ... ``` df = pd.DataFrame(data) punto_nuevo = pd.DataFrame(punto_nuevo) df punto_nuevo ``` Graficamos los puntos! ``` df.loc[df['Genero'] == 'h', 'Altura'] ax = plt.axes() ax.scatter(df.loc[df['Genero'] == 'h', 'Masa'],df.loc[df['Genero'] == 'h', 'Altura'],c="red",label="Hombre") ax.scatter(df.loc[df['Genero'] == 'm', 'Masa'],df.loc[df['Genero'] == 'm', 'Altura'],c="blue",label="Mujer") ax.scatter(punto_nuevo['Masa'],punto_nuevo['Altura'],c="black") plt.xlabel("Masa") plt.ylabel("Altura") ax.legend() plt.show() ``` A continuación entrenamos el algoritmo KNN con los datos para los que tenemos etiquetas. ``` from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) X = df[['Masa', 'Altura']] y = df[['Genero']] knn.fit(X, y) prediccion = knn.predict(punto_nuevo) print(prediccion) ``` # Mas complejo ``` data = {'Masa': [50, 80, 90, 45, 60], 'Altura': [1.48, 1.82, 1.85, 1.55, 1.60], 'Genero': ['m', 'h', 'h', 'm', 'm']} data # Individuo nuevo punto_nuevo = {'Masa': [70,69], 'Altura': [1.82,1.71]} ax = plt.axes() ax.scatter(df.loc[df['Genero'] == 'h', 'Masa'],df.loc[df['Genero'] == 'h', 'Altura'],c="red",label="Hombre") ax.scatter(df.loc[df['Genero'] == 'm', 'Masa'],df.loc[df['Genero'] == 'm', 'Altura'],c="blue",label="Mujer") ax.scatter(punto_nuevo['Masa'],punto_nuevo['Altura'],c="black") plt.xlabel("Masa") plt.ylabel("Altura") ax.legend() plt.show() df = pd.DataFrame(data) punto_nuevo = pd.DataFrame(punto_nuevo) df punto_nuevo from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) X = df[['Masa', 'Altura']] y = df[['Genero']] knn.fit(X, y) prediccion = knn.predict(punto_nuevo) print(prediccion) ```
github_jupyter
# 1: Palindrome 1 ``` palindrome_answer = "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba" def basic_palindrome(): letter = 'a' output_string = "" # chr() converts a numeric value to a character and ord() converts a character to a numeric value # This allows us to arithmetically change the value of our letter while letter != 'z': output_string += letter letter = chr(ord(letter) + 1) # The top loop adds 'a' -> 'y' to the output_string, the bottom loop adds 'z' -> 'b' to the output_string while letter != 'a': output_string += letter letter = chr(ord(letter) - 1) # We add the final 'a' here and return the answer output_string += letter return output_string print(palindrome_answer == basic_palindrome()) # We could also do: import string def string_lib_palindrome(): # string.acsii_lowercase will get us the whole alphabet in lowercase from Python # then we use list slicing to add the same list, but in reverse and removing the last 'z' return string.ascii_lowercase + string.ascii_lowercase[-2::-1] print(palindrome_answer == string_lib_palindrome()) ``` # 2: Palindrome 2 ``` palindrome_f_answer = "fghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgf" # Note that there is no error checking done here - the user could enter a whole set of letters, punctuation etc def input_palindrome(): start_letter = input("Enter a starting letter for your palindrome alphabet: ") letter = start_letter output_string = "" while letter != 'z': output_string += letter letter = chr(ord(letter) + 1) while letter != start_letter: output_string += letter letter = chr(ord(letter) - 1) output_string += letter return output_string print(palindrome_f_answer == input_palindrome()) # We could also do: import string def input_string_lib_palindrome(): start_letter = ord(input("Enter a starting letter for your palindrome alphabet: ")) - ord('a') return string.ascii_lowercase[start_letter::] + string.ascii_lowercase[-2:start_letter - 1:-1] print(palindrome_f_answer == input_string_lib_palindrome()) ``` # 3: Pyramid ``` def pyramid_printer(): pyramid_height = 15 pyramid_output = "" # This loop walks from the tip of the pyramid to the base for level in range(pyramid_height): level_string = "" # This loop adds an appropriate amount of space-padding to the left of the letters # We subtract 1 to take the central letter into account (the width of the letters in each line is: (level * 2) + 1) for space in range(pyramid_height - 1 - level): level_string += " " # This loops adds as many letters as the level we are on (so no letters on 0, 'a' on 1, 'ab' on 2 etc) # Note that this loop prints nothing at the very tip, level 0 for letter_offset in range(level): level_string += chr(ord('a') + letter_offset) # This loop prints 1 more letters than the current level # so 1 letter is printed on level 0, the letter will be 'a' + 0 - 0 ('a') This is the pyramid's tip # on level 1, 2 letters are printed: 'a' + 1 - 0 ('b') and 'a' + 1 - 1 ('a') for letter_offset in range(level + 1): level_string += chr(ord('a') + level - letter_offset) pyramid_output += level_string + "\n" return pyramid_output print(pyramid_printer()) ``` # 4: Collatz Conjecture ``` collatz_12_answer = [12, 6, 3, 10, 5, 16, 8, 4, 2, 1] # First we use the modulo operator (%) to check for evenness def collatz_sequence(starting_number): # Make sure to add the first number to the list sequence = [starting_number] # We change the name of the variable here to make it more readable in this loop current_number = starting_number while current_number != 1: if current_number % 2 == 0: # We don't have to cast down to an int here, as the value will always be exact # but it makes the output look consistent current_number = int(current_number / 2) sequence.append(current_number) else: # Again, we don't need to cast to int, but it looks nicer current_number = int((3 * current_number) + 1) sequence.append(current_number) return sequence print(collatz_12_answer == collatz_sequence(12)) # And now we use bitwise AND to check for evenness def collatz_sequence(starting_number): sequence = [starting_number] current_number = starting_number while current_number != 1: # Remember that binary reads from right to left, from indices 0 to n # Each position represents 2^position_index # To find the value of a binary number, therefore, we calculate the power of 2 for any position with a 1 and add the results together # e.g. 100110101 has 1s for values 2^0 = 1, 2^2 = 4, 2^4 = 16, 2^5 = 32, and 2^8 = 256 meaning this is 309 in binary # Notice that if the rightmost bit is set to 1, then we add 1 to the number, and for every other index we add an even number # This means that all odd binary numbers end with 1 # Therefore, f we take the bitwise AND of any number and binary 1, the result will always be 0 for even numbers, and 1 for odd numbers # e.g. 100110101 & 000000001 = 000000001 whilst 100110100 & 000000001 == 000000000 (as 1 & 1 = 1 and 1 & 0 = 0) if current_number & 1 == 0: current_number = int(current_number / 2) sequence.append(current_number) else: current_number = int((3 * current_number) + 1) sequence.append(current_number) return sequence print(collatz_12_answer == collatz_sequence(12)) ``` # 5: Run-Length Encoding ``` rle_input_01 = "aaeeeeae" rle_input_01_answer = "2a4e1a1e" rle_input_02 = "rr44errre" rle_input_02_answer = "invalid input" rle_input_03 = "eeeeeeeeeeeeeeeeeeeee" rle_input_03_answer = "21e" import string def run_length_encoder(input_to_encode): encoding = "" # This value always starts at 1 as we are always looking at some letter, so the minimum encoding length is 1 current_length = 1 # This loop walks through all indices except the final index. # We need to skip the last index as we check "index + 1" within the loop, # if we did this with the final index we would get an out of bounds error for i in range(len(input_to_encode) - 1): # First we check that the letter at the current index is a valid lowercase letter if input_to_encode[i] not in string.ascii_lowercase: return "invalid input" # Next we see if this letter is the same as the next letter, if so increase the current encoding length elif input_to_encode[i] == input_to_encode[i + 1]: current_length += 1 # Otherwise, we add the current encoding length and the relevant letter to the encoding output string # We also need to make sure we reset the encoding length back to the starting value else: encoding += (str(current_length) + input_to_encode[i]) current_length = 1 # Since we don't look at the final index directly in the loop, we must look at it here # If the letter is new, then current_length is 1 already, and we just need to add the last letter # If current_length isn't 1, then it's already at the correct value as the loop incremented the encoding length when it saw the second last letter encoding += (str(current_length) + input_to_encode[i + 1]) return encoding print(run_length_encoder(rle_input_01) == rle_input_01_answer) print(run_length_encoder(rle_input_02) == rle_input_02_answer) print(run_length_encoder(rle_input_03) == rle_input_03_answer) ```
github_jupyter
# Content: 1. [Simple example](#1.-Simple-example) 2. [Parametric equations](#2.-Parametric-equations) 3. [Polishing the plot](#3.-Polishing-the-plot) 4. [Contour plot](#4.-Contour-plot) 5. [Beginner-level animation](#5.-Beginner-level-animation) 6. [Intermediate-level animation](#6.-Intermediate-level-animation) ## 1. Simple example ``` import numpy as np import matplotlib.pyplot as plt #=== x-range x_min=-10 x_max=10 x_grids=501 x=np.linspace(x_min, x_max, x_grids) #print(x.shape[0]) #=== variables to plot y=x**2 #=== plot plt.plot(x,y) plt.title('Parabola') plt.show() ``` You can change the default style such as line color, line width, etc. Bookmark [Matplotlib documentation](https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html) and refer this page for more details. ``` #=== plot plt.plot(x,y,color='r',linestyle='dashed',linewidth=4) plt.title('Parabola') plt.show() ``` ## 2. Parametric equations [Lissajous curves](https://en.wikipedia.org/wiki/Lissajous_curve) are defined by the parametric equations $$ \begin{align} x & = A\sin(at+\pi/2)\\ y & = Bsin(bt) \end{align} $$ ``` import numpy as np import matplotlib.pyplot as plt #=== t-range t_min=-np.pi t_max=np.pi t_grids=501 t=np.linspace(t_min, t_max, t_grids) #=== Constants A=1 B=1 a=10 b=12 #=== variables to plot x=A*np.sin(a*t+np.pi/2) y=B*np.sin(b*t) #=== plot plt.plot(x,y) plt.title('Lissajous curves') plt.grid() plt.show() #=== To see the current working directory, uncomment the following 2 lines #import os #os.getcwd() ``` ## 3. Polishing the plot ``` import numpy as np import matplotlib.pyplot as plt #=== t-range t_min=-np.pi t_max=np.pi t_grids=501 t=np.linspace(t_min, t_max, t_grids) #=== Constants A=1 B=1 a=10 b=9 #=== variables to plot x=A*np.sin(a*t+np.pi/2) y=B*np.sin(b*t) #=== make it a square plot fig = plt.figure() # comment if square plot is not needed ax = fig.add_subplot(111) # comment if square plot is not needed plt.plot(x,y) ax.set_aspect('equal', adjustable='box') # comment if square plot is not needed #=== labels, titles, grids plt.xlabel("x") plt.ylabel("y") plt.title('Lissajous curves') plt.grid() #=== save in file, you can also use .pdf or .svg plt.savefig('Lissajous.png') #=== display plt.show() ``` ## 4. Contour plot ``` import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt #=== Define a 2D function def f(x,y): #z=(x**2+y**2) z=(1-x**2+y**2) return z x=np.arange(-2.0,2.0,0.1) y=np.arange(-2.0,2.0,0.1) X,Y=np.meshgrid(x,y) Z=f(X,Y) N_iso=np.arange(-2,2,0.5) CS=plt.contour(Z,N_iso,linewidths=2,cmap=mpl.cm.jet) plt.clabel(CS, inline=True, fmt='%1.1f', fontsize=10) plt.colorbar(CS) plt.title('A contour plot') plt.show() ``` ## 5. Beginner-level animation ``` import os import numpy as np import matplotlib.pyplot as plt import imageio x_min=-10 x_max=10 x_grids=501 x=np.linspace(x_min, x_max, x_grids)## ONE ## def gauss(x,x0): f=np.exp(-(x-x0)**2) return f #=== plot-1 x0=0 y=gauss(x,x0) plt.plot(x,y) plt.title('Moving Gaussian') plt.savefig('_tmp_1.png') plt.show() #=== plot-2 x0=1 y=gauss(x,x0) plt.plot(x,y) plt.title('Moving Gaussian') plt.savefig('_tmp_2.png') plt.show() #=== plot-3 x0=2 y=gauss(x,x0) plt.plot(x,y) plt.title('Moving Gaussian') plt.savefig('_tmp_3.png') plt.show() #=== plot-4 x0=3 y=gauss(x,x0) plt.plot(x,y) plt.title('Moving Gaussian') plt.savefig('_tmp_4.png') plt.show() # Build GIF with imageio.get_writer('mygif1.gif', mode='I') as writer: for filename in ['_tmp_1.png', '_tmp_2.png', '_tmp_3.png', '_tmp_4.png']: image = imageio.imread(filename) writer.append_data(image) ``` Double click the next image and then shift+enter ![SegmentLocal](mygif1.gif "segment") ## 6. Intermediate-level animation ``` import numpy as np import matplotlib.pyplot as plt #=== Particle-in-a-box solutions hbar=1 mass=1 L = 1 #=== Eigenvalues n=1 E1=n**2 * np.pi**2 * hbar**2 / (2.0 * mass * L**2) n=2 E2=n**2 * np.pi**2 * hbar**2 / (2.0 * mass * L**2) x=np.linspace(0,1,101) def psi1(x): # Ground state, n = 1 n=1 L=1 val=np.sqrt(2.0/L)*np.sin(n*np.pi*x/L) return val def psi2(x): # First excited state, n = 2 n=2 L=1 val=np.sqrt(2.0/L)*np.sin(n*np.pi*x/L) return val c1=1.0/np.sqrt(2.0) c2=1.0/np.sqrt(2.0) filenames = [] t=0 it=0 dt=0.01 i=complex(0,1) dx=0.1 #print(np.sqrt(np.dot(psi1(x)*dx,psi1(x)*dx))) # uncomment to check for Normalization while it <= 100: psi=c1*psi1(x)*dx*np.exp(-i*E1*t/hbar) + c2*psi2(x)*dx*np.exp(-i*E2*t/hbar) plt.plot(x,np.real(psi)**2+np.imag(psi)**2) plt.xlim(0, 1) plt.ylim(0, 0.2) plt.xlabel("x") plt.ylabel("$|\psi|^2$(x)") #NOTE: LaTex syntax for psi plt.title('Time evolution of $[\psi_1+\psi_2]/\sqrt{2}$') plt.text(0.2,0.15, r'$time=$ {0:10.3f} [au]'.format(t), fontsize=10) filename='_tmp_'+str(it).zfill(5)+'.png' filenames.append(filename) plt.savefig(filename) plt.close() t=t+dt it=it+1 # build gif with imageio.get_writer('mygif2.gif', mode='I') as writer: for filename in filenames: image = imageio.imread(filename) writer.append_data(image) # Remove files for filename in set(filenames): os.remove(filename) ``` Double click the next image and then shift+enter ![SegmentLocal](mygif2.gif "segment")
github_jupyter
# Least Squares Regression for Impedance Analysis ![](spectrumTest.png) ## Introduction This is a tutorial for how to set up the functions and calls for curve fitting an experimental impedance spectrum with Python using a least squares regression. Four different models are used as examples for how to set up the curve fit and estimate parameters. The first two are generic circuit element combinations, to illustrate the input-output flow of the functions, the third example is of a Randles circuit, which can be used for parameter estimation and finally the Macrohomogeneous Porous Electrode (MHPE). ## Contents * [Nomenclature](#Nomenclature) * [Modules](#Modules) * [Functions](#Functions) * [Impedance Models](#Impedance-Models) * [z_a](#z_a) - Equivalent circuit example 1 * [Inputs](#z_a-Inputs) * [Outputs](#z_a-Outputs) * [Example function call](#Example-Usage-of-z_a) * [z_b](#z_b) - Equivalent circuit example 2 * [Inputs](#z_b-Inputs) * [Outputs](#z_b-Outputs) * [Example function call](#Example-Usage-of-z_b) * [Randles Circuit](#Randles-Circuit) * [warburg](#warburg) * [Inputs](#warburg-Inptus) * [Outputs](#warburg-Outputs) * [z_randles](#z_randles) * [Inputs](#z_randles-Inptus) * [Outputs](#z_randles-Outputs) * [z_mhpe (Macrohomogeneous Porous Electrode](#z_mhpe) * [Inputs](#z_mhpe-Inputs) * [Outputs](#z_mhpe-Outputs) * [cell_response](#cell_response) * [Inputs](#cell_response-Inptus) * [Outputs](#cell_response-Outputs) * [Example function call](#Example-usage-of-cell_response) * [Least Squares](#Least-Squares) * [residual](#residual) * [Inputs](#residual-Inptus) * [Outputs](#residual-Outputs) * [Example function call](#Example-usage-of-residual) * [z_fit](#z_fit) * [z_plot](#z_plot) * [Example Function Calls](#Examples) - examples of the input - output syntax of functions * [Experimental Data](#Experimental-Data) - these are the data used in the curve fitting examples * [Curve Fitting Examples](#Curve-Fitting-Examples) * [Comparison of z_a and z_b](#Example-fitting-a-spectrum-(z_a-and-z_b)) * [Randles Circuit](#Example-fitting-a-spectrum-(z_randles)) * [Macrohomogeneous Porous Electrode](#Example-fitting-a-spectrum-(z_mhpe)) * [Appendix](#Appendix) ## Nomenclature |Parameter | Description |Unit | |---- |---- |---- | |$A$ | Geometric surface area| $cm^2$| |$ASR_x$ | Area Specific Resistance of x | $\Omega\ cm^2$| |$A_t$ | Wetted surface area | $cm^2$| |$CPE$ | Constant Phase Element| $F^P$| |$C_x$ | Concentration of species x| $mol\ cm^{-3}$| |$D_x$ | Diffusivity of species x| $cm^{2}\ s^{-1}$| |$F$ | Faraday's constant| $C\ mol^{-1}$| |$L$ | Inductance| $H$| |$P$ | CPE exponent| $-$| |$Q$ | CPE parameter| $F$| |$R$ | Universal gas constant| $J\ mol^{-1}\ K^{-1}$| |$T$ | Temperature| $K$| |$W$ | Warburg impedance| $\Omega$| |$Z_{x}$ | Impedance of x| $\Omega$| |$a$ | Nernstian diffusion layer thickness| $cm$| |$b$ | electrode thickness| $cm$| |$f$ | Scale factor| $-$| |$g_{ct}$ | charge transfer conductance (per unit length) | $S cm^{-1}$| |$i_0$ | Exchange current density| $A\ cm^{-2}$| |$j$ | Imaginary unit ($\sqrt{-1}$)| $-$| |$n$ | Number of electrons transferred| $-$| |$\lambda$ | complex decay length| cm | |$\omega$ | Angular frequency| $rad\ s^{-1}$| |$\rho_1$ | Electrolyte resistivity| $\Omega\ cm$| |$\rho_2$ | Solid Phase resistivity| $\Omega\ cm$| ### Modules The three modules used in this tutorial are [numpy](https://numpy.org/), [scipy](https://www.scipy.org/), and [matplotlib](https://matplotlib.org/). These can be installed from the shell (not iPython) with the following command: pip install numpy scipy matplotlib They are imported into the scope of the program with the following commands: [Link to Contents](#Contents) ``` from numpy import real,imag,pi,inf,array,concatenate,log,logspace,tanh,sqrt,exp,sinh from scipy.optimize import least_squares import matplotlib.pyplot as plt import matplotlib #------------------------------------------------------------------------------ # Constants F = 96485.33289 Ru = 8.3144598 #------------------------------------------------------------------------------ try: plt.style.use("jupyter_style") except: plt.rcParams['axes.labelsize'] = 24 plt.rcParams['font.size'] = 20 fs = (12,6) # figure size coth = lambda x: (exp(2*x)+1)/(exp(2*x)-1) colors = 'rgbcmyk' markers = 'x+v^os' ``` # Functions ## Impedance Models Each of the impedance models adhere to the following function template: * Inputs: * input_dict - *dictionary* containing the model parameters. There is no distinction from the perspective of the model (function) between fitted and fixed parameters. This is handled by the least_squares functions and allows the user to define which parameters should float and which should be fixed. * frequency - a frequency **or** an (numpy) *array* of frequencies at which to evaluate the model * Output: * Z($\omega$) - (complex number) [Link to Contents](#Contents) --- ### z_a *z_a* is a function which **returns** the complex impedance response of the following equivalent circuit model. ![](circuit_element/z_a.png) The equation for this circuit is: $$z_a = R_0 + (R_1^{-1} + j \omega C_1)^{-1} + (R_2^{-1} + j\omega C_2)^{-1} $$ #### z_a Inputs * a dictionary containing the parameters (indexed by keys that match the variable names) in the model: 0. 'R0' - Resistance 0 (ohmic resistance) 1. 'R1' - Resistance 1 2. 'R2' - Resistance 2 3. 'C1' - capacitance 1 (in parallel with R1) 4. 'C2' - capacitance 2 (in parallel with R2) * frequency - frequency (or array of frequencies) to calculate impedance (rad / sec) #### z_a Outputs * Z($\omega$) - (complex number) [Link to Contents](#Contents) ``` def z_a(input_dict, frequency): R0 = input_dict['R0'] R1 = input_dict['R1'] R2 = input_dict['R2'] C1 = input_dict['C1'] C2 = input_dict['C2'] return(R0+(R1**-1+1j*frequency*C1)**-1+(R2**-1+1j*frequency*C2)**-1) ``` ### z_b *z_b* is a function which **returns** the complex impedance response of the following equivalent circuit model. ![](circuit_element/z_b.png) The equation for this circuit is: $$z_b = R_0 + ((R_1 + (R_2^{-1} + j\omega C_2)^{-1})^{-1} + j \omega C_1)^{-1} $$ #### z_b Inputs * a dictionary containing the parameters (indexed by keys that match the variable names) in the model: 0. 'R0' - Resistance 0 (ohmic resistance) 1. 'R1' - Resistance 1 2. 'R2' - Resistance 2 3. 'C1' - capacitance 1 (in parallel with R1 and the parallel combination of R2 and C2) 4. 'C2' - capacitance 2 (in parallel with R2) * frequency - frequency (or array of frequencies) to calculate impedance (rad / sec) #### z_b Outputs * Z($\omega$) - (complex number) [Link to Contents](#Contents) ``` def z_b(input_dict, frequency): R0 = input_dict['R0'] R1 = input_dict['R1'] R2 = input_dict['R2'] C1 = input_dict['C1'] C2 = input_dict['C2'] return(R0+1/(1/(R1+1/(1/R2+(1j*frequency)*C2))+(1j*frequency)*C1)) ``` ### Randles Circuit The following functions set up the calculations for a Randles circuit response. This is broken up into two functions: * [warburg](#warburg) * [z_randles](#z_randles) Breaking the solution process up in this way helps the readability of the functions and the process of decomposing circuit elements. Note that each of these functions take the same arguments and follow the template described [here](#Impedance-models). Using dictionaries (instead of lists/arrays) allows for the arguments to these functions to be generic so that they can extract the values that they need without needing inputs to be ordered, which allows for higher flexibility. [z_randles](#z_randles) is called by the function [cell_response](#cell_response) to determine the response of the symmetric cell. [Link to Contents](#Contents) ### warburg The Warburg element is modeled by: $$\frac{W}{A} = \frac{RT}{A_tn^2F^2C_RfD_R}\frac{tanh\bigg(a\sqrt{\frac{j\omega}{D_R}}\bigg)}{\sqrt{\frac{j\omega}{D_R}} }+\frac{RT}{A_tn^2F^2C_OfD_O}\frac{tanh\bigg(a\sqrt{\frac{j\omega}{D_O}}\bigg)}{\sqrt{\frac{j\omega}{D_O} }}$$ #### warburg Inputs * *input_dict*: a dictionary containing all the parameters for the full cell response, the warburge element only needs the entries for: * 'T' * 'C_R' * 'C_O' * 'D_R' * 'D_O' * 'n' * 'A_t' * 'a' * 'f' * frequency - frequency to calculate impedance (rad / sec) #### warburg Outputs * W($\omega$) - (complex number) [Link to Contents](#Contents) ``` def warburg(input_dict, frequency): T = input_dict['T'] A_t = input_dict['A_t'] C_R = input_dict['C_R'] C_O = input_dict['C_O'] D_R = input_dict['D_R'] D_O = input_dict['D_O'] n = input_dict['n'] a = input_dict['a'] f = input_dict['f'] c1 = (Ru*T)/(A_t*n**2*F**2*f) # both terms multiply c1 term1 = c1*tanh(a*sqrt(1j*frequency/D_R))/(C_R*sqrt(D_R*1j*frequency)) term2 = c1*tanh(a*sqrt(1j*frequency/D_O))/(C_O*sqrt(D_O*1j*frequency)) return(term1+term2) ``` ### z_randles z_randles calculates the response of a randles circuit element with no ohmic resistance (complex number). It calls [warburg](#warburg) and returns the serial combination of the charge transfer resistance and the warburg impedance in parallel with a constant phase element (CPE). ![](circuit_element/z_randles.png) This is modeled by the equation: $$Z_{Randles} = A \times (z_{ct}^{-1}+j\omega^{P}Q)^{-1}$$ The charge transfer impedance is modeled by the equation: $$z_{ct} = R_{ct} + W $$ Where the charge transfer resistance is calculated by the equation: $$R_{ct} = \frac{RT}{A_tnFi_0}$$ The term $\frac{1}{j\omega^PQ}$ represents the CPE. #### z_randles Inputs * *input_dict*: a dictionary containing all the parameters for the full cell response, z_randles only needs the entries for: * 'T' * 'n' * 'A_t' * 'i0' * frequency - frequency to calculate impedance (rad / sec) #### z_randles Outputs * Z_ct($\omega$) / ($\Omega$ cm$^2$) - (complex number) [Link to Contents](#Contents) ``` def z_randles( input_dict, frequency): T = input_dict['T'] n = input_dict['n'] A_t = input_dict['A_t'] i0 = input_dict['i0'] P = input_dict['P'] C_dl = input_dict['C_dl'] A = input_dict['A'] # Calculate Warburg Impedance w = warburg(input_dict,frequency) # Calculate charge transfer resistance R_ct = Ru*T/(n*F*i0*A_t) serial = R_ct+w z_ct = 1/(1/serial+(1j*frequency)**P*C_dl*A_t) return(A*z_ct) ``` ### z_mhpe *z_mhpe* calculates the response of the macrohomogeneous porous electrode model to the specified inputs. Note that this function calls [z_randles](#z_randles) to to determine the Randles circuit response. The derivation of this circuit element is equivalent to a branched transmission line with Randles circuit elements defining the interfacial interaction. Which interact with different amounts of electrolyte resistivity determined by the electrode thickness. ![](circuit_element/mhpe.png) This model was derived by Paasch *et al.* and has several equivalent formulations: Equation 22 from [Paasch *et al.*](https://doi.org/10.1016/0013-4686(93)85083-B) $$ AZ_{mhpe} = \frac{(\rho_1^2+\rho_2^2)}{(\rho_1+\rho_2)}\frac{ coth(b \beta)}{\beta} + \frac{2\rho_1 \rho_2 }{(\rho_1+\rho_2)}\frac{1}{\beta sinh(b \beta)} + \frac{\rho_1 \rho_2 b}{(\rho_1+\rho_2)}$$ Equation 10 from [Nguyen *et al.*](https://doi.org/10.1016/S0022-0728(98)00343-X) $$ Z_{mhpe} \frac{A}{b} = \frac{(\rho_1^2+\rho_2^2)}{(\rho_1+\rho_2)}\frac{\lambda}{b} coth\bigg(\frac{b}{\lambda}\bigg) + \frac{2\rho_1 \rho_2 }{(\rho_1+\rho_2)}\frac{\lambda}{b}\bigg(sinh\bigg(\frac{b}{\lambda}\bigg)\bigg)^{-1} + \frac{\rho_1 \rho_2 b}{(\rho_1+\rho_2)}$$ Equation 1 from [Sun *et al.*](https://www.osti.gov/biblio/1133556-resolving-losses-negative-electrode-all-vanadium-redox-flow-batteries-using-electrochemical-impedance-spectroscopy) $$ A Z_{mhpe} = \frac{(\rho_1^2+\rho_2^2) b}{(\rho_1+\rho_2)}\frac{coth(Q_2)}{Q_2} + \frac{2\rho_1 \rho_2 b}{(\rho_1+\rho_2)Q_2sinh(Q_2)} + \frac{\rho_1 \rho_2 b}{(\rho_1+\rho_2)}$$ Clearly if these are equivalent then: $$ b\beta = \frac{b}{\lambda} = Q_2$$ #### z_mhpe Inputs * *input_dict*: a dictionary containing all the parameters for the, MHPE response : * 'rho1' * 'rho2' - $\frac{\rho_{ 2}^*f_p}{\nu_p}$ (page 2654) where $\rho_2$ = bulk electrolyte resistivity, $f_p$ is the toruosity factor and $\nu_p$ is the relative pore volume * 'b' * frequency - frequency to calculate impedance (rad / sec) #### z_mhpe Outputs * AZ_mhpe ($\omega$) / ($\Omega$ cm$^2$) - (complex number) [Link to Contents](#Contents) ``` def z_mhpe( input_dict, frequency): rho1 = input_dict['rho1'] rho2 = input_dict['rho2'] b = input_dict['b'] C_dl = input_dict['C_dl'] A_t = input_dict['A_t'] A = input_dict['A'] T = input_dict['T'] n = input_dict['n'] i0 = input_dict['i0'] P = input_dict['P'] # these are the same for each formulation of the MHPE model coeff_1 = (rho1**2+rho2**2)/(rho1+rho2) coeff_2 = 2*rho1*rho2/(rho1+rho2) term_3 = rho1*rho2*b/(rho1+rho2) ##========================================================================= ## Sun et al. 2014 ##------------------------------------------------------------------------- ## note: z_r multiplies the response by A/At so this operation is already ## finished for equation 2 ##------------------------------------------------------------------------- #z_r = z_randles(input_dict,frequency) # equation 6 #Q2 = sqrt((rho1+rho2)*b/z_r) # equation 2 #term_1 = coeff_1*(b/Q2)*coth(Q2) #term_2 = coeff_2*(b/Q2)*sinh(Q2)**(-1) ##========================================================================= ## Paasch et al. '93 ##-------------------------------------------------------------------------- ## note: modification of g_ct (below equation 9) to include mass transfer ## conductance (on unit length basis) - recall that the warburg element ## already has A_t in its denominator so it is only multiplied by b to ## account for the fact that it has A*S_c in its denominator ##-------------------------------------------------------------------------- #S_c = A_t/(b*A) # below equation 2 #C_1 = A*S_c*C_dl # equation 3 #g_ct = 1/(Ru*T/(n*F*i0*S_c*A) + b*warburg(input_dict,frequency)) #k = g_ct/C_1 # equation 12 #K = 1/(C_dl*S_c*(rho1+rho2)) # equation 12 #omega_1 = K/b**2 # equation 23 #beta = (1/b)*((k+(1j*frequency)**P)/omega_1)**(1/2) # equation 23 #term_1 = coeff_1*(coth(b*beta)/beta) #term_2 = coeff_2*(1/beta)*sinh(b*beta)**(-1) ##========================================================================= # Nguyen et al. #-------------------------------------------------------------------------- # note: Paasch was a co-author and it uses much of the same notation as '93 # They use a mass transfer hindrance term instead of warburg, so it is # replaced again here like it was for the Paasch solution. Also notice that # omega_0 is equivalent to k in Paasch et al. # the warburg element function returns W with A_t already in the # denominator, so it is multiplied by b to account for the fact that it has # S_c*A in its denominator #-------------------------------------------------------------------------- S_c = A_t/(b*A) # below equation 4 g_ct = 1/(Ru*T/(n*F*i0*S_c*A) + b*warburg(input_dict,frequency)) omega_0 = g_ct/(C_dl*S_c*A) # equation 6 g = C_dl*S_c*((1j*frequency)**P+omega_0) # equation 5 lamb = 1/sqrt(g*(rho1+rho2)) # equation 4 term_1 = coeff_1*lamb*coth(b/lamb) term_2 = coeff_2*lamb*(sinh(b/lamb))**(-1) #-------------------------------------------------------------------------- mhpe = term_1+term_2+term_3 return(mhpe) ``` ### cell_response *cell_response* calculates the Randles circuit response of a symmetric cell, which is illustrated graphically in the following circuit model. ![](circuit_element/symmetric_cell.png) The symmetric cell is assumed to contribute equally with both half-cells which necessitates the $\times 2$. The following equation models this response: $$\frac{Z_{Randles}}{A} = R_{mem} + j \omega L + 2 \times z_{electrode}$$ Where $$z_{electrode} \in [z_{randles},z_{mhpe}]$$ #### cell_response Inputs * *input_dict*: a dictionary containing all the parameters for the full cell response, z_randles only needs the entries for: * 'A' * 'C_dl' * 'A_t' * 'P' * 'ASR_mem' * 'L' * frequency - frequency to calculate impedance (rad / sec) #### cell_response Outputs * AZ_randles$($\omega$) - (complex number) [Link to Contents](#Contents) ``` def cell_response( input_dict, frequency): A = input_dict['A'] ASR_mem = input_dict['ASR_mem'] L = input_dict['L'] z_model = input_dict['z_model'] # z_model can be z_randles or z_mhpe z_elec = z_model(input_dict,frequency) return(ASR_mem+2*z_elec+1j*L*frequency*A) ``` ## Least Squares This script uses [scipy.optimize.least_squares](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). To optimize the parameters. The two functions defined here are the *residual* calculation and the fitting function *z_fit* which facilitates the I/O for the least_squares with different models. [Link to Contents](#Contents) ### *residual* *residual* is a function which is an input to scipy.optimize.least_squares. It calculates the impedance response at a given frequency (or range of frequencies) and returns the difference between the generated value(s) and the experimental data. #### *residual* Inputs * x0 - a list, which stores the arguments that are inputs to *Z*. The parameters are unpacked in the following order: * frequency - frequency argument to *Z* (can be single value or array) * data - experimental data (complex number) * input_dict - a dictionary which contains at the minimum the values that the selected model expects * floating_params - *list* which contains the keys (which are entries in input_dict) for the floating parameters * model - for the impedance models described in this tutorial, each has a template format with 3 arguments. For this reason, they can be treated as arguments to *residual* and can be used interchangeably. #### *residual* Outputs * 1D array (real numbers) with difference (at each frequency) between experimental and simulated spectrum [Link to Contents](#Contents) ``` def residual( x0, frequency, data, input_dict, floating_params, model): # the dictionary (temp_dict) is the interface between the residual calculation and the # models, by having the residual seed temp_dict with the floating # parameters, the level of abstraction given to ability of parameters to # float is increased. (not all of the models will need the same format and # they can parse dictionaries for values they are expecting) temp_dict = {} for i,key in enumerate(floating_params): temp_dict[key] = x0[i] for key in input_dict: if key not in floating_params: temp_dict[key] = input_dict[key] # generate a spectrum with the inputs Z_ = model( temp_dict,frequency) # Calculate the difference between the newly generated spectrum and the # experimental data Real = real(Z_)-real(data) Imag = imag(Z_)-imag(data) return(concatenate([Real,Imag])) ``` ### *z_fit* *z_fit* sets up the call to [scipy.optimize.least_squares](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html) and returns the fitted parameters #### *z_fit* Inputs * inputDict - a dictionary which contains the initial guess for the parameters. * residualFunction - residual to be minimized by least_squares * ReZ - real component of complex impedance ($\Omega$) * ImZ - imaginary component of complex impedance ($\Omega$) * frequency - array with same dimensions as ReZ and ImZ (rad s$^{-1}$) * area - geometric surface area (cm$^2$) * model - both z_a and z_b are valid input arguments as the model for Zfit to use. * constants - fixed parameters for the model * oneMaxKeys - *optional* - a list containing any parameters that have a maximum value of 1 (i.e. CPE exponent P) *z_fit* converts the input data from individual ReZ and ImZ arrays of resistances (in $\Omega$) to complex impedance values in ASR ($\Omega$ cm$^2$). The bounds_lower and bounds_upper variables set the bounds for the parameters (i.e. non-negative for this case). **Note**: The order of the arguments in bounds_lower and bounds_upper is the same as the order of x0 and correspond to parameters which share the same index. The default method for least_squares is *Trust Region Reflective* ('trf'), which is well suited for this case. The variable *out* contains the output of the call to least_squares. [Link to Contents](#Contents) ``` def z_fit( input_dict, ReZ, ImZ, frequency, floating_params, area, model, residual_function, one_max_keys = []): # parameter order -> [R0, R1, R2, C1, C2] data = (ReZ-1j*ImZ)*area # Set the bounds for the parameters x0 = [input_dict[key] for key in floating_params] bounds_lower = [0 for key in floating_params] bounds_upper = [inf if param not in one_max_keys else 1 for param in floating_params] out = least_squares( residual_function, x0, bounds = (bounds_lower,bounds_upper), args = (frequency,data,input_dict,floating_params,model)) output_dict = {} j = 0 print("-"*80) print("model = {}".format(input_dict['z_model'].__name__)) for key in floating_params: output_dict[key] = out.x[j] print("\t{} = {}".format(key,out.x[j])) j+=1 for key in input_dict: if key not in floating_params: output_dict[key] = input_dict[key] # the fitted parameters are extracted from the 'output' variable return(output_dict) ``` ### z_plot *z_plot* is a function used to generate plots of the spectra (both experiment and model). It creates a subplot with two columns: the first column is an Argand diagram (Nyquist plot) comparing the experimetn and model; the second column compares the spectra (real and imaginary components) as a function of frequency. #### *z_plot* Inputs * ReZ - Real(Z) of a spectrum * ImZ - Imaginary(Z) of a spectrum * ax_1 - handle for axis with nyquist plot * ax_2 - handle for axis with frequency plot * label - label the curves on each axis * color - *optional* - list of colors to be used * marker - *optional* - list of markers to be used * linestyle - *optional* - linestyle specifier * resistances - (list) contains the intercepts with the real axis [Link to Contents](#Contents) ``` def z_plot(ReZ, ImZ, frequency, ax_1, ax_2, label, color = ['k','k'], marker = ['x','+'], linestyle = '', resistances = []): # Nyquist plot for the spectrum ax_1.plot(ReZ,-ImZ,color = color[0], marker = marker[0], linestyle = linestyle, label = label) # plotting the real axis intercepts if resistances != []: R0,R1,R2 = resistances ax_1.plot(R0,0,'b+') ax_1.plot(R0+R1,0,'b+') ax_1.plot(R0+R1+R2,0,'b+',label = 'model ASR estimation') ax_1.axis('equal') ax_1.set_xlabel('Re(Z) / $\Omega$ cm$^2$') ax_1.set_ylabel('-Im(Z) / $\Omega$ cm$^2$') # |Z| as a function of frequency ax_2.plot(log(frequency),-ImZ,color = color[0], marker = marker[0], label = "-Im({})".format(label), linestyle = linestyle) ax_2.plot(log(frequency),ReZ,color = color[1], marker = marker[1], label = "Re({})".format(label), linestyle = linestyle) ax_2.set_xlabel('log(frequency) / rad s$^{-1}$') ax_2.set_ylabel('|Z| / $\Omega$ cm$^2$') ax_2.yaxis.set_label_position('right') [ax.legend(loc = 'best') for ax in [ax_1,ax_2]] ``` ### high_frequency_detail *high_frequency_detail* #### *high_frequency_detail* Inputs * ReZ - Real(Z) of a spectrum * ImZ - Imaginary(Z) of a spectrum * ax - handle for axis for nyquist plot * label - label the curves on each axis * color - *optional* - string with color * marker - *optional* - string with marker to be used * linestyle - *optional* - linestyle specifier * spacing - *optional* - how wide and tall the window will be * xlim - *optional* - list containing x limits for plot * ylim - *optional* - list containing y limits for plot [Link to Contents](#Contents) ``` def high_frequency_detail( ReZ, ImZ, ax, label, color = 'k', marker = 'x', linestyle = '', spacing = 2, x_min = 0, y_min = 0): ax.plot( ReZ,ImZ, color = color, marker = marker, label = label, linestyle = linestyle) ax.set_ylim(y_min,y_min+spacing) ax.set_xlim(x_min,x_min+spacing) ax.set_xlabel('Re(Z) / $\Omega$ cm$^2$') ax.set_ylabel('-Im(Z) / $\Omega$ cm$^2$') ``` ## Examples The following are examples demonstrating the I/O for the functions. These are the *forward* calculations of spectra (i.e. the parameters are knowns). [Here](#Curve-Fitting-Examples) is a link to the examples for curve fitting the experimental data. [Link to Contents](#Contents) ### Example Usage of z_a [Link to Contents](#Contents) ``` input_dict = { 'R0':1, 'R1':2, 'R2':2, 'C1':10e-6, 'C2':10e-3, 'z_model':z_a } fre = 100 # uncomment the following line to use a numpy array as an input to z_a #fre = logspace(-1,6,60) z_ = z_a(input_dict,fre) print(z_) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = 0) z_plot(real(z_),imag(z_),fre,ax[0],ax[1],'z_a') ``` ### Example Usage of *z_b* [Link to Contents](#Contents) ``` input_dict = { 'R0':1, 'R1':2, 'R2':2, 'C1':10e-6, 'C2':10e-3, 'z_model':z_b } fre = 100 # uncomment the following line to use a numpy array as an input to z_b #fre = logspace(-1,6,60) z_ = z_b(input_dict,fre) print(z_) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = 1) z_plot(real(z_),imag(z_),fre,ax[0],ax[1],'z_b') ``` ### Example usage of cell_response [Link to Contents](#Contents) ``` # Example Usage of cell_response input_dict = { 'T':303.15, # Temperature (K) 'A':5, # geometric surface area (cm^2) 'C_R':0.00025, # concentration of reduced species (mol / L) 'C_O':0.00025, # concentration of oxidized species (mol / L) 'rho1':1.6, # electrolyte resistivity (ohm cm^-1) 'rho2':.012, # solid phase resistivity (ohm cm^-1) 'b':.3, # electrode thickness (cm) 'D_R':1.1e-6, # Diffusion coefficient for reduced species (cm^2 / s) 'D_O':0.57e-6, # Diffusion coefficient for oxidized species (cm^2 / s) 'C_dl':20e-6, # Double layer capacitance per unit surface area 'n':1, # number of electrons transferred 'A_t':100, # Wetted surface area (cm^2) 'i0':3e-4, # exchange current density (A cm^2) 'P':.95, # CPE exponent (-) 'ASR_mem':.5, # membrane ASR (Ohm cm^2) 'a':.002, # Nernstian diffusion layer thickness (cm) 'f':.05, # scale factor (-) 'L':1e-7, # inductance (H) } fre = 100 # frequency to evaluate (rad / s) #--------------------------------------------------------------------------- # uncomment the following line to use a numpy array as an input to Z_Randles #--------------------------------------------------------------------------- #fre = logspace(-1,6,60) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = 2) for j,model in enumerate([z_randles,z_mhpe]): input_dict['z_model'] = model print("-"*80) print("Model name = ",model.__name__) z_ = cell_response(input_dict,fre) print(z_) z_plot(real(z_),imag(z_), fre, ax[0], ax[1], model.__name__, color = [colors[j]]*2) ``` ### Example usage of *residual* **Note**: *residual* is only used in the scope of [*z_fit*](#z_fit) as an argument for *scipy.optimize.least_squares*. This is simply to illustrate the way it is called. ``` input_dict = { 'R0':1, 'R1':2, 'R2':2, 'C1':10e-6, 'C2':10e-6, 'z_model':'z_a' } floating_params = list(input_dict.keys()) x0 = [input_dict[key] for key in input_dict] area = 5 # artificial data point and frequency Zexperimental = (2-1j*.3)*area freExperimental = 10 # using model z_a for this example model = z_a print(residual( x0, array([freExperimental]), array([Zexperimental]), input_dict, floating_params, model) ) ``` ## Experimental Data * 0.5 M V * 50% SoC (Anolyte) * Untreated GFD3 Electrode * 5 cm$^2$ flow through (4 cm $\times$ 1.25 cm) * Symmetric Cell * 30$^o$ C * 25 mL min$^{-1}$ * 5 mV amplitude * 50 kHz - 60 mHz (10 points per decade) * recorded with a Bio-Logic VSP potentiostat [Link to Contents](#Contents) ``` ReZ = array([ 0.08284266, 0.08796988, 0.09247773, 0.09680536, 0.1008338, 0.1046377, 0.10762515, 0.11097036, 0.11456104, 0.11730141, 0.12102044, 0.12483983, 0.12752137, 0.13284937, 0.13733491, 0.14415036, 0.15262745, 0.16596687, 0.18005887, 0.20618707, 0.23595014, 0.28682289, 0.35581028, 0.4261204, 0.56032306, 0.66784477, 0.80271685, 0.94683707, 1.0815266 , 1.1962512, 1.3139805, 1.4123734, 1.4371094, 1.4075497, 1.451781 , 1.4999349, 1.4951819, 1.520785, 1.5343723, 1.5442845, 1.5559914, 1.5715505, 1.581386, 1.6037546, 1.6127067, 1.6335728, 1.6475986 , 1.6718234, 1.6902045, 1.7113601, 1.7273785, 1.7500663, 1.7663705 , 1.7867819, 1.8013573, 1.8191988, 1.83577, 1.8508064, 1.8635432 , 1.8764733 ]) ImZ = array([ 0.01176712, 0.01655927, 0.02027502, 0.02348918, 0.02688588, 0.02939095, 0.03261841, 0.03675437, 0.04145328, 0.04685605, 0.05258239, 0.06055644, 0.07127699, 0.08661526, 0.10406214, 0.12678802, 0.15203825, 0.18704301, 0.2319441, 0.27572113, 0.33624849, 0.39666826, 0.47322401, 0.53811002, 0.58483958, 0.63875258, 0.66788822, 0.64877927, 0.58104825, 0.54410547, 0.46816054, 0.39988503, 0.36872765, 0.30746305, 0.26421374, 0.22142638, 0.18307872, 0.15832621, 0.14938028, 0.14581558, 0.13111286, 0.12468486, 0.12108799, 0.12532991, 0.12312792, 0.12196486, 0.12405467, 0.12505658, 0.12438187, 0.12210829, 0.11554052, 0.11543264, 0.11017759, 0.10541131, 0.0994625, 0.09146828, 0.0852076, 0.0776009, 0.06408801, 0.05852762]) frequency = 2*pi*array([ 5.0019516e+04, 3.9687492e+04, 3.1494135e+04, 2.5019525e+04, 1.9843742e+04, 1.5751949e+04, 1.2519524e+04, 9.9218750e+03, 7.8710889e+03, 6.2695298e+03, 5.0195298e+03, 4.0571001e+03, 3.2362456e+03, 2.4807932e+03, 1.9681099e+03, 1.5624999e+03, 1.2403966e+03, 9.8405493e+02, 7.8124994e+02, 6.2019836e+02, 4.9204675e+02, 3.9062488e+02, 3.0970264e+02, 2.4602338e+02, 1.9531244e+02, 1.5485132e+02, 1.2299269e+02, 9.7656219e+01, 7.7504944e+01, 6.1515743e+01, 4.8828110e+01, 3.8771706e+01, 3.0757868e+01, 2.4414059e+01, 1.9385853e+01, 1.5358775e+01, 1.2187985e+01, 9.6689367e+00, 7.6894670e+00, 6.0939932e+00, 4.8344669e+00, 3.8447335e+00, 3.0493746e+00, 2.4172332e+00, 1.9195327e+00, 1.5246876e+00, 1.2086166e+00, 9.5976633e-01, 7.6234382e-01, 6.0430837e-01, 4.7988322e-01, 3.8109747e-01, 3.0215418e-01, 2.3994161e-01, 1.9053015e-01, 1.5107709e-01, 1.1996347e-01, 9.5265076e-02, 7.5513750e-02, 5.9981719e-02]) ``` ## Curve Fitting Examples ### Example fitting a spectrum (z_a and z_b) [Link to Experimental data](#Experimental-Data) A *for* loop is used to iterate over the impedance models ([z_a](#z_a) and . Each iteration calculates new values for the resistances and capacitances and prints their values. A new spectrum (Z_) is generated with a call to each respective model with the newly fitted parameters. Z_ is then plotted against the experimental data. The model is shown in both an Argand diagram (Nyquist plot) and as a function of the frequency. [Link to Contents](#Contents) ``` input_dict = { 'R0':1, 'R1':2, 'R2':2, 'C1':10e-6, 'C2':10e-6, } floating_params = [key for key in input_dict] # calculating the fitted parameters with z_fit and printing their values for i,model in enumerate([z_a,z_b]): input_dict['z_model'] = model fit_spectrum = z_fit( input_dict, ReZ, ImZ, frequency, floating_params, area, model, residual) # generating a new spectrum with fitted parameters Z_ = model(fit_spectrum,frequency) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = i+3) z_plot(real(Z_),imag(Z_),frequency,ax[0],ax[1],model.__name__,color = ['r','b'],marker = ['.','.']) z_plot(ReZ*5,-ImZ*5,frequency,ax[0],ax[1],'Experiment',color = ['k','k'],marker = ['x','+']) plt.show() ``` ### Comments for z_a and z_b The models used to fit this spectrum were chosen arbitrarily as circuits that can model spectra with two semi-circles. Equivalent circuit models should always be chosen (or formulated) based on the physics of an electrochemical interface and not on the manifestation of the interface at the macro level. Clearly these models have a few limitations: * HFR - This experimental spectrum has a small distributed ionic resistance that the model is incapable of capturing. This can be observed from zooming in the high frequency content of the Nyquist plot, as well as the deviation of Re(z_a) and Re(z_b) from Re(Experiment) in the frequency plot. The result of this is that the membrane resistance will be overestimated. * Ambiguity of circuit elements in z_a - Because R1 and R2 are both resistors in parallel with capacitors, there is no guarantee that R1 will correspond with Rct and R2 will correspond with R2. The starting guesses will determine this and not the interface physics. * Constant Phase Element (CPE) - The discrepancy between Im(Z_) and Im(Experiment) in the Nyquist plot can be aided by improved by using a CPE * Capacitances in z_a - There is no reason to expect that C1 and C2 would be fully independent The model does, however, give a decent estimate of the chord of the charge transfer resistance and the diffusion resistance with some interpretation of the data. [Link to Contents](#Contents) ### Example fitting a spectrum (z_randles) [link to z_randles](#z_randles) [Link to Contents](#Contents) ``` input_dict = { 'T':303.15, # Temperature (K) 'A':5, # geometric surface area (cm^2) 'C_R':0.00025, # concentration of reduced species (mol / L) 'C_O':0.00025, # concentration of oxidized species (mol / L) 'D_R':1.1e-6, # Diffusion coefficient for reduced species (cm^2 / s) 'D_O':0.57e-6, # Diffusion coefficient for oxidized species (cm^2 / s) 'C_dl':20e-6, # Double layer capacitance per unit surface area 'n':1, # number of electrons transferred 'A_t':100, # Wetted surface area (cm^2) 'i0':1e-4, # exchange current density (A cm^2) 'P':.95, # CPE exponent (-) 'ASR_mem':.5, # membrane ASR (Ohm cm^2) 'a':.001, # Nernstian diffusion layer thickness (cm) 'f':.01, # scale factor (-) 'L':1e-7, # inductance (H) 'z_model':z_randles # tells cell_response to use z_randles for the electrode } floating_params = ['A_t','i0','P','ASR_mem','a','f','L'] # calculating the fitted parameters with z_fit and printing their values model = cell_response fit_spectrum = z_fit( input_dict, ReZ, ImZ, frequency, floating_params, area, model, residual, one_max_keys = ['P']) # generating a new spectrum with fitted parameters Z_ = model(fit_spectrum,frequency) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = 5) z_plot(real(Z_),imag(Z_), frequency, ax[0], ax[1], input_dict['z_model'].__name__, color = ['r','b'], marker = ['.','.']) z_plot(ReZ*5,-ImZ*5,frequency,ax[0],ax[1],'Experiment',color = ['k','k'],marker = ['x','+']) plt.savefig('spectrumTest.png',dpi=300) plt.show() plt.figure(6, figsize = (10,10)) ax = plt.gca() spacing = 2 y_min = -.25 x_min = 0 high_frequency_detail(ReZ*5,ImZ*5, ax, 'experiment',y_min = y_min, x_min = x_min, spacing = spacing) high_frequency_detail(real(Z_),-imag(Z_), ax, 'z_mhpe', color = 'r', marker = '.', x_min = x_min, y_min = y_min, spacing = spacing) ``` ### Example fitting a spectrum (z_mhpe) [link to z_mhpe](#z_mhpe) [Link to Contents](#Contents) ``` input_dict = { 'T':303.15, # Temperature (K) 'A':5, # geometric surface area (cm^2) 'C_R':0.00025, # concentration of reduced species (mol / L) 'C_O':0.00025, # concentration of oxidized species (mol / L) 'rho1':1.6, # electrolyte resistivity (ohm cm^-1) 'rho2':.012, # solid phase resistivity (ohm cm^-1) 'b':.3, # electrode thickness (cm) 'D_R':1.1e-6, # Diffusion coefficient for reduced species (cm^2 / s) 'D_O':0.57e-6, # Diffusion coefficient for oxidized species (cm^2 / s) 'C_dl':20e-6, # Double layer capacitance per unit surface area 'n':1, # number of electrons transferred 'A_t':100, # Wetted surface area (cm^2) 'i0':3e-4, # exchange current density (A cm^2) 'P':.95, # CPE exponent (-) 'ASR_mem':.5, # membrane ASR (Ohm cm^2) 'a':.002, # Nernstian diffusion layer thickness (cm) 'f':.05, # scale factor (-) 'L':1e-7, # inductance (H) 'z_model':z_mhpe } floating_params = ['A_t','i0','P','ASR_mem','a','f','L'] # calculating the fitted parameters with z_fit and printing their values model = cell_response fit_spectrum = z_fit( input_dict, ReZ, ImZ, frequency, floating_params, area, model, residual, one_max_keys = ['P']) # generating a new spectrum with fitted parameters Z_ = model(fit_spectrum,frequency) fig,ax = plt.subplots(nrows = 1, ncols = 2, figsize = fs, num = 7) z_plot( real(Z_),imag(Z_), frequency, ax[0], ax[1], input_dict['z_model'].__name__, color = ['r','b'], marker = ['.','.']) z_plot( ReZ*5,-ImZ*5, frequency, ax[0], ax[1], 'Experiment', color = ['k','k'], marker = ['x','+']) plt.savefig('spectrumTest.png',dpi=300) plt.show() plt.figure(8, figsize = (10,10)) ax = plt.gca() spacing = 2 y_min = -.25 x_min = 0 high_frequency_detail( ReZ*5,ImZ*5, ax, 'experiment',y_min = y_min, x_min = x_min, spacing = spacing) high_frequency_detail( real(Z_),-imag(Z_), ax, 'z_mhpe', color = 'r', marker = '.', x_min = x_min, y_min = y_min, spacing = spacing) ``` ## Appendix [Link to Contents](#Contents) ### Notes on coding style: * I have tried to stick to PEP 8 style for function and variable naming as much as possible. * It should be noted that for later versions of python, dictionary insertion order is preserved so that when the keys are queried, they return in the same order as they were inserted (not sorted alphabetically, etc.). For this reason, [z_fit](#z_fit) can use a list comprehension to extract the values of inputDict into x0 in the same order they were inserted. Without this, there is no guarantee that x0 will correspond to the expected argument that the respective model is receiving. * When a list is unpacked into parameters, passing an underscore is used only to highlight that this parameter is not used in that particular scope. * Text folding: the triple curly bracket sets are to mark the text folding. since they are behind the comment symbol ("#") they are not part of the code, but only for the text editor to hide
github_jupyter
``` import os from tensorflow.keras import layers from tensorflow.keras import Model !wget --no-check-certificate \ https://storage.googleapis.com/mledu-datasets/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 \ -O /tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 from tensorflow.keras.applications.inception_v3 import InceptionV3 local_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5' pre_trained_model = InceptionV3(input_shape = (150, 150, 3), include_top = False, weights = None) pre_trained_model.load_weights(local_weights_file) for layer in pre_trained_model.layers: layer.trainable = False pre_trained_model.summary() last_layer = pre_trained_model.get_layer('mixed7') print('last layer output shape: ', last_layer.output_shape) last_output = last_layer.output from tensorflow.keras.optimizers import RMSprop # Flatten the output layer to 1 dimension x = layers.Flatten()(last_output) # Add a fully connected layer with 1,024 hidden units and ReLU activation x = layers.Dense(1024, activation='relu')(x) # Add a dropout rate of 0.2 x = layers.Dropout(0.2)(x) # Add a final sigmoid layer for classification x = layers.Dense (1, activation='sigmoid')(x) model = Model( pre_trained_model.input, x) model.compile(optimizer = RMSprop(lr=0.0001), loss = 'binary_crossentropy', metrics = ['accuracy']) !wget --no-check-certificate \ https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip \ -O /tmp/cats_and_dogs_filtered.zip from tensorflow.keras.preprocessing.image import ImageDataGenerator import os import zipfile local_zip = '//tmp/cats_and_dogs_filtered.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp') zip_ref.close() # Define our example directories and files base_dir = '/tmp/cats_and_dogs_filtered' train_dir = os.path.join( base_dir, 'train') validation_dir = os.path.join( base_dir, 'validation') train_cats_dir = os.path.join(train_dir, 'cats') # Directory with our training cat pictures train_dogs_dir = os.path.join(train_dir, 'dogs') # Directory with our training dog pictures validation_cats_dir = os.path.join(validation_dir, 'cats') # Directory with our validation cat pictures validation_dogs_dir = os.path.join(validation_dir, 'dogs')# Directory with our validation dog pictures train_cat_fnames = os.listdir(train_cats_dir) train_dog_fnames = os.listdir(train_dogs_dir) # Add our data-augmentation parameters to ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255., rotation_range = 40, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) # Note that the validation data should not be augmented! test_datagen = ImageDataGenerator( rescale = 1.0/255. ) # Flow training images in batches of 20 using train_datagen generator train_generator = train_datagen.flow_from_directory(train_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150)) # Flow validation images in batches of 20 using test_datagen generator validation_generator = test_datagen.flow_from_directory( validation_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150)) history = model.fit( train_generator, validation_data = validation_generator, steps_per_epoch = 100, epochs = 20, validation_steps = 50, verbose = 2) import matplotlib.pyplot as plt acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend(loc=0) plt.figure() plt.show() ```
github_jupyter
``` %matplotlib inline import ipywidgets as widgets from ipywidgets import interact import numpy as np import matplotlib.pyplot as pl from scipy.spatial.distance import cdist from numpy.linalg import inv import george ``` # Gaussian process regression ## Lecture 1 ### Suzanne Aigrain, University of Oxford #### LSST DSFP Session 4, Seattle, Sept 2017 - Lecture 1: Introduction and basics - Tutorial 1: Write your own GP code - Lecture 2: Examples and practical considerations - Tutorial 3: Useful GP modules - Lecture 3: Advanced applications ## Why GPs? - flexible, robust probabilistic regression and classification tools. - applied across a wide range of fields, from finance to zoology. - useful for data containing non-trivial stochastic signals or noise. - time-series data: causation implies correlation, so noise always correlated. - increasingly popular in astronomy [mainly time-domain, but not just]. #### Spitzer exoplanet transits and eclipses (Evans et al. 2015) <img src="images/Evans_Spitzer.png" width="800"> #### GPz photometric redshifts (Almosallam, Jarvis & Roberts 2016) <img src="images/Almosallam_GPz.png" width="600"> ## What is a GP? A Gaussian process is a collection of random variables, any finite number of which have a joint Gaussian distribution. Consider a scalar variable $y$, drawn from a Gaussian distribution with mean $\mu$ and variance $\sigma^2$: $$ p(y) = \frac{1}{\sqrt{2 \pi} \sigma} \exp \left[ - \frac{(y-\mu)^2}{2 \sigma^2} \right]. $$ As a short hand, we write: $y \sim \mathcal{N}(\mu,\sigma^2)$. ``` def gauss1d(x,mu,sig): return np.exp(-(x-mu)**2/sig*2/2.)/np.sqrt(2*np.pi)/sig def pltgauss1d(sig=1): mu=0 x = np.r_[-4:4:101j] pl.figure(figsize=(10,7)) pl.plot(x, gauss1d(x,mu,sig),'k-'); pl.axvline(mu,c='k',ls='-'); pl.axvline(mu+sig,c='k',ls='--'); pl.axvline(mu-sig,c='k',ls='--'); pl.axvline(mu+2*sig,c='k',ls=':'); pl.axvline(mu-2*sig,c='k',ls=':'); pl.xlim(x.min(),x.max()); pl.ylim(0,1); pl.xlabel(r'$y$'); pl.ylabel(r'$p(y)$'); return interact(pltgauss1d, sig=widgets.FloatSlider(value=1.0, min=0.5, max=2.0, step=0.25, description=r'$\sigma$', readout_format='.2f')); ``` Now let us consider a pair of variables $y_1$ and $y_2$, drawn from a *bivariate Gaussian distribution*. The *joint probability density* for $y_1$ and $y_2$ is: $$ \left[ \begin{array}{l} y_1 \\ y_2 \end{array} \right] \sim \mathcal{N} \left( \left[ \begin{array}{l} \mu_1 \\ \mu_2 \end{array} \right] , \left[ \begin{array}{ll} \sigma_1^2 & C \\ C & \sigma_2^2 \end{array} \right] \right), $$ where $C = {\rm cov}(y_1,y_2)$ is the *covariance* between $y_1$ and $y_2$. The second term on the right hand side is the *covariance matrix*, $K$. We now use two powerful *identities* of Gaussian distributions to elucidate the relationship between $y_1$ and $y_2$. The *marginal distribution* of $y_1$ describes what we know about $y_1$ in the absence of any other information about $y_2$, and is simply: $$ p(y_1)= \mathcal{N} (\mu_1,\sigma_1^2). $$ If we know the value of $y_2$, the probability density for $y_1$ collapses to the the *conditional distribution* of $y_1$ given $y_2$: $$ p(y_1 \mid y_2) = \mathcal{N} \left( \mu_1 + C (y_2-\mu_2)/\sigma_2^2, \sigma_1^2-C^2\sigma_2^2 \right). $$ If $K$ is diagonal, i.e. if $C=0$, $p(y_1 \mid y_2) = p(y_1)$. Measuring $y_2$ doesn't teach us anything about $y_1$. The two variables are *uncorrelated*. If the variables are *correlated* ($C \neq 0$), measuring $y_2$ does alter our knowledge of $y_1$: it modifies the mean and reduces the variance. ``` def gauss2d(x1,x2,mu1,mu2,sig1,sig2,rho): z = (x1-mu1)**2/sig1**2 + (x2-mu2)**2/sig2**2 - 2*rho*(x1-mu1)*(x2-mu2)/sig1/sig2 e = np.exp(-z/2/(1-rho**2)) return e/(2*np.pi*sig1*sig2*np.sqrt(1-rho**2)) def pltgauss2d(rho=0,show_cond=0): mu1, sig1 = 0,1 mu2, sig2 = 0,1 y2o = -1 x1 = np.r_[-4:4:101j] x2 = np.r_[-4:4:101j] x22d,x12d = np.mgrid[-4:4:101j,-4:4:101j] y = gauss2d(x12d,x22d,mu1,mu2,sig1,sig2,rho) y1 = gauss1d(x1,mu1,sig1) y2 = gauss1d(x2,mu2,sig2) mu12 = mu1+rho*(y2o-mu2)/sig2**2 sig12 = np.sqrt(sig1**2-rho**2*sig2**2) y12 = gauss1d(x1,mu12,sig12) pl.figure(figsize=(10,10)) ax1 = pl.subplot2grid((3,3),(1,0),colspan=2,rowspan=2,aspect='equal') v = np.array([0.02,0.1,0.3,0.6]) * y.max() CS = pl.contour(x1,x2,y,v,colors='k') if show_cond: pl.axhline(y2o,c='r') pl.xlabel(r'$y_1$'); pl.ylabel(r'$y_2$'); pl.xlim(x1.min(),x1.max()) ax1.xaxis.set_major_locator(pl.MaxNLocator(5, prune = 'both')) ax1.yaxis.set_major_locator(pl.MaxNLocator(5, prune = 'both')) ax2 = pl.subplot2grid((3,3),(0,0),colspan=2,sharex=ax1) pl.plot(x1,y1,'k-') if show_cond: pl.plot(x1,y12,'r-') pl.ylim(0,0.8) pl.ylabel(r'$p(y_1)$') pl.setp(ax2.get_xticklabels(), visible=False) ax2.xaxis.set_major_locator(pl.MaxNLocator(5, prune = 'both')) ax2.yaxis.set_major_locator(pl.MaxNLocator(4, prune = 'upper')) pl.xlim(x1.min(),x1.max()) ax3 = pl.subplot2grid((3,3),(1,2),rowspan=2,sharey=ax1) pl.plot(y2,x2,'k-') if show_cond: pl.axhline(y2o,c='r') pl.ylim(x2.min(),x2.max()); pl.xlim(0,0.8); pl.xlabel(r'$p(y_2)$') pl.setp(ax3.get_yticklabels(), visible=False) ax3.xaxis.set_major_locator(pl.MaxNLocator(4, prune = 'upper')) ax3.yaxis.set_major_locator(pl.MaxNLocator(5, prune = 'both')) pl.subplots_adjust(hspace=0,wspace=0) return interact(pltgauss2d, rho=widgets.FloatSlider(min=-0.8,max=0.8,step=0.4,description=r'$\rho$',value=0), show_cond=widgets.Checkbox(value=True,description='show conditional distribution')); ``` To make the relation to time-series data a bit more obvious, let's plot the two variables side by side, then see what happens to one variable when we observe (fix) the other. ``` def SEKernel(par, x1, x2): A, Gamma = par D2 = cdist(x1.reshape(len(x1),1), x2.reshape(len(x2),1), metric = 'sqeuclidean') return A * np.exp(-Gamma*D2) A = 1.0 Gamma = 0.01 x = np.array([-1,1]) K = SEKernel([A,Gamma],x,x) m = np.zeros(len(x)) sig = np.sqrt(np.diag(K)) pl.figure(figsize=(15,7)) pl.subplot(121) for i in range(len(x)): pl.plot([x[i]-0.1,x[i]+0.1],[m[i],m[i]],'k-') pl.fill_between([x[i]-0.1,x[i]+0.1], [m[i]+sig[i],m[i]+sig[i]], [m[i]-sig[i],m[i]-sig[i]],color='k',alpha=0.2) pl.xlim(-2,2) pl.ylim(-2,2) pl.xlabel(r'$x$') pl.ylabel(r'$y$'); def Pred_GP(CovFunc, CovPar, xobs, yobs, eobs, xtest): # evaluate the covariance matrix for pairs of observed inputs K = CovFunc(CovPar, xobs, xobs) # add white noise K += np.identity(xobs.shape[0]) * eobs**2 # evaluate the covariance matrix for pairs of test inputs Kss = CovFunc(CovPar, xtest, xtest) # evaluate the cross-term Ks = CovFunc(CovPar, xtest, xobs) # invert K Ki = inv(K) # evaluate the predictive mean m = np.dot(Ks, np.dot(Ki, yobs)) # evaluate the covariance cov = Kss - np.dot(Ks, np.dot(Ki, Ks.T)) return m, cov xobs = np.array([-1]) yobs = np.array([1.0]) eobs = 0.0001 pl.subplot(122) pl.errorbar(xobs,yobs,yerr=eobs,capsize=0,fmt='k.') x = np.array([1]) m,C=Pred_GP(SEKernel,[A,Gamma],xobs,yobs,eobs,x) sig = np.sqrt(np.diag(C)) for i in range(len(x)): pl.plot([x[i]-0.1,x[i]+0.1],[m[i],m[i]],'k-') pl.fill_between([x[i]-0.1,x[i]+0.1], [m[i]+sig[i],m[i]+sig[i]], [m[i]-sig[i],m[i]-sig[i]],color='k',alpha=0.2) pl.xlim(-2,2) pl.ylim(-2,2) pl.xlabel(r'$x$') pl.ylabel(r'$y$'); ``` Now consider $N$ variables drawn from a multivariate Gaussian distribution: $$ \boldsymbol{y} \sim \mathcal{N} (\boldsymbol{m},K) $$ where $y = (y_1,y_2,\ldots,y_N)^T$, $\boldsymbol{m} = (m_1,m_2,\ldots,m_N)^T$ is the *mean vector*, and $K$ is an $N \times N$ positive semi-definite *covariance matrix*, with elements $K_{ij}={\rm cov}(y_i,y_j)$. A Gaussian process is an extension of this concept to infinite $N$, giving rise to a probability distribution over functions. This last generalisation may not be obvious conceptually, but in practice only ever deal with finite samples. ``` xobs = np.array([-1,1,2]) yobs = np.array([1,-1,0]) eobs = np.array([0.0001,0.1,0.1]) pl.figure(figsize=(15,7)) pl.subplot(121) pl.errorbar(xobs,yobs,yerr=eobs,capsize=0,fmt='k.') Gamma = 0.5 x = np.array([-2.5,-2,-1.5,-0.5, 0.0, 0.5,1.5,2.5]) m,C=Pred_GP(SEKernel,[A,Gamma],xobs,yobs,eobs,x) sig = np.sqrt(np.diag(C)) for i in range(len(x)): pl.plot([x[i]-0.1,x[i]+0.1],[m[i],m[i]],'k-') pl.fill_between([x[i]-0.1,x[i]+0.1], [m[i]+sig[i],m[i]+sig[i]], [m[i]-sig[i],m[i]-sig[i]],color='k',alpha=0.2) pl.xlim(-3,3) pl.ylim(-3,3) pl.xlabel(r'$x$') pl.ylabel(r'$y$'); pl.subplot(122) pl.errorbar(xobs,yobs,yerr=eobs,capsize=0,fmt='k.') x = np.linspace(-3,3,100) m,C=Pred_GP(SEKernel,[A,Gamma],xobs,yobs,eobs,x) sig = np.sqrt(np.diag(C)) pl.plot(x,m,'k-') pl.fill_between(x,m+sig,m-sig,color='k',alpha=0.2) pl.xlim(-3,3) pl.ylim(-3,3) pl.xlabel(r'$x$') pl.ylabel(r'$y$'); ``` ## Textbooks A good, detailed reference is [*Gaussian Processes for Machine Learning*](http://www.gaussianprocess.org/gpml/) by C. E. Rasmussen & C. Williams, MIT Press, 2006. The examples in the book are generated using the `Matlab` package `GPML`. ## A more formal definition A Gaussian process is completely specified by its *mean function* and *covariance function*. We define the mean function $m(x)$ and the covariance function $k(x,x)$ of a real process $y(x)$ as $$ \begin{array}{rcl} m(x) & = & \mathbb{E}[y(x)], \\ k(x,x') & = & \mathrm{cov}(y(x),y(x'))=\mathbb{E}[(y(x) − m(x))(y(x') − m(x'))]. \end{array} $$ A very common covariance function is the squared exponential, or radial basis function (RBF) kernel $$ K_{ij}=k(x_i,x_j)=A \exp\left[ - \Gamma (x_i-x_j)^2 \right], $$ which has 2 parameters: $A$ and $\Gamma$. We then write the Gaussian process as $$ y(x) \sim \mathcal{GP}(m(x), k(x,x')) $$ Here we are implicitly assuming the inputs $x$ are one-dimensional, e.g. $x$ might represent time. However, the input space can have more than one dimension. We will see an example of a GP with multi-dimensional inputs later. ## The prior Now consider a finite set of inputs $\boldsymbol{x}$, with corresponding outputs $\boldsymbol{y}$. The *joint distribution* of $\boldsymbol{y}$ given $\boldsymbol{x}$, $m$ and $k$ is $$ \mathrm{p}(\boldsymbol{y} \mid \boldsymbol{x},m,k) = \mathcal{N}( \boldsymbol{m},K), $$ where $\boldsymbol{m}=m(\boldsymbol{x})$ is the *mean vector*, and $K$ is the *covariance matrix*, with elements $K_{ij} = k(x_i,x_j)$. ## Test and training sets Suppose we have an (observed) *training set* $(\boldsymbol{x},\boldsymbol{y})$. We are interested in some other *test set* of inputs $\boldsymbol{x}_*$. The joint distribution over the training and test sets is $$ \mathrm{p} \left( \left[ \begin{array}{l} \boldsymbol{y} \\ \boldsymbol{y}_* \end{array} \right] \right) = \mathcal{N} \left( \left[ \begin{array}{l} \boldsymbol{m} \\ \boldsymbol{m}_* \end{array} \right], \left[ \begin{array}{ll} K & K_* \\ K_*^T & K_{**} \end{array} \right] \right), $$ where $\boldsymbol{m}_* = m(\boldsymbol{x}_*)$, $K_{**,ij} = k(x_{*,i},x_{*,j})$ and $K_{*,ij} = k(x_i,x_{*,j})$. For simplicity, assume the mean function is zero everywhere: $\boldsymbol{m}=\boldsymbol{0}$. We will consider to non-trivial mean functions later. ## The conditional distribution The *conditional distribution* for the test set given the training set is: $$ \mathrm{p} ( \boldsymbol{y}_* \mid \boldsymbol{y},k) = \mathcal{N} ( K_*^T K^{-1} \boldsymbol{y}, K_{**} - K_*^T K^{-1} K_* ). $$ This is also known as the *predictive distribution*, because it can be use to predict future (or past) observations. More generally, it can be used for *interpolating* the observations to any desired set of inputs. This is one of the most widespread applications of GPs in some fields (e.g. kriging in geology, economic forecasting, ...) ## Adding white noise Real observations always contain a component of *white noise*, which we need to account for, but don't necessarily want to include in the predictions. If the white noise variance $\sigma^2$ is constant, we can write $$ \mathrm{cov}(y_i,y_j)=k(x_i,x_j)+\delta_{ij} \sigma^2, $$ and the conditional distribution becomes $$ \mathrm{p} ( \boldsymbol{y}_* \mid \boldsymbol{y},k) = \mathcal{N} ( K_*^T (K + \sigma^2 \mathbb{I})^{-1} \boldsymbol{y}, K_{**} - K_*^T (K + \sigma^2 \mathbb{I})^{-1} K_* ). $$ In real life, we may need to learn $\sigma$ from the data, alongside the other contribution to the covariance matrix. We assumed constant white noise, but it's trivial to allow for different $\sigma$ for each data point. ## Single-point prediction Let us look more closely at the predictive distribution for a single test point $x_*$. It is a Gaussian with mean $$ \overline{y}_* = \boldsymbol{k}_*^T (K + \sigma^2 \mathbb{I})^{-1} \boldsymbol{y} $$ and variance $$ \mathbb{V}[y_*] = k(x_*,x_*) - \boldsymbol{k}_*^T (K + \sigma^2 \mathbb{I})^{-1} \boldsymbol{k}_*, $$ where $\boldsymbol{k}_*$ is the vector of covariances between the test point and the training points. Notice the mean is a linear combination of the observations: the GP is a *linear predictor*. It is also a linear combination of covariance functions, each centred on a training point: $$ \overline{y}_* = \sum_{i=1}^N \alpha_i k(x_i,x_*), $$ where $\alpha_i = (K + \sigma^2 \mathbb{I})^{-1} y_i$. ## The likelihood The *likelihood* of the data under the GP model is simply: $$ \mathrm{p}(\boldsymbol{y} \,|\, \boldsymbol{x}) = \mathcal{N}(\boldsymbol{y} \, | \, \boldsymbol{0},K + \sigma^2 \mathbb{I}). $$ This is a measure of how well the model explains, or predicts, the training set. In some textbooks this is referred to as the *marginal likelihood*. This arises if one considers the observed $\boldsymbol{y}$ as noisy realisations of a latent (unobserved) Gaussian process $\boldsymbol{f}$. The term *marginal* refers to marginalisation over the function values $\boldsymbol{f}$: $$ \mathrm{p}(\boldsymbol{y} \,|\, \boldsymbol{x}) = \int \mathrm{p}(\boldsymbol{y} \,|\, \boldsymbol{f},\boldsymbol{x}) \, \mathrm{p}(\boldsymbol{f} \,|\, \boldsymbol{x}) \, \mathrm{d}\boldsymbol{f}, $$ where $$ \mathrm{p}(\boldsymbol{f} \,|\, \boldsymbol{x}) = \mathcal{N}(\boldsymbol{f} \, | \, \boldsymbol{0},K) $$ is the *prior*, and $$ \mathrm{p}(\boldsymbol{y} \,|\, \boldsymbol{f},\boldsymbol{x}) = \mathcal{N}(\boldsymbol{y} \, | \, \boldsymbol{0},\sigma^2 \mathbb{I}) $$ is the *likelihood*. ## Parameters and hyper-parameters The parameters of the covariance and mean function as known as the *hyper-parameters* of the GP. This is because the actual *parameters* of the model are the function values, $\boldsymbol{f}$, but we never explicitly deal with them: they are always marginalised over. ## *Conditioning* the GP... ...means evaluating the conditional (or predictive) distribution for a given covariance matrix (i.e. covariance function and hyper-parameters), and training set. ## *Training* the GP... ...means maximising the *likelihood* of the model with respect to the hyper-parameters. ## The kernel trick Consider a linear basis model with arbitrarily many *basis functions*, or *features*, $\Phi(x)$, and a (Gaussian) prior $\Sigma_{\mathrm{p}}$ over the basis function weights. One ends up with exactly the same expressions for the predictive distribution and the likelihood so long as: $$ k(\boldsymbol{x},\boldsymbol{x'}) = \Phi(\boldsymbol{x})^{\mathrm{T}} \Sigma_{\mathrm{p}} \Phi(\boldsymbol{x'}), $$ or, writing $\Psi(\boldsymbol{x}) = \Sigma_{\mathrm{p}}^{1/2} \Phi(\boldsymbol{x})$, $$ k(\boldsymbol{x},\boldsymbol{x'}) = \Psi(\boldsymbol{x}) \cdot \Psi(\boldsymbol{x'}), $$ Thus the covariance function $k$ enables us to go from a (finite) *input space* to a (potentially infinite) *feature space*. This is known as the *kernel trick* and the covariance function is often referred to as the *kernel*. ## Non-zero mean functions In general (and in astronomy applications in particular) we often want to use non-trivial mean functions. To do this simply replace $\boldsymbol{y}$ by $\boldsymbol{r}=\boldsymbol{y}-\boldsymbol{m}$ in the expressions for predictive distribution and likelihood. The mean function represents the *deterministic* component of the model - e.g.: a linear trend, a Keplerian orbit, a planetary transit, ... The covariance function encodes the *stochastic* component. - e.g.: instrumental noise, stellar variability ## Covariance functions The only requirement for the covariance function is that it should return a positive semi-definite covariance matrix. The simplest covariance functions have two parameters: one input and one output variance (or scale). The form of the covariance function controls the degree of smoothness. ### The squared exponential The simplest, most widely used kernel is the squared exponential: $$ k_{\rm SE}(x,x') = A \exp \left[ - \Gamma (x-x')^2 \right]. $$ This gives rise to *smooth* functions with variance $A$ and inverse scale (characteristic length scale) $A$ and output scale (amplitude) $l$. ``` def kernel_SE(X1,X2,par): p0 = 10.0**par[0] p1 = 10.0**par[1] D2 = cdist(X1,X2,'sqeuclidean') K = p0 * np.exp(- p1 * D2) return np.matrix(K) def kernel_Mat32(X1,X2,par): p0 = 10.0**par[0] p1 = 10.0**par[1] DD = cdist(X1, X2, 'euclidean') arg = np.sqrt(3) * abs(DD) / p1 K = p0 * (1 + arg) * np.exp(- arg) return np.matrix(K) def kernel_RQ(X1,X2,par): p0 = 10.0**par[0] p1 = 10.0**par[1] alpha = par[2] D2 = cdist(X1, X2, 'sqeuclidean') K = p0 * (1 + D2 / (2*alpha*p1))**(-alpha) return np.matrix(K) def kernel_Per(X1,X2,par): p0 = 10.0**par[0] p1 = 10.0**par[1] period = par[2] DD = cdist(X1, X2, 'euclidean') K = p0 * np.exp(- p1*(np.sin(np.pi * DD / period))**2) return np.matrix(K) def kernel_QP(X1,X2,par): p0 = 10.0**par[0] p1 = 10.0**par[1] period = par[2] p3 = 10.0**par[3] DD = cdist(X1, X2, 'euclidean') D2 = cdist(X1, X2, 'sqeuclidean') K = p0 * np.exp(- p1*(np.sin(np.pi * DD / period))**2 - p3 * D2) return np.matrix(K) def add_wn(K,lsig): sigma=10.0**lsig N = K.shape[0] return K + sigma**2 * np.identity(N) def get_kernel(name): if name == 'SE': return kernel_SE elif name == 'RQ': return kernel_RQ elif name == 'M32': return kernel_Mat32 elif name == 'Per': return kernel_Per elif name == 'QP': return kernel_QP else: print 'No kernel called %s - using SE' % name return kernel_SE def pltsamples1(par0=0.0, par1=0.0, wn = 0.0): x = np.r_[-5:5:201j] X = np.matrix([x]).T # scipy.spatial.distance expects matrices kernel = get_kernel('SE') K = kernel(X,X,[par0,par1]) K = add_wn(K,wn) fig=pl.figure(figsize=(10,4)) ax1 = pl.subplot2grid((1,3), (0, 0), aspect='equal') pl.imshow(np.sqrt(K),interpolation='nearest',vmin=0,vmax=10) pl.title('Covariance matrix') ax2 = pl.subplot2grid((1,3), (0,1),colspan=2) np.random.seed(0) for i in range(3): y = np.random.multivariate_normal(np.zeros(len(x)),K) pl.plot(x,y-i*2) pl.xlim(-5,5) pl.ylim(-8,5) pl.xlabel('x') pl.ylabel('y') pl.title('Samples from %s prior' % 'SE') pl.tight_layout() interact(pltsamples1, par0=widgets.FloatSlider(min=-1,max=1,step=0.5,description=r'$\log_{10} A$',value=0), par1=widgets.FloatSlider(min=-1,max=1,step=0.5,description=r'$\log_{10} \Gamma$',value=0), wn=widgets.FloatSlider(min=-2,max=0,step=1,description=r'$\log_{10} \sigma$',value=-2) ); ``` ### The Matern family The Matern 3/2 kernel $$ k_{3/2}(x,x')= A \left( 1 + \frac{\sqrt{3}r}{l} \right) \exp \left( - \frac{\sqrt{3}r}{l} \right), $$ where $r =|x-x'|$. It produces somewhat rougher behaviour, because it is only differentiable once w.r.t. $r$ (whereas the SE kernel is infinitely differentiable). There is a whole family of Matern kernels with varying degrees of roughness. ## The rational quadratic kernel is equivalent to a squared exponential with a powerlaw distribution of input scales $$ k_{\rm RQ}(x,x') = A^2 \left(1 + \frac{r^2}{2 \alpha l} \right)^{-\alpha}, $$ where $\alpha$ is the index of the power law. This is useful to model data containing variations on a range of timescales with just one extra parameter. ``` # Function to plot samples from kernel def pltsamples2(par2=0.5, kernel_shortname='SE'): x = np.r_[-5:5:201j] X = np.matrix([x]).T # scipy.spatial.distance expects matrices kernel = get_kernel(kernel_shortname) K = kernel(X,X,[0.0,0.0,par2]) fig=pl.figure(figsize=(10,4)) ax1 = pl.subplot2grid((1,3), (0, 0), aspect='equal') pl.imshow(np.sqrt(K),interpolation='nearest',vmin=0,vmax=10) pl.title('Covariance matrix') ax2 = pl.subplot2grid((1,3), (0,1),colspan=2) np.random.seed(0) for i in range(3): y = np.random.multivariate_normal(np.zeros(len(x)),K) pl.plot(x,y-i*2) pl.xlim(-5,5) pl.ylim(-8,5) pl.xlabel('x') pl.ylabel('y') pl.title('Samples from %s prior' % kernel_shortname) pl.tight_layout() interact(pltsamples2, par2=widgets.FloatSlider(min=0.25,max=1,step=0.25,description=r'$\alpha$',value=0.5), kernel_shortname=widgets.RadioButtons(options=['SE','M32','RQ'], value='SE',description='kernel') ); ``` ## Periodic kernels... ...can be constructed by replacing $r$ in any of the above by a periodic function of $r$. For example, the cosine kernel: $$ k_{\cos}(x,x') = A \cos\left(\frac{2\pi r}{P}\right), $$ [which follows the dynamics of a simple harmonic oscillator], or... ...the "exponential sine squared" kernel, obtained by mapping the 1-D variable $x$ to the 2-D variable $\mathbf{u}(x)=(\cos(x),\sin(x))$, and then applying a squared exponential in $\boldsymbol{u}$-space: $$ k_{\sin^2 {\rm SE}}(x,x') = A \exp \left[ -\Gamma \sin^2\left(\frac{\pi r}{P}\right) \right], $$ which allows for non-harmonic functions. ``` # Function to plot samples from kernel def pltsamples3(par2=2.0, par3=2.0,kernel_shortname='Per'): x = np.r_[-5:5:201j] X = np.matrix([x]).T # scipy.spatial.distance expects matrices kernel = get_kernel(kernel_shortname) K = kernel(X,X,[0.0,0.0,par2,par3]) fig=pl.figure(figsize=(10,4)) ax1 = pl.subplot2grid((1,3), (0, 0), aspect='equal') pl.imshow(np.sqrt(K),interpolation='nearest',vmin=0,vmax=10) pl.title('Covariance matrix') ax2 = pl.subplot2grid((1,3), (0,1),colspan=2) np.random.seed(0) for i in range(3): y = np.random.multivariate_normal(np.zeros(len(x)),K) pl.plot(x,y-i*2) pl.xlim(-5,5) pl.ylim(-8,5) pl.xlabel('x') pl.ylabel('y') pl.title('Samples from %s prior' % kernel_shortname) pl.tight_layout() interact(pltsamples3, par2=widgets.FloatSlider(min=1,max=3,step=1,description=r'$P$',value=2), par3=widgets.FloatSlider(min=-2,max=0,step=1,description=r'$\log\Gamma_2$',value=-1), kernel_shortname=widgets.RadioButtons(options=['Per','QP'], value='QP',description='kernel') ); ``` ## Combining kernels Any *affine tranform*, sum or product of valid kernels is a valid kernel. For example, a quasi-periodic kernel can be constructed by multiplying a periodic kernel with a non-periodic one. The following is frequently used to model stellar light curves: $$ k_{\mathrm{QP}}(x,x') = A \exp \left[ -\Gamma_1 \sin^2\left(\frac{\pi r}{P}\right) -\Gamma_2 r^2 \right]. $$ ## Example: Mauna Kea CO$_2$ dataset (From Rasmussen & Williams textbook) <img height="700" src="images/RW_mauna_kea.png"> ### 2 or more dimensions So far we assumed the inputs were 1-D but that doesn't have to be the case. For example, the SE kernel can be extended to D dimensions... using a single length scale, giving the *Radial Basis Function* (RBF) kernel: $$ k_{\rm RBF}(\mathbf{x},\mathbf{x'}) = A \exp \left[ - \Gamma \sum_{j=1}^{D}(x_j-x'_j)^2 \right], $$ where $\mathbf{x}=(x_1,x_2,\ldots, x_j,\ldots,x_D)^{\mathrm{T}}$ represents a single, multi-dimensional input. or using separate length scales for each dimension, giving the *Automatic Relevance Determination* (ARD) kernel: $$ k_{\rm ARD}(\mathbf{x},\mathbf{x'}) = A \exp \left[ - \sum_{j=1}^{D} \Gamma_j (x_j-x'_j)^2 \right]. $$ ``` import george x2d, y2d = np.mgrid[-3:3:0.1,-3:3:0.1] x = x2d.ravel() y = y2d.ravel() N = len(x) X = np.zeros((N,2)) X[:,0] = x X[:,1] = y k1 = george.kernels.ExpSquaredKernel(1.0,ndim=2) s1 = george.GP(k1).sample(X).reshape(x2d.shape) k2 = george.kernels.ExpSquaredKernel(1.0,ndim=2,axes=1) + george.kernels.ExpSquaredKernel(0.2,ndim=2,axes=0) s2 = george.GP(k2).sample(X).reshape(x2d.shape) pl.figure(figsize=(10,5)) pl.subplot(121) pl.contourf(x2d,y2d,s1) pl.xlim(x.min(),x.max()) pl.ylim(y.min(),y.max()) pl.xlabel(r'$x$') pl.ylabel(r'$y$') pl.title('RBF') pl.subplot(122) pl.contourf(x2d,y2d,s2) pl.xlim(x.min(),x.max()) pl.ylim(y.min(),y.max()) pl.xlabel(r'$x$') pl.title('ARD'); # Function to plot samples from kernel def pltsamples3(par2=0.5,par3=0.5, kernel_shortname='SE'): x = np.r_[-5:5:201j] X = np.matrix([x]).T # scipy.spatial.distance expects matrices kernel = get_kernel(kernel_shortname) K = kernel(X,X,[0.0,0.0,par2,par3]) fig=pl.figure(figsize=(10,4)) ax1 = pl.subplot2grid((1,3), (0, 0), aspect='equal') pl.imshow(np.sqrt(K),interpolation='nearest',vmin=0,vmax=10) pl.title('Covariance matrix') ax2 = pl.subplot2grid((1,3), (0,1),colspan=2) np.random.seed(0) for i in range(5): y = np.random.multivariate_normal(np.zeros(len(x)),K) pl.plot(x,y) pl.xlim(-5,5) pl.ylim(-5,5) pl.xlabel('x') pl.ylabel('y') pl.title('Samples from %s prior' % kernel_shortname) pl.tight_layout() interact(pltsamples3, par2=widgets.FloatSlider(min=1,max=3,step=1,description=r'$P$',value=2), par3=widgets.FloatSlider(min=-2,max=0,step=1,description=r'$\log_{10}\Gamma_2$',value=-1.), kernel_shortname=widgets.RadioButtons(options=['Per','QP'], value='Per',description='kernel') ); ```
github_jupyter
# `stedsans` This is a notebook showing the current and most prominent capabilities of `stedsans`. It is heavily recommended to run the notebook by using Google Colab: <br> <br> [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/MalteHB/stedsans/blob/main/notebooks/stedsans_demo.ipynb) If running the notebook on your local machine consider installing [Anaconda](https://docs.anaconda.com/anaconda/install/) and then install the package `geopandas` to get the pre-built binaries, by using the `conda` package manager from an Anaconda integraged terminal: ```bash conda install geopandas ``` ## Setup We will start off by installing `stedsans` using the `pip` package manager. ``` !pip install -q stedsans==0.0.16a0 ``` If you are using either Google Colab, Linux or MacOS also feel free to install `geopandas` using `pip`, however, if you are using Windows OS install `geopandas` to by using the `conda` package manager. ``` # For Google Colab, Linux or MacOS: !pip -q install geopandas==0.9.0 ``` __Importing packages__ We start off by importing the main module of `stedsans`. ``` from stedsans import stedsans ``` ## Language capabilities of `stedsans` `stedsans` is capable of taking a either a Danish or an English sentence, and extracting the entities by using either [Ælæctra](https://huggingface.co/Maltehb/-l-ctra-danish-electra-small-cased-ner-dane) or [BERT](https://huggingface.co/dslim/bert-base-NER), respectively. The intended use of `stedsans` is to initialize a stedsans object with a text input. ``` # Define the sentence danish_sentence = "Malte er mit navn, og jeg bor på Testvej 13, Aarhus C" # By default stedsans assumes the language is Danish default_stedsans = stedsans(sentence = danish_sentence) ``` After a `stedsans` instance with a sentence has been initialized one can simply call the `extract_entities()` function and print the entities. ``` default_entities = default_stedsans.extract_entities() print(default_entities) ``` ### Multilinguistic stedsans #### (duolinguistic for now...) By default `stedsans` assumes the language is Danish, but we can also be specified using the 'language' argument. `stedsans` is currently only capable of predicting Danish and English sentences, but future enhancements will include increased language variety. ``` danish_stedsans = stedsans(danish_sentence, language="danish") danish_entities = danish_stedsans.extract_entities() print(danish_entities) english_sentence = "Hello my name is Malte and i live in Aarhus C" english_stedsans = stedsans(english_sentence, language="english") english_entities = english_stedsans.extract_entities() print(english_entities) ``` A `stedsance` instance has been initialized we also use it for predicting other sentences. ``` new_danish_sentence = "Jakob er min gode samarbejdspartners navn, og han bor også i Aarhus C" danish_sentence_entities = default_stedsans.extract_entities(new_danish_sentence) print(danish_sentence_entities) new_english_sentence = "Jakob is the name my good cooperator, and he also lives in Aarhus C" english_sentence_entities = english_stedsans.extract_entities(new_english_sentence) print(english_sentence_entities) ``` Notice here how the different models have different predictive capabilities. The Danish Ælæctra notices *'C'* as part of the location whereas BERT does not. ## Geographic capabilities of `stedsans` To show the basic geospatial functionalities of stedsans we will start of by initializing a stedsans instance, `geo_demo`, with an English text string, and printing the found location and organization entities. ``` txt = "Stedsans was developed by two knights who both live in Aarhus C. \ They are both fans of FC Midtjylland which is a football team residing at MCH Arena. \ One comes from Randers, which is home to one of the best beers in the world. \ The other comes from a small city, not too far from LEGOLAND. \ One of their favourite locations is Knebel which is located on Mols Djursland. \ They are not hateful people, but they are not too fond of AGF. What is there really to like about AGF? \ If you ever come close to Aarhus, feel free to pay them a visit. \ They will gladly take you on a tourist tour to both see Bruuns Galleri and Dokk1. \ And if you like beer they will gladly beknight you at Guldhornene Aarhus." geo_demo = stedsans(sentence = txt, language = 'english') geo_demo.print_entities() ``` We can then use the `get_coordinates()` function, to obtain both the a list of coordinates, a `pandas` dataframe and a `geopandas` geodataframe. ``` coords, df, gdf = geo_demo.get_coordinates() print("List of coordinates:\n", coords) print("Overview of the pandas dataframe:\n", df) print("Overview of the geopandas dataframe:\n", gdf) ``` As we see the two dataframes are different in that the `geopandas` dataframe also contains the `geometry` column, which enables a user of `stedsans` to do additional geoanalytical analyses. Also note how the geoparsing fails at geocoding one of the the entities. It has returned a place in France, Aérodrome d'Agen-La Garenne, for the entity *'AGF'* which actually corresponds to a substandard football club located in Aarhus. Because of this ambiguity `get_coordinates()` also takes the parameters `limit` and `limit_area` which are very convenient when only wanting locations inside a specific area. ``` coords, df, gdf = geo_demo.get_coordinates(limit="country", limit_area="Denmark") print("List of coordinates:\n", coords) print("Overview of the pandas dataframe:\n", df) print("Overview of the geopandas dataframe:\n", gdf) ``` Now the entity *'AGF'* has been removed and we are only getting the geotagged locations inside of Denmark. ### Basic Visualization: Plotting points onto a map `stedsans` comes with some basic example text files, datasets and shapefiles that can be used to explore the package. They also ideal for this demonstration of the capabilities of `stedsans`. Right now, we will load a Danish article (sorry, non-Danish-speakers) about Jutland, or Jylland in Danish, by loading it using the `Articles` class. The article can be read below. ``` from stedsans.data.load_data import Articles jylland_article = Articles.jylland() print(jylland_article) ``` We will now use the article to initialize a new `stedsans` instance, called `jutland_demo` and print the extracted entities to get a brief overview of what we are dealing with. ``` jutland_demo = stedsans(file = jylland_article, language = 'danish') jutland_demo.print_entities() ``` To visualize the points we have extracted from the article we can plot them on an interactive `Folium` and `Leaflet.js` map by using the `plot_locations()` function. ``` jutland_demo.plot_locations() ``` By default `plot_locations()` uses a 'cartodbpositron' tileset, however, you can also specify it to use 'OpenStreetMap' or any other `Foliumn` supported map layer, by using the `tiles` keyword. For additional configurations on the `tiles` argument see the [Folium documentation](https://python-visualization.github.io/folium/modules.html). ``` jutland_demo.plot_locations(tiles="OpenStreetMap") ``` Here we see that we have places all around the world. However, we know that the article concerns Jutland, and it seems a bit dubious that an article regarding Jutland mentions locations across three continents. In these situations where it known beforehand, that all or most locations should be constrained to a specific area, all `stedsans` functions takes two powerful parameters that can be used to specify a bounding box. The `bounding_box` argument lets the user define two coordinate-pairs that represent the corners of the bounding box. The Boolean `bounded` then determines how the geocoder should handle the bounding box. By default, ‘bounded’ is set to 'False’. In this setting, the specified bounding box only serves as an extra heuristic for the importance score ranking in the geocoder; results that lie within the confined area are given a higher importance score. If ‘bounded’ is set to ‘True’, the bounding box categorically restricts the geocoder to only search for locations within the borders of the box. We can try bounding to the bounding box around Region Midtjylland to see if more locations are found in this area than before: ``` jutland_demo.plot_locations(bounding_box=((55.9,7.6),(56.6, 10.9)), bounded=True) ``` We can see that by bounding the search, the geocoder often locates more places in the specified area. Bounding e.g., finds correct locations for 'Sotorå', 'Mossø' and 'Djursland'. If we wanted the geocoder to extract locations without restrcitions, but at a later stage wanted to subset and visualise only the points located in e.g. Denmark, it would be best to use the `limit` and `limit_area` arguments and set them to 'country' and 'Denmark' respectively. We can also pass a mapping layer into a `stedsans` instance. One of the datasets provided with `stedsans` is a `geopandas` dataframe, created from a shapefile of Denmark with municipality division. This dataset is provided by the `GeoData` class and can be retrieved by calling `GeoData.municipalities()`. The original shapefile was in Danish, and the column names are therefore still in Danish. ``` from stedsans.data.load_data import GeoData denmark = GeoData.municipalities() print("First five rows of the denmark dataframe:\n", denmark.head()) ``` Each row in this GeoDataFrame represents a municipality and has a polygon defined in the geometry column. The other columns hold various information on the municipalities, e.g., individual IDs (`DAGI_ID`) and the name of the region in which they are located (`REGIONNAVN`). These variables can be used for grouping the data in some of the other functions. By specifiying the 'layer' argument of `plot_locations()` to be the loaded dataframe, we can use it as a base layer. This gives os a non-interactive map created using `matplotlib`. Setting the Boolean `on_map` argument to `True` entails that only points loocated within one of the polygons are kept. ``` jutland_demo.plot_locations(layer=denmark, on_map=True) ``` ### Statistical Tools: Point Patterns Since `stedsans` is intended for more than geographical visualizations, it also comes with the ability to do Q-statistics, enabling a quick statistical analysis of the distribution of the points by checking for complete spatial randomness. We will continue to use the `jutland_demo` instance of `stedsans` from the previous section. To get the Q-statistics `stedsans` provides the function `get_quad_stats()`. ``` jutland_demo.get_quad_stats() ``` `get_quad_stats()` provides us with a 𝜒2-value and a p-value to determine whether out points are truly completely random. In this instance, since we have a 𝜒2 = 858.333 with a p-value = 0.001, we can reject the null and conclude that the points to not appear to be distributed randomly. We are also able to plot the points into quadrants using the `plot_quad_count()` function. In this example we specify the number of `squares` per axis to be 4. ``` jutland_demo.plot_quad_count(squares = 4) ``` Again we can specify the `limit` and the `limit_area`. ``` jutland_demo.get_quad_stats(limit="country", limit_area="Denmark") jutland_demo.plot_quad_count(squares = 4, limit="country", limit_area="Denmark" ) ``` ### Advanced Visualizations 1: Plotting cloropleth plots `stedsans` also provides the ability to plot cloropleth plots. This can be done by using the function `plot_cloropleth()`. By default `plot_cloropleth()` uses the entire world as a default base layer. ``` jutland_demo.plot_choropleth() ``` When only having locations in Denmark such a plot might be deemed too informative. Luckily, similarly to the `plot_locations()` function, `plot_cloropleth()` also gives us the opportunity to pass a base layer into it with the `layer` argument. We will use the already initialized `denmark` layer. ``` jutland_demo.plot_choropleth(layer=denmark) ``` By specifiying the layer we get a much more informative view of the distribution of tagged locations. `plot_cloropleth()` also has a `group_by` functionality, where you can specify the filling of the cloropleth plot to be grouped by a variable in the input layer. Here we pass the region name variable called `REGIONNAVN`. ``` jutland_demo.plot_choropleth(layer=denmark, group_by='REGIONNAVN') ``` If we only want to get a view of the location distribution of a specific region in Denmark, we can create a subset layer, `region_m`. Here we choose the region name column `REGIONNAVN` and subsets only *'Region Midtjylland'* which translates to the Central Jutland Region. ``` region_m = denmark[denmark["REGIONNAVN"] == "Region Midtjylland"] print("First five rows of the region_m dataframe:\n", region_m.head()) print("\nUnique regions in region_m:", region_m["REGIONNAVN"].unique()) ``` Now we have a layer only containing the `REGIONNAVN` called 'Region Midtjylland'. We can use this to create a cloropleth plot of only the locations located in Central Jutland Region in Denmark divided into the different municipalities. We will also make use of the `title` argument to make a nice title for the plot. ``` jutland_demo.plot_choropleth(layer=region_m, title = 'Jylland - Den Store Danske \n Central Jutland Region') ``` If you wanted to visualize the entirety of the kingdom of Denmark, but only to get the distribution of places in the Central Jutland Region you can specify a `bounding_box` and set `bounded=True`. Note how this also slightly changes (improves) the results for which locations are retrieved in the region. ``` jutland_demo.plot_choropleth(layer=denmark, title='Jylland - Den Store Danske \n Bounded to Region Midtjylland', bounding_box=((55.9,7.6),(56.6, 10.9)), bounded=True) jutland_demo.plot_choropleth(layer=denmark, title='Jylland - Den Store Danske \n Grouped by Region', group_by='REGIONNAVN', bounding_box=((54.6,7.8),(57.8, 15.2)), bounded=False) ``` ### Advanced Visualizations 2: Heatmaps Lastly, `stedsans` also provides the ability to create heatmaps by using the function `plot_heatmap()`. ``` jutland_demo.plot_heatmap() ``` Again, we can specify the `limit` and the `limit_area`. ``` jutland_demo.plot_heatmap(limit = 'country', limit_area = 'Denmark') ``` And we can set a bounding box. ``` jutland_demo.plot_heatmap(bounding_box=((55.9,7.6),(56.6,10.9)), bounded=True) ``` Making the argument names generalizable and work across multiple functions should make the usage `stedsans` more accessible for the users. There are lots of features to come and the developers are looking forward to continuously enhancing the features, and providing additional geospatial analytical tools. We hope you enjoyed the demonstration of the current capabilities of `stedsans`. Thank you! ### Contact For help or further information feel free to connect with either of the main developers: **Malte Højmark-Bertelsen** <br /> [hjb@kmd.dk](mailto:hjb@kmd.dk?subject=[GitHub]%20stedsans) [<img align="left" alt="MalteHB | Twitter" width="30px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/twitter.svg" />][twitter] [<img align="left" alt="MalteHB | LinkedIn" width="30px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/linkedin.svg" />][linkedin] <br /> </details> [twitter]: https://twitter.com/malteH_B [linkedin]: https://www.linkedin.com/in/maltehb **Jakob Grøhn Damgaard** <br /> [bokajgd@gmail.com](mailto:bokajgd@gmail.com?subject=[GitHub]%20stedsans) [<img align="left" alt="Jakob Grøhn Damgaard | Twitter" width="30px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/twitter.svg" />][twitter] [<img align="left" alt="Jakob Grøhn Damgaard | LinkedIn" width="30px" src="https://cdn.jsdelivr.net/npm/simple-icons@v3/icons/linkedin.svg" />][linkedin] <br /> </details> [twitter]: https://twitter.com/JakobGroehn [linkedin]: https://www.linkedin.com/in/jakob-gr%C3%B8hn-damgaard-04ba51144/
github_jupyter
``` import sys sys.path.append('src/') import numpy as np import torch, torch.nn from library_function import library_1D from neural_net import LinNetwork from DeepMod import * import matplotlib.pyplot as plt plt.style.use('seaborn-notebook') import torch.nn as nn from torch.autograd import grad from scipy.io import loadmat from scipy.optimize import curve_fit %load_ext autoreload %autoreload 2 ``` # Preparing data ``` rawdata = loadmat('data/kinetics_new.mat') raw = np.real(rawdata['Expression1']) raw= raw.reshape((1901,3)) t = raw[:-1,0].reshape(-1,1) X1= raw[:-1,1] X2 = raw[:-1,2] X = np.float32(t.reshape(-1,1)) y= np.vstack((X1,X2)) y = np.transpose(y) number_of_samples = 1800 idx = np.random.permutation(y.shape[0]) X_train = torch.tensor(X[idx, :][:number_of_samples], dtype=torch.float32, requires_grad=True) y_train = torch.tensor(y[idx, :][:number_of_samples], dtype=torch.float32) y_train.shape ``` # Building network ``` optim_config ={'lambda':1e-6,'max_iteration':20000} lib_config={'poly_order':1, 'diff_order':2, 'total_terms':4} network_config={'input_dim':1, 'hidden_dim':20, 'layers':8, 'output_dim':2} ``` # MSE Run ``` prediction, network, y_t, theta = DeepMod_mse(X_train, y_train,network_config, lib_config, optim_config) ``` # Least square fit ``` plt.scatter(X,y[:,0]) plt.scatter(X_train.detach().numpy(),prediction[:,0].detach().numpy()) plt.plot(X,np.gradient(y[:,0])/0.001,'r--') plt.scatter(X_train.detach().numpy()[:,0], y_t.detach().numpy()[:,0]) def func(X, a, b, c, d): x1,x2 = X return a + b*x1 + c*x2 + d*x1*x2 def func_simple(X, a, b, c): x1,x2 = X return a + b*x1 + c*x2 x1 = np.squeeze(prediction[:,0].detach().numpy()) x2 = np.squeeze(prediction[:,1].detach().numpy()) z1 = y_t.detach().numpy()[:,0] z2 = y_t.detach().numpy()[:,1] z1_ref = np.gradient(np.squeeze(prediction[:,0].detach().numpy()),np.squeeze(X_train.detach().numpy())) z2_ref = np.gradient(np.squeeze(prediction[:,1].detach().numpy()),np.squeeze(X_train.detach().numpy())) plt.scatter(X_train[:,0].detach().numpy(),z1_ref) plt.scatter(X_train[:,0].detach().numpy(),z1) x1 = y[:,0] x2 = y[:,1] z1 = np.gradient(y[:,0],np.squeeze(X)) z2 = np.gradient(y[:,1],np.squeeze(X)) # initial guesses for a,b,c: p0 = 0., 0., 0., 0. w1 = curve_fit(func, (x1,x2), z1, p0)[0] w2 = curve_fit(func, (x1,x2), z2, p0)[0] init_coeff=torch.tensor(np.transpose(np.array((w1,w2))), dtype=torch.float32, requires_grad=True) print(init_coeff) np.sum((0.2*theta[:,0]-theta[:,1]-y_t[:,0]).detach().numpy()) plt.scatter(x1,z2) plt.scatter(x1,w2[0]+w2[1]*x1+w2[2]*x2+w2[3]*x1*x2) plt.scatter(x1,x1-0.25*x2) plt.scatter(x1,z2) plt.scatter(x1,w2[0]+w2[1]*x1+w2[2]*x2+w2[3]*x1*x2) plt.scatter(x1,x1-0.25*x2) y_t,theta, weight_vector = DeepMod_single(X_train, y_train, network_config, lib_config, optim_config,network,init_coeff) plt.scatter(X[:,0],y[:,0]) plt.scatter(X[:,0],y[:,1]) plt.scatter(X_train.detach().numpy(),prediction.detach().numpy()[:,0]) plt.scatter(X_train.detach().numpy(),prediction.detach().numpy()[:,1]) plt.show() from scipy.optimize import curve_fit def func(X, a, b, c, d): x1,x2 = X return a + b*x1 + c*x2 + d*x1*x2 x1 = y[:,0] x2 = y[:,1] z1 = np.gradient(y[:,0],np.squeeze(X)) z2 = np.gradient(y[:,1],np.squeeze(X)) # initial guesses for a,b,c: p0 = 0., 0., 0., 0.0 curve_fit(func, (x1,x2), z1, p0)[0] sparse_weight_vector, sparsity_pattern, prediction, network = DeepMod(X_train, y_train,network_config, lib_config, optim_config) testlib = np.array([y[:,0],y[:,1],y[:,0]*y[:,1]]) X.shape def reg_m(y, x): ones = np.ones(len(x[0])) X = sm.add_constant(np.column_stack((x[0], ones))) for ele in x[1:]: X = sm.add_constant(np.column_stack((ele, X))) results = sm.OLS(y, X).fit() return results print(reg_m(np.gradient(y[:,0]), x).summary()) plt.scatter(X_train.detach().numpy(),prediction.detach().numpy()[:,0]) plt.scatter(X_train.detach().numpy(),prediction.detach().numpy()[:,1]) prediction = network(torch.tensor(X, dtype=torch.float32)) prediction = prediction.detach().numpy() x, y = np.meshgrid(X[:,0], X[:,1]) mask = torch.tensor((0,1,3)) mask sparse_coefs = torch.tensor((0.1,0.2,0.4)).reshape(-1,1) sparse_coefs dummy = torch.ones((5,3,1)) dummy2 = torch.ones((5,1,4)) (dummy @ dummy2).shape dummy.shape dummy.reshape(-1,3,1).shape dummy = dummy.reshape(2,2) torch.where(coefs(mask),coefs,dummy) x = np.linspace(0, 1, 100) X, Y = np.meshgrid(x, x) Z = np.sin(X)*np.sin(Y) b = torch.ones((10, 2), dtype=torch.float32, requires_grad=True) a = torch.tensor(np.ones((2,10)), dtype=torch.float32) test=torch.tensor([[0.3073, 0.4409], [0.0212, 0.6602]]) torch.where(test>torch.tensor(0.3),test, torch.zeros_like(test)) ``` ``` test2[0,:].reshape(-1,1) mask=torch.nonzero(test2[0,:]) mask=torch.reshape(torch.nonzero(test2), (1,4)) mask test2[mask[1]] a.shape[1] ```
github_jupyter
## 1. Import basic libraries ``` import pandas as pd import pandas_profiling import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns import matplotlib.ticker as mtick ``` ## 2. Read final.csv ``` data = pd.read_csv('Data/final.csv') ``` ## 3. And now let's carefully analyse the dataframe and its variables to check if we want to keep all of them and if we need to tidy any of them. ``` data.head(3) data.tail(3) report = pandas_profiling.ProfileReport(data) report data.info() ``` ## 3.1 Categorical variables: - id_assessment - id_student - is_banked - code_module - code_presentation - gender - region - highest_education - imd_band - age_band - disability - final_result ### id_assessment How many unique assessments do we have? ``` len(data.id_assessment.value_counts()) ``` As this is a categorical variable, we need to transform the column type from int64 to object. ``` data['id_assessment'] = data['id_assessment'].apply(str) crossidass = pd.crosstab(data.score, data.id_assessment, margins=True, margins_name='Total') display(crossidass.head(3)) display(crossidass.tail(3)) ``` ### id_student How many different students do we have data from? ``` len(data.id_student.value_counts()) ``` Same way as id_assessment, this is a categorical variable, so we need to apply the same transformation. ``` data['id_student'] = data['id_student'].apply(str) crossidst = pd.crosstab(data.score, data.id_student, margins=True, margins_name='Total') display(crossidst.head(3)) display(crossidst.tail(3)) ``` ### is_banked A status flag indicating that the assessment result has been transferred from a previous presentation. ``` data.is_banked.value_counts() ``` Same way as before, we apply the same transformation. ``` data['is_banked'] = data['is_banked'].apply(str) crossbanked = pd.crosstab(data.score, data.is_banked, margins=True, margins_name='Total') display(crossbanked.head(3)) display(crossbanked.tail(3)) ``` ### code_module ``` data.code_module.value_counts() crossmodule = pd.crosstab(data.score, data.code_module, margins=True, margins_name='Total') display(crossmodule.head(3)) display(crossmodule.tail(3)) ``` ### code_presentation ``` data.code_presentation.value_counts() crosspres = pd.crosstab(data.score, data.code_presentation, margins=True, margins_name='Total') display(crosspres.head(3)) display(crosspres.tail(3)) ``` ### gender ``` data.gender.value_counts() crossgender = pd.crosstab(data.score, data.gender, margins=True, margins_name='Total') display(crossgender.head(3)) display(crossgender.tail(3)) fig = plt.figure(figsize=(7,5)) ax = fig.add_subplot(111) sns.countplot(x="gender", data=data, palette='GnBu') ax.set_title("Students per gender") plt.tight_layout() plt.show() ``` ### region ``` data.region.value_counts() crossregion = pd.crosstab(data.score, data.region, margins=True, margins_name='Total') display(crossregion.head(3)) display(crossregion.tail(3)) ax = sns.countplot(x="region", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ### highest_education ``` data.highest_education.value_counts() crosshi = pd.crosstab(data.score, data.highest_education, margins=True, margins_name='Total') display(crosshi.head(3)) display(crosshi.tail(3)) ax = sns.countplot(x="highest_education", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ### imd_band Specifies the Index of Multiple Depravation band of the place where the student lived during the module-presentation. ``` data.imd_band.value_counts() crossimd = pd.crosstab(data.score, data.imd_band, margins=True, margins_name='Total') display(crossimd.head(3)) display(crossimd.tail(3)) ax = sns.countplot(x="imd_band", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ### age_band ``` data.age_band.value_counts() crossage = pd.crosstab(data.score, data.age_band, margins=True, margins_name='Total') display(crossage.head(3)) display(crossage.tail(3)) ax = sns.countplot(x="age_band", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ### disability ``` data.disability.value_counts() crossdi = pd.crosstab(data.score, data.disability, margins=True, margins_name='Total') display(crossdi.head(3)) display(crossdi.tail(3)) ax = sns.countplot(x="disability", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), ha="right") plt.tight_layout() plt.show() ``` ### final_result ``` data.final_result.value_counts() crossfi = pd.crosstab(data.score, data.final_result, margins=True, margins_name='Total') display(crossfi.head(3)) display(crossfi.tail(3)) ax = sns.countplot(x="final_result", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ## Numerical variables: - date_submitted - score - num_of_prev_attempts - studied_credits - module_presentation_length "Score" column should be numeric, so we will have to transform the column type later on, when we get to analyse the column. ### date_submitted The date of student submission, measured as the number of days since the start of the module presentation. ``` display(data.date_submitted.describe()) data.boxplot(column= ['date_submitted']) plt.show() sns.distplot(data.date_submitted) plt.show() crossdate = pd.crosstab(data.score, data.date_submitted, margins=True, margins_name='Total') display(crossdate.head(3)) display(crossdate.tail(3)) ``` We see that our minimum value is -11. This does not seem to make much sense since noone can submit an assessment before it's published. Our maximum value also seems exagerated. Let's check the relationship between our negative date_submitted values and the final_result: ``` outliers_final_result = data[data['date_submitted']< 0][['date_submitted','final_result']] outliers_final_result.final_result.value_counts() ``` Let's zoom in the Pass and Distinction, to check if this is because they were banked: ``` outliers_final_result_pass = data[(data.date_submitted < 0) & (data.final_result == "Pass")] outliers_final_result_pass.is_banked.value_counts() outliers_final_result_distinct = data[(data.date_submitted < 0) & (data.final_result == "Distinction")] outliers_final_result_distinct.is_banked.value_counts() ``` We have a total of 110 rows where the date_submitted have a negative value and the is_banked flag is 0. We'll drop those rows. ``` nonsense = data[(data.date_submitted < 0) & (data.is_banked == "0")].index data.drop(nonsense, inplace=True) data.info() ``` Now let's check the relationship between our greater than 365 date_submitted values and the final_result: ``` outliers_final_result_late = data[data['date_submitted']>365][['date_submitted','final_result']] outliers_final_result_late.final_result.value_counts() ``` ### score The student’s score in this assessment. The range is from 0 to 100. The score lower than 40 is interpreted ``` len(data.score.value_counts()) ``` Seems weird to have 102 values since students should be rated from 0 to 100 (101 values). Also, remember that this column is an object, and we need it to be numeric. ``` data.score.unique() ``` We have a '?' value! ``` #There are quite a few '?' values len(data[data['score']== '?']) ``` Let's check the relationship between those values and final_result: ``` #Most of them are 'withdrawn' or 'fail' unknown_score_final_result = data[data['score']=='?'][['score','final_result']] unknown_score_final_result.final_result.value_counts() #We transform the column type to numeric and coerce errors data.score = pd.to_numeric(data.score, errors='coerce') data.score.unique() ``` Of course, now the '?' values have been transformed to NaNs. ``` data.isnull().sum() ``` In order to get rid of those NaNs, we decide the following: - For those which final_result is "Withdrawn" of "Fail", we will change the value to 0. - For those which final_result is "Pass", we will fill the value with the mean of all "Pass". - For those which final_result is "Distinction", we will fill the value with the mean of all "Distinction". ``` data['score'] = np.where(((data['score'].isnull()) & (data['final_result'] =="Withdrawn")),0,data['score']) data['score'] = np.where(((data['score'].isnull()) & (data['final_result'] =="Fail")),0,data['score']) data['score'] = np.where(((data['score'].isnull()) & (data['final_result'] =="Pass")), data[data['final_result']=='Pass']['score'].mean(),data['score']) data['score'] = np.where(((data['score'].isnull()) & (data['final_result'] =="Distinction")), data[data['final_result']=='Distinction']['score'].mean(),data['score']) ``` We check that we successfully got rid of the NaNs. ``` data.isnull().sum() ``` So now we can analyze the column. ``` display(data.score.describe()) data.boxplot(column= ['score']) plt.show() ``` # ordenar el gráfico de arriba ### num_of_prev_attempts ``` data.num_of_prev_attempts.value_counts() crossatt = pd.crosstab(data.score, data.num_of_prev_attempts, margins=True, margins_name='Total') display(crossatt.head(3)) display(crossatt.tail(3)) sns.distplot(data.num_of_prev_attempts) plt.show() data.boxplot(column= ['num_of_prev_attempts']) ax = sns.countplot(x="num_of_prev_attempts", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() ``` ### studied_credits ``` data.studied_credits.value_counts() crosscre = pd.crosstab(data.score, data.studied_credits, margins=True, margins_name='Total') display(crosscre.head(3)) display(crosscre.tail(3)) display(data.studied_credits.describe()) sns.distplot(data.studied_credits) plt.show() ``` There are some rows where the studied_credits are greater than 360. ``` len(data[data['studied_credits']>360]) ``` Let's check the relationship between those values and the final_result. ``` studiedcreditsout = data[data['studied_credits']>360][['studied_credits','final_result']] studiedcreditsout.final_result.value_counts() ``` ### module_presentation_length ``` data.module_presentation_length.value_counts() crossle = pd.crosstab(data.score, data.module_presentation_length, margins=True, margins_name='Total') display(crossle.head(3)) display(crossle.tail(3)) data.module_presentation_length.describe() ax = sns.countplot(x="module_presentation_length", data=data, palette='YlGnBu') ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") plt.tight_layout() plt.show() data.to_csv('Data/final.csv', index=False) data.info() ``` # Let's now see the correlation ``` fig, ax = plt.subplots(figsize=(10,5)) sns.heatmap(data.corr(), annot=True, linewidths=.5, ax=ax) plt.show() data.info() data.shape data = data.to_csv('Data/ml.csv', index=False) ```
github_jupyter
# Extreme Gradient Boosting Regressor ### Required Packages ``` !pip install xgboost import warnings import numpy as np import pandas as pd import seaborn as se import xgboost as xgb import matplotlib.pyplot as plt from xgboost import XGBRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error warnings.filterwarnings('ignore') ``` ### Initialization Filepath of CSV file ``` #filepath file_path = "" ``` List of features which are required for model training . ``` #x_values features=[] ``` Target feature for prediction. ``` #y_value target = '' ``` ### Data Fetching Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. ``` df=pd.read_csv(file_path) df.head() ``` ### Feature Selections It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model. We will assign all the required input features to X and target/outcome to Y. ``` X = df[features] Y = df[target] ``` ### Data Preprocessing Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. ``` def NullClearner(df): if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])): df.fillna(df.mean(),inplace=True) return df elif(isinstance(df, pd.Series)): df.fillna(df.mode()[0],inplace=True) return df else:return df def EncodeX(df): return pd.get_dummies(df) ``` Calling preprocessing functions on the feature and target set. ``` x=X.columns.to_list() for i in x: X[i]=NullClearner(X[i]) X=EncodeX(X) Y=NullClearner(Y) X.head() ``` #### Correlation Map In order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. ``` f,ax = plt.subplots(figsize=(18, 18)) matrix = np.triu(X.corr()) se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix) plt.show() ``` ### Data Splitting The train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data. ``` X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 123) ``` ### Model XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way. For Tuning parameters, details refer to official API documentation [Tunning Parameters](https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn) ``` model = XGBRegressor(random_state = 123,n_jobs=-1) model.fit(X_train, y_train) ``` #### Model Accuracy We will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model. > **score**: The **score** function returns the coefficient of determination <code>R<sup>2</sup></code> of the prediction. ``` print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100)) ``` > **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. > **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ``` y_pred=model.predict(X_test) print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100)) print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred))) print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) ``` #### Feature Importances The Feature importance refers to techniques that assign a score to features based on how useful they are for making the prediction. ``` xgb.plot_importance(model,importance_type="gain",show_values=False) plt.rcParams['figure.figsize'] = [5, 5] plt.show() ``` #### Prediction Plot First, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. ``` plt.figure(figsize=(14,10)) plt.plot(range(20),y_test[0:20], color = "green") plt.plot(range(20),model.predict(X_test[0:20]), color = "red") plt.legend(["Actual","prediction"]) plt.title("Predicted vs True Value") plt.xlabel("Record number") plt.ylabel(target) plt.show() ``` #### Creator: Thilakraj Devadiga , Github: [Profile](https://github.com/Thilakraj1998)
github_jupyter
# Characterization of Systems in the Time Domain *This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Communications Engineering, Universität Rostock. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Analysis of a Damped Spring Pendulum The damped [spring pendulum](https://en.wikipedia.org/wiki/Spring_pendulum) is an example for a mechanical system that can be modeled by a linear ordinary differential equation (ODE) with constant coefficients. In view of the theory of signals and systems it hence can be interpreted as a linear time-invariant (LTI) system. The mechanical properties of the damped spring pendulum are analyzed by using the theory of LTI systems. The underlying mechanical setup is depicted in the following ![Damped spring pendulum](damped_spring.png) A compact mass $m$ is mounted on a spring with stiffness $k$ which is connected to the ground. A damper with viscous damping coefficient $c$ is mounted parallel to the spring to model the friction present in the system. It is assumed that the movement of the mass over time is restricted to the vertical axis, here denoted by $y$. It is further assumed that the mass is in its idle position for $t<0$. The pretension of the spring by the mass can be neglected this way. It is additionally assumed that the mass is not moving for $t<0$. Denoting the displacement of the mass over time with $y(t)$, these initial conditions are formulated as $y(t) = 0$ and $\frac{d y(t)}{dt} = 0$ for $t<0$. The normalized values $m = 0.1$, $c = 0.1$, $k = 2.5$ are used for illustration in the following. ### Differential Equation The differential equation of the mechanical system is derived by considering the force equilibrium at the mass \begin{equation} F_\text{S}(t) + F_\text{F}(t) + F_\text{I}(t) = F_\text{E}(t) \end{equation} where $F_\text{E}(t)$ denotes an external force acting onto the mass, the other forces are derived in the sequel. The force $F_\text{S}(t)$ induced by the spring is given by [Hooke's law](https://en.wikipedia.org/wiki/Hooke%27s_law) \begin{equation} F_\text{S}(t) = k y(t) \end{equation} Its common to model the frictional force $F_\text{F}(t)$ induced by the damper as being proportional to the velocity of the mass \begin{equation} F_\text{F}(t) = c \frac{d y(t)}{dt} \end{equation} The inertial force $F_\text{I}(t)$ due to the acceleration of the mass is given as \begin{equation} F_\text{I}(t) = m \frac{d^2 y(t)}{dt^2} \end{equation} Introducing the forces into the force equilibrium yields the differential equation describing the displacement of the damped spring pendulum \begin{equation} m \frac{d^2 y(t)}{dt^2} + c \frac{d y(t)}{dt} + k y(t) = F_\text{E}(t) \end{equation} as a consequence of the external force. Above equation constitutes an ODE with constant coefficients. It can be interpreted as an LTI system with the external force as input signal $x(t) = F_\text{E}(t)$ and the displacement of the mass as output signal $y(t)$. ### Comparison to Passive Electrical Networks Comparing the ODEs of the damped spring pendulum and the [second-order analog low-pass](http://localhost:8888/notebooks/systems_time_domain/network_analysis.ipynb#Differential-Equation) yields that both constitute second-order ODEs with constant coefficients. Dividing the ODE of the second-order analog low pass by $C$ results in \begin{equation} L \frac{d^2 u_\text{o}(t)}{dt^2} + R \frac{d u_\text{o}(t)}{dt} + \frac{1}{C} u_\text{o}(t) = \frac{1}{C} u_\text{i}(t) \end{equation} where $u_\text{i}(t)$ and $u_\text{o}(t)$ denote the in- and output voltage of the analog circuit. Comparison with above ODE of the spring pendulum yields the [equivalence of both systems](https://en.wikipedia.org/wiki/System_equivalence) for | &#65279;| 2nd-order low-pass | spring pendulum | |:---|:---|:---| | input signal $x(t)$ | $u_\text{i}(t) = F_\text{E}(t) C$ | $F_\text{E}(t) = \frac{u_\text{i}(t)}{C}$ | | output signal $y(t)$ | $u_\text{o}(t)$ | $y(t)$ | | &#65279; | $L = m$ | $m = L$ | | &#65279; | $R = c$ | $c = R$ | | &#65279; | $C = \frac{1}{k}$ | $k = \frac{1}{C}$ | Note, the equivalence between mechanical systems described by ODEs with constant coefficients and analog circuits was used to simulate such systems by [analog computers](https://en.wikipedia.org/wiki/Analog_computer). ### Impulse Response The LTI system corresponding to the pendulum can be characterized by its [impulse response](impulse_response.ipynb) $h(t)$. It is defined as the output of the system for a Dirac Delta impulse $x(t) = \delta(t)$ at the input. Physically this can be approximated by hitting the mass (very shortly and forceful). The impulse response characterizes the movement $y(t)$ of the mass after such an event. First the ODE of the spring pendulum is defined in `SymPy` ``` import sympy as sym sym.init_printing() t, m, c, k = sym.symbols('t m c k', real=True) x = sym.Function('x')(t) y = sym.Function('y')(t) ode = sym.Eq(m*y.diff(t, 2) + c*y.diff(t) + k*y, x) ode ``` The normalized values of the physical constants are stored in a dictionary for ease of later substitution ``` mck = {m: 0.1, c: sym.Rational('.1'), k: sym.Rational('2.5')} mck ``` The impulse response is calculated by explicit solution of the ODE. ``` solution_h = sym.dsolve( ode.subs(x, sym.DiracDelta(t)).subs(y, sym.Function('h')(t))) solution_h ``` The integration constants $C_1$ and $C_2$ have to be determined from the initial conditions $y(t) = 0$ and $\frac{d y(t)}{dt} = 0$ for $t<0$. ``` integration_constants = sym.solve((solution_h.rhs.limit( t, 0, '-'), solution_h.rhs.diff(t).limit(t, 0, '-')), ['C1', 'C2']) integration_constants ``` Substitution of the values for the integration constants $C_1$ and $C_2$ into the result from above yields the impulse response of the spring pendulum ``` h = solution_h.subs(integration_constants) h ``` The impulse response is plotted for the specific values of $m$, $c$ and $k$ given above ``` sym.plot(h.rhs.subs(mck), (t, 0, 12), ylabel=r'h(t)'); ``` ### Transfer Function For an exponential input signal $x(t) = e^{s t}$, the [transfer function](eigenfunctions.ipynb#Transfer-Function) $H(s)$ represents the weight of the exponential output signal $y(t) = H(s) \cdot e^{s t}$. The transfer function is derived by introducing $x(t)$ and $y(t)$ into the ODE and solving for $H(s)$ ``` s = sym.symbols('s') H = sym.Function('H')(s) H, = sym.solve(ode.subs(x, sym.exp(s*t)).subs(y, H*sym.exp(s*t)).doit(), H) H ``` The transfer characteristic of an LTI system for harmonic exponential signals $e^{j \omega t} = \cos(\omega t) + j \sin(\omega t)$ is of special interest in the analysis of resonating systems. It can be derived from $H(s)$ by substituting the complex frequency $s$ with $s = j \omega$. The resulting transfer function $H(j \omega)$ provides the attenuation and phase the system adds to an harmonic input signal. ``` w = sym.symbols('omega', real=True) Hjw = H.subs(s, sym.I * w) Hjw ``` The magnitude of the transfer function $|H(j \omega)|$ is plotted for the specific values of the elements given above ``` sym.plot(abs(Hjw.subs(mck)), (w, -15, 15), ylabel=r'$|H(j \omega)|$', xlabel=r'$\omega$'); ``` When inspecting the magnitude of the transfer function it becomes evident that the damped spring pendulum shows resonances (maxima) for two specific angular frequencies. These resonance frequencies $\omega_0$ are calculated by inspecting the extreme values of $|H(j \omega)|$. First the derivative of $|H(j \omega)|$ with respect to $\omega$ is computed and set to zero ``` extrema = sym.solve(sym.Eq(sym.diff(abs(Hjw), w), 0), w) extrema ``` For the maxima of the transfer function only the 2nd and 3rd extrema are of interest ``` w0 = extrema[1:3] w0 ``` The resonance frequencies are computed for the specific values of $m$, $c$ and $k$ given above ``` [w00.subs(mck) for w00 in w0] ``` The phase of the transfer function $\varphi(j \omega)$ is computed and plotted for the specific values of the elements given above ``` phi = sym.arg(Hjw) sym.plot(phi.subs(mck), (w, -15, 15), ylabel=r'$\varphi(j \omega)$', xlabel=r'$\omega$'); ``` **Exercise** * Change the viscous damping coefficient $c$ of the spring pendulum and investigate how the magnitude and phase of the transfer function $H(j \omega)$ changes. * How does the frequency of the damped harmonic oscillation in the impulse response relates to the resonance frequency? ### Application: Vibration Isolation An application of above example is the design of [vibration isolation](https://en.wikipedia.org/wiki/Vibration_isolation) by a damped spring pendulum. A typical example is a rotating machinery with mass $m$ which has some sort of imbalance. Assuming that the imbalance can be modeled as a rotating mass, the external force $F_\text{E}(t)$ is given by the vertical component of its [centrifugal force](https://en.wikipedia.org/wiki/Centrifugal_force) \begin{equation} F_\text{E}(t) = F_0 \sin(\omega t) = F_0 \cdot \Im \{e^{j \omega t} \} \end{equation} where $\omega$ denotes the angular frequency of the rotating machinery and \begin{equation} F_0 = m_\text{I} r \omega^2 \end{equation} the amplitude of the force with $m_\text{I}$ denoting the mass of the imbalance and $r$ the radius of its circular orbit. Since $e^{j \omega t}$ is an eigenfunction of the LTI system, the resulting displacement is then given as \begin{equation} y(t) = F_0 \cdot \Im \{e^{j \omega t} H(j \omega) \} \end{equation} The aim of vibration isolation is to keep the magnitude of the displacement as low as possible. **Exercise** * Compute and plot the displacement for given $m_\text{I}$ and $r$. * For which angular frequencies $\omega$ is the magnitude of the displacement largest? How is the phase relation between the external force $F_\text{E}(t)$ and displacement $y(t)$ at these frequencies? * How should the resonance frequencies $\omega_0$ of the spring pendulum be chosen in order to get a good vibration isolation for a machine rotating with angular frequency $\omega$? How is the phase relation between the external force $F_\text{E}(t)$ and displacement $y(t)$ at this frequency? **Copyright** This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Continuous- and Discrete-Time Signals and Systems - Theory and Computational Examples*.
github_jupyter
``` # LSTM for international airline passengers problem with window regression framing import numpy import numpy as np import keras import matplotlib.pyplot as plt from pandas import read_csv import math from keras.models import Sequential from keras.layers import Dense,Dropout from keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from sklearn.preprocessing import OneHotEncoder from sklearn.cross_validation import train_test_split from keras.utils.vis_utils import plot_model # convert an array of values into a dataset matrix def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back-1): a = dataset[i:(i+look_back), 0] dataX.append(a) dataY.append(dataset[i + look_back, 0]) return numpy.array(dataX), numpy.array(dataY) def create_dataset2(dataset, look_back=1): dataX, dataY = [], [] dataZ=[] for i in range(len(dataset)-look_back-1): a = dataset[i:(i+look_back), 1] dataX.append(a) b = dataset[i + look_back, 0] dataZ.append(b) dataY.append(dataset[i + look_back, 1]) return numpy.array(dataX), numpy.array(dataY),numpy.array(dataZ) # fix random seed for reproducibility numpy.random.seed(7) # load the dataset # dataframe = read_csv('w_d_v.csv', usecols=[7], engine='python', skipfooter=3) dataframe = read_csv('t6192.csv', usecols=[8,0], engine='python',dtype=np.int32,skiprows=-1,header=None,skipfooter=3) pattern = read_csv('t6192.csv', usecols=[7], engine='python',dtype=np.int32,skiprows=-1,header=None,skipfooter=3) Matrix = read_csv('matrix621.csv', usecols=[2,3,4,5,6,7,8,9,10,11,12,13], engine='python',header=None) all_data = read_csv('all_data.csv', usecols=[7], engine='python', skipfooter=3) dataset = dataframe.values Matrix = Matrix.values pattern=pattern.values allData=all_data.values Matrix=np.append([[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]],Matrix,axis=0) look_back = 3 trainX, trainY, trainZ = create_dataset2(dataset, look_back) AllX, AllY = create_dataset(allData, look_back) patternX, patternY = create_dataset(pattern, look_back) trainY=numpy.reshape(trainY,(trainY.shape[0],-1)) AllY=numpy.reshape(AllY,(AllY.shape[0],-1)) encX = OneHotEncoder() encX.fit(trainX) encY = OneHotEncoder() encY.fit(trainY) trainX_one=encX.transform(trainX).toarray() train_X=numpy.reshape(trainX_one,(trainX_one.shape[0],look_back,-1)) train_Y=encY.transform(trainY).toarray() ``` #还没能直接拆分,其他维度没有做对应 a_train, a_test, b_train, b_test = train_test_split(train_X, train_Y, test_size=0.1, random_state=42) ``` emdedding_size=Matrix.shape[1] # vo_len=look_back # vocab_size=Matrix.shape[0] # a_train=trainX.reshape(-1,3,1) a_train=a_train.reshape(-1,3) b_train=train_Y k=trainZ pretrained_weights=Matrix LSTM_size=32 print("------------------------") print("in size:") print(a_train.shape) print("------------------------") print("out size:") print(b_train.shape) print("------------------------") print("user size:") print(k.shape) print("------------------------") print("------------------------") print("input encode example1:") print(train_X[0]) print("------------------------") print("input encode example2:") for x in a_train[0]: print(pretrained_weights[x]) print("------------------------") print("input decode example:") print(a_train[0]) print("------------------------") print("output encode example:") print(b_train[0]) print("------------------------") print("output decode example:") print(trainY[0]) print("------------------------") print("user_id example:") print(k[0]) print("------------------------") print("------------------------") print("emdedding_size:") print(emdedding_size) print("------------------------") print("vocab_length:") print(vo_len) print("------------------------") print("vocab_size:") print(vocab_size) print("------------------------") print("使用 encode2 (语义权重 pretrained_weights)方法") from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model input_pattern = Input(shape=(3, ),name="input_pattern") input_id = Input(shape=(1,),name="input_id") em = Embedding(input_dim=vocab_size, output_dim=emdedding_size,input_length=vo_len,weights=[pretrained_weights])(input_pattern) lstm_out = LSTM(LSTM_size)(em) lstm_out = Dropout(0.2)(lstm_out) x = keras.layers.concatenate([lstm_out, input_id]) x=Dense(250,activation='relu',name="C")(x) x=Dropout(0.2)(x) x=Dense(b_train.shape[1],activation='softmax',name='x')(x) model = Model(inputs=[input_pattern,input_id], outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) # print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm.png',show_shapes=True) history_nopre = model.fit([a_train,k], b_train, epochs=100, batch_size=16, verbose=2) print("使用 encode1 方法") a_train=train_X from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model input_pattern = Input(shape=(3, a_train.shape[2]),name="input_pattern") input_id = Input(shape=(1,),name="input_id") lstm_out = LSTM(units=32)(input_pattern) lstm_out = Dropout(0.2)(lstm_out) x = keras.layers.concatenate([lstm_out, input_id]) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(b_train.shape[1],activation='softmax')(x) model = Model(inputs=[input_pattern,input_id], outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) # print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_encode1.png',show_shapes=True) history_encode1 = model.fit([a_train,k], b_train, epochs=100, batch_size=16, verbose=2) from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model emdedding_size=12 # vo_len=3 # vocab_size=11000 # a_train=trainX.reshape(-1,3) b_train=train_Y k=trainZ pretrained_weights=Matrix input_pattern = Input(shape=(3, ),name="input_pattern") em = Embedding(input_dim=vocab_size, output_dim=emdedding_size,input_length=vo_len)(input_pattern) lstm_out = LSTM(units=emdedding_size)(em) lstm_out = Dropout(0.2)(lstm_out) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(180,activation='softmax')(x) model = Model(inputs=input_pattern, outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history_withpre = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model emdedding_size=12 # vo_len=3 # vocab_size=11000 # a_train=patternX b_train=train_Y k=trainZ pretrained_weights=Matrix input_pattern = Input(shape=(3, ),name="input_pattern") em = Embedding(input_dim=vocab_size, output_dim=emdedding_size,input_length=vo_len, weights=[pretrained_weights])(input_pattern) lstm_out = LSTM(units=emdedding_size)(em) lstm_out = Dropout(0.2)(lstm_out) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(180,activation='softmax')(x) model = Model(inputs=input_pattern, outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history_withpre2 = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) ``` plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history_nopre = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) ``` from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model emdedding_size=12 # vo_len=3 # vocab_size=11000 # a_train=trainX.reshape(-1,3) b_train=train_Y k=trainZ pretrained_weights=Matrix input_pattern = Input(shape=(3, ),name="input_pattern") em = Embedding(input_dim=vocab_size, output_dim=emdedding_size,input_length=vo_len, weights=[pretrained_weights])(input_pattern) lstm_out = LSTM(units=emdedding_size)(em) lstm_out = Dropout(0.2)(lstm_out) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(180,activation='softmax')(x) model = Model(inputs=input_pattern, outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history_withpre2 = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model emdedding_size=12 # vo_len=3 # vocab_size=11000 # a_train=patternX.reshape(-1,3,1) b_train=train_Y k=trainZ pretrained_weights=Matrix input_pattern = Input(shape=(3, 1),name="input_pattern") lstm_out = LSTM(units=64)(input_pattern) lstm_out = Dropout(0.2)(lstm_out) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(180,activation='softmax')(x) model = Model(inputs=input_pattern, outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history_withpre2 = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) ``` plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history1 = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2) ``` from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model input_pattern = Input(shape=(3, a_train.shape[2]),name="input_pattern") lstm_out = LSTM(512,input_shape=(3, a_train.shape[2]))(input_pattern) # lstm_out = LSTM(512,return_sequences=True,input_shape=(3, a_train.shape[2]))(input_pattern) # lstm_out = LSTM(300)(lstm_out) lstm_out = Dropout(0.2)(lstm_out) x=Dense(250,activation='relu',name="C")(lstm_out) x=Dropout(0.2)(x) x=Dense(a_train.shape[2],activation='softmax')(x) model = Model(inputs=input_pattern, outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm_test.png',show_shapes=True) history = model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2, validation_data=(a_test, b_test)) print(history.history.keys()) fig = plt.figure() plt.plot(history.history['acc']) plt.plot(history1.history['acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['1-lstm', '2-lstm'], loc='upper left') fig = plt.figure() plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower left') train_X=train_X.reshape(-1,200) train_Y.reshape(-1,200) train_X.shape train_Y.shape from keras.layers import Input, Embedding, LSTM, Dense,Merge from keras.models import Model a_train=train_X b_train=train_Y k=trainZ input_pattern = Input(shape=(3, a_train.shape[2]),name="input_pattern") input_id = Input(shape=(1,),name="input_id") lstm_out = LSTM(250,input_shape=(3, a_train.shape[2]))(input_pattern) lstm_out = Dropout(0.2)(lstm_out) x = keras.layers.concatenate([lstm_out, input_id]) x=Dense(250,activation='relu',name="C")(x) x=Dropout(0.2)(x) x=Dense(a_train.shape[2],activation='softmax',name='x')(x) model = Model(inputs=[input_pattern,input_id], outputs=x) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy']) print(model.summary()) # Summarize Model plot_model(model, to_file='t_lstm.png',show_shapes=True) k=np.zeros(a_train.shape[0],dtype=np.int16) k=k.reshape(-1,1) k1=np.zeros(train_X.shape[0],dtype=np.int16) k1=k1.reshape(-1,1) history = model.fit({'input_pattern': a_train, 'input_id' : k}, {'x': b_train}, epochs=100, batch_size=64, verbose=2) fig = plt.figure() Accuracy=[42.00,47.15 ,48.36, 49.35,47.42, 50.82, 52.31,56.93 ,57.15 ] x2=(20,30,40,50,60,70,80,90,100) plt.plot(x2,Accuracy) x1=range(0,100) plt.plot(x1,history.history['acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['100% total_data Yu','100% total_data Mine'], loc='upper left') fig = plt.figure() plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['90% train_data', '100% total_data'], loc='upper left') ``` model.fit(a_train, b_train, epochs=100, batch_size=16, verbose=2, validation_data=(a_test, b_test)) ``` model.evaluate(train_X, train_Y, batch_size=64, verbose=2, sample_weight=None) trainPredict = model.predict(train_X) D=np.argmax(train_Y,axis = 1) E=np.argmax(trainPredict,axis = 1) print(D) print(E) A=0 #total number of right for i,t in enumerate(E): if D[i]==t : A=A+1 print(A/D.shape[0]) ```
github_jupyter
``` import pandas as pd import zipfile import numpy as np import sys import numpy as np import matplotlib.pyplot as plt from IPython.display import display directory_lic='C:\\repos\\public-procurement\\data\\licitaciones\\' directory_oc='C:\\repos\\public-procurement\\data\\ordenes\\' year_range=np.arange(2010,2021,1) month_range=np.arange(1,13,1) yearmonths=[str(y)+'-'+str(m) for y in year_range for m in month_range] yearmonths #target_categories=pd.read_csv('C:\\repos\\public-procurement\\data\\ordenes\\medical_categories.csv', encoding="cp1252",sep=';', low_memory=False,decimal=",") #RubroN3=target_categories['Rubro3'] #RubroN2=target_categories['Rubro2'] #RubroN1=target_categories['Rubro1'] #Vars: firms, units, montos, montos estimados. Fecha listaVariables=['Codigo','CodigoExterno','Nombre','NombreOrganismo','NombreUnidad','RutUnidad','RegionUnidad', 'Obras','FechaInicio', 'TiempoDuracionContrato','NumeroOferentes','Rubro1','Rubro2','Rubro3','Nombre producto genérico','RutProveedor', 'NombreProveedor','Monto Estimado Adjudicado','Valor Total Ofertado','Cantidad Ofertada','CantidadAdjudicada','Oferta seleccionada','MontoEstimado', 'CodigoProductoONU','ComunaUnidad','Tipo de Adquisición','Estado Oferta'] yearmonths[50:50] import codecs codecs.register_error("strict", codecs.ignore_errors) list_df_lic=[] #list_df_oc=[] filter_medical= True filter_target=True for i in yearmonths: print(i) if i=="2014-3" or i=="2014-4"or i=='2011-3': continue string_open1=directory_lic+str(i)+'.zip' string_open2=directory_oc+str(i)+'.zip' zf = zipfile.ZipFile(string_open1) df = pd.read_csv(zf.open('lic_'+str(i)+'.csv'), encoding='Windows-1252',sep=';', low_memory=False,decimal=",") if filter_target== True: #df=df[df.RubroN3.isin(RubroN3)] df=df[df.Rubro2=="CONSTRUCCIÓN DE EDIFICIOS EN GENERAL"] df=df[listaVariables] list_df_lic.append(df) df_lic=pd.concat(list_df_lic) del list_df_lic df = df_lic df = df_lic.loc[:,~df_lic.columns.duplicated()] import feather feather.write_dataframe(df, 'lic_construccion_feather.feather') import feather df=feather.read_dataframe('lic_construccion_feather.feather') #Study of the Estimated Price df.loc[:,'MCA_MPO']=df['Valor Total Ofertado']/df['MontoEstimado'] ##Check how many have quantities=1, how many NA's in estimated price. Print. dfQuantities=df.groupby(['Cantidad Ofertada'] ).agg( { # Find the min, max, and sum of the duration column 'Codigo': ["count"], } ) dfQuantities df_bids=df[(df['Cantidad Ofertada']==1)& (df['MontoEstimado']>1000)& (df['Valor Total Ofertado']>1000)& (df['MCA_MPO']>0.1)& (df['MCA_MPO']<2)] df_bids.to_csv('bids.csv',encoding='cp1252') ##Filter non selected offers and all noise in the sample to get only the expected amount. df_estimated=df[(df['Cantidad Ofertada']==1)& (df['CantidadAdjudicada']==1)& (df['MontoEstimado']>1000)& (df['Valor Total Ofertado']>1000)& (df['MCA_MPO']>0.1)& (df['MCA_MPO']<2)] ##Check possible problems in the data ###Number of lics with more quantity than 1 (maybe small objects) propQuant=((df['CantidadAdjudicada']>=1)&(df['Cantidad Ofertada']!=1)).sum() ###Too low values estimated propWong=(df['MCA_MPO']>=2).sum() #NA and missing propNA=df.MontoEstimado.isna().sum() propZero=(df.MontoEstimado<1000).sum() propValidEstim=round(len(df_estimated)/len(df[df['CantidadAdjudicada']>=1]),2) print(len(df),len(df_bids),len(df_estimated),propValidEstim,propZero,propNA,propWong,propQuant) ##Sample Statistics df_estimated['MCA_MPO'].describe() histo1=df_estimated.hist(column='MCA_MPO',bins=20) #TODO: find why some prices are so much less than estimations. df['year'] = pd.DatetimeIndex(df['FechaInicio']).year #Actors in the network. ##Firms in the network dfFirms=df_bids.groupby(['RutProveedor'] ).agg( { # Find the min, max, and sum of the duration column 'CantidadAdjudicada': [lambda x: (x>=1 ).sum()], 'Codigo': ["nunique"], 'NombreOrganismo': ["nunique"], 'RutUnidad':["nunique"], 'year':["max","min"] } ) dfFirms.columns = ["_".join(x) for x in dfFirms.columns.ravel()] dfFirms['exp']=dfFirms['year_max']-dfFirms['year_min'] display(dfFirms.describe()) dfFirms=df_estimated.groupby(['RutProveedor'] ).agg( { # Find the min, max, and sum of the duration column 'CantidadAdjudicada': [lambda x: (x>=1 ).sum()], 'Codigo': ["nunique"], 'NombreOrganismo': ["nunique"], 'RutUnidad':["nunique"], 'year':["max","min"] } ) dfFirms.columns = ["_".join(x) for x in dfFirms.columns.ravel()] dfFirms['exp']=dfFirms['year_max']-dfFirms['year_min'] display(dfFirms.describe()) len(df.RutProveedor.unique()) dfFirms=df.groupby(['RutProveedor'] ).agg( { # Find the min, max, and sum of the duration column 'Codigo': ["nunique"], 'NombreOrganismo': ["nunique"], 'RutUnidad':["nunique"] } ) display(dfFirms.describe()) ##Gov. Units in the Network dfGovs=df.groupby(['NombreOrganismo'] ).agg( { # Find the min, max, and sum of the duration column 'Codigo': ["nunique"], 'RutProveedor':["nunique"] } ) display(dfGovs.describe()) #Auctions. dfAuctions=df.groupby(['Codigo'] ).agg( { # Find the min, max, and sum of the duration column 'RutProveedor': ["nunique"], } ) dfAuctions.describe() ##Price distributions. #Participants per auction. a=pd.DataFrame(df['NombreOrganismo'].unique(),columns=['Entity']) a['Tipo']='GOV' b=pd.DataFrame(df['NombreProveedor'].unique(),columns=['Entity']) b['Tipo']='FIRM' df_entities=pd.concat([a,b]) #df_entities['Label']=df_entities['Entity'] df_entities.to_csv('Entitites.csv') df_entities.drop_duplicates(subset ="Entity", keep = False, inplace = True) df_entities.reset_index(drop=True, inplace=True) len(df_entities) import networkx as nx from matplotlib.pyplot import figure df_edges=df[['NombreOrganismo','NombreProveedor']] G = nx.from_pandas_edgelist(df_edges, 'NombreOrganismo', 'NombreProveedor') nx.set_node_attributes(G, df_entities.set_index('Entity').to_dict('index')) #figure(figsize=(10, 8)) nx.write_graphml(G,'procgraph3.graphml') ```
github_jupyter
# Simple Model of a Car on a Bumpy Road This notebook allows you to compute and visualize the car model presented in Example 2.4.2 the book. The road is described as: $$y(t) = Ysin\omega_b t$$ And $\omega_b$ is a function of the car's speed. ``` import numpy as np def x_h(t, wn, zeta, x0, xd0): """Returns the transient vertical deviation from the equilibrium of the mass. Parameters ========== t : ndarray, shape(n,) An array of monotonically increasing values for time. zeta : float The damping ratio of the system. x0 : float The initial displacement from the equilibrium. xd0 : float The initial velocity of the mass. Returns ======== x_h : ndarray, shape(n,) An array containing the displacement from equilibrium as a function of time. """ wd = wn * np.sqrt(1 - zeta**2) A = np.sqrt(x0**2 + ((xd0 + zeta * wn * x0) / wd)**2) phi = np.arctan2(x0 * wd, xd0 + zeta * wn * x0) return A * np.exp(-zeta * wn * t) * np.sin(wd * t + phi) def x_p(t, wn, zeta, Y, wb): """Returns the steady state vertical deviation from the equilibrium of the mass. Parameters ========== t : ndarray, shape(n,) An array of monotonically increasing values for time. wn : float The natural frequency of the system in radians per second. zeta : float The damping ratio of the system. Y : float The amplitude of the road bumps in meters. wb : float The frequency of the road bumps in radians per second. Returns ======== x_p : ndarray, shape(n,) An array containing the displacement from equilibrium as a function of time. """ theta1 = np.arctan2(2 * zeta * wn * wb, (wn**2 - wb**2)) theta2 = np.arctan2(wn, 2 * zeta * wb) amp = wn * Y * ((wn**2 + (2 * zeta * wb)**2) / ((wn**2 - wb**2)**2 + (2 * zeta * wn * wb)**2))**0.5 return amp * np.cos(wb * t - theta1 - theta2) def compute_force(t, m, c, k, Y, wb): """Returns the total force acting on the mass. Parameters ========== t : ndarray, shape(n,) An array of monotonically increasing values for time. m : float The mass of the vehicle in kilograms. c : float The damping coefficient in Newton seconds per meter. k : float The spring stiffness in Newtons per meter. Y : float The amplitude of the road bumps in meters. wb : float The frequency of the road bumps in radians per second. Returns ======== f : ndarray, shape(n,) An array containing the acting on the mass as a function of time. """ wn = np.sqrt(k / m) zeta = c / 2 / m / wn r = wb / wn amp = k * Y * r**2 * np.sqrt((1 + (2 * zeta * r)**2) / ((1 - r**2)**2 + (2 * zeta * r)**2)) theta1 = np.arctan2(2 * zeta * wn * wb, (wn**2 - wb**2)) theta2 = np.arctan2(wn, 2 * zeta * wb) return -amp * np.cos(wb * t - theta1 - theta2) def compute_trajectory(t, m, c, k, Y, wb, x0, xd0): """Returns the combined transient and steady state deviation of the mass from equilibrium. Parameters ========== t : ndarray, shape(n,) An array of monotonically increasing values for time. m : float The mass of the vehicle in kilograms. c : float The damping coefficient in Newton seconds per meter. k : float The spring stiffness in Newtons per meter. Y : float The amplitude of the road bumps in meters. wb : float The frequency of the road bumps in radians per second.x0 : float The initial displacement. xd0 : float The initial velocity of the mass. Returns ======== x_h : ndarray, shape(n,) An array containing the displacement from equilibrium as a function of time. """ wn = np.sqrt(k / m) zeta = c / 2 / m / wn return x_h(t, wn, zeta, x0, xd0) + x_p(t, wn, zeta, Y, wb) ``` Now start with the parameters given in the book. ``` Y = 0.01 # m v = 20 # km/h m = 1007 # kg k = 4e4 # N/m c = 20e2 # Ns/m x0 = -0.05 # m xd0 = 0 # m/s bump_distance = 6 # m ``` The bump frequency is a function of the distance between the bumps and the speed of the vehicle. ``` wb = v / bump_distance * 1000 / 3600 * 2 * np.pi # rad /s ``` It is worth noting what the frequency ratio is: ``` r = np.sqrt(k / m) / wb r ``` Now pick some time values and compute the displacement and the force trajectories. ``` t = np.linspace(0, 20, num=500) x = compute_trajectory(t, m, c, k, Y, wb, x0, xd0) f = compute_force(t, m, c, k, Y, wb) ``` Plot the trajectories. ``` import matplotlib.pyplot as plt %matplotlib notebook fig, axes = plt.subplots(2, 1, sharex=True) axes[0].plot(t, x) axes[1].plot(t, f / k) axes[1].set_xlabel('Time [s]') axes[0].set_ylabel('$x(t)$') axes[1].set_ylabel('F / k [m]') ``` Now animate the simulation of the model showing the motion and a vector that represents the force per stiffness value. ``` from matplotlib.patches import Rectangle import matplotlib.animation as animation fig, ax = plt.subplots(1, 1) ax.set_ylim((-0.1, 0.6)) ax.set_ylabel('Height [m]') #ax.set_aspect('equal') xeq = 0.1 # m view_width = 4 # m rect_width = 1.0 # m rect_height = rect_width / 4 # m bump_distance = 6 # m lat_pos = 0 lat = np.linspace(lat_pos - view_width / 2, lat_pos + view_width / 2, num=100) ax.set_xlim((lat[0], lat[-1])) rect = Rectangle( (-rect_width / 2, xeq + x0), # (x,y) rect_width, # width rect_height, # height ) car = ax.add_patch(rect) road = ax.plot(lat, Y * np.sin(2 * np.pi / bump_distance * lat), color='black')[0] suspension = ax.plot([lat_pos, lat_pos], [Y * np.sin(2 * np.pi / bump_distance * lat_pos), xeq + x0], linewidth='4', marker='o', color='yellow')[0] force_vec = ax.plot([lat_pos, lat_pos], [xeq + x0 + rect_height / 2, xeq + x0 + rect_height / 2 + 0.2], 'r', linewidth=4)[0] def kph2mps(speed): # km 1 hr 1 min 1000 m # -- * ------ * ------ * ------ # hr 60 min 60 sec 1 km return speed * 1000 / 3600 def animate(i): # update the data for all the drawn elements in this function lat_pos = kph2mps(v) * t[i] ax.set_xlim((lat_pos - view_width / 2, lat_pos + view_width / 2)) rect.set_xy([lat_pos - rect_width / 2, xeq + x[i]]) road.set_xdata(lat + lat_pos) road.set_ydata(Y * np.sin(2 * np.pi / bump_distance * (lat + lat_pos))) suspension.set_xdata([lat_pos, lat_pos]) suspension.set_ydata([Y * np.sin(2 * np.pi / bump_distance * lat_pos), xeq + x[i]]) force_vec.set_xdata([lat_pos, lat_pos]) force_vec.set_ydata([xeq + x[i] + rect_height / 2, xeq + x[i] + rect_height / 2 + f[i] / k]) ani = animation.FuncAnimation(fig, animate, frames=len(t), interval=25) ``` # Questions Explore the model and see if you can select a damping value that keeps the car pretty stable as it traverses the road. What happens if you change the driving speed? Do the values of $k$ and $c$ work well for all speeds? Can you detect the difference in displacement transmissibility and force transmissibility for different driving speeds?
github_jupyter
``` import pandas as pd import numpy as np from source.make_train_test import make_teams_target pd.set_option("max_columns", 300) def _add_stage(total): total['stage'] = '68' total.loc[(total.DayNum == 136) | (total.DayNum == 136), 'stage'] = '64' total.loc[(total.DayNum == 138) | (total.DayNum == 139), 'stage'] = '32' total.loc[(total.DayNum == 143) | (total.DayNum == 144), 'stage'] = '16' total.loc[(total.DayNum == 145) | (total.DayNum == 146), 'stage'] = '8' total.loc[(total.DayNum == 152), 'stage'] = '4' total.loc[(total.DayNum == 154), 'stage'] = 'Final' #total = pd.get_dummies(total, columns=['stage']) #del total['stage_68'] return total playoff_compact = 'data/raw_men/MDataFiles_Stage1/MNCAATourneyCompactResults.csv' seed = 'data/raw_men/MDataFiles_Stage1/MNCAATourneySeeds.csv' seeds = pd.read_csv(seed) seeds.head() target_data = pd.read_csv(playoff_compact) target_data = make_teams_target(target_data, 'men') target_data.head() seeds['region'] = seeds['Seed'].apply(lambda x: x[0]) seeds['Seed'] = seeds['Seed'].apply(lambda x: int(x[1:3])) seeds.head() target_data = pd.merge(target_data, seeds.rename(columns={'TeamID': 'Team1', 'Seed': 'T1_Seed', 'region': 'T1_region'}), on=['Season', 'Team1'], how='left') target_data = pd.merge(target_data, seeds.rename(columns={'TeamID': 'Team2', 'Seed': 'T2_Seed', 'region': 'T2_region'}), on=['Season', 'Team2'], how='left') target_data = target_data[target_data.DayNum >= 136].copy() target_data.head(10) target_data = _add_stage(target_data) target_data.head(10) target_data.rename(columns={'stage': 'real_stage'}, inplace=True) target_data['Seed_diff'] = target_data['T1_Seed'] - target_data['T2_Seed'] hist = target_data.groupby(['T1_Seed', 'real_stage'], as_index=False).target.mean() hist[hist.T1_Seed<8] hist[hist.T1_Seed>=8] def add_stage(data): data.loc[(data.T1_region == 'W') & (data.T2_region == 'X'), 'stage'] = 'finalfour' data.loc[(data.T1_region == 'X') & (data.T2_region == 'W'), 'stage'] = 'finalfour' data.loc[(data.T1_region == 'Y') & (data.T2_region == 'Z'), 'stage'] = 'finalfour' data.loc[(data.T1_region == 'Z') & (data.T2_region == 'Y'), 'stage'] = 'finalfour' data.loc[(data.T1_region == 'W') & (data.T2_region.isin(['Y', 'Z'])), 'stage'] = 'final' data.loc[(data.T1_region == 'X') & (data.T2_region.isin(['Y', 'Z'])), 'stage'] = 'final' data.loc[(data.T1_region == 'Y') & (data.T2_region.isin(['W', 'X'])), 'stage'] = 'final' data.loc[(data.T1_region == 'Z') & (data.T2_region.isin(['W', 'X'])), 'stage'] = 'final' data.loc[(data.T1_region == data.T2_region) & (data.T1_Seed + data.T2_Seed == 17), 'stage'] = 'Round1' fil = data.stage.isna() data.loc[fil & (data.T1_Seed.isin([1, 16])) & (data.T2_Seed.isin([8, 9])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([8, 9])) & (data.T2_Seed.isin([1, 16])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([5, 12])) & (data.T2_Seed.isin([4, 13])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([4, 13])) & (data.T2_Seed.isin([5, 12])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([6, 11])) & (data.T2_Seed.isin([3, 14])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([3, 14])) & (data.T2_Seed.isin([6, 11])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([7, 10])) & (data.T2_Seed.isin([2, 15])), 'stage'] = 'Round2' data.loc[fil & (data.T1_Seed.isin([2, 15])) & (data.T2_Seed.isin([7, 10])), 'stage'] = 'Round2' fil = data.stage.isna() data.loc[fil & (data.T1_Seed.isin([1, 16, 8, 9])) & (data.T2_Seed.isin([4, 5, 12, 13])), 'stage'] = 'Round3' data.loc[fil & (data.T1_Seed.isin([4, 5, 12, 13])) & (data.T2_Seed.isin([1, 16, 8, 9])), 'stage'] = 'Round3' data.loc[fil & (data.T1_Seed.isin([3, 6, 11, 14])) & (data.T2_Seed.isin([2, 7, 10, 15])), 'stage'] = 'Round3' data.loc[fil & (data.T1_Seed.isin([2, 7, 10, 15])) & (data.T2_Seed.isin([3, 6, 11, 14])), 'stage'] = 'Round3' fil = data.stage.isna() data.loc[fil & (data.T1_Seed.isin([1, 16, 8, 9, 4, 5, 12, 13])) & (data.T2_Seed.isin([3, 6, 11, 14, 2, 7, 10, 15])), 'stage'] = 'Round4' data.loc[fil & (data.T1_Seed.isin([3, 6, 11, 14, 2, 7, 10, 15])) & (data.T2_Seed.isin([1, 16, 8, 9, 4, 5, 12, 13])), 'stage'] = 'Round4' data.loc[data.stage.isna(), 'stage'] = 'impossible' return data test = add_stage(target_data) test.head() pd.crosstab(test.stage, test.real_stage) ```
github_jupyter
``` def cosamp(Phi, u, s, tol=1e-10, max_iter=1000): """ @Brief: "CoSaMP: Iterative signal recovery from incomplete and inaccurate samples" by Deanna Needell & Joel Tropp @Input: Phi - Sampling matrix u - Noisy sample vector s - Sparsity vector @Return: A s-sparse approximation "a" of the target signal """ max_iter -= 1 # Correct the while loop num_precision = 1e-12 a = np.zeros(Phi.shape[1]) v = u iter = 0 halt = False while not halt: iter += 1 print("Iteration {}\r".format(iter)) y = abs(np.dot(np.transpose(Phi), v)) Omega = [i for (i, val) in enumerate(y) if val > np.sort(y)[::-1][2*s] and val > num_precision] # quivalent to below #Omega = np.argwhere(y >= np.sort(y)[::-1][2*s] and y > num_precision) T = np.union1d(Omega, a.nonzero()[0]) #T = np.union1d(Omega, T) b = np.dot( np.linalg.pinv(Phi[:,T]), u ) igood = (abs(b) > np.sort(abs(b))[::-1][s]) & (abs(b) > num_precision) T = T[igood] a[T] = b[igood] v = u - np.dot(Phi[:,T], b[igood]) halt = np.linalg.norm(v)/np.linalg.norm(u) < tol or \ iter > max_iter return a ``` Test the cosamp Python method in the reconstruction of a high-frequency signal from sparse measurements: ``` import numpy as np import scipy.linalg import scipy.signal import matplotlib.pyplot as plt n = 4000 # number of measurements t = np.linspace(0.0, 1.0, num=n) x = np.sin(91*2*np.pi*t) + np.sin(412*2*np.pi*t) # original signal (to be reconstructed) # randomly sample signal p = 103 # random sampling (Note that this is one eighth of the Shannon–Nyquist rate!) aquis = np.round((n-1) * np.random.rand(p)).astype(int) y = x[aquis] # our compressed measurement from the random sampling # Here {y} = [C]{x} = [C][Phi]{s}, where Phi is the inverse discrete cosine transform Phi = scipy.fftpack.dct(np.eye(n), axis=0, norm='ortho') CPhi = Phi[aquis,:] # l1 minimization (through linear programming) s = cosamp(CPhi, y, 10) # obtain the sparse vector through CoSaMP algorithm xrec = scipy.fftpack.idct(s, axis=0, norm='ortho') # Reconstructed signal figw, figh = 7.0, 5.0 # figure width and height plt.figure(figsize=(figw, figh)) plt.plot(t, s) plt.title('Sparse vector $s$') plt.show() # Visualize the compressed-sensing reconstruction signal figw, figh = 7.0, 5.0 # figure width and height plt.figure(figsize=(figw, figh)) plt.plot(t, x, 'b', label='Original signal') plt.plot(t, xrec, 'r', label='Reconstructed signal') plt.xlim(0.4, 0.5) legend = plt.legend(loc='upper center', shadow=True, fontsize='x-large') # Put a nicer background color on the legend. legend.get_frame().set_facecolor('C0') plt.show() ```
github_jupyter
# SLU10 - Metrics for regression: Learning Notebook In this notebook, you will learn about: - Loss functions vs. Evaluation Metrics - Mean Squared Error (MSE) - Root Mean Squared Error (RMSE) - Mean Absolute Error (MAE) - Coefficient of Determination (R²) - Adjusted R² - Scikitlearn metrics - Using metrics ## 1 - Loss functions vs. Evaluation metrics A big part of data science is translating customer business problems into machine learning problems. An important step in this process is defining the **key performance indicators (KPIs)**. These are basically measures of success. To obtain maximum success your model should optimise towards these KPIs. Unfortunately, this is not always possible. As you know, the learning process during model training requires a differentiable loss function, and you have no guarantees that the KPI you defined with your customer will be differentiable. This means you need a proxy metric that approximates the true KPI but is differentiable. In common literature the KPI is actually called the evaluation metric, and the proxy metric you use to train the model is the loss function. Many times these are actually the same, but you should be aware that they mean different things. So, don't forget: * **Loss function** is what your model will minimize; * **Evaluation metric** is what you will use to evaluate how good your model is. Normally the workflow is that you are given or you collaboratively define an evaluation metric. If this metric is differentiable, then you should most probably use it as your loss function. If it isn't, you should find an adequate proxy loss function. Next we'll cover several metrics for regression problems that can be used both as evaluation metrics. ## 2 - Metrics for regression ### 2.1 - Mean Squared Error (MSE) $$MSE = \frac{1}{N} \sum_{n=1}^N (y_n - \hat{y}_n)^2$$ where $N$ is the number of observations in your dataset, $y_n$ is the target and $\hat{y}_n$ is the prediction given the observation $x_n$. ``` mse = lambda y, y_hat: ((y - y_hat)**2).mean() ``` * Corresponds to converging to the mean of the target distribution * Loses interpretability due to the squaring. So, if you're predicting a price, the labels have the unit \\$ but the evaluation metric has the unit \\$². * It is sensible to outliers. ### 2.2 - Root Mean Squared Error (RMSE) $$RMSE = \sqrt{MSE}$$ ``` rmse = lambda y, y_hat: np.sqrt(mse(y, y_hat)) ``` * Normally prefered to the MSE because the square root recovers some of the interpretability. Continuing the previous example, the evaluation metric now has the unit $. ### 2.3 - Mean Absolute Error (MAE) $$MAE = \frac{1}{N} \sum_{n=1}^N \left|y_n - \hat{y}_n\right|$$ where $N$ is the number of observations in your dataset, $y_n$ is the target and $\hat{y}_n$ is the prediction given the observation $x_n$. ``` mae = lambda y, y_hat: np.abs(y - y_hat).mean() ``` * Corresponds to converging towards the median of the distribution. * It's more robust to outliers. * It's more interpretable than the MSE since its values are on the same units as the target. * The output can be interpreted as the expected error measured in the same units as the target. * Given that the MAE is not differentiable at 0, most libraries implement slight variations that solve this. ### 2.4 - Coefficient of Determination (R²) $$\bar{y} = \frac{1}{N} \sum_{n=1}^N y_n$$ $$R² = 1 - \frac{MSE(y, \hat{y})}{MSE(y, \bar{y})} = 1 - \frac{\frac{1}{N} \sum_{n=1}^N (y_n - \hat{y}_n)^2}{\frac{1}{N} \sum_{n=1}^N (y_n - \bar{y})^2} = 1 - \frac{\sum_{n=1}^N (y_n - \hat{y}_n)^2}{\sum_{n=1}^N (y_n - \bar{y})^2}$$ where $N$ is the number of observations in your dataset, $y_n$ is the target and $\hat{y}_n$ is the prediction given the observation $x_n$. ``` r2 = lambda y, y_hat: 1 - (mse(y, y_hat) / mse(y, np.mean(y))) ``` * R² compares how much better your regression model is when compared with a predictor that outputs just the mean of the targets. The higher is R², the more sure you are that the independent variables you used explain how the dependent variable changes. For example, if you got a R² of 0.7, you can say that the set of features you used are able to explain 70% of the target variable. * Another interpretaiton is that R² measures the linear correlation between the predictions and the target. * The R² has an upper bound of 1, depending on your application this may be an advantage. An R² = 0 or below means that your model doesn't explain anything in the target by using the features you have selected. * Also, when using R², there are something important [caveats](https://en.wikipedia.org/wiki/Coefficient_of_determination#Caveats) to take into account. One of the caveats is that, depending on the model, using more features can inflate the R² when, in fact, those features are really noisy, meaning the model is actually fitting to the noise. ### 2.5 - Adjusted R² $$R_{adj}^2 = 1 - \frac{N - 1}{N - K - 1} (1 - R^2)$$ where $N$ is the number of observations in the training dataset and K is the number of features your model is using. ``` adjusted_r2 = lambda y, y_hat, N, K: 1 - ((N - 1) / (N - K - 1)) * (1 - r2(y, y_hat)) ``` * In order to take into account the addition of useless variables, we can use the adjusted R² score ## 3 - Using the metrics As you learned in previous units, there are many ways of selecting your best estimator, and most of it relies on some way of measuring an in-sample-error (ISE) - computed on data used for training - and an out-of-sample error (OSE) - computed on data not used for training. ### 3.1 - Hold out method One of the methods you've seen is the hold-out method, where you can just split your data in a training set, where we will compute the ISE, and a test set, where we will compute the OSE. Let's start by seeing how to use this method with different metrics. First, let's load some data. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv('data/example_data.csv') x = df['LotArea'].values y = df['SalePrice'].values plt.plot(x, y, 'r.') ``` Now, remember the sklearn function to get your split for the hold-out method: ``` from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=10) print("Number of observations:\nTrain: {} | Test: {}".format(x_train.shape[0], x_test.shape[0])) ``` We now want to train some models and get estimates on both the training data and the test data. Let's train three models: * **Linear Regression**: You have learned about this model in SLU07. It is the closed form solution for optimising towards the RMSE. * **SGDRegressor:** You have learned about this model in SLU07. It is a iterative solution for linear regression based on SGD. By default it optimises for the RMSE. * **SGDRegressor_MAE:** This is a slight variation of the SGDRegressor where we change the loss to *epsilon insensitive* and the epsilon to 0. For now you only need to know that this is an approximation so that the SGD converges to the MAE instead of the RMSE. ``` from sklearn import linear_model x_train_clf = x_train.reshape(-1, 1) x_test_clf = x_test.reshape(-1, 1) clf_1 = linear_model.LinearRegression() clf_2 = linear_model.SGDRegressor(random_state=10) clf_3 = linear_model.SGDRegressor(loss='epsilon_insensitive', epsilon=0, random_state=10) clf_1.fit(x_train_clf, y_train) clf_2.fit(x_train_clf, y_train) clf_3.fit(x_train_clf, y_train) y_hat_train_1 = clf_1.predict(x_train_clf) y_hat_train_2 = clf_2.predict(x_train_clf) y_hat_train_3 = clf_3.predict(x_train_clf) y_hat_test_1 = clf_1.predict(x_test_clf) y_hat_test_2 = clf_2.predict(x_test_clf) y_hat_test_3 = clf_3.predict(x_test_clf) ``` Let's compare the metrics on both sets: ``` print("Mean Squared Error (MAE)") print("LinearRegression (Train): {}".format(mae(y_train, y_hat_train_1))) print("SGDRegressor (Train): {}".format(mae(y_train, y_hat_train_2))) print("SGDRegressor_MAE (Train): {}".format(mae(y_train, y_hat_train_3))) print("LinearRegression (Test): {}".format(mae(y_test, y_hat_test_1))) print("SGDRegressor (Test): {}".format(mae(y_test, y_hat_test_2))) print("SGDRegressor_MAE (Test): {}".format(mae(y_test, y_hat_test_3))) print("\n========================\n") print("Root Mean Squared Error (RMSE)") print("LinearRegression (Train): {}".format(rmse(y_train, y_hat_train_1))) print("SGDRegressor (Train): {}".format(rmse(y_train, y_hat_train_2))) print("SGDRegressor_MAE (Train): {}".format(rmse(y_train, y_hat_train_3))) print("LinearRegression (Test): {}".format(rmse(y_test, y_hat_test_1))) print("SGDRegressor (Test): {}".format(rmse(y_test, y_hat_test_2))) print("SGDRegressor_MAE (Test): {}".format(rmse(y_test, y_hat_test_3))) print("\n========================\n") print("R Squared (R2)") print("LinearRegression (Train): {}".format(r2(y_train, y_hat_train_1))) print("SGDRegressor (Train): {}".format(r2(y_train, y_hat_train_2))) print("SGDRegressor_MAE (Train): {}".format(r2(y_train, y_hat_train_3))) print("LinearRegression (Test): {}".format(r2(y_test, y_hat_test_1))) print("SGDRegressor (Test): {}".format(r2(y_test, y_hat_test_2))) print("SGDRegressor_MAE (Test): {}".format(r2(y_test, y_hat_test_3))) ``` As you may have expected, the model that obtains best test MAE is the SGDRegressor_MAE. This is in line with what we previously discussed, you should always use the loss functions that best approximates your evaluation metric. In this case the MAE itself is not available as a loss function, but we can approximate it. For now you don't need to know exactly why those parameters approximate the MAE, it's just important that you remember this concept. Regarding the RMSE and the R2 the best model is the linear regression. But let's look at the atual predictions to get a better intuition: ``` plt.plot(x_test, y_test, 'r.') plt.plot(x_test, y_hat_test_1, 'r.', color='blue', label='LinearRegression') plt.plot(x_test, y_hat_test_2, 'r.', color='green', label='SGDRegressor') plt.plot(x_test, y_hat_test_3, 'r.', color='gold', label='SGDRegressor_MAE') plt.legend() ``` It seems that the default SGDRegressor is highly impacted by the outliers on the left, this results in it obtaining a worse MAE than the SGDRegressor_MAE. It's also interesting to note that the linear regression has a stronger slope than the SGDRegressor_MAE, although they have a similar intercept. Also, don't forget that the SGD is an iterative based solution that has several parameters, this means that if we tuned the parameters in an extra validation set we may be able to squeeze extra performance. Also, this is just a toy example with one feature, perhaps due to the simplicity of the data it just so happens that linear regression works best. Finally, to make a consistent analysis, you need to know if our metric should be minimized (like RMSE) or maximized (like R2). If you want to normalize this to make sure your implementation is able to pick a model you can simply impose that your metric should be maximized, for example, and just reverse metrics that don't fit this definition. For example, we can turn RMSE into negative RMSE and apply the same behavior to other metrics that aim to be minimized. That way, we could write: ``` mae_mod = lambda y, y_hat: -mae(y, y_hat) mse_mod = lambda y, y_hat: -mse(y, y_hat) rmse_mod = lambda y, y_hat: -rmse(y, y_hat) metrics = { 'Negative MAE': mae_mod, 'Negative RMSE': rmse_mod, 'R2': r2 } clfs = { 'LinearRegressor': clf_1, 'SGDRegressor': clf_2, 'SGDRegressor_MAE': clf_3 } for key, clf in clfs.items(): clf.fit(x_train_clf, y_train) lst = [] for metric, metric_f in metrics.items(): best = None best_model = None lst_lst = [] print("{}".format(metric)) for key, clf in clfs.items(): y_hat_train = clf.predict(x_train_clf) y_hat_test = clf.predict(x_test_clf) train_score = metric_f(y_train, y_hat_train) test_score = metric_f(y_test, y_hat_test) print("{} (Train): {}".format(key, train_score)) print("{} (Test): {}".format(key, test_score)) if not best or test_score > best: best = test_score best_model = key lst_lst.append([train_score,test_score]) lst.append(lst_lst) print("\nBest model with {}: {}".format(metric, best_model)) print("\n========================\n") ``` As you see, it is quite usefull for all metrics to have the same logic in terms of performance, this is, how you should interpret if the model is better or not. We will see the same for cross-validation now. ### 3.2 - K-fold cross validation Another of the methods you've seen is cross validation by using a division in train/test data K times and assessing the scores that come out of it. Let's use the same example and models as before: ``` df = pd.read_csv('data/example_data.csv') x = df['LotArea'].values y = df['SalePrice'].values x_clf = x.reshape(-1, 1) y_clf = y.reshape(-1, 1) clf_1 = linear_model.LinearRegression() clf_2 = linear_model.SGDRegressor(random_state=10) clf_3 = linear_model.SGDRegressor(loss='epsilon_insensitive', epsilon=0, random_state=10) ``` With scikitlearn, you can run the `cross_val_score` with k-fold and output the scores in each fold for both estimators: ``` from sklearn.model_selection import cross_val_score clfs = { 'LinearRegressor': clf_1, 'SGDRegressor': clf_2, 'SGDRegressor_MAE': clf_3 } for key, clf in clfs.items(): clf.fit(x_train_clf, y_train) K = 5 for key, clf in clfs.items(): scores = cross_val_score(clf, x_clf, y, cv=K) print('Estimator: {}'.format(key)) print('Score avg. : {}'.format(scores.mean())) ``` But what is this score? If the scoring method is not specified, the estimator scorer is used. For our three estimators, in this particular case, this corresponds to the coefficient of determination R2 of the prediction. But what if we want to use another metric? Actually, the `cross_val_score` gives us the possibility of doing so, by passing a `scoring` parameter, which can be a string, for example. You can check [here](https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter) all of the possibilities, but for this SLU the most important one are: * `neg_mean_absolute_error` * `neg_mean_squared_error` * `r2` In this case, the metrics follow the rule of "higher is better", thus the negative MAE and MSE options. ``` from sklearn.model_selection import cross_val_score clfs = { 'LinearRegressor': clf_1, 'SGDRegressor': clf_2, 'SGDRegressor_MAE': clf_3 } for key, clf in clfs.items(): clf.fit(x_train_clf, y_train) K = 5 for key, clf in clfs.items(): scores = cross_val_score(clf, x_clf, y, cv=K, scoring="neg_mean_absolute_error") print('Estimator: {}'.format(key)) print('Negative MAE avg. : {}'.format(scores.mean())) ``` There are also other ways of passing on metrics do these functions, and this is not the only function to perform these comparisons. You can explore the model selection to learn more about it. But for now, move forward to the exercises and the next SLUs. ![goodbye](assets/goodbye.gif) ## 4 - For the more curious This notebook is not an exhaustive exploration of this topic. Here is some curated material if you want to learn more: * [Coursera - Regression metrics review I](https://www.coursera.org/lecture/competitive-data-science/regression-metrics-review-i-UWhYf) and [II](https://www.coursera.org/lecture/competitive-data-science/regression-metrics-review-ii-qhRmV) * [Sklearn - Regression metrics](https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics) * [H2O.ai - Regression metrics’ guide](https://www.h2o.ai/blog/regression-metrics-guide/)
github_jupyter
# Model Understanding Simply examining a model's performance metrics is not enough to select a model and promote it for use in a production setting. While developing an ML algorithm, it is important to understand how the model behaves on the data, to examine the key factors influencing its predictions and to consider where it may be deficient. Determination of what "success" may mean for an ML project depends first and foremost on the user's domain expertise. blocktorch includes a variety of tools for understanding models, from graphing utilities to methods for explaining predictions. ** Graphing methods on Jupyter Notebook and Jupyter Lab require [ipywidgets](https://ipywidgets.readthedocs.io/en/latest/user_install.html) to be installed. ** If graphing on Jupyter Lab, [jupyterlab-plotly](https://plotly.com/python/getting-started/#jupyterlab-support-python-35) required. To download this, make sure you have [npm](https://nodejs.org/en/download/) installed. ## Graphing Utilities First, let's train a pipeline on some data. ``` import blocktorch from blocktorch.pipelines import BinaryClassificationPipeline X, y = blocktorch.demos.load_breast_cancer() X_train, X_holdout, y_train, y_holdout = blocktorch.preprocessing.split_data(X, y, problem_type='binary', test_size=0.2, random_seed=0) pipeline_binary = BinaryClassificationPipeline(['Simple Imputer', 'Random Forest Classifier']) pipeline_binary.fit(X_train, y_train) print(pipeline_binary.score(X_holdout, y_holdout, objectives=['log loss binary'])) ``` ### Feature Importance We can get the importance associated with each feature of the resulting pipeline ``` pipeline_binary.feature_importance ``` We can also create a bar plot of the feature importances ``` pipeline_binary.graph_feature_importance() ``` ### Permutation Importance We can also compute and plot [the permutation importance](https://scikit-learn.org/stable/modules/permutation_importance.html) of the pipeline. ``` from blocktorch.model_understanding import calculate_permutation_importance calculate_permutation_importance(pipeline_binary, X_holdout, y_holdout, 'log loss binary') from blocktorch.model_understanding import graph_permutation_importance graph_permutation_importance(pipeline_binary, X_holdout, y_holdout, 'log loss binary') ``` ### Partial Dependence Plots We can calculate the one-way [partial dependence plots](https://christophm.github.io/interpretable-ml-book/pdp.html) for a feature. ``` from blocktorch.model_understanding.graphs import partial_dependence partial_dependence(pipeline_binary, X_holdout, features='mean radius', grid_resolution=5) from blocktorch.model_understanding.graphs import graph_partial_dependence graph_partial_dependence(pipeline_binary, X_holdout, features='mean radius', grid_resolution=5) ``` You can also compute the partial dependence for a categorical feature. We will demonstrate this on the fraud dataset. ``` X_fraud, y_fraud = blocktorch.demos.load_fraud(100, verbose=False) X_fraud.ww.init(logical_types={"provider": "Categorical", 'region': "Categorical", "currency": "Categorical", "expiration_date": "Categorical"}) fraud_pipeline = BinaryClassificationPipeline(["DateTime Featurization Component","One Hot Encoder", "Random Forest Classifier"]) fraud_pipeline.fit(X_fraud, y_fraud) graph_partial_dependence(fraud_pipeline, X_fraud, features='provider') ``` Two-way partial dependence plots are also possible and invoke the same API. ``` partial_dependence(pipeline_binary, X_holdout, features=('worst perimeter', 'worst radius'), grid_resolution=5) graph_partial_dependence(pipeline_binary, X_holdout, features=('worst perimeter', 'worst radius'), grid_resolution=5) ``` ### Confusion Matrix For binary or multiclass classification, we can view a [confusion matrix](https://en.wikipedia.org/wiki/Confusion_matrix) of the classifier's predictions. In the DataFrame output of `confusion_matrix()`, the column header represents the predicted labels while row header represents the actual labels. ``` from blocktorch.model_understanding.graphs import confusion_matrix y_pred = pipeline_binary.predict(X_holdout) confusion_matrix(y_holdout, y_pred) from blocktorch.model_understanding.graphs import graph_confusion_matrix y_pred = pipeline_binary.predict(X_holdout) graph_confusion_matrix(y_holdout, y_pred) ``` ### Precision-Recall Curve For binary classification, we can view the precision-recall curve of the pipeline. ``` from blocktorch.model_understanding.graphs import graph_precision_recall_curve # get the predicted probabilities associated with the "true" label import woodwork as ww y_encoded = y_holdout.ww.map({'benign': 0, 'malignant': 1}) y_pred_proba = pipeline_binary.predict_proba(X_holdout)["malignant"] graph_precision_recall_curve(y_encoded, y_pred_proba) ``` ### ROC Curve For binary and multiclass classification, we can view the [Receiver Operating Characteristic (ROC) curve](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) of the pipeline. ``` from blocktorch.model_understanding.graphs import graph_roc_curve # get the predicted probabilities associated with the "malignant" label y_pred_proba = pipeline_binary.predict_proba(X_holdout)["malignant"] graph_roc_curve(y_encoded, y_pred_proba) ``` The ROC curve can also be generated for multiclass classification problems. For multiclass problems, the graph will show a one-vs-many ROC curve for each class. ``` from blocktorch.pipelines import MulticlassClassificationPipeline X_multi, y_multi = blocktorch.demos.load_wine() pipeline_multi = MulticlassClassificationPipeline(['Simple Imputer', 'Random Forest Classifier']) pipeline_multi.fit(X_multi, y_multi) y_pred_proba = pipeline_multi.predict_proba(X_multi) graph_roc_curve(y_multi, y_pred_proba) ``` ### Binary Objective Score vs. Threshold Graph [Some binary classification objectives](./objectives.ipynb) (objectives that have `score_needs_proba` set to False) are sensitive to a decision threshold. For those objectives, we can obtain and graph the scores for thresholds from zero to one, calculated at evenly-spaced intervals determined by `steps`. ``` from blocktorch.model_understanding.graphs import binary_objective_vs_threshold binary_objective_vs_threshold(pipeline_binary, X_holdout, y_holdout, 'f1', steps=10) from blocktorch.model_understanding.graphs import graph_binary_objective_vs_threshold graph_binary_objective_vs_threshold(pipeline_binary, X_holdout, y_holdout, 'f1', steps=100) ``` ### Predicted Vs Actual Values Graph for Regression Problems We can also create a scatterplot comparing predicted vs actual values for regression problems. We can specify an `outlier_threshold` to color values differently if the absolute difference between the actual and predicted values are outside of a given threshold. ``` from blocktorch.model_understanding.graphs import graph_prediction_vs_actual from blocktorch.pipelines import RegressionPipeline X_regress, y_regress = blocktorch.demos.load_diabetes() X_train, X_test, y_train, y_test = blocktorch.preprocessing.split_data(X_regress, y_regress, problem_type='regression') pipeline_regress = RegressionPipeline(['One Hot Encoder', 'Linear Regressor']) pipeline_regress.fit(X_train, y_train) y_pred = pipeline_regress.predict(X_test) graph_prediction_vs_actual(y_test, y_pred, outlier_threshold=50) ``` Now let's train a decision tree on some data. ``` pipeline_dt = BinaryClassificationPipeline(['Simple Imputer', 'Decision Tree Classifier']) pipeline_dt.fit(X_train, y_train) ``` ### Tree Visualization We can visualize the structure of the Decision Tree that was fit to that data, and save it if necessary. ``` from blocktorch.model_understanding.graphs import visualize_decision_tree visualize_decision_tree(pipeline_dt.estimator, max_depth=2, rotate=False, filled=True, filepath=None) ``` ## Explaining Predictions We can explain why the model made certain predictions with the [explain_predictions](../autoapi/blocktorch/model_understanding/prediction_explanations/explainers/index.rst#blocktorch.model_understanding.prediction_explanations.explainers.explain_predictions) function. This will use the [Shapley Additive Explanations (SHAP)](https://github.com/slundberg/shap) algorithm to identify the top features that explain the predicted value. This function can explain both classification and regression models - all you need to do is provide the pipeline, the input features, and a list of rows corresponding to the indices of the input features you want to explain. The function will return a table that you can print summarizing the top 3 most positive and negative contributing features to the predicted value. In the example below, we explain the prediction for the third data point in the data set. We see that the `worst concave points` feature increased the estimated probability that the tumor is malignant by 20% while the `worst radius` feature decreased the probability the tumor is malignant by 5%. ``` from blocktorch.model_understanding.prediction_explanations import explain_predictions table = explain_predictions(pipeline=pipeline_binary, input_features=X_holdout, y=None, indices_to_explain=[3], top_k_features=6, include_shap_values=True) print(table) ``` The interpretation of the table is the same for regression problems - but the SHAP value now corresponds to the change in the estimated value of the dependent variable rather than a change in probability. For multiclass classification problems, a table will be output for each possible class. Below is an example of how you would explain three predictions with [explain_predictions](../autoapi/blocktorch/model_understanding/prediction_explanations/explainers/index.rst#blocktorch.model_understanding.prediction_explanations.explainers.explain_predictions). ``` from blocktorch.model_understanding.prediction_explanations import explain_predictions report = explain_predictions(pipeline=pipeline_binary, input_features=X_holdout, y=y_holdout, indices_to_explain=[0, 4, 9], include_shap_values=True, output_format='text') print(report) ``` ### Explaining Best and Worst Predictions When debugging machine learning models, it is often useful to analyze the best and worst predictions the model made. The [explain_predictions_best_worst](../autoapi/blocktorch/model_understanding/prediction_explanations/explainers/index.rst#blocktorch.model_understanding.prediction_explanations.explainers.explain_predictions_best_worst) function can help us with this. This function will display the output of [explain_predictions](../autoapi/blocktorch/model_understanding/prediction_explanations/explainers/index.rst#blocktorch.model_understanding.prediction_explanations.explainers.explain_predictions) for the best 2 and worst 2 predictions. By default, the best and worst predictions are determined by the absolute error for regression problems and [cross entropy](https://en.wikipedia.org/wiki/Cross_entropy) for classification problems. We can specify our own ranking function by passing in a function to the `metric` parameter. This function will be called on `y_true` and `y_pred`. By convention, lower scores are better. At the top of each table, we can see the predicted probabilities, target value, error, and row index for that prediction. For a regression problem, we would see the predicted value instead of predicted probabilities. ``` from blocktorch.model_understanding.prediction_explanations import explain_predictions_best_worst report = explain_predictions_best_worst(pipeline=pipeline_binary, input_features=X_holdout, y_true=y_holdout, include_shap_values=True, top_k_features=6, num_to_explain=2) print(report) ``` We use a custom metric ([hinge loss](https://en.wikipedia.org/wiki/Hinge_loss)) for selecting the best and worst predictions. See this example: ```python import numpy as np def hinge_loss(y_true, y_pred_proba): probabilities = np.clip(y_pred_proba.iloc[:, 1], 0.001, 0.999) y_true[y_true == 0] = -1 return np.clip(1 - y_true * np.log(probabilities / (1 - probabilities)), a_min=0, a_max=None) report = explain_predictions_best_worst(pipeline=pipeline, input_features=X, y_true=y, include_shap_values=True, num_to_explain=5, metric=hinge_loss) print(report) ``` ### Changing Output Formats Instead of getting the prediction explanations as text, you can get the report as a python dictionary or pandas dataframe. All you have to do is pass `output_format="dict"` or `output_format="dataframe"` to either `explain_prediction`, `explain_predictions`, or `explain_predictions_best_worst`. ### Single prediction as a dictionary ``` import json single_prediction_report = explain_predictions(pipeline=pipeline_binary, input_features=X_holdout, indices_to_explain=[3], y=y_holdout, top_k_features=6, include_shap_values=True, output_format="dict") print(json.dumps(single_prediction_report, indent=2)) ``` ### Single prediction as a dataframe ``` single_prediction_report = explain_predictions(pipeline=pipeline_binary, input_features=X_holdout, indices_to_explain=[3], y=y_holdout, top_k_features=6, include_shap_values=True, output_format="dataframe") single_prediction_report ``` ### Best and worst predictions as a dictionary ``` report = explain_predictions_best_worst(pipeline=pipeline_binary, input_features=X, y_true=y, num_to_explain=1, top_k_features=6, include_shap_values=True, output_format="dict") print(json.dumps(report, indent=2)) ``` ### Best and worst predictions as a dataframe ``` report = explain_predictions_best_worst(pipeline=pipeline_binary, input_features=X_holdout, y_true=y_holdout, num_to_explain=1, top_k_features=6, include_shap_values=True, output_format="dataframe") report ``` ### Force Plots Force plots can be generated to predict single or multiple rows for binary, multiclass and regression problem types. Here's an example of predicting a single row on a binary classification dataset. The force plots show the predictive power of each of the features in making the negative ("Class: 0") prediction and the positive ("Class: 1") prediction. ``` import shap from blocktorch.model_understanding.force_plots import graph_force_plot rows_to_explain = [0] # Should be a list of integer indices of the rows to explain. results = graph_force_plot(pipeline_binary, rows_to_explain=rows_to_explain, training_data=X_holdout, y=y_holdout) for result in results: for cls in result: print("Class:", cls) display(result[cls]["plot"]) ``` Here's an example of a force plot explaining multiple predictions on a multiclass problem. These plots show the force plots for each row arranged as consecutive columns that can be ordered by the dropdown above. Clicking the column indicates which row explanation is underneath. ``` rows_to_explain = [0,1,2,3,4] # Should be a list of integer indices of the rows to explain. results = graph_force_plot(pipeline_multi, rows_to_explain=rows_to_explain, training_data=X_multi, y=y_multi) for idx, result in enumerate(results): print("Row:", idx) for cls in result: print("Class:", cls) display(result[cls]["plot"]) ```
github_jupyter
In this blog we will discuss about the inference for MLR. How to choose significant predictor by Hypothesis Test and Confidence Interval, as well as doing interpretations for the slope. ![jpeg](../galleries/coursera-statistics/8w17.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 00:48* <!--TEASER_END--> The study that we're going to use is from NLSY, observing 3 year old children with IQ ~ kid_score based on whether the mom go to high school or not, mom's IQ, whether the mom go to work, and mom's age. First we load the data using R, ``` cognitive = read.csv('http://bit.ly/dasi_cognitive') ``` Next we're going full model, that is using all the feature. ``` cog_full = lm(kid_score ~ mom_hs+mom_iq+mom_work+mom_age, data=cognitive) summary(cog_full) ``` Observing, mom_work, we can interpret "All else held constant, children whose mom worked during the first three years of their lives are estimated to score 2.54 higher than those whose mom did not work. ![jpeg](../galleries/coursera-statistics/8w18.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 03:36* Doing hypothesis test, the skeptical is there is no difference among the predictors, while alternative said there is a different. Using last line in our previous regression output(don't have to compute by hand!). We have F statistics, 4(number of predictor) and 429(n-k-1). What's left of is how to interpret it. If we reject the null hypothesis, doesn't mean the model is good, but there's at least one of the predictor that stands out. While if we failed to reject null hypothesis, doesn't mean the model is not good enough, but rather the combinations is not good at all for the model. ![jpeg](../galleries/coursera-statistics/8w19.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 04:44* Looking back at the regression output, we use HT as significance test predictor for mom_hs. Observing the related p-value, we can say whether or not mom going to work is significant predictor of the cognitive scores of their children, assuming all other variables included in the model. ![jpeg](../galleries/coursera-statistics/8w20.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 05:49* The best practice is to truly understand behind underlying computation software, so we observe t-statistic. This is the same as calculating single linear regression earlier, with the exception of degree of freedom decremented by number of predictors being included.This is not actually different from before, where dof is decrement by number of slopes and 1 for intercept. Linear regression has predictor 1, we can plug to (n-k-1) and we will get df = (n-2). DOF in linear regression always about sample size subtracte by number of slopes and 1 for the intercept. ![jpeg](../galleries/coursera-statistics/8w22.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 08:37* We can validate t-score and p-value from the computation using the formula given earlier. Recall that when do significance test, the null value is often zero. We're t-statistic incorporate the point estimate,null value, and SE, we have 2.201, just like the one in the computation. dof can be get like the one in example. Calculating p-value in R, ``` pt(2.201,df=429,lower.tail=F)*2 ``` The resulting p-value is the same just like in the p-value row for `mom_hs` ![jpeg](../galleries/coursera-statistics/8w23.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/167) 11:03* We also can validate CI. Remember that, CI = point_estimate +/- margin of error, where ME = t_star*SE df we have earlier is 429. Looking at the much higher df, we would expect t_star would be closely approximate to normal 95% 1.96. We still count it nevertheless, ``` qt(0.025,df=429,lower.tail=F) ``` What we get is 1.97. And plugging to the CI formula we have (-2.09,7.17). How do we interpret this? We say, **We are 95% confident, all held constant, that mom that work first three years of children lives are scored 2.09 lower to 7.17 higher than those whose mom did not work.** # Model Selection And last, we're doing what machine learning called **feature selection**. ![jpeg](../galleries/coursera-statistics/8w24.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/169) 01:17* There are two ways we can achieve this. Either by start full model and eliminate one at a time, or start empty and add one at a time. We're going to use p-value and R squared, although some method can be used. ### Backwards elimination steps - adjusted R squared * Start with the full model. * Try to eliminate one variable and observed the resulting adjusted R squared. * Repeat until all variable selected, pick the model with highest adjusted R squared. * Repeat until none of the model yield an increase in adjusted R squared. Let's take a look at the example ![jpeg](../galleries/coursera-statistics/8w25.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/169) 03:36* First, we start with the full model. Then we take iterative steps to eliminate one model at a time and observe the adjusted R squared. It turns out, only eliminating 'mom_age' we have an increase. The lowest decrease suffered from eliminating `mom_iq` which may an indication that 'mom_iq' is an important variable.After we eliminate `mom_age`, we proceed to step 2, that are same step as before, but with `mom_age` excluded. Turns out none of the variable in step 2 has adjusted R squared increase. Thus we revert back to step 1, and the last formula with adjusted R squared increase is our final decision. ### Backwards elimation steps - p-value * Again, we start with full model. * We drop the variable with the highest p-value, and refit a smaller model * Repeat the steps until all variables left in the model are significant. The principal behind this is to eliminate the difference that practically insignificant.Since we just need the model to be below the significance level, it doesn't make any sense to further include additional variable. ![jpeg](../galleries/coursera-statistics/8w26.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/169) 04:56* First, we start as a full model. We see that, `mom_age` has the highest p-value, since this is beyond significant level, we eliminate this variable. Next, we run again(mind that we don't eliminate all insignificant variable in one step), and in step two, we see `mom_iq` as insignificant variable. Eventhough using p-value and adjusted R squared yield different result, often it's expected to be similar. ![jpeg](../galleries/coursera-statistics/8w27.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/169) 06:28* This is an exceptional problem that use p-value. Here only have two that above significance level. But since these actually from levels of race categorical variable, we don't drop that simply because **at least one of the level is a significant. Therefore, we don't drop `race`**. ### adjusted R squared vs. p-value So because it's different model from using both method? Which way to choose? We're using p-value when we're testing the significance predictors. But it somewhat arbitrary, considering we use significance level(5% is the default, different level could give you different model). On the other hand, adjusted R squared is more reliable option, since it can't drop a variable unless it need too. But why p-value is more commonly used? Because using p-value is like using feature selection. Dropping more features would avoid us from Curse of Dimensionality. ### forward selection - adjusted R squared * Start with single predictor of response vs each of explanatory variables. * Try to add one explanatory that have the highest adjusted R squared. * Repeat each process until any of the addition variables does not increase adjusted R squared. ![jpeg](../galleries/coursera-statistics/8w28.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/169) 09:15* We start with one explanatory variable, and see the highest adjusted R squared. It turns out, `mom_iq` has the highest adjusted R squared. Then for each steps, we compared the highest of each variable in step 2 to the highest adjusted R squared in previous step. Adding those up, until we reach step 4, where it turns out `mom_age` addition can't get the adjusted R squared higher than step 3. So we exclude `mom_age` and arrive at the model, which is the same as backward elimination - adjusted R squared. ### backward selection - p-value * Start with single predictor response vs each of explanatory. * We select one of variables that have the lowest p-value. * Repeat until any of the remaining variables doesn't have a significant p-value. ### expert opinion In data science, you'll also comes up with domain expertise. Which domain that the problem currently in. An expert will know which of the feature is less or more matter, despite it have small p-value or higher adjusted R squared. ``` cog_final = lm(kid_score ~ mom_hs + mom_iq + mom_work, data=cognitive) summary(cog_final) ``` If see here, `mom_work` status has high significance level. But we that from before, `mom_work` status has higher adjusted R squared. So we still not exclude this variable. # Diagnostic Lastly, we have to validate the MLR for conditions to bet met. The conditions are * Linear relationships between explanatory and response * Nearly normal, constant variability, and independence of residuals. ![jpeg](../galleries/coursera-statistics/8w29.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/171) 01:31* We check the linearity(only numerical, not categorical, it doesn't makes sense to check linearity of categorical) of x and y. We do this in residuals plot, not scatter plot between x and y. The reason behind this, is that we want to make sure that we have random scatter around zero. Any pattern that is occured will be revealing that's there's some other dependent variables. Recall that we want explanatory to be all independent. ``` cog_final = lm(kid_score ~ mom_hs + mom_iq + mom_work, data =cognitive) plot(cog_final$residuals ~ cognitive$mom_iq) ``` Recall our previous formula, we have three explanatory variables, but only one numerical, `mom_iq`. So this is the only variables that we want to validate the linearity. We plot on the residuals from `cog_final` result in y axis, and `mom_iq` in x-axis. So it seems we indeed have random scatter around zero. ![jpeg](../galleries/coursera-statistics/8w30.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/171) 03:04* When we plot the residuals, we expect than random scatter is normal, centered around zero. We can see this by using histogram or normal probability plot. ``` hist(cog_final$residuals) qqnorm(cog_final$residuals) qqline(cog_final$residuals) ``` When looking at the histogram, we see the the distribution of the residuals is slightly skewed. And looking at the deviation of points from mean line, only little in the middle, except for the tails area, the conditions are fairly satisfied. ![jpeg](../galleries/coursera-statistics/8w31.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/171) 04:35* We plot the residuals vs predicted(not vs. x, because we're going to observe explanatory all at once) and observe that the plot should show points random scatter around zero, with constant width(not fan shape). We want also observe absolute residuals(convert all to positive side) to identify unusual observations. ``` #in plot, fitted = predicted plot(cog_final$residuals ~ cog_final$fitted.values) plot(abs(cog_final$residuals) ~ cog_final$fitted.values) ``` Here we can see that the plotted residuals in y-axis, against the predicted(fitted) in x-axis. We want to observe whether the plot random scatter around zero, and doesn't have fan shape. We see that the condition is met, and observe the absolute residuals plot, fan shape will get converted into triangle to shape, which also not appear in the plot. ![jpeg](../galleries/coursera-statistics/8w32.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/171) 06:36* We want to observe that residuals(observations) are independent.This is specifically concerned when talking about time series data. We can check the residuals against the order collected(scatter plot). If doesn't met, think about how the data collected met independence conditions: * Random sampling when observational study. * Random assignment when controlled experiment. * Less than 10% population. ``` plot(cog_final$residuals) ``` We can see that there's no increase/decrease pattern, so we can assume that the residuals(observations) is independent. So remember, the conditions are: * Nearly normal residuals with mean 0 * Constant variability residuals * Independent residuals * Each numerical variable linearly related to the outcome. In summary, We can test the model whether it's significance using F-test. We have a skeptical where aare the slope is no difference, the alternative as at least one of the slope not equal to zero, and using degree of freedom(n-k-1). Usually this gets reported at the bottom of regression output. Note that **p-value is arbitrary of each respective explanatory**. It will vary based on other predictors that are included in the model. As long as it below significance level, it will become a significance predictor, given other predictors included in the model. You need t_critical(based on significance level and degree of freedom) to be an input of both confidence interval and hypothesis testing. We can use stepwise model selection to make the model become parsimonious model. There's two alternative to do, forward and backward stepwise selection. Using two method, adjusted R squared and p-value. For backward stepwise, you start the with the full model. In adjusted R squared, try to eliminate one explanatory, and select the model with the highest adjusted R squared.If it's not get any higher, we cancel the elimination steps and choose that model. We keep eliminating the variables until we met the condition. For p-value, we also observe the regression output. Try to eliminate variables with the highest p-value, until there's no insignificant predictor, and the p-value of the model is still below the significance level. If p-value of at least one level in categorical explanatory is below the threshold, we shouldn't drop that explanatory. For stepwise model, we start with empty model. We try to add one explnatory, and select the model with the highest adjusted R squared. And we keep adding it until the adjusted R squared is not getting any higher. For p-value we try to add one explanatory at a time, and pick the model with lowest p-value. Then we keep trying to add one explanatory, observe p-value, and check if it's significant/insignificant. If any of them are insignificant, we should stop adding the variables. Say, why in stepwise and backwise we don't select all at once explanatory variables that below significance level? Recall that p-value is arbitrary for each of the explanatory, depending on all other predictors in the model. p-value will change if the model change. So that's the reason why we add/eliminate one at a time. Model Selection can also depending on expert opinion, you're domain expertise. If you know that the explanatory is significance, you should add those irrespective of whether p-value is insignificant/ adjusted R squared is not higher. When facing against two different model p-value vs adjusted R squared, you should also include expert opinion. Adjusted R squared will play more safely to select the model, hence more reliable vs p-value that have less explanatory overall.But p-value is more commonly, as less features are good, to avoid **curse of dimensionality**. Finally, you should validate the conditions for MLR. You want each numerical to have linearity with the response, and validate that residuals are random scatter around zero, constant variability, normally distributed, and each is independent of one another.You use scatter plot between each of numerical explanatory and the residuals, to check whether it has linearity. You use histogram or probability plot to check whether the distribution of the residuals is nearly normal. You use scatter plot between residuals and predicted to check whether residuals has constant variability.You use scatter plot of residuals and index to check if each of the residuals is independent of one another. > **REFERENCES**: > Dr. Mine Çetinkaya-Rundel, [Cousera](https://class.coursera.org/statistics-003/lecture)
github_jupyter
# Think Bayes: Chapter 7 This notebook presents code and exercises from Think Bayes, second edition. Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT ``` from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint import thinkplot ``` ## Warm-up exercises **Exercise:** Suppose that goal scoring in hockey is well modeled by a Poisson process, and that the long-run goal-scoring rate of the Boston Bruins against the Vancouver Canucks is 2.9 goals per game. In their next game, what is the probability that the Bruins score exactly 3 goals? Plot the PMF of `k`, the number of goals they score in a game. ``` # Solution goes here # Solution goes here # Solution goes here ``` **Exercise:** Assuming again that the goal scoring rate is 2.9, what is the probability of scoring a total of 9 goals in three games? Answer this question two ways: 1. Compute the distribution of goals scored in one game and then add it to itself twice to find the distribution of goals scored in 3 games. 2. Use the Poisson PMF with parameter $\lambda t$, where $\lambda$ is the rate in goals per game and $t$ is the duration in games. ``` # Solution goes here # Solution goes here ``` **Exercise:** Suppose that the long-run goal-scoring rate of the Canucks against the Bruins is 2.6 goals per game. Plot the distribution of `t`, the time until the Canucks score their first goal. In their next game, what is the probability that the Canucks score during the first period (that is, the first third of the game)? Hint: `thinkbayes2` provides `MakeExponentialPmf` and `EvalExponentialCdf`. ``` # Solution goes here # Solution goes here # Solution goes here ``` **Exercise:** Assuming again that the goal scoring rate is 2.8, what is the probability that the Canucks get shut out (that is, don't score for an entire game)? Answer this question two ways, using the CDF of the exponential distribution and the PMF of the Poisson distribution. ``` # Solution goes here # Solution goes here ``` ## The Boston Bruins problem The `Hockey` suite contains hypotheses about the goal scoring rate for one team against the other. The prior is Gaussian, with mean and variance based on previous games in the league. The Likelihood function takes as data the number of goals scored in a game. ``` from thinkbayes2 import MakeNormalPmf from thinkbayes2 import EvalPoissonPmf class Hockey(Suite): """Represents hypotheses about the scoring rate for a team.""" def __init__(self, label=None): """Initializes the Hockey object. label: string """ mu = 2.8 sigma = 0.3 pmf = MakeNormalPmf(mu, sigma, num_sigmas=4, n=101) Suite.__init__(self, pmf, label=label) def Likelihood(self, data, hypo): """Computes the likelihood of the data under the hypothesis. Evaluates the Poisson PMF for lambda and k. hypo: goal scoring rate in goals per game data: goals scored in one game """ lam = hypo k = data like = EvalPoissonPmf(k, lam) return like ``` Now we can initialize a suite for each team: ``` suite1 = Hockey('bruins') suite2 = Hockey('canucks') ``` Here's what the priors look like: ``` thinkplot.PrePlot(num=2) thinkplot.Pdf(suite1) thinkplot.Pdf(suite2) thinkplot.Config(xlabel='Goals per game', ylabel='Probability') ``` And we can update each suite with the scores from the first 4 games. ``` suite1.UpdateSet([0, 2, 8, 4]) suite2.UpdateSet([1, 3, 1, 0]) thinkplot.PrePlot(num=2) thinkplot.Pdf(suite1) thinkplot.Pdf(suite2) thinkplot.Config(xlabel='Goals per game', ylabel='Probability') suite1.Mean(), suite2.Mean() ``` To predict the number of goals scored in the next game we can compute, for each hypothetical value of $\lambda$, a Poisson distribution of goals scored, then make a weighted mixture of Poissons: ``` from thinkbayes2 import MakeMixture from thinkbayes2 import MakePoissonPmf def MakeGoalPmf(suite, high=10): """Makes the distribution of goals scored, given distribution of lam. suite: distribution of goal-scoring rate high: upper bound returns: Pmf of goals per game """ metapmf = Pmf() for lam, prob in suite.Items(): pmf = MakePoissonPmf(lam, high) metapmf.Set(pmf, prob) mix = MakeMixture(metapmf, label=suite.label) return mix ``` Here's what the results look like. ``` goal_dist1 = MakeGoalPmf(suite1) goal_dist2 = MakeGoalPmf(suite2) thinkplot.PrePlot(num=2) thinkplot.Pmf(goal_dist1) thinkplot.Pmf(goal_dist2) thinkplot.Config(xlabel='Goals', ylabel='Probability', xlim=[-0.7, 11.5]) goal_dist1.Mean(), goal_dist2.Mean() ``` Now we can compute the probability that the Bruins win, lose, or tie in regulation time. ``` diff = goal_dist1 - goal_dist2 p_win = diff.ProbGreater(0) p_loss = diff.ProbLess(0) p_tie = diff.Prob(0) print('Prob win, loss, tie:', p_win, p_loss, p_tie) ``` If the game goes into overtime, we have to compute the distribution of `t`, the time until the first goal, for each team. For each hypothetical value of $\lambda$, the distribution of `t` is exponential, so the predictive distribution is a mixture of exponentials. ``` from thinkbayes2 import MakeExponentialPmf def MakeGoalTimePmf(suite): """Makes the distribution of time til first goal. suite: distribution of goal-scoring rate returns: Pmf of goals per game """ metapmf = Pmf() for lam, prob in suite.Items(): pmf = MakeExponentialPmf(lam, high=2.5, n=1001) metapmf.Set(pmf, prob) mix = MakeMixture(metapmf, label=suite.label) return mix ``` Here's what the predictive distributions for `t` look like. ``` time_dist1 = MakeGoalTimePmf(suite1) time_dist2 = MakeGoalTimePmf(suite2) thinkplot.PrePlot(num=2) thinkplot.Pmf(time_dist1) thinkplot.Pmf(time_dist2) thinkplot.Config(xlabel='Games until goal', ylabel='Probability') time_dist1.Mean(), time_dist2.Mean() ``` In overtime the first team to score wins, so the probability of winning is the probability of generating a smaller value of `t`: ``` p_win_in_overtime = time_dist1.ProbLess(time_dist2) p_adjust = time_dist1.ProbEqual(time_dist2) p_win_in_overtime += p_adjust / 2 print('p_win_in_overtime', p_win_in_overtime) ``` Finally, we can compute the overall chance that the Bruins win, either in regulation or overtime. ``` p_win_overall = p_win + p_tie * p_win_in_overtime print('p_win_overall', p_win_overall) ``` ## Exercises **Exercise:** To make the model of overtime more correct, we could update both suites with 0 goals in one game, before computing the predictive distribution of `t`. Make this change and see what effect it has on the results. ``` # Solution goes here ``` **Exercise:** In the final match of the 2014 FIFA World Cup, Germany defeated Argentina 1-0. What is the probability that Germany had the better team? What is the probability that Germany would win a rematch? For a prior distribution on the goal-scoring rate for each team, use a gamma distribution with parameter 1.3. ``` from thinkbayes2 import MakeGammaPmf xs = np.linspace(0, 8, 101) pmf = MakeGammaPmf(xs, 1.3) thinkplot.Pdf(pmf) thinkplot.Config(xlabel='Goals per game') pmf.Mean() ``` **Exercise:** In the 2014 FIFA World Cup, Germany played Brazil in a semifinal match. Germany scored after 11 minutes and again at the 23 minute mark. At that point in the match, how many goals would you expect Germany to score after 90 minutes? What was the probability that they would score 5 more goals (as, in fact, they did)? Note: for this one you will need a new suite that provides a Likelihood function that takes as data the time between goals, rather than the number of goals in a game. **Exercise:** Which is a better way to break a tie: overtime or penalty shots? **Exercise:** Suppose that you are an ecologist sampling the insect population in a new environment. You deploy 100 traps in a test area and come back the next day to check on them. You find that 37 traps have been triggered, trapping an insect inside. Once a trap triggers, it cannot trap another insect until it has been reset. If you reset the traps and come back in two days, how many traps do you expect to find triggered? Compute a posterior predictive distribution for the number of traps.
github_jupyter
# Determining rigid body transformation using the SVD algorithm Marcos Duarte Ideally, three non-colinear markers placed on a moving rigid body is everything we need to describe its movement (translation and rotation) in relation to a fixed coordinate system. However, in pratical situations of human motion analysis, markers are placed on the soft tissue of a deformable body and this generates artifacts caused by muscle contraction, skin deformation, marker wobbling, etc. In this situation, the use of only three markers can produce unreliable results. It has been shown that four or more markers on the segment followed by a mathematical procedure to calculate the 'best' rigid-body transformation taking into account all these markers produces more robust results (Söderkvist & Wedin 1993; Challis 1995; Cappozzo et al. 1997). One mathematical procedure to calculate the transformation with three or more marker positions envolves the use of the [singular value decomposition](http://en.wikipedia.org/wiki/Singular_value_decomposition) (SVD) algorithm from linear algebra. The SVD algorithm decomposes a matrix $\mathbf{M}$ (which represents a general transformation between two coordinate systems) into three simple transformations: a rotation $\mathbf{V^T}$, a scaling factor $\mathbf{S}$ along the rotated axes and a second rotation $\mathbf{U}$: $$ \mathbf{M}= \mathbf{U\;S\;V^T}$$ And the rotation matrix is given by: $$ \mathbf{R}= \mathbf{U\:V^T}$$ The matrices $\mathbf{U}$ and $\mathbf{V}$ are both orthonormal (det = $\pm$1). For example, if we have registered the position of four markers placed on a moving segment in 100 different instants and the position of these same markers during, what is known in Biomechanics, a static calibration trial, we would use the SVD algorithm to calculate the 100 rotation matrices (between the static trials and the 100 instants) in order to find the Cardan angles for each instant. The function `svdt.py` (its code is shown at the end of this text) determines the rotation matrix ($R$) and the translation vector ($L$) for a rigid body after the following transformation: $B = R*A + L + err$. Where $A$ and $B$ represent the rigid body in different instants and err is an aleatory noise. $A$ and $B$ are matrices with the marker coordinates at different instants (at least three non-collinear markers are necessary to determine the 3D transformation). The matrix $A$ can be thought to represent a local coordinate system (but $A$ it's not a basis) and matrix $B$ the global coordinate system. The operation $P_g = R*P_l + L$ calculates the coordinates of the point $P_l$ (expressed in the local coordinate system) in the global coordinate system ($P_g$). Let's test the `svdt` function: ``` # Import the necessary libraries import numpy as np import sys sys.path.insert(1, r'./../functions') from svdt import svdt # markers in different columns (default): A = np.array([0,0,0, 1,0,0, 0,1,0, 1,1,0]) # four markers B = np.array([0,0,0, 0,1,0, -1,0,0, -1,1,0]) # four markers R, L, RMSE = svdt(A, B) print('Rotation matrix:\n', np.around(R, 4)) print('Translation vector:\n', np.around(L, 4)) print('RMSE:\n', np.around(RMSE, 4)) # markers in different rows: A = np.array([[0,0,0], [1,0,0], [ 0,1,0], [ 1,1,0]]) # four markers B = np.array([[0,0,0], [0,1,0], [-1,0,0], [-1,1,0]]) # four markers R, L, RMSE = svdt(A, B, order='row') print('Rotation matrix:\n', np.around(R, 4)) print('Translation vector:\n', np.around(L, 4)) print('RMSE:\n', np.around(RMSE, 4)) ``` For the matrix of a pure rotation around the z axis, the element in the first row and second column is $-sin\gamma$, which means the rotation was $90^o$, as expected. A typical use of the `svdt` function is to calculate the transformation between $A$ and $B$ ($B = R*A + L$), where $A$ is the matrix with the markers data in one instant (the calibration or static trial) and $B$ is the matrix with the markers data of more than one instant (the dynamic trial). Input $A$ as a 1D array `[x1, y1, z1, ..., xn, yn, zn]` where `n` is the number of markers and $B$ a 2D array with the different instants as rows (like in $A$). The output $R$ has the shape `(3, 3, tn)`, where `tn` is the number of instants, $L$ the shape `(tn, 3)`, and $RMSE$ the shape `(tn)`. If `tn` is equal to one, the outputs have the same shape as in `svdt` (the last dimension of the outputs above is dropped). Let's show this case: ``` A = np.array([0,0,0, 1,0,0, 0,1,0, 1,1,0]) # four markers B = np.array([0,0,0, 0,1,0, -1,0,0, -1,1,0]) # four markers B = np.vstack((B, B)) # simulate two instants (two rows) R, L, RMSE = svdt(A, B) print('Rotation matrix:\n', np.around(R, 4)) print('Translation vector:\n', np.around(L, 4)) print('RMSE:\n', np.around(RMSE, 4)) ``` ## References - Cappozzo A, Cappello A, Della Croce U, Pensalfini F (1997) [Surface-marker cluster design criteria for 3-D bone movement reconstruction](http://www.ncbi.nlm.nih.gov/pubmed/9401217). IEEE Trans Biomed Eng., 44:1165-1174. - Challis JH (1995). [A procedure for determining rigid body transformation parameters](http://www.ncbi.nlm.nih.gov/pubmed/7601872). Journal of Biomechanics, 28, 733-737. - Söderkvist I, Wedin PA (1993) [Determining the movements of the skeleton using well-configured markers](http://www.ncbi.nlm.nih.gov/pubmed/8308052). Journal of Biomechanics, 26, 1473-1477. ### Function svdt.py ``` %load './../functions/svdt.py' #!/usr/bin/env python """Calculates the transformation between two coordinate systems using SVD.""" __author__ = 'Marcos Duarte, https://github.com/demotu/BMC' __version__ = 'svdt.py v.1 2013/12/23' import numpy as np def svdt(A, B, order='col'): """Calculates the transformation between two coordinate systems using SVD. This function determines the rotation matrix (R) and the translation vector (L) for a rigid body after the following transformation [1]_, [2]_: B = R*A + L + err. Where A and B represents the rigid body in different instants and err is an aleatory noise (which should be zero for a perfect rigid body). A and B are matrices with the marker coordinates at different instants (at least three non-collinear markers are necessary to determine the 3D transformation). The matrix A can be thought to represent a local coordinate system (but A it's not a basis) and matrix B the global coordinate system. The operation Pg = R*Pl + L calculates the coordinates of the point Pl (expressed in the local coordinate system) in the global coordinate system (Pg). A typical use of the svdt function is to calculate the transformation between A and B (B = R*A + L), where A is the matrix with the markers data in one instant (the calibration or static trial) and B is the matrix with the markers data for one or more instants (the dynamic trial). If the parameter order='row', the A and B parameters should have the shape (n, 3), i.e., n rows and 3 columns, where n is the number of markers. If order='col', A can be a 1D array with the shape (n*3, like [x1, y1, z1, ..., xn, yn, zn] and B a 1D array with the same structure of A or a 2D array with the shape (ni, n*3) where ni is the number of instants. The output R has the shape (ni, 3, 3), L has the shape (ni, 3), and RMSE has the shape (ni,). If ni is equal to one, the outputs will have the singleton dimension dropped. Part of this code is based on the programs written by Alberto Leardini, Christoph Reinschmidt, and Ton van den Bogert. Parameters ---------- A : Numpy array Coordinates [x,y,z] of at least three markers with two possible shapes: order='row': 2D array (n, 3), where n is the number of markers. order='col': 1D array (3*nmarkers,) like [x1, y1, z1, ..., xn, yn, zn]. B : 2D Numpy array Coordinates [x,y,z] of at least three markers with two possible shapes: order='row': 2D array (n, 3), where n is the number of markers. order='col': 2D array (ni, n*3), where ni is the number of instants. If ni=1, B is a 1D array like A. order : string 'col': specifies that A and B are column oriented (default). 'row': specifies that A and B are row oriented. Returns ------- R : Numpy array Rotation matrix between A and B with two possible shapes: order='row': (3, 3). order='col': (ni, 3, 3), where ni is the number of instants. If ni=1, R will have the singleton dimension dropped. L : Numpy array Translation vector between A and B with two possible shapes: order='row': (3,) if order = 'row'. order='col': (ni, 3), where ni is the number of instants. If ni=1, L will have the singleton dimension dropped. RMSE : array Root-mean-squared error for the rigid body model: B = R*A + L + err with two possible shapes: order='row': (1,). order='col': (ni,), where ni is the number of instants. See Also -------- numpy.linalg.svd Notes ----- The singular value decomposition (SVD) algorithm decomposes a matrix M (which represents a general transformation between two coordinate systems) into three simple transformations [3]_: a rotation Vt, a scaling factor S along the rotated axes and a second rotation U: M = U*S*Vt. The rotation matrix is given by: R = U*Vt. References ---------- .. [1] Soderkvist, Kedin (1993) Journal of Biomechanics, 26, 1473-1477. .. [2] http://www.kwon3d.com/theory/jkinem/rotmat.html. .. [3] http://en.wikipedia.org/wiki/Singular_value_decomposition. Examples -------- >>> import numpy as np >>> from svdt import svdt >>> A = np.array([0,0,0, 1,0,0, 0,1,0, 1,1,0]) # four markers >>> B = np.array([0,0,0, 0,1,0, -1,0,0, -1,1,0]) # four markers >>> R, L, RMSE = svdt(A, B) >>> B = np.vstack((B, B)) # simulate two instants (two rows) >>> R, L, RMSE = svdt(A, B) >>> A = np.array([[0,0,0], [1,0,0], [ 0,1,0], [ 1,1,0]]) # four markers >>> B = np.array([[0,0,0], [0,1,0], [-1,0,0], [-1,1,0]]) # four markers >>> R, L, RMSE = svdt(A, B, order='row') """ A, B = np.asarray(A), np.asarray(B) if order == 'row' or B.ndim == 1: if B.ndim == 1: A = A.reshape(A.size/3, 3) B = B.reshape(B.size/3, 3) R, L, RMSE = _svd(A, B) else: A = A.reshape(A.size/3, 3) ni = B.shape[0] R = np.empty((ni, 3, 3)) L = np.empty((ni, 3)) RMSE = np.empty(ni) for i in range(ni): R[i, :, :], L[i, :], RMSE[i] = _svd(A, B[i, :].reshape(A.shape)) return R, L, RMSE def _svd(A, B): """Calculates the transformation between two coordinate systems using SVD. See the help of the svdt function. Parameters ---------- A : 2D Numpy array (n, 3), where n is the number of markers. Coordinates [x,y,z] of at least three markers B : 2D Numpy array (n, 3), where n is the number of markers. Coordinates [x,y,z] of at least three markers Returns ------- R : 2D Numpy array (3, 3) Rotation matrix between A and B L : 1D Numpy array (3,) Translation vector between A and B RMSE : float Root-mean-squared error for the rigid body model: B = R*A + L + err. See Also -------- numpy.linalg.svd """ Am = np.mean(A, axis=0) # centroid of m1 Bm = np.mean(B, axis=0) # centroid of m2 M = np.dot((B - Bm).T, (A - Am)) # considering only rotation # singular value decomposition U, S, Vt = np.linalg.svd(M) # rotation matrix R = np.dot(U, np.dot(np.diag([1, 1, np.linalg.det(np.dot(U, Vt))]), Vt)) # translation vector L = B.mean(0) - np.dot(R, A.mean(0)) # RMSE err = 0 for i in range(A.shape[0]): Bp = np.dot(R, A[i, :]) + L err += np.sum((Bp - B[i, :])**2) RMSE = np.sqrt(err/A.shape[0]/3) return R, L, RMSE ```
github_jupyter
``` !pip install keras from keras.models import Model from keras.optimizers import SGD,Adam,RMSprop # from keras.layers import Dense, Input, LSTM, Embedding,Dropout,Bidirectional,Flatten from keras.layers import * import os # from __future__ import print_function from keras import backend as K from keras.engine.topology import Layer import h5py from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import pandas as pd import numpy as np import keras # Position_Embedding #! -*- coding: utf-8 -*- #%% class Position_Embedding(Layer): def __init__(self, size=None, mode='sum', **kwargs): self.size = size #必须为偶数 self.mode = mode super(Position_Embedding, self).__init__(**kwargs) def call(self, x): if (self.size == None) or (self.mode == 'sum'): self.size = int(x.shape[-1]) batch_size,seq_len = K.shape(x)[0],K.shape(x)[1] position_j = 1. / K.pow(10000., \ 2 * K.arange(self.size / 2, dtype='float32' \ ) / self.size) position_j = K.expand_dims(position_j, 0) position_i = K.cumsum(K.ones_like(x[:,:,0]), 1)-1 #K.arange不支持变长,只好用这种方法生成 position_i = K.expand_dims(position_i, 2) position_ij = K.dot(position_i, position_j) position_ij = K.concatenate([K.cos(position_ij), K.sin(position_ij)], 2) if self.mode == 'sum': return position_ij + x elif self.mode == 'concat': return K.concatenate([position_ij, x], 2) def compute_output_shape(self, input_shape): if self.mode == 'sum': return input_shape elif self.mode == 'concat': return (input_shape[0], input_shape[1], input_shape[2]+self.size) # attention class Attention(Layer): def __init__(self, nb_head, size_per_head, **kwargs): self.nb_head = nb_head self.size_per_head = size_per_head self.output_dim = nb_head*size_per_head super(Attention, self).__init__(**kwargs) def build(self, input_shape): self.WQ = self.add_weight(name='WQ', shape=(input_shape[0][-1], self.output_dim), initializer='glorot_uniform', trainable=True) self.WK = self.add_weight(name='WK', shape=(input_shape[1][-1], self.output_dim), initializer='glorot_uniform', trainable=True) self.WV = self.add_weight(name='WV', shape=(input_shape[2][-1], self.output_dim), initializer='glorot_uniform', trainable=True) super(Attention, self).build(input_shape) def Mask(self, inputs, seq_len, mode='mul'): if seq_len == None: return inputs else: mask = K.one_hot(seq_len[:,0], K.shape(inputs)[1]) mask = 1 - K.cumsum(mask, 1) for _ in range(len(inputs.shape)-2): mask = K.expand_dims(mask, 2) if mode == 'mul': return inputs * mask if mode == 'add': return inputs - (1 - mask) * 1e12 def call(self, x): #如果只传入Q_seq,K_seq,V_seq,那么就不做Mask #如果同时传入Q_seq,K_seq,V_seq,Q_len,V_len,那么对多余部分做Mask if len(x) == 3: Q_seq,K_seq,V_seq = x Q_len,V_len = None,None elif len(x) == 5: Q_seq,K_seq,V_seq,Q_len,V_len = x #对Q、K、V做线性变换 Q_seq = K.dot(Q_seq, self.WQ) Q_seq = K.reshape(Q_seq, (-1, K.shape(Q_seq)[1], self.nb_head, self.size_per_head)) Q_seq = K.permute_dimensions(Q_seq, (0,2,1,3)) K_seq = K.dot(K_seq, self.WK) K_seq = K.reshape(K_seq, (-1, K.shape(K_seq)[1], self.nb_head, self.size_per_head)) K_seq = K.permute_dimensions(K_seq, (0,2,1,3)) V_seq = K.dot(V_seq, self.WV) V_seq = K.reshape(V_seq, (-1, K.shape(V_seq)[1], self.nb_head, self.size_per_head)) V_seq = K.permute_dimensions(V_seq, (0,2,1,3)) #计算内积,然后mask,然后softmax A = K.batch_dot(Q_seq, K_seq, axes=[3,3]) / self.size_per_head**0.5 A = K.permute_dimensions(A, (0,3,2,1)) A = self.Mask(A, V_len, 'add') A = K.permute_dimensions(A, (0,3,2,1)) A = K.softmax(A) #输出并mask O_seq = K.batch_dot(A, V_seq, axes=[3,2]) O_seq = K.permute_dimensions(O_seq, (0,2,1,3)) O_seq = K.reshape(O_seq, (-1, K.shape(O_seq)[1], self.output_dim)) O_seq = self.Mask(O_seq, Q_len, 'mul') return O_seq def compute_output_shape(self, input_shape): return (input_shape[0][0], input_shape[0][1], self.output_dim) def buid_model(): # LSTM 模型 print('lstm model start...\n') # 标题输入:接收一个含有 200 个整数的序列,每个整数在 1 到 3812202 之间。 main_input1 = Input(shape=(200,), name='main_input1', dtype='int32') emb1 = Embedding(output_dim=16, input_dim=3812203, input_length=200,mask_zero = False)(main_input1) emb1 = Position_Embedding()(emb1) main_input2 = Input(shape=(200,), name='main_input2', dtype='int32') emb2 = Embedding(output_dim=16, input_dim=62966, input_length=200,mask_zero = False)(main_input2) emb2 = Position_Embedding()(emb2) main_input3 = Input(shape=(200,), name='main_input3', dtype='int32') emb3 = Embedding(output_dim=16, input_dim=4445721, input_length=200,mask_zero = False)(main_input3) emb3 = Position_Embedding()(emb3) emb = keras.layers.concatenate([emb1, emb2, emb3]) O_seq = Attention(8,16)([emb,emb,emb]) O_seq = GlobalAveragePooling1D()(O_seq) # O_seq = Dropout(0.5)(O_seq)#尽量不要用 # lstm_out = Bidirectional(LSTM(10,activation='softsign',return_sequences=True))(O_seq) # lstm_out = GlobalAveragePooling1D()(lstm_out) outputs = Dense(1, activation='sigmoid', name='main_output')(O_seq) # model = Model(inputs=S_inputs, outputs=outputs) # # try using different optimizers and different optimizer configs # opt = Adam(lr=0.0005) # loss = 'categorical_crossentropy' # model.compile(loss=loss, # optimizer=opt, # metrics=['accuracy']) # 定义一个具有两个输入输出的模型 model = keras.models.Model(inputs=[main_input1,main_input2,main_input3],#,auxiliary_input], outputs=[outputs]) # 这里的输入输出顺序与fit时一致就好 # opt = RMSprop(lr=0.01, clipnorm=1.0) opt = Adam(lr=0.01) model.compile(optimizer=opt, sample_weight_mode='None',#"temporal", loss={'main_output': 'binary_crossentropy'}, metrics=['accuracy']) print(model.summary()) return model def data_load(): print('loading data ... \n') with h5py.File('../lstm_model_ad_id/word_train_ad.h5', 'r') as f: data = np.array(f.get('word_data')) label = pd.read_csv('../../train_preliminary/user.csv').sort_values(by=['user_id']) train_x, test_x, train_y, test_y = train_test_split(data, label, test_size=0.2, random_state=2020) train_y_age = train_y['age'].values - 1 train_y_age = keras.utils.np_utils.to_categorical(train_y_age, num_classes=10) train_y_gender = train_y['gender'].values - 1 test_y_age = test_y['age'].values - 1 test_y_age = keras.utils.np_utils.to_categorical(test_y_age, num_classes=10) test_y_gender = test_y['gender'].values - 1 print('get data ... \n') return train_x, test_x, train_y_age, train_y_gender,test_y_age,test_y_gender def load_data2(): with h5py.File('../lstm_model_advertiser_id/word_train_advertiser_id.h5', 'r') as f: data = np.array(f.get('word_data')) train_x, test_x= train_test_split(data, test_size=0.2, random_state=2020) return train_x, test_x def load_data3(): with h5py.File('../lstm_model_creative_id/word_train_creative_id.h5', 'r') as f: data = np.array(f.get('word_data')) train_x, test_x= train_test_split(data, test_size=0.2, random_state=2020) return train_x, test_x def get_filename_for_saving(save_dir): return os.path.join(save_dir, "trainsform_comb_gender_adm_0.01_{val_loss:.3f}-{val_acc:.3f}-{epoch:03d}-{loss:.3f}-{acc:.3f}.hdf5") model = buid_model() print('lstm model geted...\n') print(model.summary()) train_x, test_x, train_y_age, train_y_gender,test_y_age,test_y_gender = data_load() train_x2, test_x2 = load_data2() train_x3, test_x3 = load_data3() print('lstm model fit...\n') checkpointer = keras.callbacks.ModelCheckpoint( filepath=get_filename_for_saving(''), save_best_only=False) stopping = keras.callbacks.EarlyStopping(patience=8) reduce_lr = keras.callbacks.ReduceLROnPlateau(factor=0.1, patience=2, min_lr=0.0001) model.fit({'main_input1': train_x ,'main_input2': train_x2,'main_input3': train_x3}, {'main_output': train_y_gender}, epochs=100, batch_size=256, validation_data=({'main_input1': test_x,'main_input2': test_x2,'main_input3': test_x3}, {'main_output': test_y_gender}), callbacks=[checkpointer, reduce_lr, stopping]) # pre = model.predict(test_x,verbose=1) # #评估结果 # from sklearn.metrics import confusion_matrix, classification_report # y_ = np.reshape(np.argmax(test_y,axis=1),[-1]) # pre_ = np.reshape(np.argmax(pre, axis=1),[-1]) # #每个类的各项指标 # cm = confusion_matrix(y_, pre_) # # np.set_printoptions(precision=3) # cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] # print(cm_normalized) # print(classification_report(y_, pre_)) ```
github_jupyter
``` from PreFRBLE.likelihood import * from PreFRBLE.plot import * ``` ### Identify intervening galaxies Here we attempto to identify LoS with intervening galaxies. For this purpose, we compare the likelihood of temporal broadening $L(\tau)$ for scenarios with and without intervening galaxies, as well as consider a scenario that realistically considers the probability for LoS to intersect an additoinal galaxy. ``` properties_benchmark = { ## this is our benchmark scenario, fed to procedures as kwargs-dict of models considered for the different regions are provided as lists (to allow to consider multiple models in the same scenario, e. g. several types of progenitors. Use mixed models only when you kno what you are doing) 'redshift' : 0.1, ## Scenario must come either with a redshift or a pair of telescope and redshift population 'IGM' : ['primordial'], ## constrained numerical simulation of the IGM (more info in Hackstein et al. 2018, 2019 & 2020 ) 'Host' : ['Rodrigues18'], ## ensemble of host galaxies according to Rodrigues et al . 2018 # 'Inter' : ['Rodrigues18'], ## same ensemble for intervening galaxies 'Local' : ['Piro18_wind'], ## local environment of magnetar according to Piro & Gaensler 2018 # 'N_inter' : True, ## if N_Inter = True, then intervening galaxies are considered realistically, i. e. according to the expected number of intervened LoS N_inter 'f_IGM' : 0.9, ## considering baryon content f_IGM=0.9 } ## define our benchmark scenario without intervening galaxies scenario_nointer = Scenario( **properties_benchmark ) ## only LoS with a single intervening galaxy at rendom redshift, according to prior scenario_inter = Scenario( Inter='Rodrigues18', **properties_benchmark ) ## realistic mix of LoS with and without intervening galaxies, according to expectation from intersection probability scenario_realistic = Scenario( N_inter=True, Inter='Rodrigues18', **properties_benchmark ) ``` ### compare likelihoods First, we compare the distribution of $\tau$ expected to be observed by ASKAP, CHIME and Parkes. For easier interpretation we plot the complementary cumulative likelihood $P(>\tau)$, that shows how many $\tau$ are obseved above the given value ``` tau_dist = { 'ASKAP_incoh' : 0.06, 'Parkes' : 0.06, 'CHIME' : 1.8 } fig, axs = plt.subplots( 1, len(telescopes), figsize=(4*len(telescopes), 3) ) #fig, axs = plt.subplots( len(telescopes), 1, figsize=(4, len(telescopes)* 3) ) population = 'SMD' scenarios = [scenario_inter, scenario_nointer,scenario_realistic] scenario_labels = ['only intervening', 'no intervening', 'realistic'] linestyles = ['-.', ':', '-'] for telescope, ax in zip( telescopes, axs): for i_s, scenario in enumerate(scenarios): tmp = Scenario( population=population, telescope=telescope, **scenario.Properties( identifier=False ) ) L = GetLikelihood( 'tau', tmp ) L.Plot( ax=ax, deviation=True, label=scenario_labels[i_s], linestyle=linestyles[i_s], cumulative=-1 ) # P = GetLikelihood_Telescope( measure='tau', telescope=telescope, population='SMD', dev=True, **scenario ) # PlotLikelihood( *P, ax=ax, label=scenario_labels[i_s], linestyle=linestyles[i_s], measure='tau' , cumulative=-1 )#density=True ) ax.set_title(labels[telescope], fontsize=18) ax.set_ylim(1e-3,2) ax.set_xlim(1e-3, 1e2) if telescope == telescopes[0]: fig.legend(loc='center', bbox_to_anchor= (.5, 1.01), ncol=3, borderaxespad=0, frameon=False, fontsize=16, handlelength=3 ) ax.set_xscale('log') ax.set_yscale('log') ax.vlines( tau_dist[telescope], 1e-4,10 ) # AllSidesTicks(ax) #for i in range(3): # axs[i].legend(fontsize=16, loc=4+i) #axs[1].legend(fontsize=14, loc=1) fig.tight_layout() ``` ### Bayes factor & Posterior calculate bayes factor $\mathcal{B}$ as ratio of the two likelihood functions shown above. To obtain the posterior likelihood $L(\tau)$ for an $\tau$ to mark a LoS with an intervening galaxy, we have to multiply $\mathcal{B}$ by the ratio of prior likelihoods $\pi_{\rm inter}$, i. e. the ratio of expected amount of LoS with and without LoS. This amount can be found via $$ \pi_{\rm inter} = \int N_{\rm Inter}(z) \pi(z) \text{d}z . $$ For $L(\tau)>10^2$, the LoS is intersected by an intervening galaxy with >99% certainty. ``` ## first determine amount of intervened LoS telescope = 'Parkes' populations = 'SMD' for telescope in telescopes: scenario = Scenario( telescope=telescope, population=population ) L = GetLikelihood( 'z', scenario ) # Pz = GetLikelihood_Redshift( telescope=telescope, population=population ) N_Inter = np.cumsum(nInter(redshift=redshift_range[-1])) pi_inter = np.sum( N_Inter * L.Probability() ) ##plot results fig, ax = plt.subplots() L.Plot( ax=ax, label=r"$\pi$" ) # PlotLikelihood( *Pz, log=False, measure='z', ax=ax, label=r"$\pi$" ) ax.plot( L.x_central(), N_Inter, label=r"$N_{\rm Inter}$" ) print( "{}: {:.1f}% of LoS have intervening galaxy".format( telescope, 100*pi_inter ) ) ax.set_ylabel('') ax.legend() plt.show() ## Compute and plot posterior likelihood of $\tau$ to indicate an intervening galaxy fig, ax = plt.subplots( figsize=(5,3)) population = 'SMD' #for telescope, ax in zip( telescopes, axs): for telescope, color, linestyle in zip(telescopes, colors_telescope, linestyles_population): L_i = GetLikelihood( 'tau', Scenario( population=population, telescope=telescope, **scenario_inter.Properties( identifier=False ) ) ) L = GetLikelihood( 'tau', Scenario( population=population, telescope=telescope, **scenario_nointer.Properties( identifier=False ) ) ) ## force both P to same range ## give both P ranges the same min and max x_max = np.min( [L.x[-1],L_i.x[-1]] ) x_min = np.max( [L.x[0],L_i.x[0]] ) L_i.Measureable( min=x_min, max=x_max ) L.Measureable( min=x_min, max=x_max, bins=L_i.P.size ) ### use identical bins ## check if successfull if not np.all(L.x == L_i.x): print("try harder!") print(P[1], P_i[1]) break # """ B = BayesFactors( P1=L_i.P, P2=L.P ) dev_B = np.sqrt( L_i.dev**2 + L.dev**2 ) ## obtain prior Lz = GetLikelihood( 'z', Scenario( population=population, telescope=telescope ) ) # Pz = GetLikelihood_Redshift( telescope=telescope, population=population ) N_Inter = np.cumsum(nInter()) pi_inter = np.sum( N_Inter * Lz.Probability() ) ## compute posterior B *= pi_inter/(1-pi_inter) try: i_tau = first( range(len(B)), lambda i: B[i] > 1e2 ) except: print( "could not find L>100") ## highest value of P_nointer>0 i_tau = -1 ### by construction, last value # print( "B_last {} at {}".format( B[i_tau],i_tau) ) tau_decisive = L.x[1:][i_tau] print( "{}: decisive for intervening galaxies: tau>{:.3f} ms".format(telescope,tau_decisive)) ## better aestethics for results with P = 0 B[B==1] = B[B!=1][-1] * 10.**np.arange(sum(B==1)) ax.errorbar( L.x[1:], B, yerr=B*dev_B, label=r"%s, $\tau_{\rm decisive} = %.2f$ ms" % (labels[telescope], tau_decisive), color=color, linestyle=linestyle ) ax.set_xlabel( r"$\tau$ / ms", fontdict={'size':18 } ) ax.set_ylabel( r"$L$", fontdict={'size':18 } ) # ax.set_ylabel( r"$\mathcal{B}$", fontdict={'size':18 } ) ## compute how many LoS with intervening galaxies are identified / false positives ### reload the shrinked likelihood functions L_i = GetLikelihood( 'tau', Scenario( population=population, telescope=telescope, **scenario_inter.Properties( identifier=False ) ) ) L = GetLikelihood( 'tau', Scenario( population=population, telescope=telescope, **scenario_nointer.Properties( identifier=False ) ) ) #P_i, x_i = GetLikelihood_Telescope( measure='tau', telescope=telescope, population='SMD', **scenario_inter ) #P, x = GetLikelihood_Telescope( measure='tau', telescope=telescope, population='SMD', **scenario_nointer ) i_tau = first( range(len(L_i.P)), lambda i: L_i.x[i] > tau_decisive ) print( "%s, %.6f %% of interveners identified" % ( telescope, 100*np.sum( L_i.Probability()[i_tau:] ) ) ) try: i_tau = first( range(len(L.P)), lambda i: L.x[i] > tau_decisive ) except: ## fails, if chosen highest value of noInter i_tau = -1 print( "%s, %.6f %% of others give false positives" % ( telescope, 100*np.sum( L.Probability()[i_tau:] ) ) ) ax.legend(loc='lower right', fontsize=14) ax.loglog() #ax.set_xlim(1e-2,1e2) ax.set_ylim(1e-16,1e11) PlotLimit(ax=ax, x=ax.get_xlim(), y=[1e2,1e2], lower_limit=True, label='decisive', shift_text_vertical=3e3, shift_text_horizontal=-0.95) ax.tick_params(axis='both', which='major', labelsize=16) #AllSidesTicks(ax) # """ ``` ### compare to FRBcat How many FRBs in FRBcat show $\tau > \tau_{\rm dist}$? How many do we expect? ``` tau_dist = { 'ASKAP_incoh' : 0.06, 'Parkes' : 0.06, 'CHIME' : 1.8 } population='SMD' for telescope in telescopes: FRBs = GetFRBcat( telescopes=[telescope]) N_tau = sum(FRBs['tau'] > tau_dist[telescope]) N_tot = len(FRBs) print("{}: {} of {} > {} ms, {:.2f}%".format(telescope, N_tau, N_tot, tau_dist[telescope], 100*N_tau/N_tot)) scenario = Scenario( telescope=telescope, population=population, **scenario_realistic.Properties( identifier=False ) ) L = GetLikelihood( 'tau', scenario ) # L = GetLikelihood_Telescope( measure='tau', telescope=telescope, population=population, **scenario_inter_realistic) ix = first( range(len(L.P)), lambda i: L.x[i] >= tau_dist[telescope] ) # ix = np.where(L.x >= tau_dist[telescope])[0][0] print( "expected: {:.2f} % > {} ms".format( 100*L.Cumulative(-1)[ix], tau_dist[telescope] ) ) L.scenario.Key(measure='tau') ``` ### How many tau > 0.06 ms observed by Parkes can intervening galaxies account for? ``` pi_I = 0.0192 ## expected amount of LoS with tau > 0.06 ms (all from intervening) P_I = 0.4815 ## observed amount of tau > 0.06 ms, derived above print( "{:.2f} %".format(100*pi_I/P_I) ) ``` What about the other regions? ### outer scale of turbulence $L_0$ The observed values of $\tau$ from the IGM highly depend on the choice for $L_0$, whose true value is sparsely constrained, from few parsec to the Hubble scale. In our estimates, we assume constant $L_0 = 1 ~\rm Mpc$, a value expected from results by Ryu et al. 2008. The choice of constant $L_0$ allows for different choices in post processing. Simplye add a "L0" keyword with the required number in kpc. ``` scenario_IGM = { 'IGM' : ['primordial'], } scenario_ref = Scenario( telescope='Parkes', population='SMD', **scenario_realistic.Properties( identifier=False ) ) #scenario_ref = scenario_IGM tmp = scenario_ref.copy() tmp.IGM_outer_scale = 0.005 measure='tau' cumulative = -1 fig, ax = plt.subplots() L = GetLikelihood( measure, scenario_ref ) L.Plot( ax=ax, cumulative=cumulative ) #PlotLikelihood( *L, measure=measure, ax=ax, cumulative=cumulative) try: ix = first( range(len(L.P)), lambda i: L.x[i] > 0.06 ) print( "{:.2f} % > 0.06 ms for L0 = 1 Mpc".format( 100*L.Cumulative(-1)[ix] ) ) except: print( "0 > 0.06 ms for L0 = 1 Mpc") L = GetLikelihood( measure=measure, scenario=tmp, force=tmp.IGM_outer_scale<1, ) ### L0 < 1 kpc all have same keyword in likelihood file !!! CHANGE THAT L.Plot( ax=ax, cumulative=cumulative ) #PlotLikelihood( *L, measure=measure, ax=ax, cumulative=cumulative) ix = first( range(len(L.P)), lambda i: L.x[i] > 0.06 ) print( "{:.2f} % > 0.06 ms for L0 = {} kpc".format( 100*np.cumsum((L[0]*np.diff(L[1]))[::-1])[::-1][ix], tmp['L0'] ) ) ax.set_ylim(1e-3,1) ``` The results above show that very low values of $L_0<5 ~\rm pc$ are required for the IGM. It is thus more likely that a different model for the source environment can explain the high amount of $\tau > 0.06 ~\rm ms$ observed by Parkes
github_jupyter
``` from __future__ import absolute_import from __future__ import division from __future__ import print_function %pylab %matplotlib inline import os import math import time import tensorflow as tf from datasets import dataset_utils,cifar10 from tensorflow.contrib import slim ``` # lrn적용한 버젼! ``` dropout_keep_prob=0.8 image_size = 32 step=20000 learning_rate=0.0002 train_dir = '/tmp/cifar10/tanh_lrn' cifar10_data_dir='/media/ramdisk/data/cifar10' display_step=2 with tf.Graph().as_default(): dataset = cifar10.get_split('train', cifar10_data_dir) data_provider = slim.dataset_data_provider.DatasetDataProvider( dataset, common_queue_capacity=32, common_queue_min=1) image, label = data_provider.get(['image', 'label']) with tf.Session() as sess: with slim.queues.QueueRunners(sess): for i in range(display_step): np_image, np_label = sess.run([image, label]) height, width, _ = np_image.shape class_name = name = dataset.labels_to_names[np_label] plt.figure() plt.imshow(np_image) plt.title('%s, %d x %d' % (name, height, width)) plt.axis('off') plt.show() def cnn_tanh(images, num_classes, is_training): #https://github.com/agrawalnishant/tensorflow-1/tree/master/tensorflow/contrib/slim ##vgg와 cifarndet을 참조함 with slim.arg_scope([slim.max_pool2d], stride=2): net = slim.repeat(images, 2, slim.conv2d, 64, [3, 3], scope='conv1',activation_fn=tf.tanh,normalizer_fn=tf.nn.lrn) net = slim.max_pool2d(net, [2, 2], scope='pool1') net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2',activation_fn=tf.tanh,normalizer_fn=tf.nn.lrn) net = slim.max_pool2d(net, [2, 2], scope='pool2') net = slim.repeat(net, 4, slim.conv2d, 256, [3, 3], scope='conv3',activation_fn=tf.tanh,normalizer_fn=tf.nn.lrn) net = slim.max_pool2d(net, [2, 2], scope='pool3') net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv4',activation_fn=tf.tanh,normalizer_fn=tf.nn.lrn) net = slim.max_pool2d(net, [2, 2], scope='pool4') net = slim.conv2d(net, 512, [2, 2], padding="VALID", scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 512, [1, 1], scope='fc8', activation_fn=None) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc9') net = tf.squeeze(net, [1,2],name='fc9/squeezed') return net from preprocessing import cifarnet_preprocessing def load_batch(dataset, batch_size=128, height=image_size, width=image_size, is_training=False): """Loads a single batch of data. Args: dataset: The dataset to load. batch_size: The number of images in the batch. height: The size of each image after preprocessing. width: The size of each image after preprocessing. is_training: Whether or not we're currently training or evaluating. Returns: images: A Tensor of size [batch_size, height, width, 3], image samples that have been preprocessed. images_raw: A Tensor of size [batch_size, height, width, 3], image samples that can be used for visualization. labels: A Tensor of size [batch_size], whose values range between 0 and dataset.num_classes. """ data_provider = slim.dataset_data_provider.DatasetDataProvider( dataset, common_queue_capacity=128, common_queue_min=32) image_raw, label = data_provider.get(['image', 'label']) # Preprocess image for usage by Inception. image = cifarnet_preprocessing.preprocess_image(image_raw, height, width, is_training=is_training) # Preprocess the image for display purposes. image_raw = tf.expand_dims(image_raw, 0) image_raw = tf.image.resize_images(image_raw, [height, width]) image_raw = tf.squeeze(image_raw) # Batch it up. images, images_raw, labels = tf.train.batch( [image, image_raw, label], batch_size=batch_size, num_threads=4, capacity=4 * batch_size) return images, images_raw, labels %%time # This might take a few minutes. print('Will save model to %s' % train_dir) with tf.Graph().as_default(): tf.logging.set_verbosity(tf.logging.INFO) dataset = cifar10.get_split('train', cifar10_data_dir) images, _, labels = load_batch(dataset) # Create the model: logits =cnn_tanh(images, num_classes=dataset.num_classes, is_training=True) # Specify the loss function: one_hot_labels = slim.one_hot_encoding(labels, dataset.num_classes) slim.losses.softmax_cross_entropy(logits, one_hot_labels) total_loss = slim.losses.get_total_loss() # Create some summaries to visualize the training process: tf.summary.scalar('losses/Total Loss', total_loss) # Specify the optimizer and create the train op: optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = slim.learning.create_train_op(total_loss, optimizer) # Run the training: final_loss = slim.learning.train( train_op, logdir=train_dir, number_of_steps=step, log_every_n_steps=10, save_interval_secs=100, save_summaries_secs=100) print('Finished training. Final batch loss %d' % final_loss) %%time # This might take a few minutes. with tf.Graph().as_default(): tf.logging.set_verbosity(tf.logging.DEBUG) dataset = cifar10.get_split('test', cifar10_data_dir) images, _, labels = load_batch(dataset) logits = cnn_tanh(images, num_classes=dataset.num_classes, is_training=False) predictions = tf.argmax(logits, 1) # Define the metrics: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ 'eval/mse':slim.metrics.streaming_mean_squared_error(predictions, labels), 'eval/Accuracy': slim.metrics.streaming_accuracy(predictions, labels), 'eval/TruePositives': slim.metrics.streaming_true_positives(predictions, labels), 'eval/TrueNegatives': slim.metrics.streaming_true_negatives(predictions, labels), 'eval/FalsePositives': slim.metrics.streaming_false_positives(predictions, labels), 'eval/FalseNegatives': slim.metrics.streaming_false_negatives(predictions, labels), 'eval/Recall5': slim.metrics.streaming_sparse_recall_at_k(logits, labels, 5), }) print('Running evaluation Loop...') checkpoint_path = tf.train.latest_checkpoint(train_dir) metric_values = slim.evaluation.evaluate_once( master='', checkpoint_path=checkpoint_path, logdir=train_dir, eval_op=list(names_to_updates.values()), final_op=list(names_to_values.values()) ) names_to_values = dict(zip(names_to_values.keys(), metric_values)) for name in names_to_values: print('%s: %f' % (name, names_to_values[name])) %%time batch_size = 10 with tf.Graph().as_default(): tf.logging.set_verbosity(tf.logging.INFO) dataset = cifar10.get_split('test',cifar10_data_dir) images, images_raw, labels = load_batch(dataset, height=image_size, width=image_size) # Create the model, use the default arg scope to configure the batch norm parameters. logits = cnn_tanh(images, num_classes=dataset.num_classes, is_training=True) probabilities = tf.nn.softmax(logits) checkpoint_path = tf.train.latest_checkpoint(train_dir) init_fn = slim.assign_from_checkpoint_fn( checkpoint_path, slim.get_variables_to_restore()) with tf.Session() as sess: with slim.queues.QueueRunners(sess): sess.run(tf.local_variables_initializer()) init_fn(sess) np_probabilities, np_images_raw, np_labels = sess.run([probabilities, images_raw, labels]) for i in range(batch_size): image = np_images_raw[i, :, :, :] true_label = np_labels[i] predicted_label = np.argmax(np_probabilities[i, :]) predicted_name = dataset.labels_to_names[predicted_label] true_name = dataset.labels_to_names[true_label] plt.figure() plt.imshow(image.astype(np.uint8)) plt.title('Ground Truth: [%s], Prediction [%s]' % (true_name, predicted_name)) plt.axis('off') plt.show() ```
github_jupyter
# This is the Saildrone and MUR global 1 km sea surface temperature collocation code. ``` import os import numpy as np import matplotlib.pyplot as plt import datetime as dt import xarray as xr def get_sat_filename(date): dir_sat='F:/data/sst/jpl_mur/v4.1/' syr, smon, sdym, sjdy = str(date.dt.year.data), str(date.dt.month.data).zfill(2), str(date.dt.day.data).zfill(2), str(date.dt.dayofyear.data).zfill(2) sat_filename = dir_sat + syr + '/'+ sjdy + '/' + syr + smon + sdym + '090000-JPL-L4_GHRSST-SSTfnd-MUR-GLOB-v02.0-fv04.1.nc' exists = os.path.isfile(sat_filename) return sat_filename, exists def robust_std(ds): MAD = np.nanmedian(ds) std_robust = MAD * 1.482602218505602 ``` # Read in USV data Read in the Saildrone USV file either from a local disc or using OpenDAP. There are 6 NaN values in the lat/lon data arrays, interpolate across these We want to collocate with wind vectors for this example, but the wind vectors are only every 10 minutes rather than every minute, so use .dropna to remove all values in the dataset from all dataarrays when wind vectors aren't availalbe ``` file,iexist=get_sat_filename(ds_usv.time[0]) ds=xr.open_dataset(file) ds.analysed_sst.plot() tem=ds.analysed_sst.sel(lat=slice(10,20),lon=slice(-150,-140)).mean({'lat','lon'}) print(tem) filename_collocation_data = 'F:/data/cruise_data/saildrone/baja-2018/ccmp_collocation_data.nc' #filename_usv = 'https://podaac-opendap.jpl.nasa.gov/opendap/hyrax/allData/insitu/L2/saildrone/Baja/saildrone-gen_4-baja_2018-sd1002-20180411T180000-20180611T055959-1_minutes-v1.nc' filename_usv='f:/data/cruise_data/saildrone/baja-2018/saildrone-gen_4-baja_2018-sd1002-20180411T180000-20180611T055959-1_minutes-v1.nc' ds_usv = xr.open_dataset(filename_usv) ds_usv.close() ds_usv = ds_usv.isel(trajectory=0).swap_dims({'obs':'time'}).rename({'longitude':'lon','latitude':'lat'}) ds_usv = ds_usv.sel(time=slice('2018-04-12T02','2018-06-10T18')) #get rid of last part and first part where USV being towed ds_usv['lon'] = ds_usv.lon.interpolate_na(dim='time',method='linear') #there are 6 nan values ds_usv['lat'] = ds_usv.lat.interpolate_na(dim='time',method='linear') ds_usv['wind_speed']=np.sqrt(ds_usv.UWND_MEAN**2+ds_usv.VWND_MEAN**2) ds_usv['wind_dir']=np.arctan2(ds_usv.VWND_MEAN,ds_usv.UWND_MEAN)*180/np.pi ds_usv_subset = ds_usv.copy(deep=True) ds_usv_subset = ds_usv_subset.where(np.logical_not((ds_usv.time.dt.hour>12)&(ds_usv.wind_speed<7.5))) ds_usv_subset = ds_usv_subset.where(np.logical_not((ds_usv.time.dt.hour<6)&(ds_usv.wind_speed<7.5))) ds_usv_subset = ds_usv_subset.where(np.logical_not((ds_usv.time>np.datetime64('2018-05-24T12')) & (ds_usv.time<np.datetime64('2018-05-26T12')))) #ds_usv_subset = ds_usv.dropna(dim='time',subset={'UWND_MEAN'}) #get rid of all the nan #print(ds_usv_subset.UWND_MEAN[2000:2010].values) ``` In order to use open_mfdataset you need to either provide a path or a list of filenames to input Here we use the USV cruise start and end date to read in all data for that period ``` read_date,end_date = ds_usv_subset.time.min(),ds_usv_subset.time.max() filelist = [] while read_date<=(end_date+np.timedelta64(1,'D')): tem_filename,exists = get_sat_filename(read_date) if exists: filelist.append(tem_filename) read_date=read_date+np.timedelta64(1,'D') print(filelist[0]) ``` # Read in MUR data Read in data using open_mfdataset with the option coords='minimal' The dataset is printed out and you can see that rather than straight xarray data array for each of the data variables open_mfdataset using dask arrays ``` ds_sat = xr.open_mfdataset(filelist,coords='minimal') ds_sat ``` # Xarray interpolation won't run on chunked dimensions. 1. First let's subset the data to make it smaller to deal with by using the cruise lat/lons 1. Now load the data into memory (de-Dask-ify) it ``` #Step 1 from above print('min max lat lon:', ds_usv_subset.lon.min().data,ds_usv_subset.lon.max().data,ds_usv_subset.lat.min().data,ds_usv_subset.lat.max().data) subset = ds_sat.sel(lon=slice(ds_usv_subset.lon.min().data,ds_usv_subset.lon.max().data), lat=slice(ds_usv_subset.lat.min().data,ds_usv_subset.lat.max().data)) #Step 2 from above subset.load() ``` # Collocate USV data with MUR data There are different options when you interpolate. First, let's just do a linear interpolation ``` ds_collocated = subset.interp(lat=ds_usv_subset.lat,lon=ds_usv_subset.lon,time=ds_usv_subset.time,method='linear') ``` # Collocate USV data with MUR data There are different options when you interpolate. First, let's just do a nearest point rather than interpolate the data ``` ds_collocated_nearest = subset.interp(lat=ds_usv_subset.lat,lon=ds_usv_subset.lon,time=ds_usv_subset.time,method='nearest') ``` # A larger STD that isn't reflective of uncertainty in the observation The collocation above will result in multiple USV data points matched with a single satellite observation. The USV is sampling every 1 min and approximately few meters, while the satellite is an average over a footprint that is interpolated onto a daily mean map. While calculating the mean would results in a valid mean, the STD would be higher and consist of a component that reflects the uncertainty of the USV and the satellite and a component that reflects the natural variability in the region that is sampled by the USV Below we use the 'nearest' collocation results to identify when multiple USV data are collcated to a single satellite observation. This code goes through the data and creates averages of the USV data that match the single CCMP collocated value. ``` ilen,index = ds_collocated_nearest.dims['time'],0 ds_tem = ds_collocated_nearest.copy(deep=True) duu, duv1, duv2, dlat, dlon, dut = [],[],[],[],[],np.empty((),dtype='datetime64') while index <= ilen-2: index += 1 if np.isnan(ds_collocated_nearest.analysed_sst[index]): continue if np.isnan(ds_tem.analysed_sst[index]): continue # print(index, ilen) iend = index + 1000 if iend > ilen-1: iend = ilen-1 ds_tem_subset = ds_tem.analysed_sst[index:iend] ds_usv_subset2sst = ds_usv_subset.TEMP_CTD_MEAN[index:iend] ds_usv_subset2uwnd = ds_usv_subset.UWND_MEAN[index:iend] ds_usv_subset2vwnd = ds_usv_subset.VWND_MEAN[index:iend] ds_usv_subset2lat = ds_usv_subset.lat[index:iend] ds_usv_subset2lon = ds_usv_subset.lon[index:iend] ds_usv_subset2time = ds_usv_subset.time[index:iend] cond = ((ds_tem_subset==ds_collocated_nearest.analysed_sst[index])) notcond = np.logical_not(cond) #cond = ((ds_tem.analysed_sst==ds_collocated_nearest.analysed_sst[index])) #notcond = np.logical_not(cond) masked = ds_tem_subset.where(cond) if cond.sum().data==0: #don't do if data not found continue if cond.sum().data>800: print(cond.sum().data,index,ds_tem.time[index].data) masked_usvsst = ds_usv_subset2sst.where(cond,drop=True) masked_usvuwnd = ds_usv_subset2uwnd.where(cond,drop=True) masked_usvvwnd = ds_usv_subset2vwnd.where(cond,drop=True) masked_usvlat = ds_usv_subset2lat.where(cond,drop=True) masked_usvlon = ds_usv_subset2lon.where(cond,drop=True) masked_usvtime = ds_usv_subset2time.where(cond,drop=True) duu=np.append(duu,masked_usvsst.mean().data) duv1=np.append(duv1,masked_usvuwnd.mean().data) duv2=np.append(duv2,masked_usvvwnd.mean().data) dlat=np.append(dlat,masked_usvlat.mean().data) dlon=np.append(dlon,masked_usvlon.mean().data) tdif = masked_usvtime[-1].data-masked_usvtime[0].data mtime=masked_usvtime[0].data+np.timedelta64(tdif/2,'ns') if mtime>dut.max(): print(index,masked_usvtime[0].data,(masked_usvtime[-1].data-masked_usvtime[0].data)/1e9) dut=np.append(dut,mtime) ds_tem.analysed_sst[index:iend]=ds_tem.analysed_sst.where(notcond) # ds_tem=ds_tem.where(notcond,np.nan) #masked used values by setting to nan dut2 = dut[1:] #remove first data point which is a repeat from what array defined ds_new=xr.Dataset(data_vars={'sst_usv': ('time',duu),'uwnd_usv': ('time',duv1),'vwnd_usv': ('time',duv2), 'lon': ('time',dlon), 'lat': ('time',dlat)}, coords={'time':dut2}) ds_new.to_netcdf('F:/data/cruise_data/saildrone/baja-2018/mur_downsampled_usv_data2.nc') ds_new ``` # redo the collocation Now, redo the collocation, using 'linear' interpolation using the averaged data. This will interpolate the data temporally onto the USV sampling which has been averaged to the satellite data grid points ``` #for i in range(600,650): # print(ds_collocated_nearest.lat[i].data,ds_collocated_nearest.analysed_sst[i].data) #5442 with 3000 points in check #5631 with 2000 points in check #5934 with 1000 points in check ds_new #(ds_new.lat[0]-ds_new.lat[80])*111 #(ds_new.lon[0]-ds_new.lon[80])*111 #for i in range(0,100): # print(ds_new.time[i].data,ds_new.lat[i].data,ds_new.lon[i].data) ds_collocated_averaged = subset.interp(lat=ds_new.lat,lon=ds_new.lon,time=ds_new.time,method='linear') ds_collocated_averaged ds_collocated_averaged.to_netcdf('F:/data/cruise_data/saildrone/baja-2018/mur_downsampled_collocated_usv_data2.nc') ds_new.to_netcdf('F:/data/cruise_data/saildrone/baja-2018/mur_downsampled_usv_data2.nc') ds_collocated_averaged ds_collocated_averaged = xr.open_dataset('F:/data/cruise_data/saildrone/baja-2018/mur_downsampled_collocated_usv_data2.nc') ds_collocated_averaged.close() ds_new = xr.open_dataset('F:/data/cruise_data/saildrone/baja-2018/mur_downsampled_usv_data2.nc') ds_new.close() ds_collocated_averaged ds_new ``` There are different ways to select data using an Xarray dataset. - The easiest ways are to use .isel or .sel - .isel selects by integer - .sel selects by label A note of caution, if you are using .isel it is better to rename your data variable. If you run the block of code that selects the data more than once, using .sel it would still have the same result, while using .isel would apply the selection again ``` #sat_sst = ds_collocated_averaged.analysed_sst[:-19]-273.15 #usv_sst = ds_new.sst_usv[:-19] sat_sst = ds_collocated_averaged.analysed_sst[:-19]-273.15 usv_sst = ds_new.sst_usv[:-19] cond = np.isfinite(usv_sst) sat_sst = sat_sst[cond] usv_sst = usv_sst[cond] dif_sst = sat_sst-usv_sst ds_new['spd']=np.sqrt(ds_new.uwnd_usv**2+ds_new.vwnd_usv**2) usv_spd = ds_new.spd[:-19] #dif_sst = (sat_sst - usv_sst).dropna(dim='time') #std_robust = np.nanmedian(dif_sst) * 1.482602218505602 #print('mean,std,rstd, dif ',[dif_sst.mean().data,dif_sst.std().data,std_robust,dif_sst.shape[0]]) usv_spd = usv_spd[cond] sdif = (sat_sst-usv_sst).dropna('time') sdifcor = np.corrcoef(sat_sst,usv_sst)[0,1] std_robust = np.nanmedian(np.abs(sdif - np.nanmedian(sdif))) * 1.482602218505602 ilen = sdif.shape[0] print([sdif.mean().data,sdif.median().data,sdifcor,sdif.std().data,std_robust, np.abs(sdif).mean().data,sdif.shape[0]]) ds_collocated_averaged ds_new #playign around import pytz time = ds_new['time'].to_index() time_utc = time.tz_localize(pytz.UTC) au_tz = pytz.timezone('Etc/GMT+8') sat_sst = ds_collocated_averaged.analysed_sst[:-19]-273.15 usv_sst = ds_new.sst_usv[:-19] ds_new['time_local'] = time_utc.tz_convert(au_tz) usv_spd = ds_new.spd[:-19] sat_local_hr = ds_new.local_time.dt.hour[:-19] cond = np.isfinite(usv_sst) sat_sst = sat_sst[cond] usv_sst = usv_sst[cond] dif_sst = sat_sst-usv_sst usv_spd = usv_spd[cond] sat_local_hr = sat_local_hr[cond] #now remove low wind cond = usv_spd>2 sdif = (sat_sst-usv_sst).dropna('time') sdifcor = np.corrcoef(sat_sst,usv_sst)[0,1] std_robust = np.nanmedian(np.abs(sdif - np.nanmedian(sdif))) * 1.482602218505602 ilen = sdif.shape[0] print([sdif.mean().data,sdif.median().data,sdifcor,sdif.std().data,std_robust, np.abs(sdif).mean().data,sdif.shape[0]]) ds_new.local_time.dt.hour[:-19] plt.plot(usv_spd,dif_sst,'.') plt.xlabel('USV wind speed (ms$^{-1}$)') plt.ylabel('USV - Sat SST (K)') #sat_sst = ds_collocated_averaged.analysed_sst[:-19]-273.15 #usv_sst = ds_new.sst_usv[:-19] #dif_sst = sat_sst - usv_sst cond = usv_spd>2 dif_sst = dif_sst[cond] #.where(cond).dropna('time') std_robust = np.nanmedian(dif_sst) * 1.482602218505602 print('no low wind mean,std,rstd, dif ',[dif_sst.mean().data,dif_sst.std().data,std_robust,sum(cond).data]) plt.plot(usv_sst,dif_sst,'.') plt.xlabel('USV SST (K)') plt.ylabel('USV - Sat SST (K)') import cartopy.crs as ccrs import matplotlib.pyplot as plt ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() ax.plt() fig, ax = plt.subplots(figsize=(5,4)) ax.plot(sat_sst,sat_sst-usv_sst,'.') ax.set_xlabel('USV wind speed (ms$^{-1}$)') ax.set_ylabel('USV - Sat wind direction (deg)') fig_fname='F:/data/cruise_data/saildrone/baja-2018/figs/sat_sst_both_bias.png' fig.savefig(fig_fname, transparent=False, format='png') plt.plot(dif_sst[:-19],'.') subset.analysed_sst[0,:,:].plot() subset.analysed_sst.mean({'lat','lon'}).plot() subset.analysed_sst.mean({'time'}).plot() subset.analysed_sst.std({'time'}).plot() ```
github_jupyter
``` import numpy as np import cv2 import matplotlib.pyplot as plt import glob from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as K from keras.models import Model import os filenames = [] for path, subdirs, files in os.walk('Data/1obj'): for name in files: if 'src_color' in path: filenames.append(os.path.join(path, name)) print('# Training images: {}'.format(len(filenames))) n_examples = 3 for i in range(n_examples): plt.subplot(2, 2, 1) image = cv2.imread(filenames[i]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) plt.subplot(2, 2, 2) mask_file = filenames[i].replace('src_color', 'human_seg') mask = cv2.imread(glob.glob(mask_file[:-4]+'*')[0]) ret, mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY_INV) mask = mask[:,:,0] plt.imshow((mask), cmap='gray') plt.show() def dice_coef(y_true, y_pred, smooth=0.9): y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) def dice_coef_loss(y_true, y_pred): return -dice_coef(y_true, y_pred) img_rows = 240 img_cols = 240 img_channels = 3 inputs = Input((img_rows, img_cols, img_channels)) conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs) conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4) drop4 = Dropout(0.5)(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(drop4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5) drop5 = Dropout(0.5)(conv5) up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5)) merge6 = concatenate([drop4,up6], axis = 3) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6) up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6)) merge7 = concatenate([conv3,up7], axis = 3) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7) up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7)) merge8 = concatenate([conv2,up8], axis = 3) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8) up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8)) merge9 = concatenate([conv1,up9], axis = 3) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9) model = Model(inputs = inputs, outputs = conv10) opt = Adam() model.compile(optimizer = opt, loss=dice_coef_loss, metrics = [dice_coef]) model.summary() X = np.ndarray((len(filenames), img_rows, img_cols , img_channels), dtype=np.uint8) y = np.ndarray((len(filenames), img_rows, img_cols , 1), dtype=np.uint8) i=0 for image in filenames: img = cv2.imread(image) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (240,240)) mask_file = image.replace('src_color', 'human_seg') label = cv2.imread(glob.glob(mask_file[:-4]+'*')[0], 0) ret, label = cv2.threshold(label, 0, 255, cv2.THRESH_BINARY_INV) label = cv2.resize(img, (240, 240)) label = label[:,:,0].reshape((240, 240, 1)) img = np.array([img/255.]) label = np.array([label]) X[i] = img y[i] = label i+=1 n_epochs = 1 batch_size = 1 history = model.fit(X, y, batch_size=batch_size, epochs=n_epochs, verbose=1, shuffle=True, validation_split=0.1) ```
github_jupyter
Introdução ao NumPy =========== O tipo *ndarray* -------------------- O tipo *ndarray*, ou apenas *array* é um arranjo de itens homogêneos de dimensionalidade N, indexados por uma tupla de N inteiros. Existem 3 informações essenciais associadas ao *ndarray*: o tipo dos dados, suas dimensões e seus dados em si. A propriedade *dtype* permite saber o tipo de dados enquanto que *shape* é uma tupla que indica o tamanho de cada dimensão do arranjo. O acesso aos dados em si deve ser feito por indexação, por fatiamento ou pela variável em si. Existem várias maneiras de criar uma variável do tipo *ndarray*. Por exemplo, é possível criar uma a partir de uma lista (1D) ou lista de listas usando a função *array*. O tipo de matriz resultante é deduzida a partir do tipo de elementos nas sequências. Veja a seguir um vetor de inteiros com 5 elementos. Note que o vetor é uma linha com 5 colunas. Observe também que o shape é uma tupla de um único elemento (veja a vírgula que aparece por ser uma tupla). ``` import numpy as np a = np.array( [2,3,4,-1,-2] ) print('Dimensões: a.shape=', a.shape ) print('Tipo dos elementos: a.dtype=', a.dtype ) print('Imprimindo o array completo:\n a=',a ) ``` Veja a seguir uma matriz bidimensional de dados ponto flutuante de 2 linhas e 3 colunas. Observe que a tupla do shape aumenta para a esquerda, isto é, se eu tiver um vetor de 3 elementos, o seu shape é (3,) e se uma nova dimensão for adicionada, por exemplo 2 linhas e 3 colunas, o shape passa a ser (3,2). O que antes shape[0] no vetor unidimensional era colunas, já na matriz bidimensional shape[0] passou a ser o número de linhas. Assim o último elemento da tupla do ``shape`` indica o número de colunas, a penúltima o número de linhas. Assim se quisermos sempre buscar o número de colunas, independentemente do número de dimensões, shape[-1] informa sempre o número de colunas, shape[-2], o número de linhas. ``` b = np.array( [ [1.5, 2.3, 5.2], [4.2, 5.6, 4.4] ] ) print('Um array bidimensional, dimensões:(b.shape=', b.shape ) print('Tipo dos elementos: b.dtype', b.dtype ) print('Número de colunas:', b.shape[-1] ) print('Número de linhas:', b.shape[-2] ) print('Elementos, b=\n', b ) ``` Manipulação de arrays ===================== Criando arrays inicializados ------------------------------- É possível criar arrays de zeros, uns ou valores não inicializados usando as funções *zeros*, *ones* ou *empty*. As dimensões do array são obrigatórias e é dado por uma tupla e o tipo dos elementos é opcional, sendo que o default é tipo float. O código a seguir cria 3 arrays. O primeiro possui 2 linhas e 4 colunas. O segundo tem 3 dimensões: 3 fatias (ou imagens) onde cada uma tem 2 linhas e 5 colunas. Por último, é criado uma matriz booleana (True e False) de valores não inicializados de 2 linhas e 3 colunas. A vantagem do *empty* é que ele é mais rápido que o *zeros* ou *ones*. No caso abaixo, os valores mostrados na matrix criada pelo *empty* são aleatórios. ``` d = np.zeros( (2,4) ) print('Array de 0s: \n', d ) d = np.ones( (3,2,5), dtype='int16' ) print('\n\nArray de 1s: \n', d ) d = np.empty( (2,3), 'bool' ) print('Array não inicializado (vazio):\n', d ) ``` Note que o Numpy permite arrays n-dimensionais. Em imagens em níveis de cinza iremos trabalhar com matrizes bidimensionais mas se a imagem for colorida, iremos representá-la em 3 canais, R, G e B, representados na estrutura com 3 dimensões. Se for um vídeo, isto é, uma sequência de imagens, teremos que adicionar mais uma dimensão. Se for uma tomografia, também podemos representar em 3 dimensões: largura, altura e profundidade. Criando arrays com valores sequenciais ======================================= As funções *arange* e *linspace* geram um vetor sequencial. Eles diferem apenas nos parâmetros. Enquanto o *arange* gera uma sequência a partir dos valores inicial (includente e opcional), final( excludente) e passo (opcional), *linspace* gera uma sequência com valores inicial e final e número de elementos. Note as diferenças nos exemplos a seguir: ``` print('np.arange( 10) = ', np.arange(10) ) print('np.arange( 3, 8) = ', np.arange(3,8) ) print('np.arange( 0, 2, 0.5) = ', np.arange(0, 2, 0.5) ) print('np.linspace( 0, 2, 5 ) = ', np.linspace( 0, 2, 5 ) ) ``` Veja que no último caso, usando o linspace, a sequência começa em 0 e termina em 2 e deve possuir 5 elementos. Veja que para isto o passo a ser utilizado será 0.5, calculado automaticamente. Já no exemplo anterior, a sequência começa em 0 e deve terminar antes de 2 e o passo é 0.5. Fatiamento em narray unidimensional ====================================== Um recurso importante do numpy é o fatiamento no qual é possível acessar um subconjunto do array de diversas formas. O fatiamento define os índices onde o array será acessado definindo o ponto inicial, final e o passo entre eles, nesta ordem: [inicial:final:passo]. Inicializando um array unidimensional ======================================== ``` a = np.arange(20) # a é um vetor de dimensão 20 print('a = \n', a ) ``` Exemplo simples de fatiamento =============================== Para a realização do fatiamento são utilizados 3 parâmetros, colocados no local do índice do array. Os 3 parâmetros são separados por dois pontos ":". Todos os 3 parâmetros podem ser opcionais que ocorrem quando o valor inicial é 0, o valor final é o tamanho do array e o passo é 1. Lembrar que a ordem deles é: [inicial:final:passo]. Se o passo for 1 fica: [inicial:final]. Se o início for 0 fica: [:final] e se o final for o último fica: [inicio:] e se forem todos [:]. O fatiamento é feito começando pelo primeiro valor, adicionando-se o passo até antes do último valor. Três aspectos são extremamente importantes de serem lembrados: O índice inicial começa em zero, o índice final nunca é atingido, o último índice utilizado é sempre o imediatamente anterior e o Numpy admite índices negativos, que é uma indexação do último (-1) até o primeiro elemento (-W). Os exemplos a seguir ajudam a fixar estes conceitos. O código abaixo acessa os elementos ímpares começando de 1 até 14: ``` a = np.arange(20) print('Resultado da operação a[1:15:2]' ) print(a[1:15:2] ) ``` Exemplo de fatiamento com indices negativos ============================================= Acessando o último elemento com índice negativo ----------------------------------------------------------------------------- O código abaixo acessa os elementos ímpares até antes do último elemento: ``` a = np.arange(20) print('Resultado da operação a[1:-1:2]' ) print(a[1:-1:2] ) print('Note que o fatiamento termina antes do último elemento (-1)' ) ``` Inversão do array com step negativo (step = -1) ------------------------------------------------------ ``` a = np.arange(20) print('Resultado da operação a[-3:2:-1]' ) print(a[-3:2:-1] ) print( 'Note que o fatiamento retorna o array invertido' ) print( 'Antepenúltimo até o terceiro elemento com step = -1' ) ``` Fatiamento avançado ======================================== É possível realizar o fatiamento utilizando os 3 parâmetros explícitos ( o limite inferior, limite superior e o step), ou podemos suprimir algum desses parâmetros. Nestes casos a função toma o valor defaut: limite inferior = primeiro elemento, limite superior = último elemento e step = 1. |Proposta inicial | Equivalente | |---------------------|-------------| |a[0:len(a):1] | a[:] | |a[0:10:1] | a[:10] | |a[0:10:2] | a[:10:2] | |a[2:len(a):1] | a[2::] | |a[2:len(a):2] | a[2::2] | Supressão do indice limite inferior ---------------------------------------------- Quando o índice do limite inferior é omitido, é subentendido que é 0: ``` a = np.arange(20) print('Resultado da operação a[:15:2]' ) print(a[:15:2] ) print('Note que o fatiamento inicia do primeiro elemento' ) print('Primeiro elemento até antes do 15o com passo duplo' ) ``` Supressão do indice limite superior ---------------------------------------------- Quando o índice do limite superior é omitido, fica implícito que é o último elemento: ``` a = np.arange(20) print('Resultado da operação a[1::2]' ) print(a[1::2] ) print('Note que o fatiamento termina último elemento' ) print('Primeiro elemento até o último com passo duplo' ) ``` Supressão do indice do step --------------------------- O índice do step é opcional e quando não é indicado, seu valor é 1: ``` a = np.arange(20) print('Resultado da operação a[1:15]' ) print(a[1:15] ) print('Note que o fatiamento tem step unitário' ) print('Primeiro elemento até antes do 15o com passo um' ) ``` Todos os elementos com passo unitário ---------------------------------------------------- ``` a = np.arange(20) print('Resultado da operação a[:]' ) print(a[:] ) print('Todos os elementos com passo unitário' ) ``` Fatiamento no ndarray bidimensional ====================================== Um recurso importante do numpy é o fatiamento no qual é possível acessar partes do array de diversas formas, como pode ser visto abaixo: Inicializando um array e mudando o seu shape --------------------------------------------------- ``` a = np.arange(20) # a é um vetor unidimensional de 20 elementos print('a = \n', a ) a = a.reshape(4,5) # a agora é um array 4x5 (4 linhas por 5 colunas) print('a.reshape(4,5) = \n', a ) ``` Fatiamento de linhas e colunas de um array -------------------------------------------------- O operador **:** indica que todos os elementos naquela dimensão devem ser acessados. ``` print('A segunda linha do array: \n', a[1,:] ) # A segunda linha é o índice 1 print(' A primeira coluna do array: \n', a[:,0] ) # A primeira coluna corresponde ao índice 0 ``` Fatiamento de elementos específicos de um array ------------------------------------------------------ ``` print('Acessando as linhas do array de 2 em 2 começando pelo índice 0: \n', a[0::2,:] ) print(' Acessando as linhas e colunas do array de 2 em 2 começando \ pela linha 0 e coluna 1: \n', a[0::2,1::2] ) ``` Fatiamento com índices invertidos -------------------------------------- ``` b = a[-1:-3:-1,:] print('Acesso as duas últimas linhas do array em ordem reversa, \ b = a[-1:-3:-1,:] = \n',a[-1:-3:-1,:] ) print('Acesso elemento na última linha e coluna do array, a[-1,-1] =', a[-1,-1] ) c = a[::-1,:] print('Invertendo a ordem das linhas do array: c = a[::-1,:] = \n', a[::-1,:] ) ``` Copiando variáveis *ndarray* ================= O *ndarray* foi projetado para acesso otimizado a uma grande quantidade de dados. Neste sentido, os conceitos descritos a seguir sobre as três formas de cópias entre variáveis ditas sem cópia, cópia rasa (*shallow*) e cópia profunda (*deep*) são fundamentais para uma codificação eficiente. Podemos dizer que um *ndarray* possui o cabeçalho que contém dados pelas informações sobre o tipo do elemento, a dimensionalidade (*shape*) e passo ou deslocamento para o próximo elemento (*strides*) e os dados raster em si. A tabela a seguir mostra a situação do cabeçalho e dos dados nos três tipos de cópias. |Tipo | Cabeçalho:Type,Shape,Strides|Dados raster | Exemplo | |---------------------|-----------------------------|------------------|------------| |Sem cópia, apenas ref| apontador original |apontador original| a = b | |Cópia rasa | novo |apontador original|b=a.reshape | | | | |slicing, a.T| |Cópia profunda | novo |novo |a = b.copy()| Sem cópia explícita, apenas referência ====================================== No caso abaixo, usaremos o comando normal de igual como atribuição do array *a* para o array *b*. Verifica-se que tanto o shape como os dados de *b* são os mesmos de *a*. Tudo se passa como *b* fosse apenas um apontador para *a*. Qualquer modificação em *b* é refletida em *a*. ``` a = np.arange(6) b = a print("a =\n",a ) print("b =\n",b ) b.shape = (2,3) # mudança no shape de b, print("\na shape =",a.shape ) # altera o shape de a b[0,0] = -1 # mudança no conteúdo de b print("a =\n",a ) # altera o conteudo de a print("\nid de a = ",id(a) ) # id é um identificador único de objeto print("id de b = ",id(b) ) # a e b possuem o mesmo id print('np.may_share_memory(a,b):',np.may_share_memory(a,b) ) ``` Observe que mesmo no retorno de uma função, a cópia explícita pode não acontecer. Veja o exemplo a seguir de uma função que apenas retorna a variável de entrada: ``` def cc(a): return a b = cc(a) print("id de a = ",id(a) ) print("id de b = ",id(b) ) print('np.may_share_memory(a,b):',np.may_share_memory(a,b) ) ``` Cópia rasa ========== A cópia rasa é muito útil e extensivamente utilizada. É usada quando se quer indexar o array original através da mudança de dimensionalidade ou do refatiamento, porém sem a necessidade de realizar uma cópia dos dados raster. Desta forma consegue-se uma otimização no acesso ao array n-dimensional. Existem várias formas onde a cópia rasa acontece, sendo as principais: 1) no caso do *reshape* onde o número de elementos do *ndarray* é o mesmo, porém sua dimensionalidade é alterada; 2) no caso de fatiamento onde um subarray é indexado; 3) no caso de transposição do array; 4) no caso de linearização do raster através do *ravel()*. entre outros. Reshape ------- O exemplo a seguir mostra inicialmente a criação de um vetor unidimensional sequencial sendo "visto" de forma bidimensional ou tridimensional. ``` a = np.arange(30) print("a =\n", a ) b = a.reshape( (5, 6)) print("b =\n", b ) b[:, 0] = -1 print("a =\n", a ) c = a.reshape( (2, 3, 5) ) print("c =\n", c ) print('c.base is a:',c.base is a ) print('np.may_share_memory(a,c):',np.may_share_memory(a,c) ) ``` Slice - Fatiamento ------------------ O exemplo a seguir mostra a cópia rasa no uso de fatiamento. No exemplo, todos os elementos de linhas e colunas pares são modificados para 1. CUIDADO: quando é feita a atribuição de b = 1., é importante que b seja referenciado como ndarray na forma b[:,:], caso contrário, se fizermos b = 1., uma nova variável é criada. ``` a = np.zeros( (5, 6)) print('%s %s %s %s %s' % (type(a), np.shape(a), a.dtype, a.min(), a.max()) ) b = a[::2,::2] print('%s %s %s %s %s' % (type(b), np.shape(b), b.dtype, b.min(), b.max()) ) b[:,:] = 1. print('b=\n', b ) print('a=\n', a ) print('b.base is a:',b.base is a ) print('np.may_share_memory(a,b):',np.may_share_memory(a,b) ) ``` Este outro exemplo é uma forma atraente de processar uma coluna de uma matriz bidimensional, porém é preciso CUIDADO, pois o uso de b deve ser com b[:] se for atribuído um novo valor para ele, caso contrário, se fizermos b = arange(5), uma nova variável é criada. ``` a = np.arange(25).reshape((5,5)) print('a=\n',a ) b = a[:,0] print('b=',b ) b[:] = np.arange(5) print('b=',b ) print('a=\n',a ) ``` Transposto ---------- A operação matricial de transposição que troca linhas por colunas produz também um *view* da imagem, sem necessidade de cópia: ``` a = np.arange(24).reshape((4,6)) print('a:\n',a ) print('a.T:\n',a.T ) print('np.may_share_memory(a,a.T):',np.may_share_memory(a,a.T) ) ``` Ravel ------- Aplicando-se o método *ravel()* a um *ndarray*, gera-se um *view* do raster linearizado (i.e. uma única dimensão) do *ndarray*. ``` a = np.arange(24).reshape((4,6)) print('a:\n',a ) av = a.ravel() print('av.shape:',av.shape ) print('av:\n',av ) print('np.may_share_memory(a,av):',np.may_share_memory(a,av) ) ``` Cópia profunda ============== Cria uma copia completa do array, do seu shape e conteúdo. A recomendação é utilizar a função *copy()* para realizar a copia profunda, entretanto é possível conseguir a copia profunda pelo *np.array*. ``` b = a.copy() c = np.array(a, copy=True) print("id de a = ",id(a) ) print("id de b = ",id(b) ) print("id de c = ",id(c) ) ``` Operações matriciais ==================== Uma das principais vantagens da estrutura *ndarray* é sua habilidade de processamento matricial. Assim, para se multiplicar todos os elementos de um array por um escalar basta escrever *a * 5* por exemplo. Para se fazer qualquer operação lógica ou aritmética entre arrays, basta escrever *a <oper> b*: ``` a = np.arange(20).reshape(5,4) b = 2 * np.ones((5,4)) c = np.arange(12,0,-1).reshape(4,3) print('a=\n', a ) print('b=\n', b ) print('c=\n', c ) ``` Multiplicação de array por escalar: *b x 5* -------------------------------------------------- ``` b5 = 5 * b print('b5=\n', b5 ) ``` Soma de arrays: *a + b* --------------------------- ``` amb = a + b print('amb=\n', amb ) ``` Transposta de uma matriz: *a.T* ----------------------------------- A transposta de uma matriz, troca os eixos das coordenadas. O elemento que estava na posição *(r,c)* vai agora estar na posição *(c,r)*. O shape da matriz resultante ficará portanto com os valores trocados. A operação de transposição é feita através de cópia rasa, portanto é uma operação muito eficiente e deve ser utilizada sempre que possível. Veja o exemplo a seguir: ``` at = a.T print('a.shape=',a.shape ) print('a.T.shape=',a.T.shape ) print('a=\n', a ) print('at=\n', at ) ``` Multiplicação de matrizes: *a x c* ------------------------------------ A multiplicação de matrizes é feita através do operador *dot*. Para que a multiplicação seja possível é importante que o número de colunas do primeiro *ndarray* seja igual ao número de linhas do segundo. As dimensões do resultado será o número de linhas do primeiro *ndarray* pelo número de colunas do segundo *ndarray*. Confira: ``` ac = a.dot(c) print('a.shape:',a.shape ) print('c.shape:',c.shape ) print('a=\n',a ) print('c=\n',c ) print('ac=\n', ac ) print('ac.shape:',ac.shape ) ``` Linspace e Arange ================== As funções do numpy **linspace** e **arange** tem o mesmo objetivo: gerar numpy.arrays linearmente espaçados em um intervalo indicado como parâmetro. A diferença primordial entre essas funções é como será realizada a divisão no intervalo especificado. Na função linspace essa divisão é feita através da definição do intervalo fechado [inicio,fim], isto é, contém o início e o fim, e da quantidade de elementos que o numpy.array final terá. O passo portanto é calculado como (fim - inicio)/(n - 1). Dessa forma, se queremos gerar um numpy.array entre 0 e 1 com 10 elementos, utilizaremos o linspace da seguinte forma ``` # gera um numpy.array de 10 elementos, linearmente espaçados entre 0 a 1 print(np.linspace(0, 1.0, num=10).round(2) ) ``` Já na função arange, define-se o intervalo semi-aberto [inicio,fim) e o passo que será dado entre um elemento e outro. Dessa forma, para gerar um numpy.array entre 0 e 1 com 10 elementos, temos que calcular o passo (0.1) e passar esse passo como parâmetro. ``` # gera um numpy.array linearmente espaçados entre 0 a 1 com passo 0.1 print(np.arange(0, 1.0, 0.1) ) ``` Confirme que a principal diferença entre os dois que pode ser verificada nos exemplos acima é que no linspace o limite superior da distribuição é inclusivo (intervalo fechado), enquanto no arange isso não ocorre (intervalo semi-aberto). Funções indices e meshgrid ================================= As funções *indices* e *meshgrid* são extremamente úteis na geração de imagens sintéticas e o seu aprendizado permite também entender as vantagens de programação matricial, evitando-se a varredura seqüencial da imagem muito usual na programação na linguagem C. Operador indices em pequenos exemplos numéricos =============================================== A função *indices* recebe como parâmetros uma tupla com as dimensões (H,W) das matrizes a serem criadas. No exemplo a seguir, estamos gerando matrizes de 5 linhas e 10 colunas. Esta função retorna uma tupla de duas matrizes que podem ser obtidas fazendo suas atribuições como no exemplo a seguir onde criamos as matrizes *r* e *c*, ambas de tamanho (5,10), isto é, 5 linhas e 10 colunas: ``` r,c = np.indices( (5, 10) ) print('r=\n', r ) print('c=\n', c ) ``` Note que a matriz *r* é uma matriz onde cada elemento é a sua coordenada linha e a matriz *c* é uma matriz onde cada elemento é a sua coordenada coluna. Desta forma, qualquer operação matricial feita com *r* e *c*, na realidade você está processando as coordenadas da matriz. Assim, é possível gerar diversas imagens sintéticas a partir de uma função de suas coordenadas. Como o NumPy processa as matrizes diretamente, sem a necessidade de fazer um *for* explícito, a notação do programa fica bem simples e a eficiência também. O único inconveniente é o uso da memória para se calcular as matrizes de índices *r* e *c*. Iremos ver mais à frente que isto pode ser minimizado. Por exemplo seja a função que seja a soma de suas coordenadas $f(r,c) = r + c$: ``` f = r + c print('f=\n', f ) ``` Ou ainda a função diferença entre a coordenada linha e coluna $f(r,c) = r - c$: ``` f = r - c print('f=\n', f ) ``` Ou ainda a função $f(r,c) = (r + c) \% 2$ onde % é operador módulo. Esta função retorna 1 se a soma das coordenadas for ímpar e 0 caso contrário. É uma imagem no estilo de um tabuleiro de xadrez de valores 0 e 1: ``` f = (r + c) % 2 print('f=\n', f ) ``` Ou ainda a função de uma reta $f(r,c) = (r = \frac{1}{2}c)$: ``` f = (r == c//2) print('f=\n', f ) ``` Ou ainda a função parabólica dada pela soma do quadrado de suas coordenadas $f(r,c) = r^2 + c^2$: ``` f = r**2 + c**2 print('f=\n', f ) ``` Ou ainda a função do círculo de raio 4, com centro em (0,0) $f(r,c) = (r^2 + c^2 < 4^2)$: ``` f = ((r**2 + c**2) < 4**2) print('f=\n', f * 1 ) ``` Operador indices em exemplo de imagens sintéticas ================================================= Vejamos os exemplos acima, porém gerados em imagens. A diferença será no tamanho da matriz, iremos utilizar matriz (200,300), e a forma de visualizá-la através do *adshow*, ao invés de imprimir os valores como fizemos acima. Gerando as coordenadas utilizando *indices*: Observe que o parâmetro de *indices* é uma tupla. Verifique o número de parêntesis utilizados: ``` # Diretiva para mostrar gráficos inline no notebook %matplotlib inline import matplotlib.pylab as plt r,c = np.indices( (200, 300) ) plt.subplot(121) plt.imshow(r,cmap = 'gray') plt.title("linhas") plt.axis('off') plt.subplot(122) plt.imshow(c,cmap = 'gray') plt.axis('off') plt.title("colunas"); ``` Soma ---- Função soma: $f(r,c) = r + c$: ``` f = r + c plt.imshow(f,cmap = 'gray') plt.title("r+c") plt.axis("off") ``` Subtração --------- Função subtração $f(r,c) = r - c$: ``` f = r - c plt.imshow(f,cmap = 'gray') plt.title("r-c") plt.axis("off") ``` Xadrez ------ Função xadrez $f(r,c) = \frac{(r + c)}{8} \% 2$. Aqui foi feita a divisão por 8 para que o tamanho das casas do xadrez fique 8 x 8, caso contrário é muito difícil de visualizar o efeito xadrez pois a imagem possui muitos pixels.: ``` f = (r//8 + c//8) % 2 plt.imshow(f,cmap = 'gray') plt.title("(r+c)%2") plt.axis("off") ``` Reta ---- Ou ainda a função de uma reta $f(r,c) = (r = \frac{1}{2} c)$: ``` f = (r == c//2) plt.imshow(f,cmap = 'gray') plt.title('r == c//2') plt.axis("off") ``` Parábola -------- Função parabólica: $f(r,c) = r^2 + c^2$: ``` f = r**2 + c**2 plt.imshow(f,cmap = 'gray') plt.title('r**2 + c**2') plt.axis("off") ``` Círculo ------- Função do círculo de raio 190, $f(r,c) = (r^2 + c^2 < 190^2)$: ``` f = (((r-100)**2 + (c-100)**2) < 19**2) plt.imshow(f,cmap = 'gray') plt.title('((r-100)**2 + (c-100)**2) < 19**2') plt.axis("off") ``` Meshgrid ======== A função *meshgrid* é semelhante à função *indices* visto anteriormente, porém, enquanto *indices* gera as coordenadas inteiras não negativas a partir de um *shape(H,W)*, o *meshgrid* gera os valores das matrizes a partir de dois vetores de valores reais quaisquer, um para as linhas e outro para as colunas. Veja a seguir um pequeno exemplo numérico. Para que o *meshgrid* fique compatível com a nossa convenção de (linhas,colunas), deve-se usar o parâmetro *indexing='ij'*. ``` import numpy as np r, c = np.meshgrid( np.array([-1.5, -1.0, -0.5, 0.0, 0.5]), np.array([-20, -10, 0, 10, 20, 30]), indexing='ij') print('r=\n',r ) print('c=\n',c ) ``` Gerando os vetores com linspace ================================ A função *linspace* gera vetor em ponto flutuante recebendo os parâmetro de valor inicial, valor final e número de pontos do vetor. Desta forma ele é bastante usado para gerar os parâmetro para o *meshgrid*. Repetindo os mesmos valores do exemplo anterior, porém usando *linspace*. Observe que o primeiro vetor possui 5 pontos, começando com valor -1.5 e o valor final é 0.5 (inclusive). O segundo vetor possui 6 pontos, começando de -20 até 30: ``` rows = np.linspace(-1.5, 0.5, 5) cols = np.linspace(-20, 30, 6) print('rows:', rows ) print('cols:', cols ) ``` Usando os dois vetores gerados pelo *linspace* no *meshgrid*: ``` r, c = np.meshgrid(rows, cols, indexing='ij') print('r = \n', r ) print('c = \n', c ) ``` Podemos agora gerar uma matriz ou imagem que seja função destes valores. Por exemplo ser o produto deles: ``` f = r * c print('f=\n', f ) ``` Exemplo na geração da imagem sinc com meshgrid ============================================== Neste exemplo, geramos a imagem da função $sinc(r,c)$ em duas dimensões, nos intervalos na vertical, de -5 a 5 e na horizontal de -6 a 6. A função sinc é uma função trigonométrica que pode ser utilizada para filtragens. A equação é dada por: $$ sinc(r,c) = \frac{\sin(r^2 + c^2)}{r^2 + c^2}, \text{para\ } -5 \leq r \leq 5, -6 \leq c \leq 6 $$ Na origem, tanto r como c são zeros, resultando uma divisão por zero. Entretanto pela teoria dos limites, $\frac{sin(x)}{x}$ é igual a 1 quando $x$ é igual a zero. Uma forma de se obter isto em ponto flutuante é somar tanto no numerador como no denominador um *epsilon*, que é a menor valor em ponto flutuante. Epsilon pode ser obtido pela função *np.spacing*. ``` e = np.spacing(1) # epsilon to avoid 0/0 rows = np.linspace(-5.0, 5.0, 150) # coordenadas das linhas cols = np.linspace(-6.0, 6.0, 180) # coordenadas das colunas r, c = np.meshgrid(rows, cols, indexing='ij') # Grid de coordenadas estilo numpy z = np.sin(r**2 + c**2 + e) / (r**2 + c**2 + e) # epsilon is added to avoid 0/0 plt.imshow(z,cmap = 'gray') plt.title('Função sinc: sen(r² + c²)/(r²+c²) em duas dimensões') plt.axis("off") ``` Exemplo na geração da imagem sinc com indices ============================================== Outra forma de gerar a mesma imagem, usando a função *indices* é processar os indices de modo a gerar os mesmos valores relativos à grade de espaçamento regular acima, conforme ilustrado abaixo: ``` n_rows = len(rows) n_cols = len(cols) r,c = np.indices((n_rows,n_cols)) r = -5. + 10.*r.astype(float)/(n_rows-1) c = -6. + 12.*c.astype(float)/(n_cols-1) zi = np.sin(r**2 + c**2 + e) / (r**2 + c**2 + e) # epsilon is addes to avoid 0/0 plt.imshow(zi,cmap = 'gray') plt.title('Função sinc: sin(r² + c²)/(r²+c²) em duas dimensões') plt.axis("off") ``` Verificando que as duas funções são iguais: ``` print('Máxima diferença entre z e zi?', abs(z - zi).max() ) ``` Para usuários avançados ======================== Na realidade a função *indices* retorna um único array n-dimensional com uma dimensão a mais que o indicado pelo shape usado como parâmetro. Assim, quando é feito *r,c = np.indices((rows,cols))*, r é atribuído para o elemento 0 e c é atribuído para o elemento 1 do ndarray. No caso do *meshgrid*, ele retorna tantos arrays quanto forem o número de vetores passados como parâmetro para *meshgrid*. Tile ================== Uma função importante da biblioteca numpy é a tile, que gera repetições do array passado com parâmetro. A quantidade de repetições é dada pelo parâmetro reps Exemplo unidimensional - replicando as colunas ==================================================== ``` a = np.array([0, 1, 2]) print('a = \n', a ) print() print('Resultado da operação np.tile(a,2): \n',np.tile(a,2) ) ``` Exemplo unidimensional - replicando as linhas ==================================================== Para modificar as dimensões na quais a replicação será realizada modifica-se o parâmetro reps, passando ao invés de um int, uma tupla com as dimensões que se deseja alterar ``` a = np.array([0, 1, 2]) print('a = \n', a ) print() print('Resultado da operação np.tile(a,(2,1)): \n',np.tile(a,(2,1)) ) ``` Exemplo bidimensional - replicando as colunas ================================================== ``` a = np.arange(4).reshape(2,2) print('a = \n', a ) print() print('Resultado da operação np.tile(a,2): \n',np.tile(a,2) ) ``` Exemplo bidimensional - replicando as linhas ================================================== ``` a = np.arange(4).reshape(2,2) print('a = \n', a ) print() print('Resultado da operação np.tile(a,(3,1)): \n',np.tile(a,(3,1)) ) ``` Exemplo bidimensional - replicando as linhas e colunas simultaneamente ============================================================= ``` a = np.arange(4).reshape(2,2) print('a = \n', a ) print() print('Resultado da operação np.tile(a,(2,2)): \n',np.tile(a,(2,2)) ) ``` Resize ======= A função *np.resize* recebe um array *a* e retorna um array com o shape desejado. Caso o novo array seja maior que o array original o novo array é preenchido com cópias de *a*. ``` a = np.array([[0,1],[2,3]]) print('a = \n', a ) print() print('np.resize(a,(1,7)) = \n', np.resize(a,(1,7)) ) print() print('np.resize(a,(2,5)) = \n', np.resize(a,(2,5)) ) ``` Clip ====== A função clip substitui os valores de um array que estejam abaixo de um limiar mínimo ou que estejam acima de um limiar máximo, por esses limiares mínimo e máximo, respectivamente. Esta função é especialmente útil em processamento de imagens para evitar que os índices ultrapassem os limites das imagens. Exemplos ======== ``` a = np.array([11,1,2,3,4,5,12,-3,-4,7,4]) print('a = ',a ) print('np.clip(a,0,10) = ', np.clip(a,0,10) ) ``` Exemplo com ponto flutuante ============================= Observe que se os parâmetros do clip estiverem em ponto flutuante, o resultado também será em ponto flutuante: ``` a = np.arange(10).astype(np.int) print('a=',a ) print('np.clip(a,2.5,7.5)=',np.clip(a,2.5,7.5) ) ``` Formatando arrays para impressão ================================= Imprimindo arrays de ponto flutuante ======================================= Ao se imprimir arrays com valores em ponto flutuante, o NumPy em geral, imprime o array com muitas as casas decimais e com notação científica, o que dificulta a visualização. ``` A = np.exp(np.linspace(0.1,10,32)).reshape(4,8)/3000. print('A: \n', A ) ``` É possível diminuir o número de casas decimais e suprimir a notação exponencial utilizando a função **set_printoption** do numpy: ``` np.set_printoptions(suppress=True, precision=3) print('A: \n', A ) ``` Imprimindo arrays binários ============================ Array booleanos são impressos com as palavras **True** e **False**, como no exemplo a seguir: ``` A = np.random.rand(5,10) > 0.5 print('A = \n', A ) ``` Para facilitar a visualização destes arrays, é possível converter os valores para inteiros utilizando o método **astype(int)**: ``` print ('A = \n', A.astype(int)) ```
github_jupyter
## Introduction to AWS ParallelCluster For an overview of this workshop, please read [README.md](README.md) This notebook shows the main steps to create a ParallelCluster. Steps to prepare (pre and post cluster creation) for the ParallelCluster are coded in pcluster-athena.py. #### Before: - Create ssh key - Create or use existing default VPC - Create an S3 bucket for config, post install, sbatch, Athena++ initial condition files - Create or use exsiting MySQL RDS database for Slurm accounting - Update VPC security group to allow traffic to MySQL RDS - Create a secret for RDS in AWS Secret Manager - Upload post install script to S3 - Fill the ParallelCluster config template with values of region, VPC_ID, SUBNET_ID, KEY_NAME, POST_INSTALLSCRIPT_LOCATION and POST_INSALL_SCRIPT_ARGS - Upload the config file to S3 #### After - Update VPC security group attached to the headnode to open port 8082 (SLURM REST port) to this notebook #### Note: The reason to break out the process into before and after is to capture the output of the cluster creation from "pcluster create" command and display the output in the notebook. ## Before you start - install nodejs in the current kernal pcluster3 requires nodejs executables. We wil linstall that in the current kernal. SageMaker Jupyter notebook comes with multiple kernals. We use "conda_python3" in this workshop. If you need to switch to another kernal, please change the kernal in the following instructions accordingly. 1. Open a terminal window from File/New/Ternimal - this will open a terminal with "sh" shell. 2. exetute ```bash``` command to switch to "bash" shell 3. execute ```conda activate python3``` 4. execute the following commands (you can cut and paste the following lines and paste into the terminal) ``` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash chmod +x ~/.nvm/nvm.sh ~/.nvm/nvm.sh bash nvm install v16.3.0 node --version ``` **After you installed nodejs in the current kernel, restart the kernal by reselecting the "conda_python3" on the top right corner of the notebook.** You should see the output of the version of node, such as "v16.9.1" after running the following cell. ``` !node --version # install the pcluster CLI #!pip3 install --upgrade pip !sudo pip3 install --upgrade aws-parallelcluster !pcluster version import boto3 import botocore import json import time import os import sys import base64 import docker import pandas as pd import importlib import project_path # path to helper methods from lib import workshop from botocore.exceptions import ClientError from IPython.display import HTML, display #sys.path.insert(0, '.') import pcluster_athena importlib.reload(pcluster_athena) # unique name of the pcluster pcluster_name = 'myPC5c' config_name = "config3.yaml" REGION="us-east-1" # default post install script include steps to compile slurm, hdf5, athena++, which could take over 25 minutes. # For a short workshop, we will pull compiled slurm, hdf5 and athena++ from an URL and shorten the cluster creation time to around 10 minutes. # default script #post_install_script_prefix = "scripts/pcluster_post_install.sh" # faster script post_install_script_prefix = "scripts/pcluster_post_install_fast.sh" # Graviton cluster - the post install script differs for the compilation of some packages. #pcluster_name = 'myPC6g' #config_name="config-c6g" #post_install_script_prefix = "scripts/pcluster_post_install-6g.sh" # create the build folder if doesn't exist already !mkdir -p build ``` ## Load the PClusterHelper module ``` # this is used during developemnt, to reload the module after a change in the module try: del sys.modules['pcluster_athena'] except: #ignore if the module is not loaded print('Module not loaded, ignore') from pcluster_athena import PClusterHelper # create the cluster - # You can rerun the rest of the notebook again with no harm. There are checks in place for existing resoources. pcluster_helper = PClusterHelper(pcluster_name, config_name, post_install_script_prefix) ``` ## Create the parallel cluster If you are using the default post install script, the process will take up to 30 minutes. The two steps that take longer than the rest are the creation of a MySQL RDS instance, and the installation of Slurm, Athena++, HDF5 libs when running the post installation script. If you are using the faster version of the script (scripts/pcluster_post_install_fast.sh), the post installation script will pull in compiled Slurm, Athena++ and HDF5, so the process will only take around 15 minutes. **Note**: If you want to see how each step is done, please use the "pcluster-athena++" notebook in the same directory. **Note**: If you are running a workshop using this notebook, you can create the MySQL RDS instance beforehand, using the CloudFormation template in this directory "db-create.yml". This will also speedup the cluster creation. ``` pcluster_helper.create_before() # can not properly capture the status output of the command line in the notebook from within the helper class. # So broke up the creation into before , create and after # this process will take up to 30 minutes - libhdf takes a long time to compile and install !pcluster create-cluster --cluster-name $pcluster_helper.pcluster_name --rollback-on-failure False --cluster-configuration build/$config_name --region $pcluster_helper.region ``` In ParallelCluster v3, the cluster creation command is run asynchronously. Use a waitier to monitor the creation process. This will take aroudn 20 minutes. While you are waiting, please check out the config file under "build" folder and post_install scripts used for cluster creation. ``` %%time cf_client = boto3.client('cloudformation') waiter = cf_client.get_waiter('stack_create_complete') try: print("Waiting for cluster creation to complete ... ") waiter.wait(StackName=pcluster_name) except botocore.exceptions.WaiterError as e: print(e) print("Cluster creation completed. ") pcluster_helper.create_after() resp=cf_client.describe_stacks(StackName=pcluster_name) outputs=resp["Stacks"][0]["Outputs"] slurm_host='' for o in outputs: if o['OutputKey'] == 'HeadNodePrivateIP': slurm_host = o['OutputValue'] print("Slurm REST endpoint is on ", slurm_host) break; ``` ## SSH onto the headnode The previous step also created an SSH key with the name "pcluster-athena-key.pem" in the notebooks/parallelcluster folder. We can use that key to ssh onto the headnode of the cluster ``` !cp -f pcluster-athena-key.pem ~/.ssh/pcluster-athena-key.pem !chmod 400 ~/.ssh/pcluster-athena-key.pem ``` Open a terminal from "File/New/Terminal and execute the following command ``` pcluster_name=$(pcluster list-clusters --region us-east-1 | jq ".clusters[0].clusterName" | tr -d '"') pcluster ssh --cluster-name $pcluster_name -i ~/.ssh/pcluster-athena-key.pem --region us-east-1 ``` After you login to the head node, you can try Slurm commands such as - sinfo - squeue ## Integrate with Slurm REST API running on the head node ![Slurmrestd_diagram](images/parallelcluster_restd_diagram.png "Slurm REST API on AWS ParallelCluster") SLURM REST is currently running on the headnode. The JWT token is stored in AWS Secret Manager from the head node. You will need that JWT token in the header of all your REST API requests. Don't forget to add secretsmanager:GetSecretValue permission to the sagemaker execution role that runs this notebook JWT token To pass it securely to this notebook, we will first create a cron job on the headnode to retrieve the token, then save it in Secrete Manager with a name "slurm_token_{cluster_name}". The default JWT token lifespan is 1800 seconds(30 mins). Run the follow script on the head-node as a cron job to update the token every 20 mins The following steps are included in the post_install_script. You DO NOT need to run it. Step 1. Add permission to the instance role for the head-node We use additional_iam_role in the pcluster configuration file to attach SecretManager read/write policy to the instance role on the cluster. Step 2. Create a script "token_refresher.sh" Assume we save the following script at /shared/token_refresher.sh ``` #!/bin/bash REGION=us-east-1 export $(/opt/slurm/bin/scontrol token -u slurm) aws secretsmanager describe-secret --secret-id slurm_token --region $REGION if [ $? -eq 0 ] then aws secretsmanager update-secret --secret-id slurm_token --secret-string "$SLURM_JWT" --region $REGION else aws secretsmanager create-secret --name slurm_token --secret-string "$SLURM_JWT" --region $REGION fi ``` Step 3. Add a file "slurm-token" in /etc/cron.d/ ``` # Run the slurm token update every 20 minues SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root */20 * * * * root /shared/token_refresher.sh ``` Step 4. Add permission to access SecretManager for this notebook Don't forget to add secretsmanager:GetSecretValue permission to the sagemaker execution role that runs this notebook ### Inspect the Slurm REST API Schema We will start by examing the Slurm REST API schema ``` import requests import json slurm_openapi_ep = 'http://'+slurm_host+':8082/openapi/v3' slurm_rest_base='http://'+slurm_host+':8082/slurm/v0.0.35' _, get_headers = pcluster_helper.update_header_token() resp_api = requests.get(slurm_openapi_ep, headers=get_headers) print(resp_api) if resp_api.status_code != 200: # This means something went wrong. print("Error" , resp_api.status_code) with open('build/slurm_api.json', 'w') as outfile: json.dump(resp_api.json(), outfile) print(json.dumps(resp_api.json(), indent=2)) ``` ### Use REST API callls to interact with ParallelCluster Then we will make direct REST API requests to retrieve the partitions in response If you get server errors, you can login to the head-node and check the system logs of "slurmrestd", which is running as a service. ``` partition_info = ["name", "nodes", "nodes_online", "total_cpus", "total_nodes"] ##### This works as well, # update header in case the token has expired _, get_headers = pcluster_helper.update_header_token() ##### call REST API directly slurm_partitions_url= slurm_rest_base+'/partitions/' partitions = pcluster_helper.get_response_as_json(slurm_partitions_url) #20.02.4 returns a dict, not an array pcluster_helper.print_table_from_dict(partition_info, partitions['partitions']) # newer slurmrest return proper array # print_table_from_json_array(partition_info, [partitions['partitions']['q1'], partitions['partitions']['q2']] ) ``` ### Submit a job **A note about using a python client generated based on the REST API schema**: The slurm_rest_api_client job submit function doesn't include the "script" parameter. We will have to use the REST API Post directly. The body of the post should be like this. ``` {"job": {"account": "test", "ntasks": 20, "name": "test18.1", "nodes": [2, 4], "current_working_directory": "/tmp/", "environment": {"PATH": "/bin:/usr/bin/:/usr/local/bin/","LD_LIBRARY_PATH": "/lib/:/lib64/:/usr/local/lib"} }, "script": "#!/bin/bash\necho it works"} ``` When the job is submitted through REST API, it will run as the user "slurm". That's what the work directory "/shared/tmp" should be owned by "slurm:slurm", which is done in the post_install script. To run Athena++, we will need to provide a input file. Without working on the cluster directly, we will need to use a "fetch and run" method, where we can pass the S3 locations of the input file and the sbatch script file to the fetch_and_run.sh script. It will fetch the sbatch script and the input file from S3 and put them in /shared/tmp, then submit the sbatch script as a slurm job. As the result, you will see two jobs running: 1. fetch_and_run script - sinfo will show that you have one compute node spawning and then running, once the script is completed, it will start the second job 2. sbatch script - sinfo will show you ### Program batch script, input and output files To share the pcluster among different users and make sure users can only access their own input and output files, we will use user's ow S3 buckets for input and output files. The job will be running on the ParallelCluster under /efs/tmp (for example) through a fatch (from the S3 bucket) and run script and the output will be stored in the same bucket under "output" path. Let's prepare the input file and the sbatch file. ``` ################## Change these # Where the batch script, input file, output files are uploaded to S3 #cluster_instance_type = 'c6gn.2xlarge' #simulation_name = "orz-512x512" cluster_instance_type = 'c5n.2xlarge' simulation_name = "orz-512x512" # for c5n.18xlarge without HyperThreading, the number of cores is 32 - change this accordingly. #num_cores_per_node = 32 #partition = "big" # for c5n.2xlarge without HyperThreading, the number of cores is 4 - change this accordingly. num_cores_per_node = 4 partition = "big" # for c5n.2xlarge wit HyperThreading, the number of cores is 4 - change this accordingly. #num_cores_per_node = 8 #partition = "q2" job_name = f"{simulation_name}-{cluster_instance_type}" # fake account_name account_name = f"dept-2d" # turn on/off EFA support in the script use_efa="NO" ################# END change # prefix in S3 my_prefix = "athena/"+job_name # template files for input and batch script input_file_ini = "config/athinput_orszag_tang.ini" batch_file_ini = "config/batch_athena_sh.ini" # actual input and batch script files input_file = "athinput_orszag_tang.input" batch_file = "batch_athena.sh" ################## Begin ################################### # Mesh/Meshblock parameters # nx1,nx2,nx3 - number of zones in x,y,z # mbx1, mbx2, mbx3 - meshblock size # nx1/mbx1 X nx2/mbx2 X nx3/mbx3 = number of meshblocks - this should be the number of cores you are running the simulation on # e.g. mesh 100 X 100 X 100 with meshsize 50 X 50 X 50 will yield 2X2X2 = 8 blocks, run this on a cluster with 8 cores # #Mesh - actual domain of the problem # 512X512X512 cells with 64x64x64 meshblock - will have 8X8X8 = 512 meshblocks - if running on 32 cores/node, will need # 512/32=16 nodes # nx1=256 nx2=256 nx3=1 #Meshblock - each meshblock size - not too big mbnx1=64 mbnx2=64 mbnx3=1 num_of_threads = 1 ################# END #################################### #Make sure the mesh is divisible by meshblock size # e.g. num_blocks = (512/64)*(512/64)*(512/64) = 8 x 8 x 8 = 512 num_blocks = (nx1/mbnx1)*(nx2/mbnx2)*(nx3/mbnx3) ### # Batch file parameters # num_nodes should be less than or equal to the max number of nodes in your cluster # num_tasks_per_node should be less than or equal to the max number of nodes in your cluster # e.g. 512 meshblocks / 32 core/node * 1 core/meshblock = 16 nodes - c5n.18xlarge num_nodes = int(num_blocks/num_cores_per_node) num_tasks_per_node = num_blocks/num_nodes/num_of_threads cpus_per_task = num_of_threads #This is where the program is installed on the cluster exe_path = "/shared/athena-public-version/bin/athena" #This is where the program is going to run on the cluster work_dir = '/shared/tmp/'+job_name ph = { '${nx1}': str(nx1), '${nx2}': str(nx2), '${nx3}': str(nx3), '${mbnx1}': str(mbnx1), '${mbnx2}': str(mbnx2), '${mbnx3}': str(mbnx3), '${num_of_threads}' : str(num_of_threads)} pcluster_helper.template_to_file(input_file_ini, 'build/'+input_file, ph) ph = {'${nodes}': str(num_nodes), '${ntasks-per-node}': str(int(num_tasks_per_node)), '${cpus-per-task}': str(cpus_per_task), '${account}': account_name, '${partition}': partition, '${job-name}': job_name, '${EXE_PATH}': exe_path, '${WORK_DIR}': work_dir, '${input-file}': input_file, '${BUCKET_NAME}': pcluster_helper.my_bucket_name, '${PREFIX}': my_prefix, '${USE_EFA}': use_efa, '${OUTPUT_FOLDER}': "output/", '${NUM_OF_THREADS}' : str(num_of_threads)} pcluster_helper.template_to_file(batch_file_ini, 'build/'+batch_file, ph) # upload to S3 for use later pcluster_helper.upload_athena_files(input_file, batch_file, my_prefix) ``` ## Submit the job using REST API ``` job_script = "#!/bin/bash\n/shared/tmp/fetch_and_run.sh {} {} {} {} {}".format(pcluster_helper.my_bucket_name, my_prefix, input_file, batch_file, job_name) slurm_job_submit_base=slurm_rest_base+'/job/submit' #in order to use Slurm REST to submit jobs, you need to have the working directory permission set to nobody:nobody. in this case /efs/tmp data = {'job':{ 'account': account_name, 'partition': partition, 'name': job_name, 'current_working_directory':'/shared/tmp/', 'environment': {"PATH": "/bin:/usr/bin/:/usr/local/bin/:/opt/slurm/bin:/opt/amazon/openmpi/bin","LD_LIBRARY_PATH": "/lib/:/lib64/:/usr/local/lib:/opt/slurm/lib:/opt/slurm/lib64"}}, 'script':job_script} ### # This job submission will generate two jobs , the job_id returned in the response is for the bash job itself. the sbatch will be the job_id+1 run subsequently. # resp_job_submit = pcluster_helper.post_response_as_json(slurm_job_submit_base, data=json.dumps(data)) print(resp_job_submit) ``` ### List recent jobs You will see one job starting ( then followed by another job ``` # get the list of all the jobs immediately after the previous step. This should return two running jobs. slurm_jobs_base=slurm_rest_base+'/jobs' jobs = pcluster_helper.get_response_as_json(slurm_jobs_base) #print(jobs) jobs_headers = [ 'job_id', 'job_state', 'account', 'batch_host', 'nodes', 'cluster', 'partition', 'current_working_directory', 'command'] # newer version of slurm #print_table_from_json_array(jobs_headers, jobs['jobs']) pcluster_helper.print_table_from_json_array(jobs_headers, jobs) ``` A low resolution simulation will run about few minutes, plus the time for the cluster to spin up. Wait till the job finishes running then move to the next sections. Example of the output : |job_id |job_state |account | batch_host | nodes | cluster |partition |current_working_directory |command | | --- | --- | --- | --- | --- | --- | --- | --- | --- | |2|COMPLETED|dept-2d|q3-dy-c5n2xlarge-1|1|mypc5c|q3|/shared/tmp/| | | 3| CONFIGURING |dept-2d|q3-dy-c5n2xlarge-1 |4 | mypc5c| q3 |/shared/tmp/orz-512x512-c5n.2xlarge|/shared/tmp/orz-512x512-c5n.2xlarge/batch_athena.sh | You can also use ```sinfo``` command on the headnode to monitor the status of your node allocations. <img src="images/sinfo.png" width='500'> ### Compute node state AWS ParallelCluster with Slurm scheduler uses Slurm's power saving pluging (see https://docs.aws.amazon.com/parallelcluster/latest/ug/multiple-queue-mode-slurm-user-guide.html). The compute nodes go through a lifecycle with idle and alloc states - POWER_SAVING (~) - POWER_UP (#) - POWER_DOWN (%) # Visualize Athena++ Simulation Results Now we are going to use the python library comes with Athena++ to read and visualize the simulation results. Simulation data was saved in s3://\<bucketname\>/athena/$job_name/output folder. Import the hdf python code that came with Athena++ and copy the data to local file system. ``` import sys import os import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import clear_output import h5py #Do this once. clone the athena++ source code , and the hdf5 python package we need is under vis/python folder if not os.path.isdir('athena-public-version'): !git clone https://github.com/PrincetonUniversity/athena-public-version else: print("Athena++ code already cloned, skip") sys.path.insert(0, 'athena-public-version/vis/python') import athena_read data_folder=job_name+'/output' output_folder = pcluster_helper.my_bucket_name+'/athena/'+data_folder if not os.path.isdir(job_name): !mkdir -p $job_name else: !rm -rf $job_name/* !aws s3 cp s3://$output_folder/ ./$data_folder/ --recursive ``` ### Display the hst data History data shows the overs all parameter changes over time. The time interval can be different from that of the hdf5 files. In OrszagTang simulations, the variables in the hst files are 'time', 'dt', 'mass', '1-mom', '2-mom', '3-mom', '1-KE', '2-KE', '3-KE', 'tot-E', '1-ME', '2-ME', '3-ME' All the variables a ``` %matplotlib inline from matplotlib import pyplot as plt import pandas as pd import numpy as np hst = athena_read.hst(data_folder+'/OrszagTang.hst') # cannot use this reliably because hst and hdf can have different number of time steps. In this case,we have the same number of steps num_timesteps = len(hst['time']) print(hst.keys()) plt.plot(hst['time'], hst['dt']) ``` ## Reading HDF5 data files The hdf5 data files contain all variables inside all meshblocks. There are some merging and calculating work to be done before we can visualizing the result. Fortunately ,Athena++ vis/hdf package takes care of the hard part. ``` # Let's example the content of the hdf files f = h5py.File(data_folder+'/OrszagTang.out2.00001.athdf', 'r') # variable lists <KeysViewHDF5 ['B', 'Levels', 'LogicalLocations', 'prim', 'x1f', 'x1v', 'x2f', 'x2v', 'x3f', 'x3v']> print(f.keys()) #<HDF5 dataset "B": shape (3, 512, 64, 64, 64), type "<f4"> print(f['prim']) ``` ### Simulation result data Raw athdf data has the following keys <KeysViewHDF5 ['B', 'Levels', 'LogicalLocations', 'prim', 'x1f', 'x1v', 'x2f', 'x2v', 'x3f', 'x3v']> After athena_read.athdf() call, the result contains keys, which can be used as the field name ['Coordinates', 'DatasetNames', 'MaxLevel', 'MeshBlockSize', 'NumCycles', 'NumMeshBlocks', 'NumVariables', 'RootGridSize', 'RootGridX1', 'RootGridX2', 'RootGridX3', 'Time', 'VariableNames', 'x1f', 'x1v', 'x2f', 'x2v', 'x3f', 'x3v', 'rho', 'press', 'vel1', 'vel2', 'vel3', 'Bcc1', 'Bcc2', 'Bcc3'] ``` def process_athdf(filename, num_step): print("Processing ", filename) athdf = athena_read.athdf(filename) return athdf # extract list of fields and take a slice in one dimension, dimension can be 'x', 'y', 'z' def read_all_timestep (data_file_name_template, num_steps, field_names, slice_number, dimension): if not dimension in ['x', 'y', 'z']: print("dimension can only be 'x/y/z'") return # would ideally process all time steps together and store themn in memory. However, they are too big, will have to trade time for memory result = {} for f in field_names: result[f] = list() for i in range(num_steps): fn = data_file_name_template.format(str(i).zfill(5)) athdf = process_athdf(fn, i) for f in field_names: if dimension == 'x': result[f].append(athdf[f][slice_number,:,:]) elif dimension == 'y': result[f].append(athdf[f][:, slice_number,:]) else: result[f].append(athdf[f][:,:, slice_number]) return result def animate_slice(data): plt.figure() for i in range(len(data)): plt.imshow(data[i]) plt.title('Frame %d' % i) plt.show() plt.pause(0.2) clear_output(wait=True) data_file_name_template = data_folder+'/OrszagTang.out2.{}.athdf' # this is time consuming, try do it once data = read_all_timestep(data_file_name_template, num_timesteps, ['press', 'rho'], 0, 'x') # Cycle through the time steps and look at pressure animate_slice(data['press']) # Now look at density animate_slice(data['rho']) ``` # Don't forget to clean up 1. Delete the ParallelCluster 2. Delete the RDS 3. S3 bucket 4. Secrets used in this excercise Deleting VPC is risky, I will leave it out for you to manually clean it up if you created a new VPC. ``` # this is used during developemnt, to reload the module after a change in the module try: del sys.modules['pcluster_athena'] except: #ignore if the module is not loaded print('Module not loaded, ignore') from pcluster_athena import PClusterHelper importlib.reload(workshop) #from pcluster_athena import PClusterHelper # create the cluster - # You can rerun the rest of the notebook again with no harm. There are checks in place for existing resoources. pcluster_helper = PClusterHelper(pcluster_name, config_name, post_install_script_prefix) !pcluster delete-cluster --cluster-name $pcluster_helper.pcluster_name --region $REGION keep_key = True pcluster_helper.cleanup_after(KeepRDS=True,KeepSSHKey=keep_key) if not keep_key: !rm pcluster-athena-key.pem !rm -rf ~/.ssh/pcluster-athena-key.pem ```
github_jupyter
<img src="../../../../../images/qiskit_header.png" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" align="middle"> # _*Qiskit Finance: Pricing Asian Barrier Spreads*_ The latest version of this notebook is available on https://github.com/Qiskit/qiskit-tutorials. *** ### Contributors Stefan Woerner<sup>[1]</sup>, Daniel Egger<sup>[1]</sup> ### Affliation - <sup>[1]</sup>IBMQ ### Introduction <br> An Asian barrier spread is a combination of 3 different option types, and as such, combines multiple possible features that the Qiskit Finance option pricing framework supports:: - <a href="https://www.investopedia.com/terms/a/asianoption.asp">Asian option</a>: The payoff depends on the average price over the considered time horizon. - <a href="https://www.investopedia.com/terms/b/barrieroption.asp">Barrier Option</a>: The payoff is zero if a certain threshold is exceeded at any time within the considered time horizon. - <a href="https://www.investopedia.com/terms/b/bullspread.asp">(Bull) Spread</a>: The payoff follows a piecewise linear function (depending on the average price) starting at zero, increasing linear, staying constant. Suppose strike prices $K_1 < K_2$ and time periods $t=1,2$, with corresponding spot prices $(S_1, S_2)$ following a given multivariate distribution (e.g. generated by some stochastic process), and a barrier threshold $B>0$. The corresponding payoff function is defined as: <br> <br> $$ P(S_1, S_2) = \begin{cases} \min\left\{\max\left\{\frac{1}{2}(S_1 + S_2) - K_1, 0\right\}, K_2 - K_1\right\}, & \text{ if } S_1, S_2 \leq B \\ 0, & \text{otherwise.} \end{cases} $$ <br> In the following, a quantum algorithm based on amplitude estimation is used to estimate the expected payoff, i.e., the fair price before discounting, for the option: <br> <br> $$\mathbb{E}\left[ P(S_1, S_2) \right].$$ <br> The approximation of the objective function and a general introduction to option pricing and risk analysis on quantum computers are given in the following papers: - <a href="https://arxiv.org/abs/1806.06893">Quantum Risk Analysis. Woerner, Egger. 2018.</a> - <a href="https://arxiv.org/abs/1905.02666">Option Pricing using Quantum Computers. Stamatopoulos et al. 2019.</a> ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, BasicAer, execute from qiskit.aqua.algorithms import AmplitudeEstimation from qiskit.aqua.circuits import WeightedSumOperator, FixedValueComparator as Comparator from qiskit.aqua.components.uncertainty_problems import UnivariatePiecewiseLinearObjective as PwlObjective from qiskit.aqua.components.uncertainty_problems import MultivariateProblem from qiskit.aqua.components.uncertainty_models import MultivariateLogNormalDistribution ``` ### Uncertainty Model We construct a circuit factory to load a multivariate log-normal random distribution into a quantum state on $n$ qubits. For every dimension $j = 1,\ldots,d$, the distribution is truncated to a given interval $[low_j, high_j]$ and discretized using $2^{n_j}$ grid points, where $n_j$ denotes the number of qubits used to represent dimension $j$, i.e., $n_1+\ldots+n_d = n$. The unitary operator corresponding to the circuit factory implements the following: $$\big|0\rangle_{n} \mapsto \big|\psi\rangle_{n} = \sum_{i_1,\ldots,i_d} \sqrt{p_{i_1\ldots i_d}}\big|i_1\rangle_{n_1}\ldots\big|i_d\rangle_{n_d},$$ where $p_{i_1\ldots i_d}$ denote the probabilities corresponding to the truncated and discretized distribution and where $i_j$ is mapped to the right interval using the affine map: $$ \{0, \ldots, 2^{n_j}-1\} \ni i_j \mapsto \frac{high_j - low_j}{2^{n_j} - 1} * i_j + low_j \in [low_j, high_j].$$ For simplicity, we assume both stock prices are independent and indentically distributed. This assumption just simplifies the parametrization below and can be easily relaxed to more complex and also correlated multivariate distributions. The only important assumption for the current implementation is that the discretization grid of the different dimensions has the same step size. ``` # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = ((r - 0.5 * vol**2) * T + np.log(S)) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2/2) variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3*stddev) high = mean + 3*stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits=[num_uncertainty_qubits]*dimension low=low*np.ones(dimension) high=high*np.ones(dimension) mu=mu*np.ones(dimension) cov=sigma**2*np.eye(dimension) # construct circuit factory u = MultivariateLogNormalDistribution(num_qubits=num_qubits, low=low, high=high, mu=mu, cov=cov) # plot PDF of uncertainty model x = [ v[0] for v in u.values ] y = [ v[1] for v in u.values ] z = u.probabilities #z = map(float, z) #z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits])*1j grid_x, grid_y = np.mgrid[min(x):max(x):resolution[0], min(y):max(y):resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) fig = plt.figure(figsize=(10, 8)) ax = fig.gca(projection='3d') ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel('Spot Price $S_1$ (\$)', size=15) ax.set_ylabel('Spot Price $S_2$ (\$)', size=15) ax.set_zlabel('Probability (\%)', size=15) plt.show() ``` ### Payoff Function For simplicity, we consider the sum of the spot prices instead of their average. The result can be transformed to the average by just dividing it by 2. The payoff function equals zero as long as the sum of the spot prices $(S_1 + S_2)$ is less than the strike price $K_1$ and then increases linearly until the sum of the spot prices reaches $K_2$. Then payoff stays constant to $K_2 - K_1$ unless any of the two spot prices exceeds the barrier threshold $B$, then the payoff goes immediately down to zero. The implementation first uses a weighted sum operator to compute the sum of the spot prices into an ancilla register, and then uses a comparator, that flips an ancilla qubit from $\big|0\rangle$ to $\big|1\rangle$ if $(S_1 + S_2) \geq K_1$ and another comparator/ancilla to capture the case that $(S_1 + S_2) \geq K_2$. These ancillas are used to control the linear part of the payoff function. In addition, we add another ancilla variable for each time step and use additional comparators to check whether $S_1$, respectively $S_2$, exceed the barrier threshold $B$. The payoff function is only applied if $S_1, S_2 \leq B$. The linear part itself is approximated as follows. We exploit the fact that $\sin^2(y + \pi/4) \approx y + 1/2$ for small $|y|$. Thus, for a given approximation scaling factor $c_{approx} \in [0, 1]$ and $x \in [0, 1]$ we consider $$ \sin^2( \pi/2 * c_{approx} * ( x - 1/2 ) + \pi/4) \approx \pi/2 * c_{approx} * ( x - 1/2 ) + 1/2 $$ for small $c_{approx}$. We can easily construct an operator that acts as $$\big|x\rangle \big|0\rangle \mapsto \big|x\rangle \left( \cos(a*x+b) \big|0\rangle + \sin(a*x+b) \big|1\rangle \right),$$ using controlled Y-rotations. Eventually, we are interested in the probability of measuring $\big|1\rangle$ in the last qubit, which corresponds to $\sin^2(a*x+b)$. Together with the approximation above, this allows to approximate the values of interest. The smaller we choose $c_{approx}$, the better the approximation. However, since we are then estimating a property scaled by $c_{approx}$, the number of evaluation qubits $m$ needs to be adjusted accordingly. For more details on the approximation, we refer to: <a href="https://arxiv.org/abs/1806.06893">Quantum Risk Analysis. Woerner, Egger. 2018.</a> Since the weighted sum operator (in its current implementation) can only sum up integers, we need to map from the original ranges to the representable range to estimate the result, and reverse this mapping before interpreting the result. The mapping essentially corresponds to the affine mapping described in the context of the uncertainty model above. ``` # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] n_s = WeightedSumOperator.get_required_sum_qubits(weights) # create circuit factory agg = WeightedSumOperator(sum(num_qubits), weights) # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = (strike_price_1 - dimension*low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) mapped_strike_price_2 = (strike_price_2 - dimension*low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2]*dimension for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) conditions += [(i, Comparator(num_qubits[i], mapped_barrier[i] + 1, geq=False))] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 bull_spread_objective = PwlObjective( n_s, 0, max_value, breakpoints, slopes, offsets, f_min, f_max, c_approx ) # define overall multivariate problem asian_barrier_spread = MultivariateProblem(u, agg, bull_spread_objective, conditions=conditions) # plot exact payoff function plt.figure(figsize=(15,5)) plt.subplot(1,2,1) x = np.linspace(sum(low), sum(high)) y = (x <= 5)*np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, 'r-') plt.grid() plt.title('Payoff Function (for $S_1 = S_2$)', size=15) plt.xlabel('Sum of Spot Prices ($S_1 + S_2)$', size=15) plt.ylabel('Payoff', size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) # plot contour of payoff function with respect to both time steps, including barrier plt.subplot(1,2,2) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum(np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title('Payoff Function', size =15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel('Spot Price $S_1$', size=15) plt.ylabel('Spot Price $S_2$', size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [ np.max(v) <= barrier for v in u.values ] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print('exact expected value:\t%.4f' % exact_value) ``` ### Evaluate Expected Payoff We first verify the quantum circuit by simulating it and analyzing the resulting probability to measure the $|1\rangle$ state in the objective qubit ``` num_req_qubits = asian_barrier_spread.num_target_qubits num_req_ancillas = asian_barrier_spread.required_ancillas() q = QuantumRegister(num_req_qubits, name='q') q_a = QuantumRegister(num_req_ancillas, name='q_a') qc = QuantumCircuit(q, q_a) asian_barrier_spread.build(qc, q, q_a) print('state qubits: ', num_req_qubits) print('circuit width:', qc.width()) print('circuit depth:', qc.depth()) job = execute(qc, backend=BasicAer.get_backend('statevector_simulator')) # evaluate resulting statevector value = 0 for i, a in enumerate(job.result().get_statevector()): b = ('{0:0%sb}' % asian_barrier_spread.num_target_qubits).format(i)[-asian_barrier_spread.num_target_qubits:] prob = np.abs(a)**2 if prob > 1e-4 and b[0] == '1': value += prob # all other states should have zero probability due to ancilla qubits if i > 2**num_req_qubits: break # map value to original range mapped_value = asian_barrier_spread.value_to_estimation(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print('Exact Operator Value: %.4f' % value) print('Mapped Operator value: %.4f' % mapped_value) print('Exact Expected Payoff: %.4f' % exact_value) ``` Next we use amplitude estimation to estimate the expected payoff. Note that this can take a while since we are simulating a large number of qubits. The way we designed the operator (asian_barrier_spread) impliesthat the number of actual state qubits is significantly smaller, thus, helping to reduce the overall simulation time a bit. ``` # set number of evaluation qubits (=log(samples)) m = 3 # construct amplitude estimation ae = AmplitudeEstimation(m, asian_barrier_spread) # result = ae.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100) result = ae.run(quantum_instance=BasicAer.get_backend('statevector_simulator')) print('Exact value: \t%.4f' % exact_value) print('Estimated value:\t%.4f' % (result['estimation'] / (2**num_uncertainty_qubits - 1) * (high_ - low_))) print('Probability: \t%.4f' % result['max_probability']) # plot estimated values for "a" plt.bar(result['values'], result['probabilities'], width=0.5/len(result['probabilities'])) plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title('"a" Value', size=15) plt.ylabel('Probability', size=15) plt.ylim((0,1)) plt.grid() plt.show() # plot estimated values for option price (after re-scaling and reversing the c_approx-transformation) mapped_values = np.array(result['mapped_values']) / (2**num_uncertainty_qubits - 1) * (high_ - low_) plt.bar(mapped_values, result['probabilities'], width=1/len(result['probabilities'])) plt.plot([exact_value, exact_value], [0,1], 'r--', linewidth=2) plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title('Estimated Option Price', size=15) plt.ylabel('Probability', size=15) plt.ylim((0,1)) plt.grid() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright ```
github_jupyter
# Deep Markov Model ## Introduction We're going to build a deep probabilistic model for sequential data: the deep markov model. The particular dataset we want to model is composed of snippets of polyphonic music. Each time slice in a sequence spans a quarter note and is represented by an 88-dimensional binary vector that encodes the notes at that time step. Since music is (obviously) temporally coherent, we need a model that can represent complex time dependencies in the observed data. It would not, for example, be appropriate to consider a model in which the notes at a particular time step are independent of the notes at previous time steps. One way to do this is to build a latent variable model in which the variability and temporal structure of the observations is controlled by the dynamics of the latent variables. One particular realization of this idea is a markov model, in which we have a chain of latent variables, with each latent variable in the chain conditioned on the previous latent variable. This is a powerful approach, but if we want to represent complex data with complex (and in this case unknown) dynamics, we would like our model to be sufficiently flexible to accommodate dynamics that are potentially highly non-linear. Thus a deep markov model: we allow for the transition probabilities governing the dynamics of the latent variables as well as the the emission probabilities that govern how the observations are generated by the latent dynamics to be parameterized by (non-linear) neural networks. The specific model we're going to implement is based on the following reference: [1] `Structured Inference Networks for Nonlinear State Space Models`,<br />&nbsp;&nbsp;&nbsp;&nbsp; Rahul G. Krishnan, Uri Shalit, David Sontag Please note that while we do not assume that the reader of this tutorial has read the reference, it's definitely a good place to look for a more comprehensive discussion of the deep markov model in the context of other time series models. We've described the model, but how do we go about training it? The inference strategy we're going to use is variational inference, which requires specifying a parameterized family of distributions that can be used to approximate the posterior distribution over the latent random variables. Given the non-linearities and complex time-dependencies inherent in our model and data, we expect the exact posterior to be highly non-trivial. So we're going to need a flexible family of variational distributions if we hope to learn a good model. Happily, together PyTorch and Pyro provide all the necessary ingredients. As we will see, assembling them will be straightforward. Let's get to work. ## The Model A convenient way to describe the high-level structure of the model is with a graphical model. Here, we've rolled out the model assuming that the sequence of observations is of length three: $\{{\bf x}_1, {\bf x}_2, {\bf x}_3\}$. Mirroring the sequence of observations we also have a sequence of latent random variables: $\{{\bf z}_1, {\bf z}_2, {\bf z}_3\}$. The figure encodes the structure of the model. The corresponding joint distribution is $$p({\bf x}_{123} , {\bf z}_{123})=p({\bf x}_1|{\bf z}_1)p({\bf x}_2|{\bf z}_2)p({\bf x}_3|{\bf z}_3)p({\bf z}_1)p({\bf z}_2|{\bf z}_1)p({\bf z}_3|{\bf z}_2)$$ Conditioned on ${\bf z}_t$, each observation ${\bf x}_t$ is independent of the other observations. This can be read off from the fact that each ${\bf x}_t$ only depends on the corresponding latent ${\bf z}_t$, as indicated by the downward pointing arrows. We can also read off the markov property of the model: each latent ${\bf z}_t$, when conditioned on the previous latent ${\bf z}_{t-1}$, is independent of all previous latents $\{ {\bf z}_{t-2}, {\bf z}_{t-3}, ...\}$. This effectively says that everything one needs to know about the state of the system at time $t$ is encapsulated by the latent ${\bf z}_{t}$. We will assume that the observation likelihoods, i.e. the probability distributions $p({{\bf x}_t}|{{\bf z}_t})$ that control the observations, are given by the bernoulli distribution. This is an appropriate choice since our observations are all 0 or 1. For the probability distributions $p({\bf z}_t|{\bf z}_{t-1})$ that control the latent dynamics, we choose (conditional) gaussian distributions with diagonal covariances. This is reasonable since we assume that the latent space is continuous. The solid black squares represent non-linear functions parameterized by neural networks. This is what makes this a _deep_ markov model. Note that the black squares appear in two different places: in between pairs of latents and in between latents and observations. The non-linear function that connects the latent variables ('Trans' in Fig. 1) controls the dynamics of the latent variables. Since we allow the conditional probability distribution of ${\bf z}_{t}$ to depend on ${\bf z}_{t-1}$ in a complex way, we will be able to capture complex dynamics in our model. Similarly, the non-linear function that connects the latent variables to the observations ('Emit' in Fig. 1) controls how the observations depend on the latent dynamics. Some additional notes: - we can freely choose the dimension of the latent space to suit the problem at hand: small latent spaces for simple problems and larger latent spaces for problems with complex dynamics - note the parameter ${\bf z}_0$ in Fig. 1. as will become more apparent from the code, this is just a convenient way for us to parameterize the probability distribution $p({\bf z}_1)$ for the first time step, where there are no previous latents to condition on. ### The Gated Transition and the Emitter Without further ado, let's start writing some code. We first define the two PyTorch Modules that correspond to the black squares in Fig. 1. First the emission function: ```python class Emitter(nn.Module): """ Parameterizes the bernoulli observation likelihood p(x_t | z_t) """ def __init__(self, input_dim, z_dim, emission_dim): super().__init__() # initialize the three linear transformations used in the neural network self.lin_z_to_hidden = nn.Linear(z_dim, emission_dim) self.lin_hidden_to_hidden = nn.Linear(emission_dim, emission_dim) self.lin_hidden_to_input = nn.Linear(emission_dim, input_dim) # initialize the two non-linearities used in the neural network self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, z_t): """ Given the latent z at a particular time step t we return the vector of probabilities `ps` that parameterizes the bernoulli distribution p(x_t|z_t) """ h1 = self.relu(self.lin_z_to_hidden(z_t)) h2 = self.relu(self.lin_hidden_to_hidden(h1)) ps = self.sigmoid(self.lin_hidden_to_input(h2)) return ps ``` In the constructor we define the linear transformations that will be used in our emission function. Note that `emission_dim` is the number of hidden units in the neural network. We also define the non-linearities that we will be using. The forward call defines the computational flow of the function. We take in the latent ${\bf z}_{t}$ as input and do a sequence of transformations until we obtain a vector of length 88 that defines the emission probabilities of our bernoulli likelihood. Because of the sigmoid, each element of `ps` will be between 0 and 1 and will define a valid probability. Taken together the elements of `ps` encode which notes we expect to observe at time $t$ given the state of the system (as encoded in ${\bf z}_{t}$). Now we define the gated transition function: ```python class GatedTransition(nn.Module): """ Parameterizes the gaussian latent transition probability p(z_t | z_{t-1}) See section 5 in the reference for comparison. """ def __init__(self, z_dim, transition_dim): super().__init__() # initialize the six linear transformations used in the neural network self.lin_gate_z_to_hidden = nn.Linear(z_dim, transition_dim) self.lin_gate_hidden_to_z = nn.Linear(transition_dim, z_dim) self.lin_proposed_mean_z_to_hidden = nn.Linear(z_dim, transition_dim) self.lin_proposed_mean_hidden_to_z = nn.Linear(transition_dim, z_dim) self.lin_sig = nn.Linear(z_dim, z_dim) self.lin_z_to_loc = nn.Linear(z_dim, z_dim) # modify the default initialization of lin_z_to_loc # so that it's starts out as the identity function self.lin_z_to_loc.weight.data = torch.eye(z_dim) self.lin_z_to_loc.bias.data = torch.zeros(z_dim) # initialize the three non-linearities used in the neural network self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() self.softplus = nn.Softplus() def forward(self, z_t_1): """ Given the latent z_{t-1} corresponding to the time step t-1 we return the mean and scale vectors that parameterize the (diagonal) gaussian distribution p(z_t | z_{t-1}) """ # compute the gating function _gate = self.relu(self.lin_gate_z_to_hidden(z_t_1)) gate = self.sigmoid(self.lin_gate_hidden_to_z(_gate)) # compute the 'proposed mean' _proposed_mean = self.relu(self.lin_proposed_mean_z_to_hidden(z_t_1)) proposed_mean = self.lin_proposed_mean_hidden_to_z(_proposed_mean) # assemble the actual mean used to sample z_t, which mixes # a linear transformation of z_{t-1} with the proposed mean # modulated by the gating function loc = (1 - gate) * self.lin_z_to_loc(z_t_1) + gate * proposed_mean # compute the scale used to sample z_t, using the proposed # mean from above as input. the softplus ensures that scale is positive scale = self.softplus(self.lin_sig(self.relu(proposed_mean))) # return loc, scale which can be fed into Normal return loc, scale ``` This mirrors the structure of `Emitter` above, with the difference that the computational flow is a bit more complicated. This is for two reasons. First, the output of `GatedTransition` needs to define a valid (diagonal) gaussian distribution. So we need to output two parameters: the mean `loc`, and the (square root) covariance `scale`. These both need to have the same dimension as the latent space. Second, we don't want to _force_ the dynamics to be non-linear. Thus our mean `loc` is a sum of two terms, only one of which depends non-linearily on the input `z_t_1`. This way we can support both linear and non-linear dynamics (or indeed have the dynamics of part of the latent space be linear, while the remainder of the dynamics is non-linear). ### Model - a Pyro Stochastic Function So far everything we've done is pure PyTorch. To finish translating our model into code we need to bring Pyro into the picture. Basically we need to implement the stochastic nodes (i.e. the circles) in Fig. 1. To do this we introduce a callable `model()` that contains the Pyro primitive `pyro.sample`. The `sample` statements will be used to specify the joint distribution over the latents ${\bf z}_{1:T}$. Additionally, the `obs` argument can be used with the `sample` statements to specify how the observations ${\bf x}_{1:T}$ depend on the latents. Before we look at the complete code for `model()`, let's look at a stripped down version that contains the main logic: ```python def model(...): z_prev = self.z_0 # sample the latents z and observed x's one time step at a time for t in range(1, T_max + 1): # the next two lines of code sample z_t ~ p(z_t | z_{t-1}). # first compute the parameters of the diagonal gaussian # distribution p(z_t | z_{t-1}) z_loc, z_scale = self.trans(z_prev) # then sample z_t according to dist.Normal(z_loc, z_scale) z_t = pyro.sample("z_%d" % t, dist.Normal(z_loc, z_scale)) # compute the probabilities that parameterize the bernoulli likelihood emission_probs_t = self.emitter(z_t) # the next statement instructs pyro to observe x_t according to the # bernoulli distribution p(x_t|z_t) pyro.sample("obs_x_%d" % t, dist.Bernoulli(emission_probs_t), obs=mini_batch[:, t - 1, :]) # the latent sampled at this time step will be conditioned upon # in the next time step so keep track of it z_prev = z_t ``` The first thing we need to do is sample ${\bf z}_1$. Once we've sampled ${\bf z}_1$, we can sample ${\bf z}_2 \sim p({\bf z}_2|{\bf z}_1)$ and so on. This is the logic implemented in the `for` loop. The parameters `z_loc` and `z_scale` that define the probability distributions $p({\bf z}_t|{\bf z}_{t-1})$ are computed using `self.trans`, which is just an instance of the `GatedTransition` module defined above. For the first time step at $t=1$ we condition on `self.z_0`, which is a (trainable) `Parameter`, while for subsequent time steps we condition on the previously drawn latent. Note that each random variable `z_t` is assigned a unique name by the user. Once we've sampled ${\bf z}_t$ at a given time step, we need to observe the datapoint ${\bf x}_t$. So we pass `z_t` through `self.emitter`, an instance of the `Emitter` module defined above to obtain `emission_probs_t`. Together with the argument `dist.Bernoulli()` in the `sample` statement, these probabilities fully specify the observation likelihood. Finally, we also specify the slice of observed data ${\bf x}_t$: `mini_batch[:, t - 1, :]` using the `obs` argument to `sample`. This fully specifies our model and encapsulates it in a callable that can be passed to Pyro. Before we move on let's look at the full version of `model()` and go through some of the details we glossed over in our first pass. ```python def model(self, mini_batch, mini_batch_reversed, mini_batch_mask, mini_batch_seq_lengths, annealing_factor=1.0): # this is the number of time steps we need to process in the mini-batch T_max = mini_batch.size(1) # register all PyTorch (sub)modules with pyro # this needs to happen in both the model and guide pyro.module("dmm", self) # set z_prev = z_0 to setup the recursive conditioning in p(z_t | z_{t-1}) z_prev = self.z_0.expand(mini_batch.size(0), self.z_0.size(0)) # we enclose all the sample statements in the model in a plate. # this marks that each datapoint is conditionally independent of the others with pyro.plate("z_minibatch", len(mini_batch)): # sample the latents z and observed x's one time step at a time for t in range(1, T_max + 1): # the next chunk of code samples z_t ~ p(z_t | z_{t-1}) # note that (both here and elsewhere) we use poutine.scale to take care # of KL annealing. we use the mask() method to deal with raggedness # in the observed data (i.e. different sequences in the mini-batch # have different lengths) # first compute the parameters of the diagonal gaussian # distribution p(z_t | z_{t-1}) z_loc, z_scale = self.trans(z_prev) # then sample z_t according to dist.Normal(z_loc, z_scale). # note that we use the reshape method so that the univariate # Normal distribution is treated as a multivariate Normal # distribution with a diagonal covariance. with poutine.scale(None, annealing_factor): z_t = pyro.sample("z_%d" % t, dist.Normal(z_loc, z_scale) .mask(mini_batch_mask[:, t - 1:t]) .to_event(1)) # compute the probabilities that parameterize the bernoulli likelihood emission_probs_t = self.emitter(z_t) # the next statement instructs pyro to observe x_t according to the # bernoulli distribution p(x_t|z_t) pyro.sample("obs_x_%d" % t, dist.Bernoulli(emission_probs_t) .mask(mini_batch_mask[:, t - 1:t]) .to_event(1), obs=mini_batch[:, t - 1, :]) # the latent sampled at this time step will be conditioned upon # in the next time step so keep track of it z_prev = z_t ``` The first thing to note is that `model()` takes a number of arguments. For now let's just take a look at `mini_batch` and `mini_batch_mask`. `mini_batch` is a three dimensional tensor, with the first dimension being the batch dimension, the second dimension being the temporal dimension, and the final dimension being the features (88-dimensional in our case). To speed up the code, whenever we run `model` we're going to process an entire mini-batch of sequences (i.e. we're going to take advantage of vectorization). This is sensible because our model is implicitly defined over a single observed sequence. The probability of a set of sequences is just given by the products of the individual sequence probabilities. In other words, given the parameters of the model the sequences are conditionally independent. This vectorization introduces some complications because sequences can be of different lengths. This is where `mini_batch_mask` comes in. `mini_batch_mask` is a two dimensional 0/1 mask of dimensions `mini_batch_size` x `T_max`, where `T_max` is the maximum length of any sequence in the mini-batch. This encodes which parts of `mini_batch` are valid observations. So the first thing we do is grab `T_max`: we have to unroll our model for at least this many time steps. Note that this will result in a lot of 'wasted' computation, since some of the sequences will be shorter than `T_max`, but this is a small price to pay for the big speed-ups that come with vectorization. We just need to make sure that none of the 'wasted' computations 'pollute' our model computation. We accomplish this by passing the mask appropriate to time step $t$ to the `mask` method (which acts on the distribution that needs masking). Finally, the line `pyro.module("dmm", self)` is equivalent to a bunch of `pyro.param` statements for each parameter in the model. This lets Pyro know which parameters are part of the model. Just like for the `sample` statement, we give the module a unique name. This name will be incorporated into the name of the `Parameters` in the model. We leave a discussion of the KL annealing factor for later. ## Inference At this point we've fully specified our model. The next step is to set ourselves up for inference. As mentioned in the introduction, our inference strategy is going to be variational inference (see [SVI Part I](svi_part_i.ipynb) for an introduction). So our next task is to build a family of variational distributions appropriate to doing inference in a deep markov model. However, at this point it's worth emphasizing that nothing about the way we've implemented `model()` ties us to variational inference. In principle we could use _any_ inference strategy available in Pyro. For example, in this particular context one could imagine using some variant of Sequential Monte Carlo (although this is not currently supported in Pyro). ### Guide The purpose of the guide (i.e. the variational distribution) is to provide a (parameterized) approximation to the exact posterior $p({\bf z}_{1:T}|{\bf x}_{1:T})$. Actually, there's an implicit assumption here which we should make explicit, so let's take a step back. Suppose our dataset $\mathcal{D}$ consists of $N$ sequences $\{ {\bf x}_{1:T_1}^1, {\bf x}_{1:T_2}^2, ..., {\bf x}_{1:T_N}^N \}$. Then the posterior we're actually interested in is given by $p({\bf z}_{1:T_1}^1, {\bf z}_{1:T_2}^2, ..., {\bf z}_{1:T_N}^N | \mathcal{D})$, i.e. we want to infer the latents for _all_ $N$ sequences. Even for small $N$ this is a very high-dimensional distribution that will require a very large number of parameters to specify. In particular if we were to directly parameterize the posterior in this form, the number of parameters required would grow (at least) linearly with $N$. One way to avoid this nasty growth with the size of the dataset is *amortization* (see the analogous discussion in [SVI Part II](svi_part_ii.ipynb)). #### Aside: Amortization This works as follows. Instead of introducing variational parameters for each sequence in our dataset, we're going to learn a single parametric function $f({\bf x}_{1:T})$ and work with a variational distribution that has the form $\prod_{n=1}^N q({\bf z}_{1:T_n}^n | f({\bf x}_{1:T_n}^n))$. The function $f(\cdot)$&mdash;which basically maps a given observed sequence to a set of variational parameters tailored to that sequence&mdash;will need to be sufficiently rich to capture the posterior accurately, but now we can handle large datasets without having to introduce an obscene number of variational parameters. So our task is to construct the function $f(\cdot)$. Since in our case we need to support variable-length sequences, it's only natural that $f(\cdot)$ have a RNN in the loop. Before we look at the various component parts that make up our $f(\cdot)$ in detail, let's look at a computational graph that encodes the basic structure: <p> At the bottom of the figure we have our sequence of three observations. These observations will be consumed by a RNN that reads the observations from right to left and outputs three hidden states $\{ {\bf h}_1, {\bf h}_2,{\bf h}_3\}$. Note that this computation is done _before_ we sample any latent variables. Next, each of the hidden states will be fed into a `Combiner` module whose job is to output the mean and covariance of the the conditional distribution $q({\bf z}_t | {\bf z}_{t-1}, {\bf x}_{t:T})$, which we take to be given by a diagonal gaussian distribution. (Just like in the model, the conditional structure of ${\bf z}_{1:T}$ in the guide is such that we sample ${\bf z}_t$ forward in time.) In addition to the RNN hidden state, the `Combiner` also takes the latent random variable from the previous time step as input, except for $t=1$, where it instead takes the trainable (variational) parameter ${\bf z}_0^{\rm{q}}$. #### Aside: Guide Structure Why do we setup the RNN to consume the observations from right to left? Why not left to right? With this choice our conditional distribution $q({\bf z}_t |...)$ depends on two things: - the latent ${\bf z}_{t-1}$ from the previous time step; and - the observations ${\bf x}_{t:T}$, i.e. the current observation together with all future observations We are free to make other choices; all that is required is that that the guide is a properly normalized distribution that plays nice with autograd. This particular choice is motivated by the dependency structure of the true posterior: see reference [1] for a detailed discussion. In brief, while we could, for example, condition on the entire sequence of observations, because of the markov structure of the model everything that we need to know about the previous observations ${\bf x}_{1:t-1}$ is encapsulated by ${\bf z}_{t-1}$. We could condition on more things, but there's no need; and doing so will probably tend to dilute the learning signal. So running the RNN from right to left is the most natural choice for this particular model. Let's look at the component parts in detail. First, the `Combiner` module: ```python class Combiner(nn.Module): """ Parameterizes q(z_t | z_{t-1}, x_{t:T}), which is the basic building block of the guide (i.e. the variational distribution). The dependence on x_{t:T} is through the hidden state of the RNN (see the pytorch module `rnn` below) """ def __init__(self, z_dim, rnn_dim): super().__init__() # initialize the three linear transformations used in the neural network self.lin_z_to_hidden = nn.Linear(z_dim, rnn_dim) self.lin_hidden_to_loc = nn.Linear(rnn_dim, z_dim) self.lin_hidden_to_scale = nn.Linear(rnn_dim, z_dim) # initialize the two non-linearities used in the neural network self.tanh = nn.Tanh() self.softplus = nn.Softplus() def forward(self, z_t_1, h_rnn): """ Given the latent z at at a particular time step t-1 as well as the hidden state of the RNN h(x_{t:T}) we return the mean and scale vectors that parameterize the (diagonal) gaussian distribution q(z_t | z_{t-1}, x_{t:T}) """ # combine the rnn hidden state with a transformed version of z_t_1 h_combined = 0.5 * (self.tanh(self.lin_z_to_hidden(z_t_1)) + h_rnn) # use the combined hidden state to compute the mean used to sample z_t loc = self.lin_hidden_to_loc(h_combined) # use the combined hidden state to compute the scale used to sample z_t scale = self.softplus(self.lin_hidden_to_scale(h_combined)) # return loc, scale which can be fed into Normal return loc, scale ``` This module has the same general structure as `Emitter` and `GatedTransition` in the model. The only thing of note is that because the `Combiner` needs to consume two inputs at each time step, it transforms the inputs into a single combined hidden state `h_combined` before it computes the outputs. Apart from the RNN, we now have all the ingredients we need to construct our guide distribution. Happily, PyTorch has great built-in RNN modules, so we don't have much work to do here. We'll see where we instantiate the RNN later. Let's instead jump right into the definition of the stochastic function `guide()`. ```python def guide(self, mini_batch, mini_batch_reversed, mini_batch_mask, mini_batch_seq_lengths, annealing_factor=1.0): # this is the number of time steps we need to process in the mini-batch T_max = mini_batch.size(1) # register all PyTorch (sub)modules with pyro pyro.module("dmm", self) # if on gpu we need the fully broadcast view of the rnn initial state # to be in contiguous gpu memory h_0_contig = self.h_0.expand(1, mini_batch.size(0), self.rnn.hidden_size).contiguous() # push the observed x's through the rnn; # rnn_output contains the hidden state at each time step rnn_output, _ = self.rnn(mini_batch_reversed, h_0_contig) # reverse the time-ordering in the hidden state and un-pack it rnn_output = poly.pad_and_reverse(rnn_output, mini_batch_seq_lengths) # set z_prev = z_q_0 to setup the recursive conditioning in q(z_t |...) z_prev = self.z_q_0.expand(mini_batch.size(0), self.z_q_0.size(0)) # we enclose all the sample statements in the guide in a plate. # this marks that each datapoint is conditionally independent of the others. with pyro.plate("z_minibatch", len(mini_batch)): # sample the latents z one time step at a time for t in range(1, T_max + 1): # the next two lines assemble the distribution q(z_t | z_{t-1}, x_{t:T}) z_loc, z_scale = self.combiner(z_prev, rnn_output[:, t - 1, :]) z_dist = dist.Normal(z_loc, z_scale) # sample z_t from the distribution z_dist with pyro.poutine.scale(None, annealing_factor): z_t = pyro.sample("z_%d" % t, z_dist.mask(mini_batch_mask[:, t - 1:t]) .to_event(1)) # the latent sampled at this time step will be conditioned # upon in the next time step so keep track of it z_prev = z_t ``` The high-level structure of `guide()` is very similar to `model()`. First note that the model and guide take the same arguments: this is a general requirement for model/guide pairs in Pyro. As in the model, there's a call to `pyro.module` that registers all the parameters with Pyro. Also, the `for` loop has the same structure as the one in `model()`, with the difference that the guide only needs to sample latents (there are no `sample` statements with the `obs` keyword). Finally, note that the names of the latent variables in the guide exactly match those in the model. This is how Pyro knows to correctly align random variables. The RNN logic should be familar to PyTorch users, but let's go through it quickly. First we prepare the initial state of the RNN, `h_0`. Then we invoke the RNN via its forward call; the resulting tensor `rnn_output` contains the hidden states for the entire mini-batch. Note that because we want the RNN to consume the observations from right to left, the input to the RNN is `mini_batch_reversed`, which is a copy of `mini_batch` with all the sequences running in _reverse_ temporal order. Furthermore, `mini_batch_reversed` has been wrapped in a PyTorch `rnn.pack_padded_sequence` so that the RNN can deal with variable-length sequences. Since we do our sampling in latent space in normal temporal order, we use the helper function `pad_and_reverse` to reverse the hidden state sequences in `rnn_output`, so that we can feed the `Combiner` RNN hidden states that are correctly aligned and ordered. This helper function also unpacks the `rnn_output` so that it is no longer in the form of a PyTorch `rnn.pack_padded_sequence`. ## Packaging the Model and Guide as a PyTorch Module At this juncture, we're ready to proceed to inference. But before we do so let's quickly go over how we packaged the model and guide as a single PyTorch Module. This is generally good practice, especially for larger models. ```python class DMM(nn.Module): """ This PyTorch Module encapsulates the model as well as the variational distribution (the guide) for the Deep Markov Model """ def __init__(self, input_dim=88, z_dim=100, emission_dim=100, transition_dim=200, rnn_dim=600, rnn_dropout_rate=0.0, num_iafs=0, iaf_dim=50, use_cuda=False): super().__init__() # instantiate pytorch modules used in the model and guide below self.emitter = Emitter(input_dim, z_dim, emission_dim) self.trans = GatedTransition(z_dim, transition_dim) self.combiner = Combiner(z_dim, rnn_dim) self.rnn = nn.RNN(input_size=input_dim, hidden_size=rnn_dim, nonlinearity='relu', batch_first=True, bidirectional=False, num_layers=1, dropout=rnn_dropout_rate) # define a (trainable) parameters z_0 and z_q_0 that help define # the probability distributions p(z_1) and q(z_1) # (since for t = 1 there are no previous latents to condition on) self.z_0 = nn.Parameter(torch.zeros(z_dim)) self.z_q_0 = nn.Parameter(torch.zeros(z_dim)) # define a (trainable) parameter for the initial hidden state of the rnn self.h_0 = nn.Parameter(torch.zeros(1, 1, rnn_dim)) self.use_cuda = use_cuda # if on gpu cuda-ize all pytorch (sub)modules if use_cuda: self.cuda() # the model p(x_{1:T} | z_{1:T}) p(z_{1:T}) def model(...): # ... as above ... # the guide q(z_{1:T} | x_{1:T}) (i.e. the variational distribution) def guide(...): # ... as above ... ``` Since we've already gone over `model` and `guide`, our focus here is on the constructor. First we instantiate the four PyTorch modules that we use in our model and guide. On the model-side: `Emitter` and `GatedTransition`. On the guide-side: `Combiner` and the RNN. Next we define PyTorch `Parameter`s for the initial state of the RNN as well as `z_0` and `z_q_0`, which are fed into `self.trans` and `self.combiner`, respectively, in lieu of the non-existent random variable $\bf z_0$. The important point to make here is that all of these `Module`s and `Parameter`s are attributes of `DMM` (which itself inherits from `nn.Module`). This has the consequence they are all automatically registered as belonging to the module. So, for example, when we call `parameters()` on an instance of `DMM`, PyTorch will know to return all the relevant parameters. It also means that when we invoke `pyro.module("dmm", self)` in `model()` and `guide()`, all the parameters of both the model and guide will be registered with Pyro. Finally, it means that if we're running on a GPU, the call to `cuda()` will move all the parameters into GPU memory. ## Stochastic Variational Inference With our model and guide at hand, we're finally ready to do inference. Before we look at the full logic that is involved in a complete experimental script, let's first see how to take a single gradient step. First we instantiate an instance of `DMM` and setup an optimizer. ```python # instantiate the dmm dmm = DMM(input_dim, z_dim, emission_dim, transition_dim, rnn_dim, args.rnn_dropout_rate, args.num_iafs, args.iaf_dim, args.cuda) # setup optimizer adam_params = {"lr": args.learning_rate, "betas": (args.beta1, args.beta2), "clip_norm": args.clip_norm, "lrd": args.lr_decay, "weight_decay": args.weight_decay} optimizer = ClippedAdam(adam_params) ``` Here we're using an implementation of the Adam optimizer that includes gradient clipping. This mitigates some of the problems that can occur when training recurrent neural networks (e.g. vanishing/exploding gradients). Next we setup the inference algorithm. ```python # setup inference algorithm svi = SVI(dmm.model, dmm.guide, optimizer, Trace_ELBO()) ``` The inference algorithm `SVI` uses a stochastic gradient estimator to take gradient steps on an objective function, which in this case is given by the ELBO (the evidence lower bound). As the name indicates, the ELBO is a lower bound to the log evidence: $\log p(\mathcal{D})$. As we take gradient steps that maximize the ELBO, we move our guide $q(\cdot)$ closer to the exact posterior. The argument `Trace_ELBO()` constructs a version of the gradient estimator that doesn't need access to the dependency structure of the model and guide. Since all the latent variables in our model are reparameterizable, this is the appropriate gradient estimator for our use case. (It's also the default option.) Assuming we've prepared the various arguments of `dmm.model` and `dmm.guide`, taking a gradient step is accomplished by calling ```python svi.step(mini_batch, ...) ``` That's all there is to it! Well, not quite. This will be the main step in our inference algorithm, but we still need to implement a complete training loop with preparation of mini-batches, evaluation, and so on. This sort of logic will be familiar to any deep learner but let's see how it looks in PyTorch/Pyro. ## The Black Magic of Optimization Actually, before we get to the guts of training, let's take a moment and think a bit about the optimization problem we've setup. We've traded Bayesian inference in a non-linear model with a high-dimensional latent space&mdash;a hard problem&mdash;for a particular optimization problem. Let's not kid ourselves, this optimization problem is pretty hard too. Why? Let's go through some of the reasons: - the space of parameters we're optimizing over is very high-dimensional (it includes all the weights in all the neural networks we've defined). - our objective function (the ELBO) cannot be computed analytically. so our parameter updates will be following noisy Monte Carlo gradient estimates - data-subsampling serves as an additional source of stochasticity: even if we wanted to, we couldn't in general take gradient steps on the ELBO defined over the whole dataset (actually in our particular case the dataset isn't so large, but let's ignore that). - given all the neural networks and non-linearities we have in the loop, our (stochastic) loss surface is highly non-trivial The upshot is that if we're going to find reasonable (local) optima of the ELBO, we better take some care in deciding how to do optimization. This isn't the time or place to discuss all the different strategies that one might adopt, but it's important to emphasize how decisive a good or bad choice in learning hyperparameters (the learning rate, the mini-batch size, etc.) can be. Before we move on, let's discuss one particular optimization strategy that we're making use of in greater detail: KL annealing. In our case the ELBO is the sum of two terms: an expected log likelihood term (which measures model fit) and a sum of KL divergence terms (which serve to regularize the approximate posterior): $\rm{ELBO} = \mathbb{E}_{q({\bf z}_{1:T})}[\log p({\bf x}_{1:T}|{\bf z}_{1:T})] - \mathbb{E}_{q({\bf z}_{1:T})}[ \log q({\bf z}_{1:T}) - \log p({\bf z}_{1:T})]$ This latter term can be a quite strong regularizer, and in early stages of training it has a tendency to favor regions of the loss surface that contain lots of bad local optima. One strategy to avoid these bad local optima, which was also adopted in reference [1], is to anneal the KL divergence terms by multiplying them by a scalar `annealing_factor` that ranges between zero and one: $\mathbb{E}_{q({\bf z}_{1:T})}[\log p({\bf x}_{1:T}|{\bf z}_{1:T})] - \rm{annealing\_factor} \times \mathbb{E}_{q({\bf z}_{1:T})}[ \log q({\bf z}_{1:T}) - \log p({\bf z}_{1:T})]$ The idea is that during the course of training the `annealing_factor` rises slowly from its initial value at/near zero to its final value at 1.0. The annealing schedule is arbitrary; below we will use a simple linear schedule. In terms of code, to scale the log likelihoods by the appropriate annealing factor we enclose each of the latent sample statements in the model and guide with a `pyro.poutine.scale` context. Finally, we should mention that the main difference between the DMM implementation described here and the one used in reference [1] is that they take advantage of the analytic formula for the KL divergence between two gaussian distributions (whereas we rely on Monte Carlo estimates). This leads to lower variance gradient estimates of the ELBO, which makes training a bit easier. We can still train the model without making this analytic substitution, but training probably takes somewhat longer because of the higher variance. To use analytic KL divergences use [TraceMeanField_ELBO](http://docs.pyro.ai/en/stable/inference_algos.html#pyro.infer.trace_mean_field_elbo.TraceMeanField_ELBO). ## Data Loading, Training, and Evaluation First we load the data. There are 229 sequences in the training dataset, each with an average length of ~60 time steps. ```python jsb_file_loc = "./data/jsb_processed.pkl" data = pickle.load(open(jsb_file_loc, "rb")) training_seq_lengths = data['train']['sequence_lengths'] training_data_sequences = data['train']['sequences'] test_seq_lengths = data['test']['sequence_lengths'] test_data_sequences = data['test']['sequences'] val_seq_lengths = data['valid']['sequence_lengths'] val_data_sequences = data['valid']['sequences'] N_train_data = len(training_seq_lengths) N_train_time_slices = np.sum(training_seq_lengths) N_mini_batches = int(N_train_data / args.mini_batch_size + int(N_train_data % args.mini_batch_size > 0)) ``` For this dataset we will typically use a `mini_batch_size` of 20, so that there will be 12 mini-batches per epoch. Next we define the function `process_minibatch` which prepares a mini-batch for training and takes a gradient step: ```python def process_minibatch(epoch, which_mini_batch, shuffled_indices): if args.annealing_epochs > 0 and epoch < args.annealing_epochs: # compute the KL annealing factor appropriate # for the current mini-batch in the current epoch min_af = args.minimum_annealing_factor annealing_factor = min_af + (1.0 - min_af) * \ (float(which_mini_batch + epoch * N_mini_batches + 1) / float(args.annealing_epochs * N_mini_batches)) else: # by default the KL annealing factor is unity annealing_factor = 1.0 # compute which sequences in the training set we should grab mini_batch_start = (which_mini_batch * args.mini_batch_size) mini_batch_end = np.min([(which_mini_batch + 1) * args.mini_batch_size, N_train_data]) mini_batch_indices = shuffled_indices[mini_batch_start:mini_batch_end] # grab the fully prepped mini-batch using the helper function in the data loader mini_batch, mini_batch_reversed, mini_batch_mask, mini_batch_seq_lengths \ = poly.get_mini_batch(mini_batch_indices, training_data_sequences, training_seq_lengths, cuda=args.cuda) # do an actual gradient step loss = svi.step(mini_batch, mini_batch_reversed, mini_batch_mask, mini_batch_seq_lengths, annealing_factor) # keep track of the training loss return loss ``` We first compute the KL annealing factor appropriate to the mini-batch (according to a linear schedule as described earlier). We then compute the mini-batch indices, which we pass to the helper function `get_mini_batch`. This helper function takes care of a number of different things: - it sorts each mini-batch by sequence length - it calls another helper function to get a copy of the mini-batch in reversed temporal order - it packs each reversed mini-batch in a `rnn.pack_padded_sequence`, which is then ready to be ingested by the RNN - it cuda-izes all tensors if we're on a GPU - it calls another helper function to get an appropriate 0/1 mask for the mini-batch We then pipe all the return values of `get_mini_batch()` into `elbo.step(...)`. Recall that these arguments will be further piped to `model(...)` and `guide(...)` during construction of the gradient estimator in `elbo`. Finally, we return a float which is a noisy estimate of the loss for that mini-batch. We now have all the ingredients required for the main bit of our training loop: ```python times = [time.time()] for epoch in range(args.num_epochs): # accumulator for our estimate of the negative log likelihood # (or rather -elbo) for this epoch epoch_nll = 0.0 # prepare mini-batch subsampling indices for this epoch shuffled_indices = np.arange(N_train_data) np.random.shuffle(shuffled_indices) # process each mini-batch; this is where we take gradient steps for which_mini_batch in range(N_mini_batches): epoch_nll += process_minibatch(epoch, which_mini_batch, shuffled_indices) # report training diagnostics times.append(time.time()) epoch_time = times[-1] - times[-2] log("[training epoch %04d] %.4f \t\t\t\t(dt = %.3f sec)" % (epoch, epoch_nll / N_train_time_slices, epoch_time)) ``` At the beginning of each epoch we shuffle the indices pointing to the training data. We then process each mini-batch until we've gone through the entire training set, accumulating the training loss as we go. Finally we report some diagnostic info. Note that we normalize the loss by the total number of time slices in the training set (this allows us to compare to reference [1]). ## Evaluation This training loop is still missing any kind of evaluation diagnostics. Let's fix that. First we need to prepare the validation and test data for evaluation. Since the validation and test datasets are small enough that we can easily fit them into memory, we're going to process each dataset batchwise (i.e. we will not be breaking up the dataset into mini-batches). [_Aside: at this point the reader may ask why we don't do the same thing for the training set. The reason is that additional stochasticity due to data-subsampling is often advantageous during optimization: in particular it can help us avoid local optima._] And, in fact, in order to get a lessy noisy estimate of the ELBO, we're going to compute a multi-sample estimate. The simplest way to do this would be as follows: ```python val_loss = svi.evaluate_loss(val_batch, ..., num_particles=5) ``` This, however, would involve an explicit `for` loop with five iterations. For our particular model, we can do better and vectorize the whole computation. The only way to do this currently in Pyro is to explicitly replicate the data `n_eval_samples` many times. This is the strategy we follow: ```python # package repeated copies of val/test data for faster evaluation # (i.e. set us up for vectorization) def rep(x): return np.repeat(x, n_eval_samples, axis=0) # get the validation/test data ready for the dmm: pack into sequences, etc. val_seq_lengths = rep(val_seq_lengths) test_seq_lengths = rep(test_seq_lengths) val_batch, val_batch_reversed, val_batch_mask, val_seq_lengths = poly.get_mini_batch( np.arange(n_eval_samples * val_data_sequences.shape[0]), rep(val_data_sequences), val_seq_lengths, cuda=args.cuda) test_batch, test_batch_reversed, test_batch_mask, test_seq_lengths = \ poly.get_mini_batch(np.arange(n_eval_samples * test_data_sequences.shape[0]), rep(test_data_sequences), test_seq_lengths, cuda=args.cuda) ``` With the test and validation data now fully prepped, we define the helper function that does the evaluation: ```python def do_evaluation(): # put the RNN into evaluation mode (i.e. turn off drop-out if applicable) dmm.rnn.eval() # compute the validation and test loss val_nll = svi.evaluate_loss(val_batch, val_batch_reversed, val_batch_mask, val_seq_lengths) / np.sum(val_seq_lengths) test_nll = svi.evaluate_loss(test_batch, test_batch_reversed, test_batch_mask, test_seq_lengths) / np.sum(test_seq_lengths) # put the RNN back into training mode (i.e. turn on drop-out if applicable) dmm.rnn.train() return val_nll, test_nll ``` We simply call the `evaluate_loss` method of `elbo`, which takes the same arguments as `step()`, namely the arguments that are passed to the model and guide. Note that we have to put the RNN into and out of evaluation mode to account for dropout. We can now stick `do_evaluation()` into the training loop; see [the source code](https://github.com/pyro-ppl/pyro/blob/dev/examples/dmm.py) for details. ## Results Let's make sure that our implementation gives reasonable results. We can use the numbers reported in reference [1] as a sanity check. For the same dataset and a similar model/guide setup (dimension of the latent space, number of hidden units in the RNN, etc.) they report a normalized negative log likelihood (NLL) of `6.93` on the testset (lower is better$)^{\S}$. This is to be compared to our result of `6.87`. These numbers are very much in the same ball park, which is reassuring. It seems that, at least for this dataset, not using analytic expressions for the KL divergences doesn't degrade the quality of the learned model (although, as discussed above, the training probably takes somewhat longer). In the figure we show how the test NLL progresses during training for a single sample run (one with a rather conservative learning rate). Most of the progress is during the first 3000 epochs or so, with some marginal gains if we let training go on for longer. On a GeForce GTX 1080, 5000 epochs takes about 20 hours. | `num_iafs` | test NLL | |---|---| | `0` | `6.87` | | `1` | `6.82` | | `2` | `6.80` | Finally, we also report results for guides with normalizing flows in the mix (details to be found in the next section). ${ \S\;}$ Actually, they seem to report two numbers—6.93 and 7.03—for the same model/guide and it's not entirely clear how the two reported numbers are different. ## Bells, whistles, and other improvements ### Inverse Autoregressive Flows One of the great things about a probabilistic programming language is that it encourages modularity. Let's showcase an example in the context of the DMM. We're going to make our variational distribution richer by adding normalizing flows to the mix (see reference [2] for a discussion). **This will only cost us four additional lines of code!** First, in the `DMM` constructor we add ```python iafs = [AffineAutoregressive(AutoRegressiveNN(z_dim, [iaf_dim])) for _ in range(num_iafs)] self.iafs = nn.ModuleList(iafs) ``` This instantiates `num_iafs` many bijective transforms of the `AffineAutoregressive` type (see references [3,4]); each normalizing flow will have `iaf_dim` many hidden units. We then bundle the normalizing flows in a `nn.ModuleList`; this is just the PyTorchy way to package a list of `nn.Module`s. Next, in the guide we add the lines ```python if self.iafs.__len__() > 0: z_dist = TransformedDistribution(z_dist, self.iafs) ``` Here we're taking the base distribution `z_dist`, which in our case is a conditional gaussian distribution, and using the `TransformedDistribution` construct we transform it into a non-gaussian distribution that is, by construction, richer than the base distribution. Voila! ### Checkpointing If we want to recover from a catastrophic failure in our training loop, there are two kinds of state we need to keep track of. The first is the various parameters of the model and guide. The second is the state of the optimizers (e.g. in Adam this will include the running average of recent gradient estimates for each parameter). In Pyro, the parameters can all be found in the `ParamStore`. However, PyTorch also keeps track of them for us via the `parameters()` method of `nn.Module`. So one simple way we can save the parameters of the model and guide is to make use of the `state_dict()` method of `dmm` in conjunction with `torch.save()`; see below. In the case that we have `AffineAutoregressive`'s in the loop, this is in fact the only option at our disposal. This is because the `AffineAutoregressive` module contains what are called 'persistent buffers' in PyTorch parlance. These are things that carry state but are not `Parameter`s. The `state_dict()` and `load_state_dict()` methods of `nn.Module` know how to deal with buffers correctly. To save the state of the optimizers, we have to use functionality inside of `pyro.optim.PyroOptim`. Recall that the typical user never interacts directly with PyTorch `Optimizers` when using Pyro; since parameters can be created dynamically in an arbitrary probabilistic program, Pyro needs to manage `Optimizers` for us. In our case saving the optimizer state will be as easy as calling `optimizer.save()`. The loading logic is entirely analagous. So our entire logic for saving and loading checkpoints only takes a few lines: ```python # saves the model and optimizer states to disk def save_checkpoint(): log("saving model to %s..." % args.save_model) torch.save(dmm.state_dict(), args.save_model) log("saving optimizer states to %s..." % args.save_opt) optimizer.save(args.save_opt) log("done saving model and optimizer checkpoints to disk.") # loads the model and optimizer states from disk def load_checkpoint(): assert exists(args.load_opt) and exists(args.load_model), \ "--load-model and/or --load-opt misspecified" log("loading model from %s..." % args.load_model) dmm.load_state_dict(torch.load(args.load_model)) log("loading optimizer states from %s..." % args.load_opt) optimizer.load(args.load_opt) log("done loading model and optimizer states.") ``` ## Some final comments A deep markov model is a relatively complex model. Now that we've taken the effort to implement a version of the deep markov model tailored to the polyphonic music dataset, we should ask ourselves what else we can do. What if we're handed a different sequential dataset? Do we have to start all over? Not at all! The beauty of probalistic programming is that it enables&mdash;and encourages&mdash;modular approaches to modeling and inference. Adapting our polyphonic music model to a dataset with continuous observations is as simple as changing the observation likelihood. The vast majority of the code could be taken over unchanged. This means that with a little bit of extra work, the code in this tutorial could be repurposed to enable a huge variety of different models. See the complete code on [Github](https://github.com/pyro-ppl/pyro/blob/dev/examples/dmm.py). ## References [1] `Structured Inference Networks for Nonlinear State Space Models`,<br />&nbsp;&nbsp;&nbsp;&nbsp; Rahul G. Krishnan, Uri Shalit, David Sontag [2] `Variational Inference with Normalizing Flows`, <br />&nbsp;&nbsp;&nbsp;&nbsp; Danilo Jimenez Rezende, Shakir Mohamed [3] `Improving Variational Inference with Inverse Autoregressive Flow`, <br />&nbsp;&nbsp;&nbsp;&nbsp; Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling [4] `MADE: Masked Autoencoder for Distribution Estimation`, <br />&nbsp;&nbsp;&nbsp;&nbsp; Mathieu Germain, Karol Gregor, Iain Murray, Hugo Larochelle [5] `Modeling Temporal Dependencies in High-Dimensional Sequences:` <br />&nbsp;&nbsp;&nbsp;&nbsp; `Application to Polyphonic Music Generation and Transcription`, <br />&nbsp;&nbsp;&nbsp;&nbsp; Boulanger-Lewandowski, N., Bengio, Y. and Vincent, P.
github_jupyter
This notebook demonstrates [vaquero](https://github.com/jbn/vaquero), as both a library and data cleaning pattern. ``` from vaquero import Vaquero, callables_from ``` # Task Say you think you have pairs of numbers serialized as comma separated values in a file. You want to extract the pair from each line, then sum over the result (per line). ## Sample Data ``` lines = ["1, 1.0", # An errant float "1, $", # A bad number "1,-1", # A good line "10"] # Missing the second value ``` ## Initial Implementation ``` def extract_pairs(s): return s.split(",") def to_int(items): return [int(item) for item in items] def sum_pair(items): return items[0], items[1] ``` # Iteration 1 First, instantiate a vaquero instance. Here, I've set the maximum number of failures allowed to 5. After that many failures, the `Vaquero` object raises a `VaqueroException`. Generally, you want it to be large enough to collect a lot of unexpected failures. But, you don't want it to be so large you exhaust memory. This is an iterative process. Also, as a tip, always instantiate the `Vaquero` object in its own cell. This way, you get to inspect it in your notebook even if it raises a `VaqueroException`. I also registered all functions (well, callables) in this notebook with `vaquero`. The error capturing machinery only operates on the registered functions. And, it always ignores a `KeyboardInterrupt`. ``` vaquero = Vaquero(max_failures=5) vaquero.register_targets(callables_from(globals())) ``` Just to be sure, I'll check the registered functions. It does matching by name, which is a bit naive. But, it's also surprisingly robust given vaquero usage patterns. Looking, you can see some things that don't belong. But, again, it mostly works well. ``` vaquero.target_funcs ``` Now, run my trivial examples over the initial implementation. ``` results = [] for s in lines: with vaquero.on_input(s): results.append(sum_pair(to_int(extract_pairs(s)))) ``` It was not successful. ``` vaquero.was_successful ``` So, look at the failures. There were two functions, and both had failures. ``` vaquero.stats() ``` To get a sense of what happened, examine the failing functions. You can do this by calling `examine` with the name of the function (or the function object). It returns the captured invocations and errors. Here you can see that the `to_int` function from cell `In [3]` failed with a `ValueError` exception. ``` vaquero.examine('to_int') ``` Often though, we want to query only parts of the capture for a specific function. To do so, you can use [JMESPath](http://jmespath.org/), specifying the selector as an argument to `exam`. Also, you can say, show me only the set applied to the selected result (assuming it's hashable), to simplify things. ``` vaquero.examine('to_int', '[*].exc_value', as_set=True) ``` And, for `sum_pair`. ``` vaquero.examine('sum_pair') ``` # Iteration 2 We know know that there are some ints encoded as doubles. But, we know from our data source, it can only be an int. So, in `to_ints`, let's parse the strings first as `float`s, then create an `int` from it. It's robust. Also, we know that some lines don't have two components. Those are just bad lines. Let's assert there are two parts as post condition of `extract_pairs`. Finally, after a bit of digging, we found that `$` means `NA`. After cursing for a minute -- because that's crazy -- you decide to ignore those entries. Instead of adding this to an existing function, you write an `assert_no_missing_data` function. ``` def no_missing_data(s): assert '$' not in s, "'{}' has missing data".format(s) def extract_pairs(s): parts = s.split(",") assert len(parts) == 2, "'{}' not in 2 parts".format(s) return tuple(parts) def to_int(items): return [int(float(item)) for item in items] def sum_pair(items): assert len(items) == 2, "Line is improperly formatted" return items[0] + items[1] vaquero.reset() # Clear logged errors, mostly. vaquero.register_targets(globals()) results = [] for s in lines: with vaquero.on_input(s): no_missing_data(s) results.append(sum_pair(to_int(extract_pairs(s)))) ``` Now, we have one more success, but still two failures. ``` vaquero.stats() ``` Let's quickly examine. ``` vaquero.examine('extract_pairs') vaquero.examine('no_missing_data') ``` Both these exceptions are bad data. We want to ignore them. ``` vaquero.stats_ignoring('AssertionError') ``` Looking at the results accumulated, ``` results ``` Things look good. Now that we have something that works, we can use Vaquero in a more production-oriented mode. That is, we allow for unlimited errors, but we don't capture anything. That is, we note the failure, but otherwise ignore it since we won't be post-processing. ``` vaquero.reset(turn_off_error_capturing=True) # Or, Vaquero(capture_error_invocations=False) results = [] for s in lines: with vaquero.on_input(s): no_missing_data(s) results.append(sum_pair(to_int(extract_pairs(s)))) results ``` They still show up as failures, but it doesn't waste memory storing the captures. ``` vaquero.stats() ```
github_jupyter
``` %matplotlib inline ``` **1**. (25 points) We have a surgeon who wants to find rich, obese patients for bariatric surgery. The surgeon purchases 3rd party databases that include the following: - patients - includes height and weight for 100 patients - finances - income of patients - orders - patients who have bought weight loss products before We want to help the surgeon find his potential patients. Her criteria are - patient must be obese with BMI (weight (kg) / (height (m) * height (m)) - patient must be rich - income > $100,000 - patient must have bought weight loss products previously Find the patient names, bmi and income for those meeting the 3 criteria using - EQUIJOIN (no subqueries) - INNER JOIN (no subqueries) - Subqueries - Common table expressions - Views ``` from faker import Faker import numpy as np import pandas as pd np.random.seed(123) fake = Faker() names = [fake.name() for i in range(100)] hts = np.random.normal(1.7, 0.1, 100) wts = np.random.normal(85, 10, 100) patients = pd.DataFrame(dict(name=names, wt=wts, ht=hts)) patients.index.name = 'patient_id' incomes = np.random.np.random.lognormal(11, 1, 100).astype('int') finances = pd.DataFrame(dict(income=incomes, patient_id=np.random.permutation(100))) finances.index.name = 'finance_id' order_total = np.random.randint(100, 100000, 200) patient_ids = np.random.randint(0, 500, 200) orders = pd.DataFrame(dict(sales=order_total, patient_id=patient_ids)) orders.index.name = 'order_id' %load_ext sql %sql sqlite:// %sql DROP TABLE IF EXISTS patients %sql DROP TABLE IF EXISTS finances %sql DROP TABLE IF EXISTS orders %sql PERSIST patients %sql PERSIST finances %sql PERSIST orders ``` Using EQUIJOIN Using INNEr JOIN Using subtable. Using CTE Using views. **2**. (25 points) Use windows functions in SQL to achieve the same effect as these `pandas` operations.`m ``` url = 'https://raw.githubusercontent.com/statsmodels/statsmodels/master/statsmodels/datasets/nile/nile.csv' nile = pd.read_csv(url, index_col=0) %sql PERSIST nile nile.shape nile.head(3) a1 = nile.rolling(5, min_periods=1).mean() a1.head(6) ax = nile.plot() a1.plot(color='red', ax=ax) pass ``` SQL solution here ``` a2 = nile.rolling(5, center=True, min_periods=1).mean() a2.head(6) ax = nile.plot() a2.plot(color='red', ax=ax) pass ``` SQL solution here ``` a3 = nile.expanding().mean() a3.head(6) ax = nile.plot() a3.plot(color='red', ax=ax) pass ``` SQL solution here ``` a4 = nile.rank(method='dense').sort_values('volume') a4.head(6) ``` SQL solution here ``` quartiles = pd.qcut(nile.volume, np.linspace(0,1,5), labels=['Q1', 'Q2', 'Q3', 'Q4']) quartiles.name = 'quartile' quartiles df = pd.concat([nile, quartiles], axis=1) df.groupby('quartile').sum() ``` SQL solution here **3**. (50 points) Convert the flat file data in `h04q03.csv` into a well-structured relational database (i.e. at least in 3NF) in SQLite3 as `ho4q03.db`. Note - salary information is confidential and should be kept in a separate table from other personal data. - Use only `pandas` operations. - Do not make use of SQL line or cell magic ``` df = pd.read_csv('h04q03.csv') ```
github_jupyter
# Customer Segmentation in Python This notebook explains how to perform Association Analysis from customer purchase history data. We are using [pandas](https://pandas.pydata.org) (for data manipulation) and [mlxtend](https://github.com/rasbt/mlxtend) (for apriori and association rules algorithnms). The data we're using comes from John Foreman's book [Data Smart](http://www.john-foreman.com/data-smart-book.html). ## Understanding the data The dataset contains both information on marketing newsletters/e-mail campaigns (e-mail offers sent)... ``` import pandas as pd df_offers = pd.read_excel("data/WineKMC.xlsx", sheet_name=0) df_offers.columns = ["offer_id", "campaign", "varietal", "min_qty", "discount", "origin", "past_peak"] df_offers.head() ``` and transaction level data from customers (which offer customers responded to and what they bought). ``` df_transactions = pd.read_excel("data/WineKMC.xlsx", sheet_name=1) df_transactions.columns = ["customer_name", "offer_id"] df_transactions['n'] = 1 df_transactions.head() ``` ## Clustering the data First we are going to combine both data sets ``` # join the offers and transactions table df = pd.merge(df_offers, df_transactions) # create a "pivot table" which will give us the number of times each customer responded to a given offer matrix = df.pivot_table(index=['customer_name'], columns=['offer_id'], values='n') # a little tidying up. fill NA values with 0 and make the index into a column matrix = matrix.fillna(0).reset_index() # save a list of the 0/1 columns. we'll use these a bit later x_cols = matrix.columns[1:] ``` We need to propose a proper number of clusters. Let's use the silhouette score ``` from sklearn.metrics import silhouette_score range_n_clusters = [2, 3, 4, 5, 6, 7, 8, 9, 10] # clusters range you want to select dataToFit = matrix[matrix.columns[2:]] best_clusters = 0 # best cluster number which you will get previous_silh_avg = 0.0 for n_clusters in range_n_clusters: clusterer = KMeans(n_clusters=n_clusters) cluster_labels = clusterer.fit_predict(dataToFit) silhouette_avg = silhouette_score(dataToFit, cluster_labels) print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg) if silhouette_avg > previous_silh_avg: previous_silh_avg = silhouette_avg best_clusters = n_clusters # Final Kmeans for best_clusters kmeans = KMeans(n_clusters=best_clusters, random_state=0).fit(dataToFit) ``` According to this analysis 5 is a good candidate. Let's determine the number of customers per cluster. ``` cluster = KMeans(n_clusters=5) # slice matrix so we only include the 0/1 indicator columns in the clustering matrix['cluster'] = cluster.fit_predict(matrix[x_cols]) matrix.cluster.value_counts() ```
github_jupyter
# Algo - Aparté sur le voyageur de commerce Le voyageur de commerce ou Travelling Salesman Problem en anglais est le problème NP-complet emblématique : il n'existe pas d'algorithme capable de trouver la solution optimale en temps polynômial. La seule option est de parcourir toutes les configurations pour trouver la meilleure. Ce notebook ne fait qu'aborder le problème. ``` from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline ``` ## Tirer des points aléatoirement et les afficher ``` import numpy points = numpy.random.random((6, 2)) points ``` ## Distance d'un chemin ``` def distance_chemin(points, chemin): dist = 0 for i in range(1, len(points)): dx, dy = points[chemin[i], :] - points[chemin[i-1], :] dist += (dx ** 2 + dy ** 2) ** 0.5 dx, dy = points[chemin[0], :] - points[chemin[-1], :] dist += (dx ** 2 + dy ** 2) ** 0.5 return dist distance_chemin(points, list(range(points.shape[0]))) ``` ## Visualisation ``` import matplotlib.pyplot as plt def plot_points(points, chemin): fig, ax = plt.subplots(1, 2, figsize=(8, 4)) loop = list(chemin) + [chemin[0]] p = points[loop] ax[0].plot(points[:, 0], points[:, 1], 'o') ax[1].plot(p[:, 0], p[:, 1], 'o-') ax[1].set_title("dist=%1.2f" % distance_chemin(points, chemin)) return ax plot_points(points, list(range(points.shape[0]))); ``` ## Parcourir toutes les permutations ``` from itertools import permutations def optimisation(points, chemin): dist = distance_chemin(points, chemin) best = chemin for perm in permutations(chemin): d = distance_chemin(points, perm) if d < dist: dist = d best = perm return best res = optimisation(points, list(range(points.shape[0]))) plot_points(points, res); ``` ## Module tqdm Utile seulement dans un notebook, très utile pour les impatients. ``` from tqdm import tqdm def optimisation(points, chemin): dist = distance_chemin(points, chemin) best = chemin loop = tqdm(permutations(chemin)) for perm in loop: loop.set_description(str(perm)) d = distance_chemin(points, perm) if d < dist: dist = d best = perm return best res = optimisation(points, list(range(points.shape[0]))) plot_points(points, res); ``` ## Retournement Les permutations ça prend du temps même avec les machines d'aujourd'hui. ``` def optimisation_retournement(points, chemin): dist = distance_chemin(points, chemin) best = chemin for i in range(1, len(chemin)): for j in range(i+1, len(chemin)): chemin[i: j] = chemin[j-1: i-1: -1] d = distance_chemin(points, chemin) if d < dist: dist = d else: chemin[i: j] = chemin[j-1: i-1: -1] return chemin res = optimisation_retournement(points, list(range(points.shape[0]))) plot_points(points, res); ```
github_jupyter
``` import os import json tmp = dict() """ Daily Met Livneh 2013 """ tmp['dailymet_livneh2013'] = dict() tmp['dailymet_livneh2013']['spatial_resolution'] = '1/16-degree' tmp['dailymet_livneh2013']['web_protocol'] = 'ftp' tmp['dailymet_livneh2013']['domain'] = 'livnehpublicstorage.colorado.edu' tmp['dailymet_livneh2013']['subdomain'] = '/public/Livneh.2013.CONUS.Dataset/Meteorology.asc.v.1.2.1915.2011.bz2/' tmp['dailymet_livneh2013']['decision_steps'] = 'files organized by spatial bounding boxes' tmp['dailymet_livneh2013']['filename_structure'] = 'Meteorology_Livneh_CONUSExt_v.1.2_2013_{LAT}_{LONG}' tmp['dailymet_livneh2013']['file_format'] = 'bz2-compressed ASCII' tmp['dailymet_livneh2013']['reference']=dict() tmp['dailymet_livneh2013']['reference'][1] = "Livneh, B., E. A. Rosenberg, C. Lin, B. Nijssen, V. Mishra, K. M. Andreadis, E. P. Maurer, and D. P. Lettenmaier, 2013: A Long-Term Hydrologically Based Dataset of Land Surface Fluxes and States for the Conterminous United States: Update and Extensions. J. Climate, 26, 9384-9392." tmp['dailymet_livneh2013']['reference'][2] = "ftp://livnehpublicstorage.colorado.edu/public/Livneh.2013.CONUS.Dataset/readme.txt" tmp['dailymet_livneh2013']['start_date'] = '1915-01-01' tmp['dailymet_livneh2013']['end_date'] = '2011-12-31' tmp['dailymet_livneh2013']['temporal_resolution'] = 'D' tmp['dailymet_livneh2013']['delimiter'] = '\t' tmp['dailymet_livneh2013']['variable_list'] = ['PRECIP', 'TMAX', 'TMIN', 'WINDSPD'] tmp['dailymet_livneh2013']['variable_info'] = dict() tmp['dailymet_livneh2013']['variable_info']['PRECIP'] = dict() tmp['dailymet_livneh2013']['variable_info']['PRECIP']={'desc':'daily precipitation (mm)', 'dtypes':'float64','units':'mm'} tmp['dailymet_livneh2013']['variable_info']['TMAX'] = dict() tmp['dailymet_livneh2013']['variable_info']['TMAX']={'desc':'daily maximum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_livneh2013']['variable_info']['TMIN'] = dict() tmp['dailymet_livneh2013']['variable_info']['TMIN']={'desc':'daily minimum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_livneh2013']['variable_info']['WINDSPD'] = dict() tmp['dailymet_livneh2013']['variable_info']['WINDSPD']={'desc':'daily mean wind speed (m/s)', 'dtypes':'float64','units':'m/s'} """ Daily MET Livneh 2015 """ tmp['dailymet_livneh2015']=dict() tmp['dailymet_livneh2015']['spatial_resolution'] = '1/16-degree' tmp['dailymet_livneh2015']['web_protocol'] = 'ftp' tmp['dailymet_livneh2015']['domain'] = '192.12.137.7' tmp['dailymet_livneh2015']['subdomain'] = '/pub/dcp/archive/OBS/livneh2014.1_16deg/ascii/daily/' tmp['dailymet_livneh2015']['decision_steps'] = 'files organized by Latitude' tmp['dailymet_livneh2015']['filename_structure'] = 'Meteorology_Livneh_NAmerExt_15Oct2014_{LAT}_{LONG}' tmp['dailymet_livneh2015']['file_format'] = 'bz2-compressed ASCII' tmp['dailymet_livneh2015']['reference']=dict() tmp['dailymet_livneh2015']['reference'][1]= "Livneh B., T.J. Bohn, D.S. Pierce, F. Munoz-Ariola, B. Nijssen, R. Vose, D. Cayan, and L.D. Brekke, 2015: A spatially comprehensive, hydrometeorological data set for Mexico, the U.S., and southern Canada 1950-2013, Nature Scientific Data, 5:150042, doi:10.1038/sdata.2015.42." tmp['dailymet_livneh2015']['reference'][2]= "ftp://livnehpublicstorage.colorado.edu/public/Livneh.2013.CONUS.Dataset/readme.txt" tmp['dailymet_livneh2015']['start_date'] = '1950-01-01' tmp['dailymet_livneh2015']['end_date'] = '2013-12-31' tmp['dailymet_livneh2015']['temporal_resolution'] = 'D' tmp['dailymet_livneh2015']['delimiter'] = '\\s+' tmp['dailymet_livneh2015']['variable_list'] = ['PRECIP', 'TMAX', 'TMIN', 'WINDSPD'] tmp['dailymet_livneh2015']['variable_info'] = dict() tmp['dailymet_livneh2015']['variable_info']['PRECIP'] = dict() tmp['dailymet_livneh2015']['variable_info']['PRECIP']={'desc':'daily precipitation (mm)', 'dtypes':'float64','units':'mm'} tmp['dailymet_livneh2015']['variable_info']['TMAX'] = dict() tmp['dailymet_livneh2015']['variable_info']['TMAX']={'desc':'daily maximum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_livneh2015']['variable_info']['TMIN'] = dict() tmp['dailymet_livneh2015']['variable_info']['TMIN']={'desc':'daily minimum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_livneh2015']['variable_info']['WINDSPD'] = dict() tmp['dailymet_livneh2015']['variable_info']['WINDSPD']={'desc':'daily mean wind speed (m/s)', 'dtypes':'float64','units':'m/s'} """ Daily VIC Livneh 2013 """ tmp['dailyvic_livneh2013'] = dict() tmp['dailyvic_livneh2013']['spatial_resolution'] = '1/16-degree' tmp['dailyvic_livneh2013']['web_protocol'] = 'ftp' tmp['dailyvic_livneh2013']['domain'] = 'livnehpublicstorage.colorado.edu' tmp['dailyvic_livneh2013']['subdomain'] = '/public/Livneh.2013.CONUS.Dataset/Fluxes.asc.v.1.2.1915.2011.bz2/' tmp['dailyvic_livneh2013']['decision_steps'] = 'files organized by spatial bounding boxes' tmp['dailyvic_livneh2013']['filename_structure'] = 'VIC_fluxes_Livneh_CONUSExt_v.1.2_2013_{LAT}_{LONG}' tmp['dailyvic_livneh2013']['file_format'] = 'bz2-compressed ASCII' tmp['dailyvic_livneh2013']['reference']=dict() tmp['dailyvic_livneh2013']['reference'][1] = "Livneh, B., E. A. Rosenberg, C. Lin, B. Nijssen, V. Mishra, K. M. Andreadis, E. P. Maurer, and D. P. Lettenmaier, 2013: A Long-Term Hydrologically Based Dataset of Land Surface Fluxes and States for the Conterminous United States: Update and Extensions. J. Climate, 26, 9384-9392." tmp['dailyvic_livneh2013']['reference'][2] = "ftp://livnehpublicstorage.colorado.edu/public/Livneh.2013.CONUS.Dataset/readme.txt" tmp['dailyvic_livneh2013']['start_date'] = '1915-01-01' tmp['dailyvic_livneh2013']['end_date'] = '2011-12-31' tmp['dailyvic_livneh2013']['temporal_resolution'] = 'D' tmp['dailyvic_livneh2013']['delimiter'] = '\t' tmp['dailyvic_livneh2013']['variable_list'] = ['YEAR','MONTH','DAY','EVAP','RUNOFF','BASEFLOW','SMTOP','SMMID','SMBOT','SWE','WDEW','SENSIBLE','LATENT','GRNDFLUX','RNET','RADTEMP','PREC'] tmp['dailyvic_livneh2013']['variable_info'] = dict() tmp['dailyvic_livneh2013']['variable_info']['YEAR'] = dict() tmp['dailyvic_livneh2013']['variable_info']['YEAR']={'desc':'year', 'dtypes':'int8','units':'yr'} tmp['dailyvic_livneh2013']['variable_info']['MONTH'] = dict() tmp['dailyvic_livneh2013']['variable_info']['MONTH']={'desc':'month', 'dtypes':'int8','units':'mo'} tmp['dailyvic_livneh2013']['variable_info']['DAY'] = dict() tmp['dailyvic_livneh2013']['variable_info']['DAY']={'desc':'day', 'dtypes':'int8','units':'day'} tmp['dailyvic_livneh2013']['variable_info']['EVAP'] = dict() tmp['dailyvic_livneh2013']['variable_info']['EVAP']={'desc':'Total ET rate-- includes Canopy, Sub-canopy Evaporation, Transpiration, and Snow Sublimation', 'dtypes':'float64','units':'mm/s'} tmp['dailyvic_livneh2013']['variable_info']['RUNOFF'] = dict() tmp['dailyvic_livneh2013']['variable_info']['RUNOFF']={'desc':'Runoff', 'dtypes':'float64','units':'mm/s'} tmp['dailyvic_livneh2013']['variable_info']['BASEFLOW'] = dict() tmp['dailyvic_livneh2013']['variable_info']['BASEFLOW']={'desc':'Baseflow', 'dtypes':'float64','units':'mm/s'} tmp['dailyvic_livneh2013']['variable_info']['SMTOP'] = dict() tmp['dailyvic_livneh2013']['variable_info']['SMTOP']={'desc':'Soil moisture top layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2013']['variable_info']['SMMID'] = dict() tmp['dailyvic_livneh2013']['variable_info']['SMMID']={'desc':'Soil moisture middle layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2013']['variable_info']['SMBOT'] = dict() tmp['dailyvic_livneh2013']['variable_info']['SMBOT']={'desc':'Soil moisture bottom layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2013']['variable_info']['SWE'] = dict() tmp['dailyvic_livneh2013']['variable_info']['SWE']={'desc':'Snow water equivalent (SWE)', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2013']['variable_info']['WDEW'] = dict() tmp['dailyvic_livneh2013']['variable_info']['WDEW']={'desc':'Canopy water', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2013']['variable_info']['SENSIBLE'] = dict() tmp['dailyvic_livneh2013']['variable_info']['SENSIBLE']={'desc':'Net sensible heat flux', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2013']['variable_info']['LATENT'] = dict() tmp['dailyvic_livneh2013']['variable_info']['LATENT']={'desc':'Net latent heat flux', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2013']['variable_info']['GRNDFLUX'] = dict() tmp['dailyvic_livneh2013']['variable_info']['GRNDFLUX']={'desc':'Net heat flux into ground', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2013']['variable_info']['RNET'] = dict() tmp['dailyvic_livneh2013']['variable_info']['RNET']={'desc':'Net downward radiation flux', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2013']['variable_info']['RADTEMP'] = dict() tmp['dailyvic_livneh2013']['variable_info']['RADTEMP']={'desc':'Mean radiative surface temperature', 'dtypes':'float64','units':'K'} tmp['dailyvic_livneh2013']['variable_info']['PREC'] = dict() tmp['dailyvic_livneh2013']['variable_info']['PREC']={'desc':'Incoming precipitation rate', 'dtypes':'float64','units':'mm/s'} """ Daily Met bias-corrected Livneh 2013 """ tmp['dailymet_bclivneh2013'] = dict() tmp['dailymet_bclivneh2013']['spatial_resolution'] = '1/16-degree' tmp['dailymet_bclivneh2013']['web_protocol'] = 'http' tmp['dailymet_bclivneh2013']['domain'] = 'cses.washington.edu' tmp['dailymet_bclivneh2013']['subdomain'] = '/rocinante/Livneh/bcLivneh_WWA_2013/forcings_ascii/' tmp['dailymet_bclivneh2013']['decision_steps'] = '' tmp['dailymet_bclivneh2013']['filename_structure'] = 'data_{LAT}_{LONG}' tmp['dailymet_bclivneh2013']['file_format'] = 'ASCII' tmp['dailymet_bclivneh2013']['reference']=dict() tmp['dailymet_bclivneh2013']['reference'][1] = "Livneh, B., E. A. Rosenberg, C. Lin, B. Nijssen, V. Mishra, K. M. Andreadis, E. P. Maurer, and D. P. Lettenmaier, 2013: A Long-Term Hydrologically Based Dataset of Land Surface Fluxes and States for the Conterminous United States: Update and Extensions. J. Climate, 26, 9384-9392." tmp['dailymet_bclivneh2013']['reference'][2] = "ftp://livnehpublicstorage.colorado.edu/public/Livneh.2013.CONUS.Dataset/readme.txt" tmp['dailymet_bclivneh2013']['start_date'] = '1915-01-01' tmp['dailymet_bclivneh2013']['end_date'] = '2011-12-31' tmp['dailymet_bclivneh2013']['temporal_resolution'] = 'D' tmp['dailymet_bclivneh2013']['delimiter'] = '\t' tmp['dailymet_bclivneh2013']['variable_list'] = ['PRECIP', 'TMAX', 'TMIN', 'WINDSPD'] tmp['dailymet_bclivneh2013']['variable_info'] = dict() tmp['dailymet_bclivneh2013']['variable_info']['PRECIP'] = dict() tmp['dailymet_bclivneh2013']['variable_info']['PRECIP']={'desc':'daily precipitation (mm)', 'dtypes':'float64','units':'mm'} tmp['dailymet_bclivneh2013']['variable_info']['TMAX'] = dict() tmp['dailymet_bclivneh2013']['variable_info']['TMAX']={'desc':'daily maximum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_bclivneh2013']['variable_info']['TMIN'] = dict() tmp['dailymet_bclivneh2013']['variable_info']['TMIN']={'desc':'daily minimum temperature (C)', 'dtypes':'float64','units':'C'} tmp['dailymet_bclivneh2013']['variable_info']['WINDSPD'] = dict() tmp['dailymet_bclivneh2013']['variable_info']['WINDSPD']={'desc':'daily mean wind speed (m/s)', 'dtypes':'float64','units':'m/s'} """ Daily VIC Livneh 2015 """ tmp['dailyvic_livneh2015']=dict() tmp['dailyvic_livneh2015']['spatial_resolution']='1/16-degree' tmp['dailyvic_livneh2015']['web_protocol']='ftp' tmp['dailyvic_livneh2015']['domain']='192.12.137.7' tmp['dailyvic_livneh2015']['subdomain']='/pub/dcp/archive/OBS/livneh2014.1_16deg/VIC.ASCII/' tmp['dailyvic_livneh2015']['decision_steps']='files organized by Latitude' tmp['dailyvic_livneh2015']['filename_structure']='Fluxes_Livneh_NAmerExt_15Oct2014_{LAT}_{LONG}' tmp['dailyvic_livneh2015']['file_format']='bz2-compressed ASCII' tmp['dailyvic_livneh2015']['reference']=dict() tmp['dailyvic_livneh2015']['reference'][1]="Livneh B., T.J. Bohn, D.S. Pierce, F. Munoz-Ariola, B. Nijssen, R. Vose, D. Cayan, and L.D. Brekke, 2015: A spatially comprehensive, hydrometeorological data set for Mexico, the U.S., and southern Canada 1950-2013, Nature Scientific Data, 5:150042, doi:10.1038/sdata.2015.42." tmp['dailyvic_livneh2015']['reference'][2]="ftp://192.12.137.7/pub/dcp/archive/OBS/livneh2014.1_16deg/README.Livneh.Grids.txt.v3.txt" tmp['dailyvic_livneh2015']['start_date']='1950-01-01' tmp['dailyvic_livneh2015']['end_date']='2013-12-31' tmp['dailyvic_livneh2015']['temporal_resolution']='D' tmp['dailyvic_livneh2015']['delimiter']='\t' tmp['dailyvic_livneh2015']['variable_list']=['YEAR','MONTH','DAY','EVAP','RUNOFF','BASEFLOW','SMTOP','SMMID','SMBOT','SWE','WDEW','SENSIBLE','LATENT','GRNDFLUX','RNET','PETTALL','PETSHORT','PETNATVEG'] tmp['dailyvic_livneh2015']['variable_info']=dict() tmp['dailyvic_livneh2015']['variable_info']['YEAR']=dict() tmp['dailyvic_livneh2015']['variable_info']['YEAR']={'desc':'year', 'dtypes':'int8','units':'yr'} tmp['dailyvic_livneh2015']['variable_info']['MONTH']=dict() tmp['dailyvic_livneh2015']['variable_info']['MONTH']={'desc':'month', 'dtypes':'int8','units':'mo'} tmp['dailyvic_livneh2015']['variable_info']['DAY']=dict() tmp['dailyvic_livneh2015']['variable_info']['DAY']={'desc':'day', 'dtypes':'int8','units':'day'} tmp['dailyvic_livneh2015']['variable_info']['EVAP']=dict() tmp['dailyvic_livneh2015']['variable_info']['EVAP']={'desc':'Total ET rate-- includes Canopy, Sub-canopy Evaporation, Transpiration, and Snow Sublimation', 'dtypes':'float64','units':'mm/day'} tmp['dailyvic_livneh2015']['variable_info']['RUNOFF']=dict() tmp['dailyvic_livneh2015']['variable_info']['RUNOFF']={'desc':'Runoff', 'dtypes':'float64','units':'mm/day'} tmp['dailyvic_livneh2015']['variable_info']['BASEFLOW']=dict() tmp['dailyvic_livneh2015']['variable_info']['BASEFLOW']={'desc':'Baseflow', 'dtypes':'float64','units':'mm/day'} tmp['dailyvic_livneh2015']['variable_info']['SMTOP']=dict() tmp['dailyvic_livneh2015']['variable_info']['SMTOP']={'desc':'Soil moisture top layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2015']['variable_info']['SMMID']=dict() tmp['dailyvic_livneh2015']['variable_info']['SMMID']={'desc':'Soil moisture middle layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2015']['variable_info']['SMBOT']=dict() tmp['dailyvic_livneh2015']['variable_info']['SMBOT']={'desc':'Soil moisture bottom layer', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2015']['variable_info']['SWE']=dict() tmp['dailyvic_livneh2015']['variable_info']['SWE']={'desc':'Snow water equivalent (SWE)', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2015']['variable_info']['WDEW']=dict() tmp['dailyvic_livneh2015']['variable_info']['WDEW']={'desc':'Canopy water', 'dtypes':'float64','units':'mm'} tmp['dailyvic_livneh2015']['variable_info']['SENSIBLE']=dict() tmp['dailyvic_livneh2015']['variable_info']['SENSIBLE']={'desc':'Net sensible heat flux', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2015']['variable_info']['LATENT']=dict() tmp['dailyvic_livneh2015']['variable_info']['LATENT']={'desc':'Net latent heat flux', 'dtypes':'float64', 'units':'W/m^2'} tmp['dailyvic_livneh2015']['variable_info']['GRNDFLUX']=dict() tmp['dailyvic_livneh2015']['variable_info']['GRNDFLUX']={'desc':'Net heat flux into ground', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2015']['variable_info']['RNET']=dict() tmp['dailyvic_livneh2015']['variable_info']['RNET']={'desc':'Net downward radiation flux', 'dtypes':'float64','units':'W/m^2'} tmp['dailyvic_livneh2015']['variable_info']['PETTALL']=dict() tmp['dailyvic_livneh2015']['variable_info']['PETTALL']={'desc':'Potential Evapotranspiration from tall crop (Alfalfa)', 'dtypes':'float64','units':'mm/day'} tmp['dailyvic_livneh2015']['variable_info']['PETSHORT']=dict() tmp['dailyvic_livneh2015']['variable_info']['PETSHORT']={'desc':'Potential Evapotranspiration from short crop (Grass)', 'dtypes':'float64','units':'mm/day'} tmp['dailyvic_livneh2015']['variable_info']['PETNATVEG']=dict() tmp['dailyvic_livneh2015']['variable_info']['PETNATVEG']={'desc':'Potential Evapotranspiration from current vegetation', 'dtypes':'float64','units':'mm/day'} """ Daily wrf-nnrp Salathe 2014 """ tmp['dailywrf_salathe2014'] = dict() tmp['dailywrf_salathe2014']['spatial_resolution'] = '1/16-degree' tmp['dailywrf_salathe2014']['web_protocol'] = 'http' tmp['dailywrf_salathe2014']['domain'] = 'cses.washington.edu/' tmp['dailywrf_salathe2014']['subdomain'] = '/rocinante/WRF/NNRP/vic_16d/WWA_1950_2010/raw/forcings_ascii/' tmp['dailywrf_salathe2014']['decision_steps'] = '' tmp['dailywrf_salathe2014']['filename_structure'] = 'data_{LAT}_{LONG}' tmp['dailywrf_salathe2014']['file_format'] = 'ASCII' tmp['dailywrf_salathe2014']['reference']=dict() tmp['dailywrf_salathe2014']['reference'][1]="Salathé Jr EP, Hamlet AF, Mass CF, Lee SY, Stumbaugh M, Steed R. Estimates of twenty-first-century flood risk in the Pacific Northwest based on regional climate model simulations. Journal of Hydrometeorology. 2014 Oct;15(5):1881-99. DOI: 10.1175/JHM-D-13-0137.1" tmp['dailywrf_salathe2014']['reference'][2]="http://cses.washington.edu/rocinante/WRF/README" tmp['dailywrf_salathe2014']['start_date'] = '1950-01-01' tmp['dailywrf_salathe2014']['end_date'] = '2010-12-31' tmp['dailywrf_salathe2014']['temporal_resolution'] = 'D' tmp['dailywrf_salathe2014']['delimiter'] = '\\s+' tmp['dailywrf_salathe2014']['variable_list'] = ['PRECIP', 'TMAX', 'TMIN', 'WINDSPD'] tmp['dailywrf_salathe2014']['variable_info'] = dict() tmp['dailywrf_salathe2014']['variable_info']['PRECIP'] = dict() tmp['dailywrf_salathe2014']['variable_info']['PRECIP']={'desc':'Daily accumulated precipitation', 'dtypes':'float64','units':'mm'} tmp['dailywrf_salathe2014']['variable_info']['TMAX'] = dict() tmp['dailywrf_salathe2014']['variable_info']['TMAX']={'desc':'Maximum temperature at 2m', 'dtypes':'float64','units':'C'} tmp['dailywrf_salathe2014']['variable_info']['TMIN'] = dict() tmp['dailywrf_salathe2014']['variable_info']['TMIN']={'desc':'Minimum temperature at 2m', 'dtypes':'float64','units':'C'} tmp['dailywrf_salathe2014']['variable_info']['WINDSPD'] = dict() tmp['dailywrf_salathe2014']['variable_info']['WINDSPD']={'desc':'Wind Speed', 'dtypes':'float64','units':'m/s'} """ Daily WRF-nnrp bias-corrected Salathe 2014 """ tmp['dailywrf_bcsalathe2014']=dict() tmp['dailywrf_bcsalathe2014']['spatial_resolution'] = '1/16-degree' tmp['dailywrf_bcsalathe2014']['web_protocol'] = 'http' tmp['dailywrf_bcsalathe2014']['domain'] = 'cses.washington.edu/' tmp['dailywrf_bcsalathe2014']['subdomain'] = '/rocinante/WRF/NNRP/vic_16d/WWA_1950_2010/bc/forcings_ascii/' tmp['dailywrf_bcsalathe2014']['decision_steps'] = '' tmp['dailywrf_bcsalathe2014']['filename_structure'] = 'data_{LAT}_{LONG}' tmp['dailywrf_bcsalathe2014']['file_format'] = 'ASCII' tmp['dailywrf_bcsalathe2014']['reference']=dict() tmp['dailywrf_bcsalathe2014']['reference'][1]="Salathé Jr EP, Hamlet AF, Mass CF, Lee SY, Stumbaugh M, Steed R. Estimates of twenty-first-century flood risk in the Pacific Northwest based on regional climate model simulations. Journal of Hydrometeorology. 2014 Oct;15(5):1881-99. DOI: 10.1175/JHM-D-13-0137.1" tmp['dailywrf_bcsalathe2014']['reference'][2]="http://cses.washington.edu/rocinante/WRF/README" tmp['dailywrf_bcsalathe2014']['start_date'] = '1950-01-01' tmp['dailywrf_bcsalathe2014']['end_date'] = '2010-12-31' tmp['dailywrf_bcsalathe2014']['temporal_resolution'] = 'D' tmp['dailywrf_bcsalathe2014']['delimiter'] = '\\s+' tmp['dailywrf_bcsalathe2014']['variable_list'] = ['PRECIP', 'TMAX', 'TMIN', 'WINDSPD'] tmp['dailywrf_bcsalathe2014']['variable_info'] = dict() tmp['dailywrf_bcsalathe2014']['variable_info']['PRECIP'] = dict() tmp['dailywrf_bcsalathe2014']['variable_info']['PRECIP']={'desc':'Daily accumulated precipitation', 'dtypes':'float64','units':'mm'} tmp['dailywrf_bcsalathe2014']['variable_info']['TMAX'] = dict() tmp['dailywrf_bcsalathe2014']['variable_info']['TMAX']={'desc':'Maximum temperature at 2m', 'dtypes':'float64','units':'C'} tmp['dailywrf_bcsalathe2014']['variable_info']['TMIN'] = dict() tmp['dailywrf_bcsalathe2014']['variable_info']['TMIN']={'desc':'Minimum temperature at 2m', 'dtypes':'float64','units':'C'} tmp['dailywrf_bcsalathe2014']['variable_info']['WINDSPD'] = dict() tmp['dailywrf_bcsalathe2014']['variable_info']['WINDSPD']={'desc':'Wind Speed', 'dtypes':'float64','units':'m/s'} sorted(tmp.keys()) # output the file json.dump(tmp, open('ogh_meta.json', 'w'), ensure_ascii=False) # perform a test read json.load(open('ogh_meta.json')) ```
github_jupyter
# Метод ADMM (alternating direction methods of multipliers) ## На прошлом семинаре - Субградиентный метод: базовый метод решения негладких задач - Проксимальный метод и его свойства: альтернатива градиентному спуску - Проксимальный градиентный метод: заглядывание в чёрный ящик - Ускорение проксимального градиентного метода, ISTA и FISTA ## План на сегодня - Использование Лагранжиана как модели целевой функции в задаче условной оптимизации - Чередование спуска и подъёма для решения минимаксной задачи - Регуляризация лагранжиана - ADMM ## Двойственная задача: напоминание - Исходная задача \begin{align*} & \min f(x) \\ \text{s.t. } & Ax = b \end{align*} - Лагранжиан $$ L(x, \lambda) = f(x) + \lambda^{\top}(Ax - b) $$ - Двойственная задача $$ \max_{\lambda} g(\lambda), $$ где $g(\lambda) = \inf_x L(x, \lambda)$ - Восстановление решения исходной заадчи $$ x^* = \arg\min_x L(x, \lambda^*) $$ ## Решение двойственной задачи - Градиентный подъём, так как задача без ограничений $$ \lambda_{k+1} = \lambda_k + \alpha_k g'(\lambda_k) $$ - При этом градиент двойственной функции $$ g'(\lambda_k) = A\hat{x} - b, $$ где $\hat{x} = \arg\min_x L(x, \lambda_k)$ - Объединим два шага в один и получим \begin{align*} & x_{k+1} = \arg\min_x L(x, \lambda_k)\\ & \lambda_{k+1} = \lambda_k + \alpha_k (Ax_{k+1} - b) \end{align*} ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rc("text", usetex=True) import cvxpy as cvx def dual_ascent(update_x, A, b, alpha, x0, lambda0, max_iter): x = x0.copy() lam = lambda0.copy() conv_x = [x] conv_lam = [lam] for i in range(max_iter): x = update_x(x, lam, A, b) lam = lam + alpha * (A @ x - b) conv_x.append(x.copy()) conv_lam.append(lam.copy()) return x, lam, conv_x, conv_lam ``` ### Модельный пример \begin{align*} & \min \frac{1}{2}x^{\top}Px - c^{\top}x\\ \text{s.t. } & Ax = b \end{align*} - Лагранжиан $L(x, \lambda) = \frac{1}{2}x^{\top}Px - c^{\top}x + \lambda^{\top}(Ax - b)$ - Обновление прямых переменных $$ x_{k+1} = P^{-1}(c - A^{\top}\lambda_k) $$ ``` m, n = 10, 20 A = np.random.randn(m, n) b = np.random.randn(m) P = np.random.randn(n, n) P = P.T @ P c = np.random.randn(n) spec = np.linalg.eigvalsh(P) mu = spec.min() print(mu) x = cvx.Variable(n) obj = 0.5 * cvx.quad_form(x, P) - c @ x problem = cvx.Problem(cvx.Minimize(obj), [A @ x == b]) problem.solve(verbose=True) print(np.linalg.norm(A @ x.value - b)) print(problem.value) x0 = np.random.randn(n) lam0 = np.random.randn(m) max_iter = 100000 alpha = mu / 10 def f(x): return 0.5 * x @ P @ x - c @ x def L(x, lam): return f(x) + lam @ (A @ x - b) def update_x(x, lam, A, b): return np.linalg.solve(P, c - A.T @ lam) x_da, lam_da, conv_x_da, conv_lam_da = dual_ascent(update_x, A, b, alpha, x0, lam0, max_iter) print(np.linalg.norm(A @ x_da - b)) print(0.5 * x_da @ P @ x_da - c @ x_da) plt.plot([f(x) for x in conv_x_da], label="Objective") plt.plot(problem.value * np.ones(len(conv_x_da)), label="Target value") # plt.yscale("log") plt.xscale("log") plt.legend(fontsize=20) plt.xlabel("\# iterations", fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.plot([L(x, lam) for x, lam in zip(conv_x_da, conv_lam_da)], label="Lagrangian") plt.legend(fontsize=20) plt.xlabel("\# iterations", fontsize=20) plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_da], label="$\|Ax - b\|_2$") plt.legend(fontsize=20) plt.xlabel("\# iterations", fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.grid(True) ``` ### Важный частный случай - Функция сепарабельна - Обновление $x$ распадается на параллельные задачи по каждой координате ## Явный учёт наличия ограничений - регуляризация Лагранжиана $$ L_{\rho}(x, \lambda) = f(x) + \lambda^{\top}(Ax - b) + \frac{\rho}{2} \|Ax - b\|_2^2 $$ - Теперь метод примет вид \begin{align*} & x_{k+1} = \arg\min_x L_{\rho}(x, \lambda)\\ & \lambda_{k+1} = \lambda_k + \rho (Ax_{k+1} - b) \end{align*} - Возможны изменения $\rho$ в процессе сходимости - Замена $\alpha_k$ на $\rho$ связаны с условиями оптимальности ``` def augmented_lagrangian(update_x, A, b, rho0, x0, lambda0, max_iter): x = x0.copy() lam = lambda0.copy() conv_x = [x] conv_lam = [lam] rho = rho0 for i in range(max_iter): x = update_x(x, lam, A, b) lam = lam + rho * (A @ x - b) conv_x.append(x.copy()) conv_lam.append(lam.copy()) return x, lam, conv_x, conv_lam def update_x_al(x, lam, A, b): return np.linalg.solve(P + rho * A.T @ A, c - A.T @ lam + A.T @ b) rho = 10 max_iter = 1000 x_al, lam_al, conv_x_al, conv_lam_al = augmented_lagrangian(update_x_al, A, b, rho, x0, lam0, max_iter) print(np.linalg.norm(A @ x_al - b)) print(0.5 * x_al @ P @ x_al - c @ x_al) plt.plot([f(x) for x in conv_x_da], label="DA") plt.plot([f(x) for x in conv_x_al], label="AL") # plt.yscale("log") plt.xscale("log") plt.legend(fontsize=20) plt.xlabel("\# iterations", fontsize=20) plt.ylabel("Objective", fontsize=20) plt.plot([L(x, lam) for x, lam in zip(conv_x_da, conv_lam_da)], label="DA") plt.plot([L(x, lam) for x, lam in zip(conv_x_al, conv_lam_al)], label="AL") plt.legend(fontsize=20) plt.xscale("log") plt.xlabel("\# iterations", fontsize=20) plt.xlabel("Lagrangian", fontsize=20) plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_da], label="DA") plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_al], label="AL") plt.legend(fontsize=20) plt.xscale("log") plt.xlabel("\# iterations", fontsize=20) plt.ylabel("$\|Ax - b\|_2$", fontsize=20) plt.yticks(fontsize=20) plt.xticks(fontsize=20) ``` ### Существенная проблема - Слагаемое $\|Ax - b\|_2^2$ сделало лагранжиан НЕсепарабельным! ## Сделаем его сепарабельным и получим ADMM Задача станет такой \begin{align*} & \min f(x) + I_{Ax = b} (z)\\ \text{s.t. } & x = z \end{align*} Для неё модифицированный лагранжиан примет вид $$ L_{\rho}(x, z, \lambda) = f(x) + I_{Ax = b} (z) + \lambda^{\top}(x - z) + \frac{\rho}{2}\|x - z\|_2^2 $$ - Теперь метод примет вид \begin{align*} & x_{k+1} = \arg\min_x L_{\rho}(x, z_k, \lambda_k)\\ & z_{k+1} = \arg\min_z L_{\rho}(x_{k+1}, z, \lambda_k) \\ & \lambda_{k+1} = \lambda_k + \rho (x_{k+1} - z_{k+1}) \end{align*} - Обновление $z$ эквивалентно $\pi_{Ax = b}(x_{k+1} + \frac{\lambda_k}{\rho})$ ``` def admm(update_x, update_z, rho0, x0, z0, lambda0, max_iter): x = x0.copy() z = z0.copy() lam = lambda0.copy() conv_x = [x] conv_z = [z] conv_lam = [lam] rho = rho0 for i in range(max_iter): x = update_x(x, z, lam, A, b) z = update_z(x, z, lam, A, b) lam = lam + rho * (x - z) conv_x.append(x.copy()) conv_z.append(z.copy()) conv_lam.append(lam.copy()) return x, z, lam, conv_x, conv_z, conv_lam def update_x_admm(x, z, lam, A, b): n = x.shape[0] return np.linalg.solve(P + rho*np.eye(n), -lam + c + rho * z) def update_z_admm(x, z, lam, A, b): x_hat = lam / rho + x return x_hat - A.T @ np.linalg.solve(A @ A.T, A @ x_hat - b) z0 = np.random.randn(n) lam0 = np.random.randn(n) rho = 1 x_admm, z_admm, lam_admm, conv_x_admm, conv_z_admm, conv_lam_admm = admm(update_x_admm, update_z_admm, rho, x0, z0, lam0, max_iter=10000) plt.figure(figsize=(10, 8)) plt.plot([f(x) for x in conv_x_da], label="DA") plt.plot([f(x) for x in conv_x_al], label="AL") plt.plot([f(x) for x in conv_x_admm], label="ADMM x") plt.plot([f(z) for z in conv_z_admm], label="ADMM z") # plt.yscale("log") plt.xscale("log") plt.legend(fontsize=20) plt.xlabel("\# iterations", fontsize=20) plt.ylabel("Objective", fontsize=20) plt.grid(True) plt.yticks(fontsize=20) plt.xticks(fontsize=20) plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_da], label="DA") plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_al], label="AL") plt.semilogy([np.linalg.norm(A @ x - b) for x in conv_x_admm], label="ADMM") plt.legend(fontsize=20) plt.xscale("log") plt.xlabel("\# iterations", fontsize=20) plt.ylabel("$\|Ax - b\|_2$", fontsize=20) plt.grid(True) plt.yticks(fontsize=20) plt.show() plt.semilogy([np.linalg.norm(x - z) for x, z in zip(conv_x_admm, conv_z_admm)]) plt.grid(True) plt.xlabel("\# iterations", fontsize=20) plt.ylabel("$\|x_k - z_k\|_2$", fontsize=20) plt.yticks(fontsize=20) plt.show() ``` ### Учтём, что все свойства сохранятся при аффинных преобразованиях - Тогда наша задача в общем виде может быть записана как \begin{align*} & \min f(x) + g(z)\\ \text{s.t. } & Ax + Bz = d \end{align*} - Модифицированный лагранжиан для неё будет $$ L_{\rho}(x, z, \lambda) = f(x) + g(z) + \lambda^{\top}(Ax + Bz - d) + \frac{\rho}{2}\|Ax + Bz - d\|_2^2 $$ - В этом случае сепарабельность по $z$ и $x$, но не внутри этих переменных - В итоге, после внесения линейного слагаемого в квадратичное получим \begin{align*} & x_{k+1} = \arg\min_x \left( f(x) + \frac{\rho}{2}\|Ax + Bz_k - d + u_k \|_2^2 \right)\\ & z_{k+1} = \arg\min_z \left( g(z) + \frac{\rho}{2}\|Ax_{k+1} + Bz - d + u_k \|_2^2 \right)\\ & u_{k+1} = u_k + x_{k+1} - z_{k+1}, \end{align*} где $u_k = \lambda_k / \rho$ ### Как это всё использовать? - Часто приводить вашу задачу к стандартному виду с предыдущего слайда неудобно - Поэтому лучше для конкретной задачи приводить её руками к виду, который допускает применение ADMM - Выписать аналитически все решения вспомогательных задач - Реализовать их вычисления наиболее оптимальным образом (сделать факторизации матриц, которые не меняются с итерациями) ## Задача линейного программирования \begin{align*} & \min c^{\top}x\\ \text{s.t. } & Ax = b\\ & x \geq 0 \end{align*} - Модифицированный лагранжиан $$ L_{\rho}(x, z, \lambda) = c^{\top}x + I_{z \geq 0}(z) + \lambda^{\top}(x - z) + \frac{\rho}{2}\|x - z\|_2^2, $$ где $c^{\top}x$ определена на множестве $Ax = b$. - Шаг обновления по $x$ примет вид $$ x_{k+1} = \arg\min_{x: \; Ax = b} c^{\top}x +\lambda^{\top}x + \frac{\rho}{2}\|x - z\|_2^2 $$ - Получим систему из условий оптимальности $$ \begin{bmatrix} \rho I & A^{\top} \\ A & 0 \end{bmatrix} \begin{bmatrix} x_{k+1}\\ \mu \end{bmatrix} = \begin{bmatrix} -\lambda_k - c + \rho z_k\\ b \end{bmatrix} $$ ``` import scipy.optimize as scopt m, n = 10, 200 A = np.random.rand(m, n) b = np.random.rand(m) c = np.random.rand(n) scipy_linprog_conv = [] def callback_splin(cur_res): scipy_linprog_conv.append(cur_res) res = scopt.linprog(c, A_eq=A, b_eq=b, bounds=[(0, None) for i in range(n)], callback=callback_splin, method="simplex") print(res) def update_x_admm(x, z, lam, A, b): n = x.shape[0] m = A.shape[0] C = np.block([[rho * np.eye(n), A.T], [A, np.zeros((m, m))]]) rhs = np.block([-lam - c + rho * z, b]) return np.linalg.solve(C, rhs)[:n] def update_z_admm(x, z, lam, A, b): x_hat = lam / rho + x return np.clip(x_hat, 0, np.max(x_hat)) x0 = np.random.randn(n) z0 = np.random.randn(n) lam0 = np.random.randn(n) rho = 1 x_admm, z_admm, lam_admm, conv_x_admm, conv_z_admm, conv_lam_admm = admm(update_x_admm, update_z_admm, rho, x0, z0, lam0, max_iter=100) print(c @ x_admm - res.fun, np.linalg.norm(x_admm - res.x)) plt.figure(figsize=(10, 8)) plt.plot([c @ x for x in conv_x_admm], label="ADMM") plt.plot([c @ res.x for res in scipy_linprog_conv], label="Scipy") plt.legend(fontsize=20) plt.grid(True) plt.xlabel("\# iterations", fontsize=20) plt.ylabel("$c^{\\top}x_k$", fontsize=20) plt.yticks(fontsize=20) plt.xticks(fontsize=20) ``` ## Комментарии - Сходимость по итерациям медленнее, но стоимость одной итерации также меньше - Основной выигрыш при использовании ADMM в получении не очень точного решения **параллельно** и очень быстро - Различные способы представления задачи в виде, пригодном для использования ADMM, порождают различные методы, которые имеют различные свойства - Например в [этой](https://papers.nips.cc/paper/6746-a-new-alternating-direction-method-for-linear-programming.pdf) статье предлагается альтернативный способ решения задачи линейного программирования через ADMM - [Метод SCS](https://stanford.edu/~boyd/papers/pdf/scs_long.pdf), используемый по умолчанию в CVXPy, основан на применеии ADMM к коническому представлению исходной задачи
github_jupyter
# Summary Statistics - Exercises In these exercises we'll use a real life medical dataset to learn how to obtain basic statistics from the data. This dataset comes from [Gluegrant](https://www.gluegrant.org/), an American project that aims to find a which genes are more important for the recovery of severely injured patients! ## Objectives In this exercise the objective is for you to learn how to use Pandas functions to obtain simple statistics of Datasets. ## Dataset information The dataset is a medical dataset with 184 patients, distributed into 2 test groups where each group divided in 2, patients and control. The dataset is composed of clinical values: * Patient.id * Age * Sex * Group (to what group they belong) * Results (outcome of the patient) and of the gene expression (higher = more expressed): * Gene1: [MMP9](https://www.ncbi.nlm.nih.gov/gene/4318) * Gene2: [S100A12](https://www.ncbi.nlm.nih.gov/gene/6283) * Gene3: [MCEMP1](https://www.ncbi.nlm.nih.gov/gene/199675) * Gene4: [ACSL1](https://www.ncbi.nlm.nih.gov/gene/2180) * Gene5: [SLC7A2](https://www.ncbi.nlm.nih.gov/gene/6542) * Gene6: [CDC14B](https://www.ncbi.nlm.nih.gov/gene/8555) ``` import pandas as pd import numpy as np import math patient_data = pd.read_csv('data/everyone.csv') patient_data.head() ``` # Exercise 1 - Lets get a quick look at the groups Ok, first lets get a quick look at who is in each of the groups. In medical studies it's important that the control and patient groups aren't too different from each other, so that we can draw relevant results. ### Separate the patients and control into 2 dataframes Since we are going to perform multiple statistics on the patient and control groups, we should create a variable for each one of the groups, so that we mantain our code readable! _Remember:_ If you want to subset the comand is: `DataFrame[DataFrame.column == "Value"]` ``` # get one dataframe for each group - Patient and Control # patients = ... # control = ... # YOUR CODE HERE raise NotImplementedError() assert(patients.Group.unique()[0] == 'Patient') assert(control.Group.unique()[0] == 'Control') ``` ### Find out the Age means for each of the groups _Remember_: To find the mean of a dataframe column, just use Name_of_dataframe.column.mean() ``` # patient_mean = # Calculate the mean of the patients # control_mean = # Calculate the mean of the controls # YOUR CODE HERE raise NotImplementedError() print('The patient mean age is: {} and the control mean age is: {}'.format(patient_mean, control_mean)) ``` Expected output: The patient mean age is: 33.64556962025316 and the control mean age is: 29.884615384615383 ``` assert(math.isclose(patient_mean, 33.64556962025316, abs_tol=0.01)) ``` ### Find the Median Age of each group As seen on the presentation, the mean can affected by outliers on the data, lets check that out with the median. ``` # patient_median = # Calculate the median age of the patients # control_median = # Calculate the median age of the controls # YOUR CODE HERE raise NotImplementedError() print('The patient median age is: {} and the control median age is: {}'.format(patient_median,control_median)) ``` Expected output: The patient median age is: 33.0 and the control median age is: 33.0 ``` assert math.isclose(patient_median, 33) ``` ### Find the Standard deviation Age of each group Let's see if there is a large deviation from the mean in each of the groups. ``` # patient_std = # Standard Deviation age of the patients # control_std = # Standard Deviation age of the controls # YOUR CODE HERE raise NotImplementedError() print('The patient std is: {} and the control std is: {}'.format(patient_std,control_std)) ``` Expected output: The patient std is: 11.16698725935228 and the control std is: 10.19539866048179 ``` assert(math.isclose(patient_std, 11.1669872593522, abs_tol=0.01)) assert(math.isclose(control_std, 10.1953986604817, abs_tol=0.01)) ``` ### Find the quantiles of the Age Let's use the quantiles to obtain the dispersion of the groups. Get the 0, 0.25, 0.5, 0.75 and 1 quantiles. ``` # patient_quantiles = # Patient quantiles of the Age # control_quantiles = # Control quantiles of the Age # YOUR CODE HERE raise NotImplementedError() print(patient_quantiles) print(control_quantiles) ``` Expected output 0.00 16.0 0.25 24.0 0.50 33.0 0.75 43.0 1.00 55.0 Name: Age, dtype: float64 0.00 17.0 0.25 21.5 0.50 28.0 0.75 34.0 1.00 54.0 Name: Age, dtype: float64 ``` assert (patient_quantiles.sum()==171) assert (control_quantiles.sum()==154.5) ``` ### Find out how many patients are male and how many are female Next, let's try to find out the number or each of the sex and the prercentage of males in each of the groups. _Remember:_ To get a frequency table you can use `pd.crosstab()` - Rows: Sex - Columns: Group ``` # crosstab = # get a frequency table for Sex and Group # YOUR CODE HERE raise NotImplementedError() crosstab assert (crosstab.iloc[1,0]==17) assert (crosstab.iloc[1,1]==98) assert (crosstab.iloc[0,0]==9) assert (crosstab.iloc[0,1]==60) ``` # Exercise 2 The objective here is for you to try to find genes that are different from the patient group and control group using the tools that you learned on exercise 1. ### Gene 1 ``` #gene1_patients = # get the series of patients for Gene1 #gene1_control = # get the series of control for Gene1 # Mean # mean_gene1_patients = # Gene1 mean for patients # mean_gene1_control = # Gene1 mean for control # Median # median_gene1_patients = # Gene1 median for patients # median_gene1_control = # Gene1 median for control # Std # std_gene1_patients = # Gene1 std for patents # std_gene1_control = # Gene1 std for control # YOUR CODE HERE raise NotImplementedError() print("Patients: Mean =", mean_gene1_patients, "Median =", median_gene1_patients, "Std =", std_gene1_patients, "\t") print("Control: Mean =", mean_gene1_control, "Median =", median_gene1_control, "Std =", std_gene1_control, "\t") ``` Expected outcome: Patients: Mean = 13676.395265822784 Median = 13555.230500000001 Std = 3092.69814423062 Control: Mean = 1156.0739230769232 Median = 947.1095 Std = 854.9755207222215 ``` assert math.isclose(mean_gene1_patients, 13676.39526582278, abs_tol=0.01) assert math.isclose(mean_gene1_control, 1156.073923076923, abs_tol=0.01) assert math.isclose(median_gene1_patients, 13555.23050000000, abs_tol=0.01) assert math.isclose(median_gene1_control, 947.1095, abs_tol=0.01) ``` ### Gene 2 ``` #gene2_patients = # get the Series of patients for Gene2 #gene2_control = # get the series of control for Gene2 # Mean #mean_gene2_patients = # Gene2 mean for patients #mean_gene2_control = # Gene2 mean for control # Median # median_gene2_patients = # Gene2 median for patients # median_gene2_control = # Gene2 median for control # Std # std_gene2_patients = # Gene2 std for patents # std_gene2_control = # Gene2 std for control # YOUR CODE HERE raise NotImplementedError() print("Patients: Mean =", mean_gene2_patients, "Median =", median_gene2_patients, "Std =", std_gene2_patients, "\t") print("Control: Mean =", mean_gene2_control, "Median =", median_gene2_control, "Std =", std_gene2_control, "\t") ``` Expected outcome: Patients: Mean = 16955.4325 Median = 17023.491 Std = 2743.7304882937474 Control: Mean = 3439.741 Median = 3067.3015 Std = 1549.3355492407961 ``` assert math.isclose(mean_gene2_patients, 16955.4325, abs_tol=0.01) assert math.isclose(mean_gene2_control, 3439.741, abs_tol=0.01) assert math.isclose(median_gene2_patients, 17023.491, abs_tol=0.01) assert math.isclose(median_gene2_control, 3067.3015, abs_tol=0.01) ``` ## Can we do this without so much code? Can we obtain the previous statistics for the 2 genes without all the effort? Remember the `.describe()` method? ### Let's see for Patients ``` gene_names = ["Gene1", "Gene2"] # Get a dataframe that uses the describe for both genes for Patient group # describe_patients = # YOUR CODE HERE raise NotImplementedError() assert math.isclose(describe_patients['Gene1']['count'], 158, abs_tol=0.01) assert math.isclose(describe_patients['Gene1']['std'], 3092.698144, abs_tol=0.01) assert math.isclose(describe_patients['Gene1']['50%'], 13555.230500, abs_tol=0.01) assert math.isclose(describe_patients['Gene2']['50%'], 17023.491000, abs_tol=0.01) ``` ### Let's see for Control ``` ###### gene_names = ["Gene1", "Gene2"] # Get a dataframe that uses the describe both genes for Control group # describe_control = # YOUR CODE HERE raise NotImplementedError() assert math.isclose(describe_control['Gene1']['count'], 26) assert math.isclose(describe_control['Gene1']['std'], 854.975521) assert math.isclose(describe_control['Gene1']['50%'], 947.109500) assert math.isclose(describe_control['Gene2']['50%'], 3067.301500) ``` ## Get a list with the possible Result (there is a column `Result`) ``` # get a list with the unique possible results (there is a column for this) # result_list = # YOUR CODE HERE raise NotImplementedError() assert len(result_list)==8 assert 'control' in result_list assert '02: Skilled nursing facility' in result_list ```
github_jupyter
``` # -*- coding: utf-8 -*- import pymongo import pymysql from lxml import etree import re import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") # -*- coding: utf-8 -*- import pymongo import urllib def get_mongo_db_client(): username_str = 'breadt' password_str = 'Breadt@2019' username = urllib.parse.quote_plus(username_str) password = urllib.parse.quote_plus(password_str) client = pymongo.MongoClient('mongodb://%s:%s@192.168.31.87:27017/' % (username, password)) return client def get_data_from_db(date, city): client = get_mongo_db_client() db = client['ke'] data = [] cursor = db['kelist'].find({'date': date, 'city': city}) for r in cursor: content = re.sub(r'<script[^>]*?>(?:.|\n)*?<\/script>', '', r['content']) content = re.sub(r'<meta.+>', '', content) content = re.sub(r'<link.+>', '', content) content = re.sub(r'<!--.+-->', '', content) content = re.sub(r'\n', '', content) content = re.sub(r'<br/>', '', content) content = re.sub(r'<span class="houseIcon"></span>', '', content) pattern = re.compile(r'<li class="clear">.*?</li>') # 查找数字 result = pattern.findall(content) for item in result: html = etree.HTML(item) house_info = html.xpath('//div[@class="houseInfo"]/text()')[0].replace(' ', '') house_info_arr = house_info.split('|') if len(house_info_arr) == 5: year = house_info_arr[1].replace('年建', '') elif len(house_info_arr) == 4: year = house_info_arr[1].replace('年建', '') else: year = 0 if len(house_info_arr) == 5: size = house_info_arr[3].replace('平米', '') elif len(house_info_arr) == 3: size = house_info_arr[1].replace('平米', '') else: size = house_info_arr[-1].replace('平米', '') if len(house_info_arr) == 5: structure = house_info_arr[2] elif len(house_info_arr) == 4: structure = house_info_arr[2] else: structure = house_info_arr[0].split(')')[1] if len(house_info_arr) == 5: op = house_info_arr[4] elif len(house_info_arr) == 3: op = house_info_arr[2] else: op = 0 if len(house_info_arr) == 5: level = house_info_arr[0] elif len(house_info_arr) == 3: level = house_info_arr[0].split(')')[0] else: level = house_info_arr[0] tax_info = html.xpath('//span[@class="taxfree"]/text()') data.append({ 'city': r['city'], 'district': r['district'], 'hotpot': r['hotpot'], 'href': html.xpath('//a[contains(@class,"maidian-detail")]/@href')[0], 'title':html.xpath('//a[contains(@class,"maidian-detail")]/@title')[0], 'info': house_info, 'level': level, 'year': year, 'structure': structure, 'size': size, 'op': op, 'price': html.xpath('//div[@class="totalPrice"]/span/text()')[0], 'tax': tax_info[0] if len(tax_info) > 0 else 0, 'date': r['date'], 'address': html.xpath('//div[@class="positionInfo"]//a/text()')[0], }) return data data = get_data_from_db('2019-11-26', '上海') df = pd.DataFrame(data) t = df[['address', 'level', 'op', 'price', 'size','structure', 'tax', 'title', 'year']] t['price'] = t['price'].astype(np.float32) t['size'] = t['size'].astype(np.float32) t['avg_price'] = t['price'] / t['size'] t.to_csv('shanghai.csv', index=False) ```
github_jupyter
<a href="https://colab.research.google.com/github/mikislin/summer20-Intro-python/blob/master/07_Matplotlib_Solutions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **(a)** Write a Python program to draw a scatter plot using random distributions to generate drops of different sizes and colors ``` import numpy as np import matplotlib.pyplot as plt # create random data no_of_balls = 25 x = [np.random.triangular(0.1,0.5,1) for i in range(no_of_balls)] y = [np.random.random(1) for i in range(no_of_balls)] colors = [np.random.randint(1, 4) for i in range(no_of_balls)] areas = [np.pi * np.random.randint(5, 15)**2 for i in range(no_of_balls)] # draw the plot plt.figure() plt.scatter(x, y, s=areas, c=colors, alpha=0.85) plt.axis([0.0, 1.0, 0.0, 1.0]) plt.xlabel("X") plt.ylabel("Y") plt.show() ``` **(b)** creat a random grayscale image (5,5) and apply apply the following interpolations with imshow() [None, 'none', 'nearest', 'bilinear','bicubic', 'spline16', 'spline36', 'hanning', 'hamming','hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'] show results side-by-side hint: use `subplot_kw={'xticks': [], 'yticks': []}` when defining the fig and axs to remove x,y ticks ``` methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'] # Fixing random state for reproducibility np.random.seed(123) grid = np.random.rand(5, 5) fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6), subplot_kw={'xticks': [], 'yticks': []}) for ax, interp_method in zip(axs.flat, methods): ax.imshow(grid, interpolation=interp_method, cmap='viridis') ax.set_title(str(interp_method)) plt.tight_layout() plt.show() ``` **(c)** Make two 50 sec signals with 10ms time resolution and consist of a coherent part (cos(pi * 2 * freq *x) at 5Hz and a random part (white noise). Plot coherence and cross-correlation of two signals with ax.cohere() and ax.xcorr(). Add autocorrelations with ax.acorr() and maxlags=50 ``` np.random.seed(123) dt = 0.01 t = np.arange(0, 50, dt) nse1 = np.random.randn(len(t)) # white noise 1 nse2 = np.random.randn(len(t)) # white noise 2 # Two signals with a coherent part at 10Hz and a random part s1 = np.cos(np.pi* 10 * t) + nse1 s2 = np.cos(np.pi *10* t) + nse2 fig, axs = plt.subplots(2, 1) axs[0].plot(t, s1, t, s2) axs[0].set_xlim(0, 5) axs[0].set_xlabel('time') axs[0].set_ylabel('s1 and s2') axs[0].grid(True) axs[1].cohere(s1, s2, 256, 1. / dt) axs[1].set_ylabel('coherence') fig.tight_layout() plt.show() fig, axs = plt.subplots(3, 1, sharex=True) axs[0].xcorr(s1, s2, usevlines=True, maxlags=50, normed=True, lw=2) axs[0].grid(True) axs[1].acorr(s1, usevlines=True, normed=True, maxlags=50, lw=2) axs[1].grid(True) axs[2].acorr(s2, usevlines=True, normed=True, maxlags=50, lw=2) axs[2].grid(True) fig.tight_layout() plt.show() ```
github_jupyter
<b> One-Layer Atmosphere Model </b><br> Reference: Walter A. Robinson, Modeling Dynamic Climate Systems ``` import numpy as np import matplotlib.pyplot as plt plt.style.use("seaborn-dark") # Step size dt = 0.01 # Set up a 10 years simulation tmin = 0 tmax = 10 t = np.arange(tmin, tmax + dt, dt) n = len(t) # Seconds per year seconds_per_year = 365 * 24 * 60 * 60 # Albedo albedo = 0.3 # Emissivity e = 0.85 # Atmospheric Absorption atmospheric_abs = 0.1 # Stefan-Boltzmann constant sigma = 5.6696e-8 # W/m^2*K^4 # Solar constant solar_const = 1367 # W/m^2 # Density of water water_density = 1000 # kg/m^3 # Depth of the mixed layer depth_mixed_layer = 50 # m # Specific heat capacity of water spec_heat_water = 4218 # J/kg*K # Specific heat capacity of atmosphere spec_heat_atm = 1004 # J/kg*K # Gravity accelleration g = 9.81 # m/s^2 # Atmospheric pressure atm_press = 1e5; # Pa (kg/m*s^2) # Atmospheric mass mass_atm = atm_press/g; # kg # Heat capacity water heat_capacity_water = water_density * depth_mixed_layer * spec_heat_water # J/K # Heat capacity atmosphere heat_capacity_atm = mass_atm * spec_heat_atm # J/K # Initialize temperature ts = np.zeros((n,)) # Surface temperature ts[0] = 273.15 ta = np.zeros((n,)) # Atmospheric temperature ta[0] = 273.15 # Inflows (Solar to earth, IR down) - Surface # Absorbed solar energy solar = solar_const/4 * (1 - albedo) * seconds_per_year # Solar to earth solar_to_earth = solar * (1 - atmospheric_abs) # IR Down ir_down = sigma * e * ta[0] ** 4 * seconds_per_year # Outflows (IR) - Surface ir = sigma * ts[0] ** 4 * seconds_per_year # Inflows (solar to atmosphere, IR) - Atmosphere # Solar to atmosphere solar_to_atm = solar * atmospheric_abs # Outflows (IR down, IR to space) - Atmosphere # IR to space ir_to_space = ir * (1 - e) + ir_down # Flows of energy # IR norm ir_norm = np.zeros((n, )) ir_norm[0] = ir/seconds_per_year # IR down norm ir_down_norm = np.zeros((n, )) ir_down_norm[0] = ir_down/seconds_per_year # Solar to earth norm solar_to_earth_norm = np.zeros((n, )) solar_to_earth_norm[0] = solar_to_earth/seconds_per_year for k in range(1, n): # Inflows (Solar to earth, IR down) - Surface solar_to_earth = (solar_const/4 * (1 - albedo) * seconds_per_year) * (1 - atmospheric_abs) ir_down = sigma * e * ta[k-1] ** 4 * seconds_per_year # Outflows (IR) - Surface ir = sigma * ts[k-1] ** 4 * seconds_per_year # Calculate the temperature - Surface energy_ts = ts[k-1] * heat_capacity_water + (solar_to_earth + ir_down - ir) * dt ts[k] = energy_ts/heat_capacity_water # Inflows (solar to atmosphere, IR) - Atmosphere solar_to_atm = (solar_const/4 * (1 - albedo) * seconds_per_year) * atmospheric_abs # Outflows (IR down, IR to space) - Atmosphere ir_to_space = ir * (1 - e) + ir_down # Calculate the temperature - Atmosphere energy_ta = ta[k-1] * heat_capacity_atm + (ir + solar_to_atm - ir_down - ir_to_space) * dt ta[k] = energy_ta/heat_capacity_atm # Calculate IR norm, IR down, Solar to earth norm ir_norm[k] = ir/seconds_per_year ir_down_norm[k] = ir_down/seconds_per_year solar_to_earth_norm[k] = solar_to_earth/seconds_per_year # Convert to °C ts = ts - 273.15 ta = ta - 273.15 # Plot Ts and Ta fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (8, 6)) ax1.set_xlabel("Years") ax1.set_ylabel("Temperature (°C)") ax1.set_title("Surface and atmospheric temperatures in the one-layer climate model") ax1.plot(t, ts, c="tab:red") ax1.plot(t, ta, c="tab:blue") ax1.legend(("T surface","T atmosphere")) ax1.grid() # Plot the Flows ax2.set_xlabel("Years") ax2.set_ylabel("Flow of energy ($W/m^{2}$)") ax2.set_title("Flows of energy to and from the surface in the one-layer model") ax2.set_ylim(0, ir_norm.max() + 10) ax2.plot(t, ir_norm, c="tab:purple") ax2.plot(t, solar_to_earth_norm, c="tab:orange") ax2.plot(t, ir_down_norm, c="tab:green") ax2.grid() ax2.legend(("IR", "Solar to earth", "IR down")) plt.tight_layout() plt.show() print(f"Final Temperature, T={round(ts[-1])}°C") ```
github_jupyter
``` import keras from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, CuDNNLSTM, CuDNNGRU, BatchNormalization, LocallyConnected2D, Permute, TimeDistributed, Bidirectional from keras.layers import Concatenate, Reshape, Softmax, Conv2DTranspose, Embedding, Multiply from keras.callbacks import ModelCheckpoint, EarlyStopping, Callback from keras import regularizers from keras import backend as K from keras.utils.generic_utils import Progbar from keras.layers.merge import _Merge import keras.losses from functools import partial from collections import defaultdict import tensorflow as tf from tensorflow.python.framework import ops import isolearn.keras as iso import numpy as np import tensorflow as tf import logging logging.getLogger('tensorflow').setLevel(logging.ERROR) import pandas as pd import os import pickle import numpy as np import scipy.sparse as sp import scipy.io as spio import matplotlib.pyplot as plt import isolearn.io as isoio import isolearn.keras as isol from sequence_logo_helper_protein import plot_protein_logo as plot_protein_logo_scrambler from sequence_logo_helper_protein import plot_importance_scores import pandas as pd from keras.backend.tensorflow_backend import set_session from adam_accumulate_keras import * def contain_tf_gpu_mem_usage() : config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) set_session(sess) contain_tf_gpu_mem_usage() class EpochVariableCallback(Callback) : def __init__(self, my_variable, my_func) : self.my_variable = my_variable self.my_func = my_func def on_epoch_begin(self, epoch, logs={}) : K.set_value(self.my_variable, self.my_func(K.get_value(self.my_variable), epoch)) class IdentityEncoder(iso.SequenceEncoder) : def __init__(self, seq_len, channel_map) : super(IdentityEncoder, self).__init__('identity', (seq_len, len(channel_map))) self.seq_len = seq_len self.n_channels = len(channel_map) self.encode_map = channel_map self.decode_map = { val : key for key, val in channel_map.items() } def encode(self, seq) : encoding = np.zeros((self.seq_len, self.n_channels)) for i in range(len(seq)) : if seq[i] in self.encode_map : channel_ix = self.encode_map[seq[i]] encoding[i, channel_ix] = 1. return encoding def encode_inplace(self, seq, encoding) : for i in range(len(seq)) : if seq[i] in self.encode_map : channel_ix = self.encode_map[seq[i]] encoding[i, channel_ix] = 1. def encode_inplace_sparse(self, seq, encoding_mat, row_index) : raise NotImplementError() def decode(self, encoding) : seq = '' for pos in range(0, encoding.shape[0]) : argmax_nt = np.argmax(encoding[pos, :]) max_nt = np.max(encoding[pos, :]) if max_nt == 1 : seq += self.decode_map[argmax_nt] else : seq += self.decode_map[-1] return seq def decode_sparse(self, encoding_mat, row_index) : encoding = np.array(encoding_mat[row_index, :].todense()).reshape(-1, 4) return self.decode(encoding) class NopTransformer(iso.ValueTransformer) : def __init__(self, n_classes) : super(NopTransformer, self).__init__('nop', (n_classes, )) self.n_classes = n_classes def transform(self, values) : return values def transform_inplace(self, values, transform) : transform[:] = values def transform_inplace_sparse(self, values, transform_mat, row_index) : transform_mat[row_index, :] = np.ravel(values) from seqprop_protein_utils import * from seqprop_rosetta_kl_helper import _get_kl_divergence_numpy, _get_smooth_kl_divergence_numpy, _get_smooth_circular_kl_divergence_numpy from seqprop_rosetta_kl_helper import _get_kl_divergence_keras, _get_smooth_kl_divergence_keras, _get_smooth_circular_kl_divergence_keras from basinhopping_rosetta import * from trrosetta_single_model_no_msa_batched_simpler_1d_features_2 import load_saved_predictor, InstanceNormalization, msa2pssm, reweight, fast_dca, keras_collect_features, pssm_func dataset_name = "hallucinated_1517" fig_name = dataset_name def make_a3m(seqs) : alphabet = np.array(list("ARNDCQEGHILKMFPSTWYV-"), dtype='|S1').view(np.uint8) msa = np.array([list(s) for s in seqs], dtype='|S1').view(np.uint8) for i in range(alphabet.shape[0]): msa[msa == alphabet[i]] = i msa[msa > 20] = 20 return msa a3m = ["GQTFLFIHVGDDPSQMNWLHHFLQQRGMTYTEVSIPADDPSYLERTVKNALELAKESRKKGTPILIYVDDPSAASTVAKAIQEAGLDNVWVFRNGELRPV"] msa_one_hot = np.expand_dims(one_hot_encode_msa(make_a3m(a3m)), axis=0)[:, :1, ...] print(msa_one_hot.shape) #Create test data x_test = msa_one_hot[:, :1, :, :20] print(x_test.shape) x_train = np.transpose(msa_one_hot[:, ..., :20], (1, 0, 2, 3)) print(x_train.shape) #Initialize sequence encoder seq_length = x_test.shape[2] residues = list("ARNDCQEGHILKMFPSTWYV") residue_map = { residue : residue_ix for residue_ix, residue in enumerate(residues) } encoder = IdentityEncoder(seq_length, residue_map) #Define sequence templates sequence_template = '$' * seq_length sequence_mask = np.array([1 if sequence_template[j] == '$' else 0 for j in range(len(sequence_template))]) #Calculate background distribution x_mean = np.tile(np.array([0.07892653, 0.04979037, 0.0451488 , 0.0603382 , 0.01261332, 0.03783883, 0.06592534, 0.07122109, 0.02324815, 0.05647807, 0.09311339, 0.05980368, 0.02072943, 0.04145316, 0.04631926, 0.06123779, 0.0547427 , 0.01489194, 0.03705282, 0.0691271 ]).reshape(1, -1), (seq_length, 1)) x_mean_logits = np.log(x_mean) plot_protein_logo_scrambler(residue_map, np.copy(x_mean), sequence_template=sequence_template, figsize=(12, 1), logo_height=1.0, plot_start=0, plot_end=seq_length) #Calculate mean test seqeunce kl-divergence against background x_test_clipped = np.clip(np.copy(x_test[:, 0, :, :]), 1e-8, 1. - 1e-8) kl_divs = np.sum(x_test_clipped * np.log(x_test_clipped / np.tile(np.expand_dims(x_mean, axis=0), (x_test_clipped.shape[0], 1, 1))), axis=-1) / np.log(2.0) x_mean_kl_divs = np.sum(kl_divs * sequence_mask, axis=-1) / np.sum(sequence_mask) x_mean_kl_div = np.mean(x_mean_kl_divs) print("Mean KL Div against background (bits) = " + str(x_mean_kl_div)) from tensorflow.python.framework import ops #Stochastic Binarized Neuron helper functions (Tensorflow) #ST Estimator code adopted from https://r2rt.com/beyond-binary-ternary-and-one-hot-neurons.html #See Github https://github.com/spitis/ def st_sampled_softmax(logits): with ops.name_scope("STSampledSoftmax") as namescope : nt_probs = tf.nn.softmax(logits) onehot_dim = logits.get_shape().as_list()[1] sampled_onehot = tf.one_hot(tf.squeeze(tf.multinomial(logits, 1), 1), onehot_dim, 1.0, 0.0) with tf.get_default_graph().gradient_override_map({'Ceil': 'Identity', 'Mul': 'STMul'}): return tf.ceil(sampled_onehot * nt_probs) def st_hardmax_softmax(logits): with ops.name_scope("STHardmaxSoftmax") as namescope : nt_probs = tf.nn.softmax(logits) onehot_dim = logits.get_shape().as_list()[1] sampled_onehot = tf.one_hot(tf.argmax(nt_probs, 1), onehot_dim, 1.0, 0.0) with tf.get_default_graph().gradient_override_map({'Ceil': 'Identity', 'Mul': 'STMul'}): return tf.ceil(sampled_onehot * nt_probs) @ops.RegisterGradient("STMul") def st_mul(op, grad): return [grad, grad] #Gumbel Distribution Sampler def gumbel_softmax(logits, temperature=0.5) : gumbel_dist = tf.contrib.distributions.RelaxedOneHotCategorical(temperature, logits=logits) batch_dim = logits.get_shape().as_list()[0] onehot_dim = logits.get_shape().as_list()[1] return gumbel_dist.sample() #PWM Masking and Sampling helper functions def mask_pwm(inputs) : pwm, onehot_template, onehot_mask = inputs return pwm * onehot_mask + onehot_template def sample_pwm_st(pwm_logits) : n_sequences = K.shape(pwm_logits)[0] seq_length = K.shape(pwm_logits)[2] flat_pwm = K.reshape(pwm_logits, (n_sequences * seq_length, 20)) sampled_pwm = st_sampled_softmax(flat_pwm) return K.reshape(sampled_pwm, (n_sequences, 1, seq_length, 20)) def sample_pwm_gumbel(pwm_logits) : n_sequences = K.shape(pwm_logits)[0] seq_length = K.shape(pwm_logits)[2] flat_pwm = K.reshape(pwm_logits, (n_sequences * seq_length, 20)) sampled_pwm = gumbel_softmax(flat_pwm, temperature=0.5) return K.reshape(sampled_pwm, (n_sequences, 1, seq_length, 20)) #Generator helper functions def initialize_sequence_templates(generator, encoder, sequence_templates, background_matrices, model_suffix='') : embedding_templates = [] embedding_masks = [] embedding_backgrounds = [] for k in range(len(sequence_templates)) : sequence_template = sequence_templates[k] onehot_template = encoder(sequence_template).reshape((1, len(sequence_template), 20)) for j in range(len(sequence_template)) : if sequence_template[j] not in ['$', '@'] : nt_ix = np.argmax(onehot_template[0, j, :]) onehot_template[:, j, :] = -4.0 onehot_template[:, j, nt_ix] = 10.0 onehot_mask = np.zeros((1, len(sequence_template), 20)) for j in range(len(sequence_template)) : if sequence_template[j] == '$' : onehot_mask[:, j, :] = 1.0 embedding_templates.append(onehot_template.reshape(1, -1)) embedding_masks.append(onehot_mask.reshape(1, -1)) embedding_backgrounds.append(background_matrices[k].reshape(1, -1)) embedding_templates = np.concatenate(embedding_templates, axis=0) embedding_masks = np.concatenate(embedding_masks, axis=0) embedding_backgrounds = np.concatenate(embedding_backgrounds, axis=0) generator.get_layer('template_dense' + model_suffix).set_weights([embedding_templates]) generator.get_layer('template_dense' + model_suffix).trainable = False generator.get_layer('mask_dense' + model_suffix).set_weights([embedding_masks]) generator.get_layer('mask_dense' + model_suffix).trainable = False generator.get_layer('background_dense' + model_suffix).set_weights([embedding_backgrounds]) generator.get_layer('background_dense' + model_suffix).trainable = False #Generator construction function def build_sampler(batch_size, seq_length, n_classes=1, n_samples=1, sample_mode='st', model_suffix='') : #Initialize Reshape layer reshape_layer = Reshape((1, seq_length, 20)) #Initialize background matrix onehot_background_dense = Embedding(n_classes, seq_length * 20, embeddings_initializer='zeros', name='background_dense' + model_suffix) #Initialize template and mask matrices onehot_template_dense = Embedding(n_classes, seq_length * 20, embeddings_initializer='zeros', name='template_dense' + model_suffix) onehot_mask_dense = Embedding(n_classes, seq_length * 20, embeddings_initializer='ones', name='mask_dense' + model_suffix) #Initialize Templating and Masking Lambda layer masking_layer = Lambda(mask_pwm, output_shape = (1, seq_length, 20), name='masking_layer' + model_suffix) background_layer = Lambda(lambda x: x[0] + x[1], name='background_layer' + model_suffix) #Initialize PWM normalization layer pwm_layer = Softmax(axis=-1, name='pwm' + model_suffix) #Initialize sampling layers sample_func = None if sample_mode == 'st' : sample_func = sample_pwm_st elif sample_mode == 'gumbel' : sample_func = sample_pwm_gumbel upsampling_layer = Lambda(lambda x: K.tile(x, [n_samples, 1, 1, 1]), name='upsampling_layer' + model_suffix) sampling_layer = Lambda(sample_func, name='pwm_sampler' + model_suffix) permute_layer = Lambda(lambda x: K.permute_dimensions(K.reshape(x, (n_samples, batch_size, 1, seq_length, 20)), (1, 0, 2, 3, 4)), name='permute_layer' + model_suffix) def _sampler_func(class_input, raw_logits) : #Get Template and Mask onehot_background = reshape_layer(onehot_background_dense(class_input)) onehot_template = reshape_layer(onehot_template_dense(class_input)) onehot_mask = reshape_layer(onehot_mask_dense(class_input)) #Add Template and Multiply Mask pwm_logits = masking_layer([background_layer([raw_logits, onehot_background]), onehot_template, onehot_mask]) #Compute PWM (Nucleotide-wise Softmax) pwm = pwm_layer(pwm_logits) #Tile each PWM to sample from and create sample axis pwm_logits_upsampled = upsampling_layer(pwm_logits) sampled_pwm = sampling_layer(pwm_logits_upsampled) sampled_pwm = permute_layer(sampled_pwm) sampled_mask = permute_layer(upsampling_layer(onehot_mask)) return pwm_logits, pwm, sampled_pwm, onehot_mask, sampled_mask return _sampler_func #Scrambler network definition def load_scrambler_network(seq_length, model_suffix='') : #Discriminator network definition seed_input = Lambda(lambda x: K.zeros((1, 1), dtype=tf.int32)) mask_dense = Embedding(1, seq_length, embeddings_initializer='glorot_normal', name='scrambler_mask_dense' + model_suffix) mask_reshape = Reshape((1, seq_length, 1)) mask_norm = BatchNormalization(axis=-1, name='scrambler_mask_norm' + model_suffix) mask_act = Activation('softplus') onehot_to_logits = Lambda(lambda x: 2. * x - 1., name='scrambler_onehot_to_logits' + model_suffix) scale_logits = Lambda(lambda x: x[1] * K.tile(x[0], (1, 1, 1, 20)), name='scrambler_logit_scale' + model_suffix) def _scrambler_func(sequence_input) : #Final conv out final_conv_out = mask_act(mask_norm(mask_reshape(mask_dense(seed_input(sequence_input))), training=True)) #final_conv_out = mask_act(mask_reshape(mask_dense(seed_input(sequence_input)))) #Scale inputs by importance scores scaled_inputs = scale_logits([final_conv_out, onehot_to_logits(sequence_input)]) return scaled_inputs, final_conv_out return _scrambler_func #Keras loss functions def get_margin_entropy_ame_masked(pwm_start, pwm_end, pwm_background, max_bits=1.0) : def _margin_entropy_ame_masked(pwm, pwm_mask) : conservation = pwm[:, 0, pwm_start:pwm_end, :] * K.log(K.clip(pwm[:, 0, pwm_start:pwm_end, :], K.epsilon(), 1. - K.epsilon()) / K.constant(pwm_background[pwm_start:pwm_end, :])) / K.log(2.0) conservation = K.sum(conservation, axis=-1) mask = K.max(pwm_mask[:, 0, pwm_start:pwm_end, :], axis=-1) n_unmasked = K.sum(mask, axis=-1) mean_conservation = K.sum(conservation * mask, axis=-1) / n_unmasked margin_conservation = K.switch(mean_conservation > K.constant(max_bits, shape=(1,)), mean_conservation - K.constant(max_bits, shape=(1,)), K.zeros_like(mean_conservation)) return margin_conservation return _margin_entropy_ame_masked def get_target_entropy_sme_masked(pwm_start, pwm_end, pwm_background, target_bits=1.0) : def _target_entropy_sme_masked(pwm, pwm_mask) : conservation = pwm[:, 0, pwm_start:pwm_end, :] * K.log(K.clip(pwm[:, 0, pwm_start:pwm_end, :], K.epsilon(), 1. - K.epsilon()) / K.constant(pwm_background[pwm_start:pwm_end, :])) / K.log(2.0) conservation = K.sum(conservation, axis=-1) mask = K.max(pwm_mask[:, 0, pwm_start:pwm_end, :], axis=-1) n_unmasked = K.sum(mask, axis=-1) mean_conservation = K.sum(conservation * mask, axis=-1) / n_unmasked return (mean_conservation - target_bits)**2 return _target_entropy_sme_masked def get_weighted_loss(loss_coeff=1.) : def _min_pred(y_true, y_pred) : return loss_coeff * y_pred return _min_pred #Initialize Encoder and Decoder networks batch_size = 1 #seq_length = 81 n_samples = 4 sample_mode = 'gumbel' #Load scrambler scrambler = load_scrambler_network(seq_length) #Load sampler sampler = build_sampler(batch_size, seq_length, n_classes=1, n_samples=n_samples, sample_mode=sample_mode) #Load trRosetta predictor def _tmp_load_model(model_path) : saved_model = load_model(model_path, custom_objects = { 'InstanceNormalization' : InstanceNormalization, 'reweight' : reweight, 'wmin' : 0.8, 'msa2pssm' : msa2pssm, 'tf' : tf, 'fast_dca' : fast_dca, 'keras_collect_features' : pssm_func#keras_collect_features }) return saved_model #Specfiy file path to pre-trained predictor network save_dir = os.path.join(os.getcwd(), '../../../seqprop/examples/rosetta/trRosetta/network/model2019_07') #model_name = 'model.xaa_batched_no_drop_2.h5' #Without drop model_name = 'model.xaa_batched.h5' #With drop model_path = os.path.join(save_dir, model_name) predictor = _tmp_load_model(model_path) predictor.trainable = False predictor.compile( loss='mse', optimizer=keras.optimizers.SGD(lr=0.1) ) predictor.inputs predictor.outputs #Test predictor on sequence save_figs = True pd, pt, pp, po = predictor.predict(x=[x_test[:, 0, :, :], np.concatenate([x_test, np.zeros((1, 1, x_test.shape[2], 1))], axis=-1)], batch_size=1) f, ax_list = plt.subplots(1, 4, figsize=(12, 3)) p_list = [ [pd, 'distance', ax_list[0]], [pt, 'theta', ax_list[1]], [pp, 'phi', ax_list[2]], [po, 'omega', ax_list[3]] ] for p_keras, p_name, p_ax in p_list : p_keras_vals = np.argmax(p_keras[0, ...], axis=-1) p_ax.imshow(np.max(p_keras_vals) - p_keras_vals, cmap="Reds", vmin=0, vmax=np.max(p_keras_vals)) p_ax.set_title(p_name, fontsize=14) p_ax.set_xlabel("Position", fontsize=14) p_ax.set_ylabel("Position", fontsize=14) plt.sca(p_ax) plt.xticks([0, p_keras_vals.shape[0]], [0, p_keras_vals.shape[0]], fontsize=14) plt.yticks([0, p_keras_vals.shape[1]], [0, p_keras_vals.shape[1]], fontsize=14) plt.tight_layout() if save_figs : plt.savefig(fig_name + '_p_distribs.png', transparent=True, dpi=150) plt.savefig(fig_name + '_p_distribs.svg') plt.savefig(fig_name + '_p_distribs.eps') plt.show() #Build scrambler model scrambler_class = Input(shape=(1,), name='scrambler_class') scrambler_input = Input(shape=(1, seq_length, 20), name='scrambler_input') scrambled_pwm, importance_scores = scrambler(scrambler_input) pwm_logits, pwm, sampled_pwm, _, sampled_mask = sampler(scrambler_class, scrambled_pwm) scrambler_model = Model([scrambler_input, scrambler_class], [pwm, importance_scores]) #Initialize Sequence Templates and Masks initialize_sequence_templates(scrambler_model, encoder, [sequence_template], [x_mean_logits]) scrambler_model.compile( optimizer=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999), loss='mean_squared_error' ) def _get_kl_divergence_keras(p_dist, p_theta, p_phi, p_omega, t_dist, t_theta, t_phi, t_omega) : kl_dist = K.mean(K.sum(t_dist * K.log(t_dist / p_dist), axis=-1), axis=(-1, -2)) kl_theta = K.mean(K.sum(t_theta * K.log(t_theta / p_theta), axis=-1), axis=(-1, -2)) kl_phi = K.mean(K.sum(t_phi * K.log(t_phi / p_phi), axis=-1), axis=(-1, -2)) kl_omega = K.mean(K.sum(t_omega * K.log(t_omega / p_omega), axis=-1), axis=(-1, -2)) return K.mean(kl_dist + kl_theta + kl_phi + kl_omega, axis=1) #Build Auto-scrambler pipeline #Define model inputs ae_scrambler_class = Input(batch_shape=(1, 1), name='ae_scrambler_class') ae_scrambler_input = Input(batch_shape=(1, 1, seq_length, 20), name='ae_scrambler_input') scrambled_in, importance_scores = scrambler(ae_scrambler_input) #Run encoder and decoder _, scrambled_pwm, scrambled_sample, pwm_mask, sampled_mask = sampler(ae_scrambler_class, scrambled_in) #Define layer to deflate sample axis deflate_scrambled_sample = Lambda(lambda x: K.reshape(x, (batch_size * n_samples, 1, seq_length, 20)), name='deflate_scrambled_sample') #Deflate sample axis scrambled_sample_deflated = deflate_scrambled_sample(scrambled_sample) #Make reference prediction on non-scrambled input sequence collapse_input_layer_non_scrambled = Lambda(lambda x: x[:, 0, :, :], output_shape=(seq_length, 20)) create_msa_layer_non_scrambled = Lambda(lambda x: K.concatenate([x, K.zeros((x.shape[0], x.shape[1], x.shape[2], 1))], axis=-1), output_shape=(1, seq_length, 21)) collapsed_in_non_scrambled = collapse_input_layer_non_scrambled(ae_scrambler_input) collapsed_in_non_scrambled_msa = create_msa_layer_non_scrambled(ae_scrambler_input) p_dist_non_scrambled_deflated, p_theta_non_scrambled_deflated, p_phi_non_scrambled_deflated, p_omega_non_scrambled_deflated = predictor([collapsed_in_non_scrambled, collapsed_in_non_scrambled_msa]) #Make prediction on scrambled sequence samples collapse_input_layer = Lambda(lambda x: x[:, 0, :, :], output_shape=(seq_length, 20)) create_msa_layer = Lambda(lambda x: K.concatenate([x, K.zeros((x.shape[0], x.shape[1], x.shape[2], 1))], axis=-1), output_shape=(1, seq_length, 21)) collapsed_in = collapse_input_layer(scrambled_sample_deflated) collapsed_in_msa = create_msa_layer(scrambled_sample_deflated) p_dist_scrambled_deflated, p_theta_scrambled_deflated, p_phi_scrambled_deflated, p_omega_scrambled_deflated = predictor([collapsed_in, collapsed_in_msa]) #Define layer to inflate sample axis inflate_dist_target = Lambda(lambda x: K.expand_dims(x, axis=1), name='inflate_dist_target') inflate_theta_target = Lambda(lambda x: K.expand_dims(x, axis=1), name='inflate_theta_target') inflate_phi_target = Lambda(lambda x: K.expand_dims(x, axis=1), name='inflate_phi_target') inflate_omega_target = Lambda(lambda x: K.expand_dims(x, axis=1), name='inflate_omega_target') inflate_dist_prediction = Lambda(lambda x: K.reshape(x, (batch_size, n_samples, seq_length, seq_length, 37)), name='inflate_dist_prediction') inflate_theta_prediction = Lambda(lambda x: K.reshape(x, (batch_size, n_samples, seq_length, seq_length, 25)), name='inflate_theta_prediction') inflate_phi_prediction = Lambda(lambda x: K.reshape(x, (batch_size, n_samples, seq_length, seq_length, 13)), name='inflate_phi_prediction') inflate_omega_prediction = Lambda(lambda x: K.reshape(x, (batch_size, n_samples, seq_length, seq_length, 25)), name='inflate_omega_prediction') #Inflate sample axis p_dist_non_scrambled = inflate_dist_target(p_dist_non_scrambled_deflated) p_theta_non_scrambled = inflate_theta_target(p_theta_non_scrambled_deflated) p_phi_non_scrambled = inflate_phi_target(p_phi_non_scrambled_deflated) p_omega_non_scrambled = inflate_omega_target(p_omega_non_scrambled_deflated) p_dist_scrambled = inflate_dist_prediction(p_dist_scrambled_deflated) p_theta_scrambled = inflate_theta_prediction(p_theta_scrambled_deflated) p_phi_scrambled = inflate_phi_prediction(p_phi_scrambled_deflated) p_omega_scrambled = inflate_omega_prediction(p_omega_scrambled_deflated) #Cost function parameters pwm_start = 0 pwm_end = seq_length target_bits = 1.0 #NLL cost nll_loss_func = _get_kl_divergence_keras #Conservation cost conservation_loss_func = get_target_entropy_sme_masked(pwm_start=pwm_start, pwm_end=pwm_end, pwm_background=x_mean, target_bits=1.8) #Entropy cost entropy_loss_func = get_target_entropy_sme_masked(pwm_start=pwm_start, pwm_end=pwm_end, pwm_background=x_mean, target_bits=target_bits) #entropy_loss_func = get_margin_entropy_ame_masked(pwm_start=pwm_start, pwm_end=pwm_end, pwm_background=x_mean, max_bits=target_bits) #Define annealing coefficient anneal_coeff = K.variable(0.0) #Execute NLL cost nll_loss = Lambda(lambda x: nll_loss_func(x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]), name='nll')([ p_dist_non_scrambled, p_theta_non_scrambled, p_phi_non_scrambled, p_omega_non_scrambled, p_dist_scrambled, p_theta_scrambled, p_phi_scrambled, p_omega_scrambled ]) #Execute conservation cost conservation_loss = Lambda(lambda x: anneal_coeff * conservation_loss_func(x[0], x[1]), name='conservation')([scrambled_pwm, pwm_mask]) #Execute entropy cost entropy_loss = Lambda(lambda x: (1. - anneal_coeff) * entropy_loss_func(x[0], x[1]), name='entropy')([scrambled_pwm, pwm_mask]) loss_model = Model( [ae_scrambler_class, ae_scrambler_input], [nll_loss, conservation_loss, entropy_loss] ) #Initialize Sequence Templates and Masks initialize_sequence_templates(loss_model, encoder, [sequence_template], [x_mean_logits]) opt = AdamAccumulate(lr=0.01, beta_1=0.5, beta_2=0.9, accum_iters=2) loss_model.compile( optimizer=opt, loss={ 'nll' : get_weighted_loss(loss_coeff=1.0), 'conservation' : get_weighted_loss(loss_coeff=1.0), 'entropy' : get_weighted_loss(loss_coeff=10.0) } ) scrambler_model.summary() loss_model.summary() #Training configuration #Define number of training epochs n_iters = 500 * 2 #Define experiment suffix (optional) experiment_suffix = "_kl_divergence_per_example_gradacc_2_native_bg" model_name = "autoscrambler_rosetta_" + dataset_name + "_n_iters_" + str(n_iters) + "_n_samples_" + str(n_samples) + "_target_bits_" + str(target_bits).replace(".", "") + experiment_suffix print("Model save name = " + model_name) #(Re-)Initialize scrambler mask def reset_generator(scrambler_model, verbose=False) : session = K.get_session() for layer in scrambler_model.layers : if 'scrambler' in layer.name : for v in layer.__dict__: v_arg = getattr(layer, v) if hasattr(v_arg,'initializer'): initializer_method = getattr(v_arg, 'initializer') initializer_method.run(session=session) if verbose : print('reinitializing layer {}.{}'.format(layer.name, v)) #(Re-)Initialize Optimizer def reset_optimizer(opt, verbose=False) : session = K.get_session() for v in opt.__dict__: v_arg = getattr(opt, v) if hasattr(v_arg,'initializer'): initializer_method = getattr(v_arg, 'initializer') initializer_method.run(session=session) if verbose : print('reinitializing optimizer parameter {}'.format(v)) #Reset mask reset_generator(scrambler_model, verbose=True) reset_generator(loss_model, verbose=True) reset_optimizer(opt, verbose=True) #Execute training procedure class LossHistory(keras.callbacks.Callback) : def on_train_begin(self, logs={}): self.nll_losses = [] self.entropy_losses = [] self.conservation_losses = [] def on_batch_end(self, batch, logs={}) : self.nll_losses.append(logs.get('nll_loss')) self.entropy_losses.append(logs.get('entropy_loss')) self.conservation_losses.append(logs.get('conservation_loss')) s_test = np.zeros((1, 1)) pwm_test = [] importance_scores_test = [] train_histories = [] for data_ix in range(x_test.shape[0]) : if data_ix % 100 == 0 : print("Optimizing example " + str(data_ix) + "...") train_history = LossHistory() # train the autoscrambler _ = loss_model.fit( [s_test, x_test[data_ix:data_ix+1]], [s_test, s_test, s_test], epochs=1, steps_per_epoch=n_iters, callbacks=[train_history] ) temp_pwm, temp_importance_scores = scrambler_model.predict_on_batch(x=[x_test[data_ix:data_ix+1], s_test]) pwm_test.append(temp_pwm) importance_scores_test.append(temp_importance_scores) train_histories.append(train_history) #Reset mask reset_generator(scrambler_model) reset_generator(loss_model) reset_optimizer(opt) save_figs = True def _rolling_average(x, window=1) : x_avg = [] for j in range(x.shape[0]) : j_min = max(j - window + 1, 0) x_avg.append(np.mean(x[j_min:j+1])) return np.array(x_avg) train_history = train_histories[0] f, (ax1, ax2) = plt.subplots(1, 2, figsize=(2 * 4, 3)) n_epochs_actual = len(train_history.nll_losses) nll_rolling_window = 50 entropy_rolling_window = 1 ax1.plot(np.arange(1, n_epochs_actual + 1), _rolling_average(np.array(train_history.nll_losses), window=nll_rolling_window), linewidth=3, color='green') plt.sca(ax1) plt.xlabel("Epochs", fontsize=14) plt.ylabel("NLL", fontsize=14) plt.xlim(1, n_epochs_actual) plt.xticks([1, n_epochs_actual], [1, n_epochs_actual], fontsize=12) plt.yticks(fontsize=12) ax2.plot(np.arange(1, n_epochs_actual + 1), _rolling_average(np.array(train_history.entropy_losses), window=entropy_rolling_window), linewidth=3, color='orange') plt.sca(ax2) plt.xlabel("Epochs", fontsize=14) plt.ylabel("Entropy Loss", fontsize=14) plt.xlim(1, n_epochs_actual) plt.xticks([1, n_epochs_actual], [1, n_epochs_actual], fontsize=12) plt.yticks(fontsize=12) plt.tight_layout() if save_figs : plt.savefig(model_name + '_losses.png', transparent=True, dpi=150) plt.savefig(model_name + '_losses.eps') plt.show() #Visualize a reconstructed sequence pattern save_figs = True for plot_i in range(0, 1) : print("Test sequence " + str(plot_i) + ":") subtracted_logits_test = (2. * np.array(x_test[plot_i:plot_i+1], dtype=np.float64) - 1.) * np.maximum(np.array(importance_scores_test[plot_i], dtype=np.float64), 1e-7) subtracted_pwm_test = np.exp(subtracted_logits_test) / np.expand_dims(np.sum(np.exp(subtracted_logits_test), axis=-1), axis=-1) plot_protein_logo_scrambler(residue_map, x_test[plot_i, 0, :, :], sequence_template=sequence_template, figsize=(12, 1), plot_start=0, plot_end=seq_length, save_figs=save_figs, fig_name=model_name + "_orig_sequence") plot_protein_logo_scrambler(residue_map, pwm_test[plot_i][0, 0, :, :], sequence_template=sequence_template, figsize=(12, 1), plot_start=0, plot_end=seq_length, save_figs=save_figs, fig_name=model_name + "_scrambled_pwm") plot_protein_logo_scrambler(residue_map, subtracted_pwm_test[0, 0, :, :], sequence_template=sequence_template, figsize=(12, 1), plot_start=0, plot_end=seq_length, save_figs=save_figs, fig_name=model_name + "_scrambled_pwm_no_bg") importance_scores = np.concatenate(importance_scores_test, axis=0) #Visualize importance scores save_figs = True f = plt.figure(figsize=(4, 1)) plt.imshow(importance_scores.reshape(1, -1), aspect='auto', cmap="hot", vmin=0, vmax=np.max(importance_scores)) plt.xticks([], []) plt.yticks([], []) plt.tight_layout() if save_figs : plt.savefig(model_name + '_p_vis1.png', transparent=True, dpi=150) plt.savefig(model_name + '_p_vis1.svg') plt.savefig(model_name + '_p_vis1.eps') plt.show() f = plt.figure(figsize=(4, 4)) p_keras_vals = np.argmax(pd[0, ...], axis=-1) plt.imshow(np.max(p_keras_vals) - p_keras_vals, cmap="Reds", vmin=0, vmax=np.max(p_keras_vals)) plt.xticks([], []) plt.yticks([], []) plt.tight_layout() if save_figs : plt.savefig(model_name + '_p_vis2.png', transparent=True, dpi=150) plt.savefig(model_name + '_p_vis2.svg') plt.savefig(model_name + '_p_vis2.eps') plt.show() #Test reconstructive ability on scrambled samples scrambled_pwm = pwm_test[0][0, 0, :, :] n_test_samples = 512 nts = np.arange(20) test_samples = np.zeros((n_test_samples, 1, scrambled_pwm.shape[0], scrambled_pwm.shape[1])) for sample_ix in range(n_test_samples) : for j in range(scrambled_pwm.shape[0]) : rand_nt = np.random.choice(nts, p=scrambled_pwm[j, :]) test_samples[sample_ix, 0, j, rand_nt] = 1. test_samples_msa = np.concatenate([ test_samples, np.zeros((test_samples.shape[0], test_samples.shape[1], test_samples.shape[2], 1)) ], axis=-1) #Test predictor on scrambled sequences pd_scrambled, pt_scrambled, pp_scrambled, po_scrambled = predictor.predict(x=[test_samples[:, 0, :, :], test_samples_msa], batch_size=4) #Calculate KL-divergences to unscrambled distributions def _get_kl_divergence_numpy(p_dist, p_theta, p_phi, p_omega, t_dist, t_theta, t_phi, t_omega) : kl_dist = np.mean(np.sum(t_dist * np.log(t_dist / p_dist), axis=-1), axis=(-2, -1)) kl_theta = np.mean(np.sum(t_theta * np.log(t_theta / p_theta), axis=-1), axis=(-2, -1)) kl_phi = np.mean(np.sum(t_phi * np.log(t_phi / p_phi), axis=-1), axis=(-2, -1)) kl_omega = np.mean(np.sum(t_omega * np.log(t_omega / p_omega), axis=-1), axis=(-2, -1)) return kl_dist + kl_theta + kl_phi + kl_omega save_figs = True kl_divs = _get_kl_divergence_numpy(pd_scrambled, pt_scrambled, pp_scrambled, po_scrambled, pd, pt, pp, po) print("Mean KL Div = " + str(round(np.mean(kl_divs), 3))) print("Median KL Div = " + str(round(np.median(kl_divs), 3))) kl_x_min = 0.0 kl_x_max = 9.0#3.0 n_bins = 50 kl_divs_histo, bin_edges = np.histogram(kl_divs, bins=n_bins, range=[kl_x_min, kl_x_max], density=True) f = plt.figure(figsize=(6, 4)) plt.bar(bin_edges[:-1], kl_divs_histo, width=(kl_x_max - kl_x_min) / n_bins, edgecolor='black', color='orange', linewidth=2) plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.xlabel("KL Divergence", fontsize=12) plt.ylabel("Sample Density", fontsize=12) plt.xlim(kl_x_min, kl_x_max) plt.tight_layout() if save_figs : plt.savefig(model_name + '_kl_hist.png', transparent=True, dpi=150) plt.savefig(model_name + '_kl_hist.eps') plt.show() #Compute mean distributions for plotting pd_scrambled_mean = np.mean(pd_scrambled, axis=0, keepdims=True) pt_scrambled_mean = np.mean(pt_scrambled, axis=0, keepdims=True) pp_scrambled_mean = np.mean(pp_scrambled, axis=0, keepdims=True) po_scrambled_mean = np.mean(po_scrambled, axis=0, keepdims=True) f, ax_list = plt.subplots(1, 4, figsize=(12, 3)) p_list = [ [pd_scrambled_mean, 'distance', ax_list[0]], [pt_scrambled_mean, 'theta', ax_list[1]], [pp_scrambled_mean, 'phi', ax_list[2]], [po_scrambled_mean, 'omega', ax_list[3]] ] for p_keras, p_name, p_ax in p_list : p_keras_vals = np.argmax(p_keras[0, ...], axis=-1) p_ax.imshow(np.max(p_keras_vals) - p_keras_vals, cmap="Reds", vmin=0, vmax=np.max(p_keras_vals)) p_ax.set_title(p_name, fontsize=14) p_ax.set_xlabel("Position", fontsize=14) p_ax.set_ylabel("Position", fontsize=14) plt.sca(p_ax) plt.xticks([0, p_keras_vals.shape[0]], [0, p_keras_vals.shape[0]], fontsize=14) plt.yticks([0, p_keras_vals.shape[1]], [0, p_keras_vals.shape[1]], fontsize=14) plt.tight_layout() if save_figs : plt.savefig(model_name + '_p_mean_distribs.png', transparent=True, dpi=150) plt.savefig(model_name + '_p_mean_distribs.eps') plt.show() kl_divs_argsort = np.argsort(kl_divs)[::-1] qt = 0.95 qt_ix = kl_divs_argsort[int(qt * kl_divs_argsort.shape[0])] pd_scrambled_qt = pd_scrambled[qt_ix:qt_ix+1] pt_scrambled_qt = pt_scrambled[qt_ix:qt_ix+1] pp_scrambled_qt = pp_scrambled[qt_ix:qt_ix+1] po_scrambled_qt = po_scrambled[qt_ix:qt_ix+1] f, ax_list = plt.subplots(1, 4, figsize=(12, 3)) p_list = [ [pd_scrambled_qt, 'distance', ax_list[0]], [pt_scrambled_qt, 'theta', ax_list[1]], [pp_scrambled_qt, 'phi', ax_list[2]], [po_scrambled_qt, 'omega', ax_list[3]] ] for p_keras, p_name, p_ax in p_list : p_keras_vals = np.argmax(p_keras[0, ...], axis=-1) p_ax.imshow(np.max(p_keras_vals) - p_keras_vals, cmap="Reds", vmin=0, vmax=np.max(p_keras_vals)) p_ax.set_title(p_name, fontsize=14) p_ax.set_xlabel("Position", fontsize=14) p_ax.set_ylabel("Position", fontsize=14) plt.sca(p_ax) plt.xticks([0, p_keras_vals.shape[0]], [0, p_keras_vals.shape[0]], fontsize=14) plt.yticks([0, p_keras_vals.shape[1]], [0, p_keras_vals.shape[1]], fontsize=14) plt.tight_layout() if save_figs : plt.savefig(model_name + '_p_qt_' + str(qt).replace(".", "") + '_distribs.png', transparent=True, dpi=150) plt.savefig(model_name + '_p_qt_' + str(qt).replace(".", "") + '_distribs.eps') plt.show() kl_divs_argsort = np.argsort(kl_divs)[::-1] qt = 0.99 qt_ix = kl_divs_argsort[int(qt * kl_divs_argsort.shape[0])] pd_scrambled_qt = pd_scrambled[qt_ix:qt_ix+1] pt_scrambled_qt = pt_scrambled[qt_ix:qt_ix+1] pp_scrambled_qt = pp_scrambled[qt_ix:qt_ix+1] po_scrambled_qt = po_scrambled[qt_ix:qt_ix+1] f, ax_list = plt.subplots(1, 4, figsize=(12, 3)) p_list = [ [pd_scrambled_qt, 'distance', ax_list[0]], [pt_scrambled_qt, 'theta', ax_list[1]], [pp_scrambled_qt, 'phi', ax_list[2]], [po_scrambled_qt, 'omega', ax_list[3]] ] for p_keras, p_name, p_ax in p_list : p_keras_vals = np.argmax(p_keras[0, ...], axis=-1) p_ax.imshow(np.max(p_keras_vals) - p_keras_vals, cmap="Reds", vmin=0, vmax=np.max(p_keras_vals)) p_ax.set_title(p_name, fontsize=14) p_ax.set_xlabel("Position", fontsize=14) p_ax.set_ylabel("Position", fontsize=14) plt.sca(p_ax) plt.xticks([0, p_keras_vals.shape[0]], [0, p_keras_vals.shape[0]], fontsize=14) plt.yticks([0, p_keras_vals.shape[1]], [0, p_keras_vals.shape[1]], fontsize=14) plt.tight_layout() if save_figs : plt.savefig(model_name + '_p_qt_' + str(qt).replace(".", "") + '_distribs.png', transparent=True, dpi=150) plt.savefig(model_name + '_p_qt_' + str(qt).replace(".", "") + '_distribs.eps') plt.show() #Save importance scores np.save(model_name + "_importance_scores", importance_scores) ```
github_jupyter
# Math Operations ``` from __future__ import print_function import torch import numpy as np from datetime import date date.today() author = "kyubyong. https://github.com/Kyubyong/pytorch_exercises" torch.__version__ np.__version__ ``` NOTE on notation _x, _y, _z, ...: NumPy 0-d or 1-d arrays<br/> _X, _Y, _Z, ...: NumPy 2-d or higer dimensional arrays<br/> x, y, z, ...: 0-d or 1-d tensors<br/> X, Y, Z, ...: 2-d or higher dimensional tensors ## Trigonometric functions Q1. Calculate sine, cosine, and tangent of x, element-wise. ``` x = torch.FloatTensor([0., 1., 30, 90]) sinx = x.sin() cosx = x.cos() tanx = x.tan() print("• sine x=", sinx) print("• cosine x=", cosx) print("• tangent x=", tanx) assert np.allclose(sinx.numpy(), np.sin(x.numpy())) assert np.allclose(cosx.numpy(), np.cos(x.numpy()) ) assert np.allclose(tanx.numpy(), np.tan(x.numpy()) ) ``` Q2. Calculate inverse sine, inverse cosine, and inverse tangent of x, element-wise. ``` x = torch.FloatTensor([-1., 0, 1.]) asinx = x.asin() acosx = x.acos() atanx = x.atan() print("• inverse sine x=", asinx) print("• inversecosine x=", acosx) print("• inverse tangent x=", atanx) assert np.allclose(asinx.numpy(), np.arcsin(x.numpy()) ) assert np.allclose(acosx.numpy(), np.arccos(x.numpy()) ) assert np.allclose(atanx.numpy(), np.arctan(x.numpy()) ) ``` ## Hyperbolic functions Q3. Calculate hyperbolic sine, hyperbolic cosine, and hyperbolic tangent of x, element-wise. ``` x = torch.FloatTensor([-1., 0, 1.]) sinhx = x.sinh() coshx = x.cosh() tanhx = x.tanh() print("• hyperbolic sine x=", sinhx) print("• hyperbolic cosine x=", coshx) print("• hyperbolic tangent x=", tanhx) assert np.allclose(sinhx.numpy(), np.sinh(x.numpy())) assert np.allclose(coshx.numpy(), np.cosh(x.numpy())) assert np.allclose(tanhx.numpy(), np.tanh(x.numpy())) ``` ## Rounding Q4. Predict the results of these. ``` x = torch.FloatTensor([2.1, 1.5, 2.5, 2.9, -2.1, -2.5, -2.9]) roundx = x.round() floorx = x.floor() ceilx = x.ceil() truncx = x.trunc() print("• roundx=", roundx) print("• floorx=", floorx) print("• ceilx=", ceilx) print("• truncx=", truncx) ``` ## Sum, product Q5. Sum the elements of X along the first dimension, retaining it. ``` X = torch.Tensor( [[1, 2, 3, 4], [5, 6, 7, 8]]) print(X.sum(dim=0, keepdim=True)) ``` Q6. Return the product of all elements in X. ``` X = torch.Tensor( [[1, 2, 3, 4], [5, 6, 7, 8]]) print(X.prod()) ``` Q7. Return the cumulative sum of all elements along the second axis in X. ``` X = torch.Tensor( [[1, 2, 3, 4], [5, 6, 7, 8]]) print(X.cumsum(dim=1)) ``` Q8. Return the cumulative product of all elements along the second axis in X. ``` X = torch.Tensor( [[1, 2, 3, 4], [5, 6, 7, 8]]) print(X.cumprod(dim=1)) ``` ## Exponents and logarithms Q9. Compute $e^x$, element-wise. ``` x = torch.Tensor([1., 2., 3.]) y = x.exp() print(y) assert np.array_equal(y.numpy(), np.exp(x.numpy())) ``` Q10. Compute logarithms of x element-wise. ``` x = torch.Tensor([1, np.e, np.e**2]) y = x.log() print(y) assert np.allclose(y.numpy(), np.log(x.numpy())) ``` ## Arithmetic Ops Q11. Add x and y element-wise. ``` x = torch.Tensor([1, 2, 3]) y = torch.Tensor([-1, -2, -3]) z = x.add(y) print(z) assert np.array_equal(z.numpy(), np.add(x.numpy(), y.numpy())) ``` Q12. Subtract y from x element-wise. ``` x = torch.Tensor([1, 2, 3]) y = torch.Tensor([-1, -2, -3]) z = y.sub(x) print(z) assert np.array_equal(z.numpy(), np.subtract(y.numpy(), x.numpy())) ``` Q13. Multiply x by y element-wise. ``` x = torch.Tensor([3, 4, 5]) y = torch.Tensor([1, 0, -1]) x_y = x.mul(y) print(x_y) assert np.array_equal(x_y.numpy(), np.multiply(x.numpy(), y.numpy())) ``` Q14. Divide x by y element-wise. ``` x = torch.FloatTensor([3., 4., 5.]) y = torch.FloatTensor([1., 2., 3.]) z = x.div(y) print(z) assert np.allclose(z.numpy(), np.true_divide(x.numpy(), y.numpy())) ``` Q15. Compute numerical negative value of x, element-wise. ``` x = torch.Tensor([1, -1]) negx = x.neg() print(negx) assert np.array_equal(negx.numpy(), np.negative(x.numpy())) ``` Q16. Compute the reciprocal of x, element-wise. ``` x = torch.Tensor([1., 2., .2]) y = x.reciprocal() print(y) assert np.array_equal(y.numpy(), np.reciprocal(x.numpy())) ``` Q17. Compute $X^Y$, element-wise. ``` X = torch.Tensor([[1, 2], [3, 4]]) Y = torch.Tensor([[1, 2], [1, 2]]) X_Y = X.pow(Y) print(X_Y) assert np.array_equal(X_Y.numpy(), np.power(X.numpy(), Y.numpy())) ``` Q18. Compute the remainder of x / y element-wise. ``` x = torch.Tensor([-3, -2, -1, 1, 2, 3]) y = 2. z = x.remainder(y) print(z) assert np.array_equal(z.numpy(), np.remainder(x.numpy(), y)) ``` Q19. Compute the fractional portion of each element of x. ``` x = torch.Tensor([1., 2.5, -3.2]) y = x.frac() print(y) assert np.allclose(y.numpy(), np.modf(x.numpy())[0]) ``` ## Comparision Ops Q20. Return True if X and Y have the same size and elements, otherise False. ``` x = torch.randperm(3) y = torch.randperm(3) print("x=", x) print("y=", y) z = x.equal(y) print(z) #np.array_equal(x.numpy(), y.numpy()) ``` Q21. Return 1 if an element of X is 0, otherwise 0. ``` X = torch.Tensor( [[-1, -2, -3], [0, 1, 2]] ) Y = X.eq(0) print(Y) assert np.allclose(Y.numpy(), np.equal(X.numpy(), 0)) ``` Q22. Return 0 if an element of X is 0, otherwise 1. ``` X = torch.Tensor( [[-1, -2, -3], [0, 1, 2]] ) Y = X.ne(0) print(Y) assert np.allclose(Y.numpy(), np.not_equal(X.numpy(), 0)) ``` Q23. Compute x >= y, x > y, x < y, and x <= y element-wise. ``` x = torch.randperm(3) y = torch.randperm(3) print("x=", x) print("y=", y) #1. x >= y z = x.ge(y) print("#1. x >= y", z) #2. x > y z = x.gt(y) print("#2. x > y", z) #3. x <= y z = x.le(y) print("#3. x <= y", z) #4. x < y z = x.lt(y) print("#4. x < y", z) ``` ## Miscellaneous Q24. If an element of x is smaller than 3, replace it with 3. And if an element of x is bigger than 7, replace it with 7. ``` x = torch.arange(0, 10) y = x.clamp(min=3, max=7) print(y) assert np.array_equal(y.numpy(), np.clip(x.numpy(), a_min=3, a_max=7)) ``` Q25. If an element of x is smaller than 3, replace it with 3. ``` x = torch.arange(0, 10) y = x.clamp(min=3) print(y) assert np.array_equal(y.numpy(), np.clip(x.numpy(), a_min=3, a_max=None)) ``` Q26. If an element of x is bigger than 7, replace it with 7. ``` x = torch.arange(0, 10) y = x.clamp(max=7) print(y) assert np.array_equal(y.numpy(), np.clip(x.numpy(), a_min=None, a_max=7)) ``` Q27. Compute square root of x element-wise. ``` x = torch.Tensor([1., 4., 9.]) y = x.sqrt() print(y) assert np.array_equal(y.numpy(), np.sqrt(x.numpy())) ``` Q28. Compute the reciprocal of the square root of x, element-wise. ``` x = torch.Tensor([1., 4., 9.]) y = x.rsqrt() print(y) assert np.allclose(y.numpy(), np.reciprocal(np.sqrt(x.numpy()))) ``` Q29. Compute the absolute value of X. ``` X = torch.Tensor([[1, -1], [3, -3]]) Y = X.abs() print(Y) assert np.array_equal(Y.numpy(), np.abs(X.numpy())) ``` Q30. Compute an element-wise indication of the sign of x, element-wise. ``` x = torch.Tensor([1, 3, 0, -1, -3]) y = x.sign() print(y) assert np.array_equal(y.numpy(), np.sign(x.numpy())) ``` Q31. Compute the sigmoid of x, elemet-wise. ``` x = torch.FloatTensor([1.2, 0.7, -1.3, 0.1]) y = x.sigmoid() print(y) assert np.allclose(y.numpy(), 1. / (1 + np.exp(-x.numpy()))) ``` Q32. Interpolate X and Y linearly with a weight of .9 on Y. ``` X = torch.Tensor([1,2,3,4]) Y = torch.Tensor([10,10,10,10]) Z = X.lerp(Y, .9) print(Z) assert np.allclose(Z.numpy(), X.numpy() + (Y.numpy()-X.numpy())*.9) ```
github_jupyter
``` import os import tensorflow as tf import pandas as pd from sklearn.utils import shuffle import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image import shutil import keras import keras.backend as K from keras.models import Model from keras import backend as K from keras.utils import np_utils from keras.optimizers import SGD, Adam from keras.datasets import cifar10 from keras.layers.core import Layer from keras.models import model_from_json from keras.callbacks import LearningRateScheduler from keras.layers import Conv2D, MaxPool2D, Dropout, Dense, Input, concatenate, GlobalAveragePooling2D, AveragePooling2D,Flatten import cv2 import numpy as np import math dest = "/content/drive/My Drive/GRID" #Note: The GRID folder here contains another GRID folder inside which has all the images in a images folder #Example: "/content/drive/My Drive/GRID/GRID/images/JPEG_20161128_141221_1000743655515.png" os.chdir(dest) print('\nCurrent...') !ls #Generate Path and labels to Training Data df = pd.read_csv('training_set.csv') df = shuffle(df, random_state=42) df['x1'] = df['x1']/640 df['x2'] = df['x2']/640 df['y1'] = df['y1']/480 df['y2'] = df['y2']/480 df['xc'] = (df['x1']+df['x2'])/2 df['yc'] = (df['y1']+df['y2'])/2 df['w'] = (df['x2']-df['x1']) df['h'] = (df['y2']-df['y1']) trainfileslist = df['image_name'].tolist() trainfileslist = ["GRID/images/" + s for s in trainfileslist] trainfileslist = [os.path.abspath(s) for s in trainfileslist ] print('Path.... =>', trainfileslist[10]) coordinates = df[['xc', 'yc', 'w', 'h']].values #Plot Image with Bounding Box def plot_image(i): img = Image.open(trainfileslist[i]) fig,ax = plt.subplots(1) ax.imshow(img) x = (coordinates[i,0]-(coordinates[i,2]/2))*640 y = (coordinates[i,1]-(coordinates[i,3]/2))*480 w = (coordinates[i,2])*640 h = (coordinates[i,3])*480 rect = patches.Rectangle((x,y),w,h,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) plt.show() plot_image(9999) #save train images in a separate folder (train_file) def save_train(): dest = "/content/drive/My Drive/GRID/GRID/train_file/" os.chdir("../..") for file_name in trainfileslist: if (os.path.isfile(file_name)): shutil.copy(file_name, dest) save_train() #Develop the Architecture and compile as a Keras model def inception_module(x, filters_1x1, filters_3x3_reduce, filters_3x3, filters_5x5_reduce, filters_5x5, filters_pool_proj, name=None): conv_1x1 = Conv2D(filters_1x1, (1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_3x3 = Conv2D(filters_3x3_reduce, (1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_3x3 = Conv2D(filters_3x3, (3, 3), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(conv_3x3) conv_5x5 = Conv2D(filters_5x5_reduce, (1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_5x5 = Conv2D(filters_5x5, (5, 5), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(conv_5x5) pool_proj = MaxPool2D((3, 3), strides=(1, 1), padding='same')(x) pool_proj = Conv2D(filters_pool_proj, (1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(pool_proj) output = concatenate([conv_1x1, conv_3x3, conv_5x5, pool_proj], axis=3, name=name) return output kernel_init = keras.initializers.glorot_uniform() bias_init = keras.initializers.Constant(value=0.2) input_layer = Input(shape=(224, 224, 3)) x = Conv2D(64, (7, 7), padding='same', strides=(2, 2), activation='relu', name='conv_1_7x7/2', kernel_initializer=kernel_init, bias_initializer=bias_init)(input_layer) x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_1_3x3/2')(x) x = Conv2D(64, (1, 1), padding='same', strides=(1, 1), activation='relu', name='conv_2a_3x3/1')(x) x = Conv2D(192, (7, 7), padding='same', strides=(2, 2), activation='relu', name='conv_2b_3x3/1')(x) x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_2_3x3/2')(x) x = inception_module(x, filters_1x1=64, filters_3x3_reduce=96, filters_3x3=128, filters_5x5_reduce=16, filters_5x5=32, filters_pool_proj=32, name='inception_3a') x1 = AveragePooling2D((5, 5), strides=3)(x) x1 = Conv2D(128, (1, 1), padding='same', activation='relu')(x1) x1 = Flatten()(x1) x1 = Dense(1024, activation='relu')(x1) #x1 = Dropout(rate = 0.1)(x1) x1 = Dense(2, activation='sigmoid', name='auxilliary_output_1')(x1) x = inception_module(x, filters_1x1=160, filters_3x3_reduce=112, filters_3x3=224, filters_5x5_reduce=24, filters_5x5=64, filters_pool_proj=64, name='inception_4b') x2 = AveragePooling2D((5, 5), strides=3)(x) x2 = Conv2D(128, (1, 1), padding='same', activation='relu')(x2) x2 = Flatten()(x2) x2 = Dense(1024, activation='relu')(x2) #x2 = Dropout(rate = 0.1)(x2) x2 = Dense(2, activation='sigmoid', name='auxilliary_output_2')(x2) #save the Architecture as model and compile it appropriate losses model = Model(input_layer, [x1, x2], name='inception_v1') model.summary() initial_lrate = 0.025 sgd = SGD(lr=initial_lrate, momentum=0.9, nesterov=False) adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) model.compile(loss='mean_absolute_error', optimizer=sgd) # Function to load Training Data in Batches def load_batch_data(index, minibatchsize): images = [] batchlist = trainfileslist[index*minibatchsize:(index+1)*minibatchsize] for i,f in enumerate(batchlist): image = Image.open(f) image = image.resize((224, 224)) image = np.array(image) images.append(image) images = np.array(images) X_train = images.astype('float32') X_train = (X_train) / 255.0 Y_train = coordinates[index*minibatchsize:(index+1)*minibatchsize,:] Y_train = Y_train.astype('float32') return X_train, Y_train # Load model and compile if already available json_file = open('model.json', 'r') model = json_file.read() json_file.close() model = model_from_json(model) model.load_weights('/content/drive/My Drive/GRID/model.h5') model.compile(loss='mean_absolute_error', optimizer=sgd) #Train the Model! minibatchsize = 250 def train(i): print("start") X_train, Y_train = load_batch_data(i, minibatchsize) print('end') history = model.train_on_batch(X_train, [Y_train[:,:2],Y_train[:,2:]]) score = model.evaluate(x=X_train, y=[Y_train[:,:2],Y_train[:,2:]], batch_size=None, verbose=1, sample_weight=None, steps=None) print('Epoch: ', j, 'Iter: ', i, "Metric: ", score) if i%10 == 5: model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights("model.h5") print("Saved model to disk") for j in range(10): for i in range(int(14000/minibatchsize)): train(i) #Check Predictions from Training Data def eval(): minibatchsize = 250 for j in range(1): for i in range(int(250/minibatchsize)): print("s") X_test, Y_test = load_batch_data(i, minibatchsize) print('e') predict = model.predict(X_test, batch_size=None, verbose=0, steps=None) print(np.shape(predict)) predcoords = predict return predcoords predcoords = eval() #Plot images to show Predictions vs Ground Truth def plot_image(i): img = Image.open(trainfileslist[i]) fig,ax = plt.subplots(1) ax.imshow(img) x = (coordinates[i,0]-(coordinates[i,2]/2))*640 y = (coordinates[i,1]-(coordinates[i,3]/2))*480 w = (coordinates[i,2])*640 h = (coordinates[i,3])*480 rect = patches.Rectangle((x,y),w,h,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) x = (predcoords[0][i][0]-(predcoords[1][i][0]/2))*640 y = (predcoords[0][i][1]-(predcoords[1][i][1]/2))*480 w = (predcoords[1][i][0])*640 h = (predcoords[1][i][1])*480 rect = patches.Rectangle((x,y),w,h,linewidth=1,edgecolor='g',facecolor='none') ax.add_patch(rect) plt.show() plot_image(5) plot_image(15) plot_image(25) plot_image(35) plot_image(45) plot_image(55) plot_image(65) plot_image(75) plot_image(85) plot_image(95) plot_image(105) plot_image(115) plot_image(125) plot_image(135) plot_image(145) plot_image(155) plot_image(165) plot_image(175) ```
github_jupyter
<a href="https://colab.research.google.com/github/AlexTeboul/msds/blob/main/csc594-topics-in-artificial-intelligence/CSC594_Emotional_Contagion_Content_Theory_Implementation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> #Alex Teboul #CSC 594 - Emotionally Intelligent Chatbot ##Content Theory Implementation: Emotional Contagion **Structured Outline Link: [Leveraging Emotional Contagion in Social Media Networks: Risks and Opportunities](https://docs.google.com/document/d/1ogNq4K2P4T7HVEK87tJAvS613AGk1N7jhonwYHgMxC8/edit?usp=sharing)** **6 Emotional States** For the purposes of this content theory, I only include the following base emotions. These help limit the scope of the emotional contagion content theory. * Joy * Sadness * Anger * Fear * Love * Surprise **3 Sentiment States** As part of the content theory, there are also 3 sentiment states that can be infered from text. These help provide a baseline for interpretting the emotional state of users. * Negative (-) * Neutral * Positive (+) **Final Implementation Goals:** *Emotional Contagion in Text* 1. Have a user input text about how they are feeling. 2. Classify the emotion in the speech or text. 3. Return the prediction of the user's emotional state in the form, "I sense that you are feeling ...[emotional state]." 4. Display 5. From the classified emotions, display content that matches those emotions **or** displays content that is antagonistic to those emotions in an effort to alter the emotional state of the user. 6. Do the same based on sentiment. 7. Ask the user's emotional state again and see if it has changed. 8. User emotional state will be transferred to the emotionally intelligent agent through this process. EIA emotional state may be transferred to user. **Reference Notebooks:** 1. Code Reference: [Deep Learning Based Emotion Recognition with TensorFlow](https://colab.research.google.com/drive/14I-31WuynLg1B0RQHWwwRgBmqTlDgkwV#scrollTo=ezRBSSehGFP_) #1. Emotional States Model Building **About this section:** In this section, I attempt to build a train a model to recognize emotional states in text. I am using a process demonstrated by Elvis Saravia to use GRU RNN. The dataset used contains roughly 417k pre-processed tweets with associated joy, sadness, anger, fear, love, and surprise labels. ## 1. Setup ``` from google.colab import drive drive.mount('/content/gdrive') #Setup import re import numpy as np import time from sklearn import preprocessing from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt %matplotlib inline import itertools import pandas as pd from scipy import stats from sklearn import metrics from sklearn.preprocessing import LabelEncoder ### Helper functions import pickle def convert_to_pickle(item, directory): pickle.dump(item, open(directory,"wb")) def load_from_pickle(directory): return pickle.load(open(directory,"rb")) import tensorflow as tf ``` ## Get the Dataset ``` # load data from tensorflow #https://github.com/omarsar/nlp_pytorch_tensorflow_notebooks/blob/master/data/merged_training.pkl data = load_from_pickle(directory="/content/gdrive/My Drive/Colab Notebooks/datasets/merged_training.pkl") plt.title("Count of Tweet Emotions in Dataset") data.emotions.value_counts().plot.bar() #count of emotions in dataset out of 416,809 #ex. there are 141,067 tweets containing the general emotion "joy" or something close to it. data.emotions.value_counts() #sample of the dataset data.head(10) ``` ## Tokenization, Sampling, Vocabulary Construction, Index-Word Mapping ``` # keep 80 tokens or less data["token_size"] = data["text"].apply(lambda x: len(x.split(' '))) data = data.loc[data['token_size'] < 70].copy() # sampling 50k data = data.sample(n=50000) # see now we have 50k tweets only that are 80 tokens or less data.shape # now we data.head() # This class creates a word -> index mapping # ("think" -> 27) and vice-versa # (27 -> "think") across this dataset sample class ConstructVocab(): def __init__(self, sentences): self.sentences = sentences self.word2idx = {} self.idx2word = {} self.vocab = set() self.create_index() def create_index(self): for s in self.sentences: # update with individual tokens self.vocab.update(s.split(' ')) # sort the vocab self.vocab = sorted(self.vocab) # add a padding token with index 0 self.word2idx['<pad>'] = 0 # word to index mapping for index, word in enumerate(self.vocab): self.word2idx[word] = index + 1 # +1 because of pad token # index to word mapping for word, index in self.word2idx.items(): self.idx2word[index] = word ``` ## Put sample Data in Tensors ``` # construct vocab and indexing inputs = ConstructVocab(data["text"].values.tolist()) # examples of what is in the vocab inputs.vocab[0:20] # how many 'words' are in the vocabulary len(inputs.vocab) # vectorize to tensor input_tensor = [[inputs.word2idx[s] for s in es.split(' ')] for es in data["text"].values.tolist()] input_tensor[0:2] def max_length(tensor): return max(len(t) for t in tensor) # calculate the max_length of input tensor max_length_inp = max_length(input_tensor) print(max_length_inp) # Padding the input and output tensor to the maximum length input_tensor = tf.keras.preprocessing.sequence.pad_sequences(input_tensor, maxlen=max_length_inp, padding='post') #Show what it's like now that it's padded input_tensor[0:2] ``` ## Binarization ``` ### convert targets to one-hot encoding vectors emotions = list(set(data.emotions.unique())) num_emotions = len(emotions) # binarizer mlb = preprocessing.MultiLabelBinarizer() data_labels = [set(emos) & set(emotions) for emos in data[['emotions']].values] bin_emotions = mlb.fit_transform(data_labels) target_tensor = np.array(bin_emotions.tolist()) # So that first row in the tensor here represents a tweet and it's corresponding emotion of sadness. target_tensor[0:2] # we now have a 6 dimensional tensor with our 60k sample tweet texts laid out by emotional state. # Refer to why in the emotion_dict produced a few code blocks below target_tensor.shape ``` ## 6 Emotional States Dictionary ``` data.head() get_emotion = lambda t: np.argmax(t) get_emotion(target_tensor[0]) #Dictionary of 6 Emotional-States emotion_dict = {0: 'anger', 1: 'fear', 2: 'joy', 3: 'love', 4: 'sadness', 5: 'surprise'} #This is the emotional state from that first entry in the target_tensor. emotion_dict[get_emotion(target_tensor[0])] ``` ## Training and Validation Set Splitting Necessary to train the model ``` # Creating training and validation sets using an 80-20 split input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2) # Split the validataion further to obtain a holdout dataset (for testing) -- split 50:50 input_tensor_val, input_tensor_test, target_tensor_val, target_tensor_test = train_test_split(input_tensor_val, target_tensor_val, test_size=0.5) # Show length len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val), len(input_tensor_test), len(target_tensor_test) ``` * We now 80-20 train test splits for NN to learn on. There's also a holdout for validation. ``` # Data Loader Code TRAIN_BUFFER_SIZE = len(input_tensor_train) VAL_BUFFER_SIZE = len(input_tensor_val) TEST_BUFFER_SIZE = len(input_tensor_test) BATCH_SIZE = 64 TRAIN_N_BATCH = TRAIN_BUFFER_SIZE // BATCH_SIZE VAL_N_BATCH = VAL_BUFFER_SIZE // BATCH_SIZE TEST_N_BATCH = TEST_BUFFER_SIZE // BATCH_SIZE embedding_dim = 256 units = 1024 vocab_inp_size = len(inputs.word2idx) target_size = num_emotions train_dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(TRAIN_BUFFER_SIZE) train_dataset = train_dataset.batch(BATCH_SIZE, drop_remainder=True) val_dataset = tf.data.Dataset.from_tensor_slices((input_tensor_val, target_tensor_val)).shuffle(VAL_BUFFER_SIZE) val_dataset = val_dataset.batch(BATCH_SIZE, drop_remainder=True) test_dataset = tf.data.Dataset.from_tensor_slices((input_tensor_test, target_tensor_test)).shuffle(TEST_BUFFER_SIZE) test_dataset = test_dataset.batch(BATCH_SIZE, drop_remainder=True) # checking minibatch print(train_dataset) print(val_dataset) print(test_dataset) ``` ## Build Model - Gated Recurrent Neural Network (GRU) Now that the data is preprocessed and transformed, we can build the model. This particular model can uses a computation graph to train our emotion classifier. A recurrent neural network could also be used instead. **Model Basic Architecture** ![alt txt](https://github.com/omarsar/nlp_pytorch_tensorflow_notebooks/blob/master/img/gru-model.png?raw=true) ``` ### define the GRU component def gru(units): # If you have a GPU, we recommend using CuDNNGRU(provides a 3x speedup than GRU) # the code automatically does that. if tf.test.is_gpu_available(): return tf.compat.v1.keras.layers.CuDNNGRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform') else: return tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_activation='relu', recurrent_initializer='glorot_uniform') ### Build the model class EmoGRU(tf.keras.Model): def __init__(self, vocab_size, embedding_dim, hidden_units, batch_sz, output_size): super(EmoGRU, self).__init__() self.batch_sz = batch_sz self.hidden_units = hidden_units # layers self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim) self.dropout = tf.keras.layers.Dropout(0.5) self.gru = gru(self.hidden_units) self.fc = tf.keras.layers.Dense(output_size) def call(self, x, hidden): x = self.embedding(x) # batch_size X max_len X embedding_dim output, state = self.gru(x, initial_state = hidden) # batch_size X max_len X hidden_units out = output[:,-1,:] out = self.dropout(out) out = self.fc(out) # batch_size X max_len X output_size return out, state def initialize_hidden_state(self): return tf.zeros((self.batch_sz, self.hidden_units)) #test that it works model = EmoGRU(vocab_inp_size, embedding_dim, units, BATCH_SIZE, target_size) # initialize the hidden state of the RNN hidden = model.initialize_hidden_state() # testing for the first batch only then break the for loop # Potential bug: out is not randomized enough for (batch, (inp, targ)) in enumerate(train_dataset): out, state = model(inp, hidden) print(out.shape) break ``` Train the GRU Model ``` optimizer = tf.optimizers.Adam() def loss_function(y, prediction): return tf.compat.v1.losses.softmax_cross_entropy(y, logits=prediction) def accuracy(y, yhat): #compare the predictions to the truth yhat = tf.argmax(yhat, 1).numpy() y = tf.argmax(y , 1).numpy() return np.sum(y == yhat)/len(y) EPOCHS = 10 for epoch in range(EPOCHS): start = time.time() ### Initialize hidden state hidden = model.initialize_hidden_state() total_loss = 0 train_accuracy, val_accuracy = 0, 0 ### Training for (batch, (inp, targ)) in enumerate(train_dataset): loss = 0 with tf.GradientTape() as tape: predictions,_ = model(inp, hidden) loss += loss_function(targ, predictions) batch_loss = (loss / int(targ.shape[1])) total_loss += batch_loss batch_accuracy = accuracy(targ, predictions) train_accuracy += batch_accuracy gradients = tape.gradient(loss, model.variables) optimizer.apply_gradients(zip(gradients, model.variables)) if batch % 100 == 0: print('Epoch {} Batch {} Val. Loss {:.4f}'.format(epoch + 1, batch, batch_loss.numpy())) ### Validating hidden = model.initialize_hidden_state() for (batch, (inp, targ)) in enumerate(val_dataset): predictions,_ = model(inp, hidden) batch_accuracy = accuracy(targ, predictions) val_accuracy += batch_accuracy print('Epoch {} Loss {:.4f} -- Train Acc. {:.4f} -- Val Acc. {:.4f}'.format(epoch + 1, total_loss / TRAIN_N_BATCH, train_accuracy / TRAIN_N_BATCH, val_accuracy / VAL_N_BATCH)) print('Time taken for 1 epoch {} sec\n'.format(time.time() - start)) model.summary() test_accuracy = 0 all_predictions = [] x_raw = [] y_raw = [] hidden = model.initialize_hidden_state() for (batch, (inp, targ)) in enumerate(test_dataset): predictions,_ = model(inp, hidden) batch_accuracy = accuracy(targ, predictions) test_accuracy += batch_accuracy x_raw = x_raw + [x for x in inp] y_raw = y_raw + [y for y in targ] all_predictions.append(predictions) print("Test Accuracy: ", test_accuracy/TEST_N_BATCH) #Save the model: model.save_weights('emo_model') ### Class to Properly Evaluate our Models class Evaluate(): def va_dist(cls, prediction, target, va_df, binarizer, name='', silent=False): """ Computes distance between actual and prediction through cosine distance """ va_matrix = va_df.loc[binarizer.classes_][['valence','arousal']].values y_va = target.dot(va_matrix) F_va = prediction.dot(va_matrix) # dist is a one row vector with size of the test data passed(emotion) dist = metrics.pairwise.paired_cosine_distances(y_va, F_va) res = stats.describe(dist) # print by default (if silent=False) if not silent: print('%s\tmean: %f\tvariance: %f' % (name, res.mean, res.variance)) return { 'distances': dist, 'dist_stat': res } def evaluate_class(cls, predictions, target, target2=None, silent=False): """ Compute only the predicted class """ p_2_annotation = dict() precision_recall_fscore_support = [ (pair[0], pair[1].mean()) for pair in zip( ['precision', 'recall', 'f1', 'support'], metrics.precision_recall_fscore_support(target, predictions) ) ] metrics.precision_recall_fscore_support(target, predictions) # confusion matrix le = LabelEncoder() target_le = le.fit_transform(target) predictions_le = le.transform(predictions) cm = metrics.confusion_matrix(target_le, predictions_le) # prediction if two annotations are given on test data if target2: p_2_annotation = pd.DataFrame( [(pred, pred in set([t1,t2])) for pred, t1, t2 in zip(predictions, target, target2)], columns=['emo','success'] ).groupby('emo').apply(lambda emo: emo.success.sum()/ len(emo.success)).to_dict() if not silent: print("Default Classification report") print(metrics.classification_report(target, predictions)) # print if target2 was provided if len(p_2_annotation) > 0: print('\nPrecision on 2 annotations:') for emo in p_2_annotation: print("%s: %.2f" % (emo, p_2_annotation[emo])) # print accuracies, precision, recall, and f1 print('\nAccuracy:') print(metrics.accuracy_score(target, predictions)) print("Correct Predictions: ", metrics.accuracy_score(target, predictions,normalize=False)) for to_print in precision_recall_fscore_support[:3]: print( "%s: %.2f" % to_print ) # normalizing the values of the consfusion matrix print('\nconfusion matrix\n %s' % cm) print('(row=expected, col=predicted)') cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] cls.plot_confusion_matrix(cm_normalized, le.classes_, 'Confusion matrix Normalized') return { 'precision_recall_fscore_support': precision_recall_fscore_support, 'accuracy': metrics.accuracy_score(target, predictions), 'p_2_annotation': p_2_annotation, 'confusion_matrix': cm } def predict_class(cls, X_train, y_train, X_test, y_test, pipeline, silent=False, target2=None): """ Predicted class,then run some performance evaluation """ pipeline.fit(X_train, y_train) predictions = pipeline.predict(X_test) print("predictions computed....") return cls.evaluate_class(predictions, y_test, target2, silent) def evaluate_prob(cls, prediction, target_rank, target_class, binarizer, va_df, silent=False, target2=None): """ Evaluate through probability """ # Run normal class evaluator predict_class = binarizer.classes_[prediction.argmax(axis=1)] class_eval = cls.evaluate_class(predict_class, target_class, target2, silent) if not silent: print('\n - First Emotion Classification Metrics -') print('\n - Multiple Emotion rank Metrics -') print('VA Cosine Distance') classes_dist = [ ( emo, cls.va_dist( prediction[np.array(target_class) == emo], target_rank[np.array(target_class) == emo], va_df, binarizer, emo, silent) ) for emo in binarizer.classes_ ] avg_dist = cls.va_dist(prediction, target_rank, va_df, binarizer, 'avg', silent) coverage_error = metrics.coverage_error(target_rank, prediction) average_precision_score = metrics.average_precision_score(target_rank, prediction) label_ranking_average_precision_score = metrics.label_ranking_average_precision_score(target_rank, prediction) label_ranking_loss = metrics.label_ranking_loss(target_rank, prediction) # recall at 2 # obtain top two predictions top2_pred = [set([binarizer.classes_[i[0]], binarizer.classes_[i[1]]]) for i in (prediction.argsort(axis=1).T[-2:].T)] recall_at_2 = pd.DataFrame( [ t in p for t, p in zip(target_class, top2_pred) ], index=target_class, columns=['recall@2']).groupby(level=0).apply(lambda emo: emo.sum()/len(emo)) # combine target into sets if target2: union_target = [set(t) for t in zip(target_class, target2)] else: union_target = [set(t) for t in zip(target_class)] # precision at k top_k_pred = [ [set([binarizer.classes_[i] for i in i_list]) for i_list in (prediction.argsort(axis=1).T[-i:].T)] for i in range(2, len(binarizer.classes_)+1)] precision_at_k = [ ('p@' + str(k+2), np.array([len(t & p)/(k+2) for t, p in zip(union_target, top_k_pred[k])]).mean()) for k in range(len(top_k_pred))] # do this if silent= False if not silent: print('\n') print(recall_at_2) print('\n') print('p@k') for pk in precision_at_k: print(pk[0] + ':\t' + str(pk[1])) print('\ncoverage_error: %f' % coverage_error) print('average_precision_score: %f' % average_precision_score) print('label_ranking_average_precision_score: %f' % label_ranking_average_precision_score) print('label_ranking_loss: %f' % label_ranking_loss) return { 'class_eval': class_eval, 'recall_at_2': recall_at_2.to_dict(), 'precision_at_2': precision_at_k, 'classes_dist': classes_dist, 'avg_dist': avg_dist, 'coverage_error': coverage_error, 'average_precision_score': average_precision_score, 'label_ranking_average_precision_score': label_ranking_average_precision_score, 'label_ranking_loss': label_ranking_loss } def predict_prob(cls, X_train, y_train, X_test, y_test, label_test, pipeline, binarizer, va_df, silent=False, target2=None): """ Output predcations based on training and labels """ pipeline.fit(X_train, y_train) predictions = pipeline.predict_proba(X_test) pred_to_mlb = [np.where(pipeline.classes_ == emo)[0][0] for emo in binarizer.classes_.tolist()] return cls.evaluate_prob(predictions[:,pred_to_mlb], y_test, label_test, binarizer, va_df, silent, target2) def plot_confusion_matrix(cls, cm, my_tags, title='Confusion matrix', cmap=plt.cm.Blues): """ Plotting the confusion_matrix""" plt.rc('figure', figsize=(4, 4), dpi=100) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(my_tags)) target_names = my_tags plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) # add normalized values inside the Confusion matrix fmt = '.2f' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') ``` ## results ``` evaluator = Evaluate() final_predictions = [] for p in all_predictions: for sub_p in p: final_predictions.append(sub_p) predictions = [np.argmax(p).item() for p in final_predictions] targets = [np.argmax(t).item() for t in y_raw] correct_predictions = float(np.sum(predictions == targets)) # predictions predictions_human_readable = ((x_raw, predictions)) # actual targets target_human_readable = ((x_raw, targets)) emotion_dict = {0: 'anger', 1: 'fear', 2: 'joy', 3: 'love', 4: 'sadness', 5: 'surprise'} # convert results into dataframe model_test_result = pd.DataFrame(predictions_human_readable[1],columns=["emotion"]) test = pd.DataFrame(target_human_readable[1], columns=["emotion"]) model_test_result.emotion = model_test_result.emotion.map(lambda x: emotion_dict[int(float(x))]) test.emotion = test.emotion.map(lambda x: emotion_dict[int(x)]) evaluator.evaluate_class(model_test_result.emotion, test.emotion ) ``` # 2. Sentiment States Model Building ###1. Get IMDB dataset which contains movie reviews data and preprocess it ``` #Get the IMDB Dataset, format data appropriate to input into model from keras.datasets import imdb top_words = 10000 (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=top_words) #a total of 88000 words are contained in the dictionary and imdb.get_word_index() word_dict_sent = imdb.get_word_index() word_dict_sent = { key:(value + 3) for key, value in word_dict_sent.items() } word_dict_sent[''] = 0 # Padding word_dict_sent['>'] = 1 # Start word_dict_sent['?'] = 2 # Unknown word reverse_word_dict = { value:key for key, value in word_dict_sent.items() } from keras.preprocessing import sequence max_review_length = 500 x_train = sequence.pad_sequences(x_train, maxlen=max_review_length) x_test = sequence.pad_sequences(x_test, maxlen=max_review_length) print(x_train.shape, x_test.shape) import pandas as pd dfff = pd.DataFrame(x_train) dfff.head() ``` ###2. Using a standard sequential model, relu activations, adam optimizer, and a binary crossentropy loss function ``` #Building a model with keras from keras.models import Sequential from keras.layers import Dense from keras.layers.embeddings import Embedding from keras.layers import Flatten embedding_vector_length = 32 model_sent = Sequential() model_sent.add(Embedding(top_words, embedding_vector_length, input_length=max_review_length)) model_sent.add(Flatten()) model_sent.add(Dense(16, activation='relu')) model_sent.add(Dense(16, activation='relu')) model_sent.add(Dense(1, activation='sigmoid')) model_sent.compile(loss='binary_crossentropy',optimizer='adam', metrics=['accuracy']) print(model_sent.summary()) # Output network visualization from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from keras.utils.vis_utils import plot_model SVG(model_to_dot(model_sent).create(prog='dot', format='svg')) plot_model(model_sent, to_file='model_plot.png', show_shapes=True, show_layer_names=True) ``` ###3. With a batch size of 128 and 5 epochs, train the model ``` hist = model_sent.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=5, batch_size=128) ``` ###4. Display results of training ``` scores = model_sent.evaluate(x_test, y_test, verbose=0) print("Accuracy: %.2f%%" % (scores[1] * 100)) ``` ###5. Build an analyzer function to apply this outside model to our Yelp data ``` #Build analyzer function based on the model to apply to the vegas dataset. import string import numpy as np def analyzer(text): # Prepare the input by removing punctuation characters, converting # characters to lower case, and removing words containing numbers translator = str.maketrans('', '', string.punctuation) text = text.translate(translator) text = text.lower().split(' ') text = [word for word in text if word.isalpha()] # Generate an input tensor input = [1] for word in text: if word in word_dict_sent and word_dict_sent[word] < top_words: input.append(word_dict_sent[word]) else: input.append(2) padded_input = sequence.pad_sequences([input], maxlen=max_review_length) # Invoke the model and return the result result = model_sent.predict(np.array([padded_input][0]))[0][0] sentiment='' #how positive or negative if result > 0.66: sentiment = 'positive' elif result > 0.33: sentiment = 'neutral' else: sentiment = 'negative' return result, sentiment ``` ###7. Test the model on some phrases ``` analyzer('I love this class!') analyzer('my day was okay. some good parts. fine') analyzer('my car broke down. i am so sad') ``` ## Implementation 1. A agent's sentiment state is initialized 2. A user tells the agent something. Can be good or bad. A story, how they're feeling, an idea, etc. 3. The agent interprets the sentiment of what it was told and its internal state moves in the direction of the overall sentiment of the user's input. ``` import pandas as pd import numpy as np import ipywidgets as wg from IPython.display import display import random pd.set_option('display.max_colwidth', 240) data.head() # positives joy = data['emotions'] == "joy" love = data['emotions'] == "love" sadness = data['emotions'] == "sadness" # joy samples data[joy].sample(n=5) # sadness samples data[sadness].sample(n=5) # # Emotional Contagion Beta: Agent Takes on Sentiment of Others # import random # game_running = True until someone quits game_running = True user_input='hello_world' while game_running: # Greet the user to our game print() print("Hello and Welcome to the Emotional Contagion Game. \n Enter q to exit the simulation \n Otherwise, tell the agent something (eg. something that happened to you, how you are feeling right now, a story, etc.) \n" ) # *** The agent sentiment is randomly initialized between 0 and 1 *** agent1_init_sentiment = round(random.randint(0, 10)*.1,2) print("agent1_sentiment = ", agent1_init_sentiment) agent1_sentiment = agent1_init_sentiment # *** The agent's probability of emotional contagion is set (in this case, can't be 0)*** #agent1_prob_emo_contagion = round(random.randint(1, 10)*.1,2) #print("agent1_prob_emo_contagion = ", agent1_prob_emo_contagion) # Get some sample statements with a particular sentiment agent_negative_sentiment_statements_list = ["Man today really sucks. I'm not feeling good.", "I've just been so depressed lately. Hope this game makes me feel better.", "Ugh. What do you want. Can't you tell I'm not happy right now.", "Sigh, leave me alone. Today sucks.", "Just had a hard day at work. Hope your's was better."] agent_neutral_sentiment_statements_list = ["I feel pretty good today. Work was so so, but I'm fine.", "Today was a bit of a bummer. But tonight should be fun.", "I'm fine. How're you doing?", "I'm feeling okay I suppose."] agent_positive_sentiment_statements_list = ["I feel pretty great today. Things are looking up.", "What a beautiful day, I'm feeling good.", "Today has been unusually good. I feel quite happy." ] # Get some sample statements to respond to an input agent_negative_sentiment_responses_list = ["Well that stinks. I don't feel better after hearing that.", "Awwh. Dang.", "That's too bad. Got me bummed out..", "Aye, my condolences.", "Ugh, sad..", "Give me some positive content. I'm not feeling good now...", "I'm not as happy now.. ", "What a bummer.."] agent_neutral_sentiment_responses_list = ["Well, that's not too rough. Good to know..", "Don't know how to feel about that.", "Hmmm. I'm feeling neutral about that.", "Okay then.. ", "Really didn't change my sentiment state at all.. Tell me something more EXTREME!" ] agent_positive_sentiment_responses_list = ["That's good news. I feel better.", "I'm feeling better after hearing that.", "Good stuff. Glad to hear it.." "Seem's positive to me. Tell me more!", "You know, after hearing that, I feel a little better.", "Need more of these positive vibes in my life. Thanks.", "Glad to hear it. Any more good news?"] #randomly if agent1_sentiment < 0.33: print("agent1_init_state:", random.choice(agent_negative_sentiment_statements_list)) elif agent1_sentiment < 0.66: print("agent1_init_state:", random.choice(agent_neutral_sentiment_statements_list)) else: print("agent1_init_state:", random.choice(agent_positive_sentiment_statements_list)) while user_input != "q": # Get the player's guess from the player print() user_input = input("Tell me something: ") # Does the user want to quit playing? if user_input == "q": game_running = False break #If the user has responded, update the sentiment of the agent with probability of contagion applied else: agent1_sentiment_analysis_of_user = analyzer(user_input) print("agent1_sentiment_analysis_of_user: ", agent1_sentiment_analysis_of_user) #Optionally hide this if agent1_sentiment_analysis_of_user[0] < 0.33: print("agent1_init_state:", random.choice(agent_negative_sentiment_responses_list)) agent1_sentiment = (agent1_sentiment + agent1_sentiment_analysis_of_user[0]) / 2 print("updated_agent1_sentiment: ", round(agent1_sentiment,2)) elif agent1_sentiment_analysis_of_user[0] < 0.66: print("agent1_init_state:", random.choice(agent_neutral_sentiment_responses_list)) #agent1_sentiment = (agent1_sentiment + agent1_sentiment_analysis_of_user[0]) / 2 agent1_sentiment = agent1_sentiment print("updated_agent1_sentiment: ", round(agent1_sentiment,2)) else: print("agent1_init_state:", random.choice(agent_positive_sentiment_responses_list)) agent1_sentiment = (agent1_sentiment + agent1_sentiment_analysis_of_user[0]) / 2 print("updated_agent1_sentiment: ", round(agent1_sentiment,2)) # Say goodbye to the player print() print("Thanks for playing Emotional Contagion Beta") ```
github_jupyter
# Introduction In this tutorial, we will train a regression model with Foreshadow using the [House Pricing](https://www.kaggle.com/c/house-prices-advanced-regression-techniques) dataset from Kaggle. # Getting Started To get started with foreshadow, install the package using `pip install foreshadow`. This will also install the dependencies. Now create a simple python script that uses all the defaults with Foreshadow. Note that Foreshadow requires `Python >=3.6, <4.0`. First import foreshadow related classes. Also import sklearn, pandas and numpy packages. ``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import ElasticNet from sklearn.metrics import get_scorer from sklearn.metrics import mean_squared_log_error from foreshadow import Foreshadow from foreshadow.intents import IntentType from foreshadow.utils import ProblemType pd.options.display.max_columns=None RANDOM_SEED=42 np.random.seed(RANDOM_SEED) ``` # Load the dataset ``` df_train = pd.read_csv("train.csv") X_df = df_train.drop(columns="SalePrice") y_df = df_train[["SalePrice"]] X_train, X_test, y_train, y_test = train_test_split(X_df, y_df, test_size=0.2) X_train.head() ``` # Model Training Iteration 1 - ElasticNet ``` def measure(model, X_test, y_test): y_pred = model.predict(X_test) rmsle = np.sqrt(mean_squared_log_error(y_test, y_pred)) print('root mean squared log error = %5.4f' % rmsle) return rmsle shadow1 = Foreshadow(problem_type=ProblemType.REGRESSION, random_state=RANDOM_SEED, n_jobs=-1, estimator=ElasticNet(random_state=RANDOM_SEED)) _ = shadow1.fit(X_train, y_train) _ = measure(shadow1, X_test, y_test) ``` ### You might be curious how Foreshadow handled the input data. Let's take a look ``` shadow1.get_data_summary() ``` #### Foreshadow use a machine learning model to identify the 'intent' of features. 3 intents are supported as of v1.0 and they are 'Categorical', 'Numeric' and 'Text'. Foreshadow will transform the features intelligently according to its intent and statistics. Features not belonging to these three are tagged as 'Droppable'. For example, the Id is droppable since it has a unique value for each row and will not provide any signal to the model. Also in the above table, 'Label' in the intent row indicate that is the target column. # Model Training Iteration 2 - Override ``` shadow2 = Foreshadow(problem_type=ProblemType.REGRESSION, random_state=RANDOM_SEED, n_jobs=-1, estimator=ElasticNet(random_state=RANDOM_SEED)) shadow2.override_intent('ExterQual', IntentType.CATEGORICAL) shadow2.override_intent('ExterCond', IntentType.CATEGORICAL) shadow2.override_intent('LotShape', IntentType.CATEGORICAL) shadow2.override_intent('HeatingQC', IntentType.CATEGORICAL) shadow2.override_intent('YearBuilt', IntentType.NUMERIC) shadow2.override_intent('YearRemodAdd', IntentType.NUMERIC) shadow2.override_intent('YrSold', IntentType.NUMERIC) _ = shadow2.fit(X_train, y_train) _ = measure(shadow2, X_test, y_test) ``` # Model Training Iteration 3 - AutoEstimator #### Instead of trying one estimator, we can leverage AutoEstimator to search ML models and hyper-parameters. When we do not provide an estimator, Foreshadow will create the AutoEstimator automatically. ``` shadow3 = Foreshadow(problem_type=ProblemType.REGRESSION, allowed_seconds=300, random_state=RANDOM_SEED, n_jobs=-1) shadow3.override_intent('ExterQual', IntentType.CATEGORICAL) shadow3.override_intent('ExterCond', IntentType.CATEGORICAL) shadow3.override_intent('LotShape', IntentType.CATEGORICAL) shadow3.override_intent('HeatingQC', IntentType.CATEGORICAL) shadow3.override_intent('YearBuilt', IntentType.NUMERIC) shadow3.override_intent('YearRemodAdd', IntentType.NUMERIC) shadow3.override_intent('YrSold', IntentType.NUMERIC) _ = shadow3.fit(X_train, y_train) _ = measure(shadow3, X_test, y_test) ``` # Model Training Iteration 4 - Customize Scoring Function in Search #### The Kaggle competition use root mean squared log error to rank result. Let's ask the AutoEstimator to optimize for this scoring function ``` shadow4 = Foreshadow(problem_type=ProblemType.REGRESSION, allowed_seconds=300, random_state=RANDOM_SEED, n_jobs=-1, auto_estimator_kwargs={"scoring": get_scorer('neg_mean_squared_log_error')}) shadow4.override_intent('ExterQual', IntentType.CATEGORICAL) shadow4.override_intent('ExterCond', IntentType.CATEGORICAL) shadow4.override_intent('LotShape', IntentType.CATEGORICAL) shadow4.override_intent('HeatingQC', IntentType.CATEGORICAL) shadow4.override_intent('YearBuilt', IntentType.NUMERIC) shadow4.override_intent('YearRemodAdd', IntentType.NUMERIC) shadow4.override_intent('YrSold', IntentType.NUMERIC) _ = shadow4.fit(X_train, y_train) rmsle = measure(shadow4, X_train, y_train) ``` ## Compare Kaggle Leaderboard ``` leaderboard = pd.read_csv('house-prices-advanced-regression-techniques-publicleaderboard.csv') leaderboard.sort_values(by='Score', ascending=True, inplace=True) better_solutions = leaderboard[leaderboard.Score < rmsle] ranking = len(better_solutions) * 100.0 / len(leaderboard) print('Our solution ranked at %dth position within top %0.2f%%' % (len(better_solutions), ranking)) ```
github_jupyter
``` import re import requests from html.parser import HTMLParser from time import sleep from tqdm import tqdm #手工输入会议以及链接 # """GECCO, SSBSE, QRS还没找到""" journals = [] confs = [] for line in open("conf_list.csv"): line = line.replace("http://","https://").replace("/index.html","/") data = line.split("\t") if data[1] == "journal": journals.append((data[0],data[2].replace("\n",""))) elif data[1] == "conf": confs.append((data[0],data[2].replace("\n",""))) print(line.split("\t")) #先按照链接获取到dblp里面对应的journal所有volume的链接 #再进入各个卷的链接,获取全部文章 from bs4 import BeautifulSoup import re volums_jour = [] for journal, link in tqdm(journals,"Journals"): r = requests.get(link, headers={"Connection": "close"}) if r.status_code == 200: html = r.text else: print(r.status_code) r.close() sleep(0.01) bs = BeautifulSoup(html,"html.parser") for item in bs.find_all("li"): if item.attrs == {} and item.a != None and item.img == None and item.a.attrs['href'].startswith(link): year = re.findall('\d{4}', item.text.split('\n')[0], flags=0)[0] for a in item.find_all('a'): vol = re.findall('\d+', a.text.replace(year, ""), flags=0)[0] volums_jour.append((journal, year, vol, a.attrs['href'])) jour_paper_list = [] for conf, year, conf_det, href in tqdm(volums_jour,"Journal"): r = requests.get(href, headers={"Connection": "close"}) if r.status_code == 200: html = r.text else: print(r.status_code) r.close() sleep(0.01) bs = BeautifulSoup(html,"html.parser") first = True for item in bs.find_all("cite"): for title in item.find_all("span", "title"): if first: first = False else: jour_paper_list.append((conf, year, conf_det, title.text)) #先按照链接获取到dblp里面对应的conference所有track的链接 #再进入各个卷的链接,获取全部文章 from bs4 import BeautifulSoup import re volums_conf = [] for conf, link in tqdm(confs,"Conferences"): r = requests.get(link, headers={"Connection": "close"}) if r.status_code == 200: html = r.text else: print(r.status_code) r.close() sleep(0.01) bs = BeautifulSoup(html,"html.parser") for item in bs.find_all("cite"): if item.find("span", itemprop="publisher"): publisher = item.find("span", itemprop="publisher").text else: # print(item) break year = item.find("span", itemprop="datePublished").text for title in item.find_all("span", "title"): href = list(title.next_siblings)[-1].attrs["href"] volums_conf.append((conf, year, publisher, title.text, href)) conf_paper_list = [] for conf, year, publisher, conf_det, href in tqdm(volums_conf,"Conferences"): r = requests.get(href, headers={"Connection": "close"}) if r.status_code == 200: html = r.text else: print(r.status_code) r.close() sleep(0.01) bs = BeautifulSoup(html,"html.parser") first = True for item in bs.find_all("cite"): for title in item.find_all("span", "title"): if first: first = False else: conf_paper_list.append((conf, year, publisher, conf_det, title.text)) len(jour_paper_list) len(conf_paper_list) #储存全部的文章列表 writer = open("conf_paper_list.csv", 'w', encoding="utf-8") for conf, year, publisher, conf_det, title in conf_paper_list: line = "{}\t{}\t{}\t{}\t{}\n".format(conf, year, publisher, conf_det, title) writer.write(line) writer.close() writer = open("jour_paper_list.csv", 'w', encoding="utf-8") for conf, year, conf_det, title in jour_paper_list: line = "{},{},{},{}\n".format(conf, year, conf_det, title) writer.write(line) writer.close() conf_paper_list = [] for line in open("conf_paper_list.csv", encoding="utf-8"): line = line.replace("\n","") conf = line.split("\t")[0] year = line.split("\t")[1] publisher = line.split("\t")[2] conf_det = line.split("\t")[3] title = line.split("\t")[-1] conf_paper_list.append((conf, year, publisher, conf_det, title)) jour_paper_list = [] for line in open("jour_paper_list.csv", encoding="utf-8"): line = line.replace("\n","") conf = line.split(",")[0] year = line.split(",")[1] conf_det = line.split(",")[2] title = line.split(",")[3] jour_paper_list.append((conf, year, conf_det, title)) #筛选并存储 keywords = [ "deep learning", "neural network", "dnn", "cnn", "machine learning", "autonomous vehicle", "autonomous driving", "self-driving", "automatics", "autonomous car", "driver assistance", "adas", "self driving", "overtaking", "automated vehicle", "automated driving", "automated car", "driving scenarios", "vehicle safety", "intelligent vehicle", "intelligent car", "apollo", "waymo", "vehicle signalization system", "pedestrian", "lane", "carla", "lgsvl", "vehicle", "v2x", "autonomous electric vehicle", "autonomous electric car", "connected vehicle", "object detection", "lidar", "traffic scene", "traffic accident", "driving simulator", "vision-based control systems" ] keywords_dict = {} for keyword in keywords: keywords_dict[keyword] = 0 # keywords = [ # "autonomous vehicle", # "autonomous driving", # "self-driving", # "automatics", # "autonomous car", # "driver assistance", # "adas", # "self driving", # "vechicle", # "overtaking", # "automated vehicle", # "automated driving", # "automated car", # "driving scenarios", # "vehicle safety", # "intelligent vehicle", # "intelligent car", # "apollo", # "waymo", # "vehicle signalization system", # "pedestrian", # "carla", # "lgsvl", # "v2x", # "autonomous electric vehicle", # "autonomous electric car", # "connected vehicle", # "object detection", # "traffic scene", # "traffic accident", # "driving simulator", # "vision-based control systems" # ] # keywords_dict = {} # for keyword in keywords: # keywords_dict[keyword] = 0 conf_paper_filt = [] for conf, year, publisher, conf_det, title in conf_paper_list: if int(year) > 2015: filted = True for keyword in keywords: if keyword in title.lower(): filted = False for words in ["by deep learning", "using deep learning", "by machine learning", "using machine learning", "by cnn", "using cnn", "by dnn", "using dnn"]: if words in title.lower(): filted = True if not filted: keywords_dict[keyword] += 1 if not filted: conf_paper_filt.append((conf, year, publisher, conf_det, title)) writer = open("conf_paper_filt.tsv", 'w', encoding="utf-8") for conf, year, publisher, conf_det, title in conf_paper_filt: line="{}\t{}\t{}\t{}\t{}\n".format(conf, year, publisher, conf_det, title) writer.write(line) writer.close() len(conf_paper_filt) jour_paper_filt = [] for jour, year, jour_det, title in jour_paper_list: if int(year) > 2015: filted = True for keyword in keywords: if keyword in title.lower(): filted = False for words in ["by deep learning", "using deep learning", "by machine learning", "using machine learning", "by cnn", "using cnn", "by dnn", "using dnn"]: if words in title.lower(): filted = True if not filted: keywords_dict[keyword] += 1 if not filted: jour_paper_filt.append((jour, year, jour_det, title)) # jour_paper_filt = [] # for jour, year, jour_det, title in jour_paper_list: # if int(year) > 2015: # filted = True # for keyword in keywords: # if keyword in title.lower(): # filted = False # keywords_dict[keyword] += 1 # if not filted: # jour_paper_filt.append((jour, year, jour_det, title)) writer = open("jour_paper_filt.tsv", 'w', encoding="utf-8") for jour, year, conf_det, title in jour_paper_filt: line="{}\t{}\t{}\t{}t\n".format(jour, year, jour_det, title) writer.write(line) writer.close() len(jour_paper_filt) keywords_dict writer = open("keyword.tsv","w",encoding="utf-8") for keyword in keywords_dict: writer.write("{}\t{}\n".format(keyword, keywords_dict[keyword])) writer.close() ```
github_jupyter
# Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like translations. ## Readings Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material. * A really good [conceptual overview](http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/) of word2vec from Chris McCormick * [First word2vec paper](https://arxiv.org/pdf/1301.3781.pdf) from Mikolov et al. * [NIPS paper](http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf) with improvements for word2vec also from Mikolov et al. * An [implementation of word2vec](http://www.thushv.com/natural_language_processing/word2vec-part-1-nlp-with-deep-learning-with-tensorflow-skip-gram/) from Thushan Ganegedara * TensorFlow [word2vec tutorial](https://www.tensorflow.org/tutorials/word2vec) ## Word embeddings When you're dealing with language and words, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram. <img src="assets/word2vec_architectures.png" width="500"> In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts. First up, importing packages. ``` import time import numpy as np import tensorflow as tf import utils ``` Load the [text8 dataset](http://mattmahoney.net/dc/textdata.html), a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the `data` folder. Then you can extract it and delete the archive file to save storage space. ``` from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(dataset_filename): with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset_name) as pbar: urlretrieve( 'http://mattmahoney.net/dc/text8.zip', dataset_filename, pbar.hook) if not isdir(dataset_folder_path): with zipfile.ZipFile(dataset_filename) as zip_ref: zip_ref.extractall(dataset_folder_path) with open('data/text8') as f: text = f.read() ``` ## Preprocessing Here I'm fixing up the text to make training easier. This comes from the `utils` module I wrote. The `preprocess` function coverts any punctuation into tokens, so a period is changed to ` <PERIOD> `. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it. ``` words = utils.preprocess(text) print(words[:30]) print("Total words: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) ``` And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list `int_words`. ``` vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] ``` ## Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by $$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$ where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset. I'm going to leave this up to you as an exercise. Check out my solution to see how I did it. > **Exercise:** Implement subsampling for the words in `int_words`. That is, go through `int_words` and discard each word given the probablility $P(w_i)$ shown above. Note that $P(w_i)$ is that probability that a word is discarded. Assign the subsampled data to `train_words`. ``` from collections import Counter import random threshold = 1e-5 word_counts = Counter(int_words) total_count = len(int_words) freqs = {word: count/total_count for word, count in word_counts.items()} p_drop = {word: 1 - np.sqrt(threshold/freqs[word]) for word in word_counts} train_words = [word for word in int_words if p_drop[word] < random.random()] ``` ## Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From [Mikolov et al.](https://arxiv.org/pdf/1301.3781.pdf): "Since the more distant words are usually less related to the current word than those close to it, we give less weight to the distant words by sampling less from those words in our training examples... If we choose $C = 5$, for each training word we will select randomly a number $R$ in range $< 1; C >$, and then use $R$ words from history and $R$ words from the future of the current word as correct labels." > **Exercise:** Implement a function `get_target` that receives a list of words, an index, and a window size, then returns a list of words in the window around the index. Make sure to use the algorithm described above, where you chose a random number of words to from the window. ``` def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' R = np.random.randint(1, window_size+1) start = idx - R if (idx - R) > 0 else 0 stop = idx + R target_words = set(words[start:idx] + words[idx+1:stop+1]) return list(target_words) ``` Here's a function that returns batches for our network. The idea is that it grabs `batch_size` words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory. ``` def get_batches(words, batch_size, window_size=5): ''' Create a generator of word batches as a tuple (inputs, targets) ''' n_batches = len(words)//batch_size # only full batches words = words[:n_batches*batch_size] for idx in range(0, len(words), batch_size): x, y = [], [] batch = words[idx:idx+batch_size] for ii in range(len(batch)): batch_x = batch[ii] batch_y = get_target(batch, ii, window_size) y.extend(batch_y) x.extend([batch_x]*len(batch_y)) yield x, y ``` ## Building the graph From Chris McCormick's blog, we can see the general structure of our network. ![embedding_network](./assets/skip_gram_net_arch.png) The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden layer weight matrix to find efficient representations for our words. This weight matrix is usually called the embedding matrix or embedding look-up table. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset. I'm going to have you build the graph in stages now. First off, creating the `inputs` and `labels` placeholders like normal. > **Exercise:** Assign `inputs` and `labels` using `tf.placeholder`. We're going to be passing in integers, so set the data types to `tf.int32`. The batches we're passing in will have varying sizes, so set the batch sizes to [`None`]. To make things work later, you'll need to set the second dimension of `labels` to `None` or `1`. ``` train_graph = tf.Graph() with train_graph.as_default(): inputs = tf.placeholder(tf.int32, [None], name='inputs') labels = tf.placeholder(tf.int32, [None, None], name='labels') ``` ## Embedding The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix: ![one-hot matrix multiplication](assets/matrix_mult_w_one_hot.png) You don't actually need to do the matrix multiplication, you just need to select the row in the embedding matrix that corresponds to the input word. Then, the embedding matrix becomes a lookup table, you're looking up a vector the size of the hidden layer that represents the input word. <img src="assets/word2vec_weight_matrix_lookup_table.png" width=500> > **Exercise:** Tensorflow provides a convenient function [`tf.nn.embedding_lookup`](https://www.tensorflow.org/api_docs/python/tf/nn/embedding_lookup) that does this lookup for us. You pass in the embedding matrix and a tensor of integers, then it returns rows in the matrix corresponding to those integers. Below, set the number of embedding features you'll use (200 is a good start), create the embedding matrix variable, and use `tf.nn.embedding_lookup` to get the embedding tensors. For the embedding matrix, I suggest you initialize it with a uniform random numbers between -1 and 1 using [tf.random_uniform](https://www.tensorflow.org/api_docs/python/tf/random_uniform). ``` n_vocab = len(int_to_vocab) n_embedding = 200 # Number of embedding features with train_graph.as_default(): embedding = tf.Variable(tf.random_uniform((n_vocab, n_embedding), -1, 1)) embed = tf.nn.embedding_lookup(embedding, inputs) ``` ## Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called ["negative sampling"](http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf). Tensorflow has a convenient function to do this, [`tf.nn.sampled_softmax_loss`](https://www.tensorflow.org/api_docs/python/tf/nn/sampled_softmax_loss). > **Exercise:** Below, create weights and biases for the softmax layer. Then, use [`tf.nn.sampled_softmax_loss`](https://www.tensorflow.org/api_docs/python/tf/nn/sampled_softmax_loss) to calculate the loss. Be sure to read the documentation to figure out how it works. ``` # Number of negative labels to sample n_sampled = 100 with train_graph.as_default(): softmax_w = tf.Variable(tf.truncated_normal((n_vocab, n_embedding), stddev=0.1)) softmax_b = tf.Variable(tf.zeros(n_vocab)) # Calculate the loss using negative sampling loss = tf.nn.sampled_softmax_loss(softmax_w, softmax_b, labels, embed, n_sampled, n_vocab) cost = tf.reduce_mean(loss) optimizer = tf.train.AdamOptimizer().minimize(cost) ``` ## Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. ``` with train_graph.as_default(): ## From Thushan Ganegedara's implementation valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent valid_examples = np.array(random.sample(range(valid_window), valid_size//2)) valid_examples = np.append(valid_examples, random.sample(range(1000,1000+valid_window), valid_size//2)) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # We use the cosine distance: norm = tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keep_dims=True)) normalized_embedding = embedding / norm valid_embedding = tf.nn.embedding_lookup(normalized_embedding, valid_dataset) similarity = tf.matmul(valid_embedding, tf.transpose(normalized_embedding)) # If the checkpoints directory doesn't exist: !mkdir checkpoints epochs = 10 batch_size = 1000 window_size = 10 with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: iteration = 1 loss = 0 sess.run(tf.global_variables_initializer()) for e in range(1, epochs+1): batches = get_batches(train_words, batch_size, window_size) start = time.time() for x, y in batches: feed = {inputs: x, labels: np.array(y)[:, None]} train_loss, _ = sess.run([cost, optimizer], feed_dict=feed) loss += train_loss if iteration % 100 == 0: end = time.time() print("Epoch {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Avg. Training loss: {:.4f}".format(loss/100), "{:.4f} sec/batch".format((end-start)/100)) loss = 0 start = time.time() if iteration % 1000 == 0: # note that this is expensive (~20% slowdown if computed every 500 steps) sim = similarity.eval() for i in range(valid_size): valid_word = int_to_vocab[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k+1] log = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = int_to_vocab[nearest[k]] log = '%s %s,' % (log, close_word) print(log) iteration += 1 save_path = saver.save(sess, "checkpoints/text8.ckpt") embed_mat = sess.run(normalized_embedding) ``` Restore the trained network if you need to: ``` with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) embed_mat = sess.run(embedding) ``` ## Visualizing the word vectors Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out [this post from Christopher Olah](http://colah.github.io/posts/2014-10-Visualizing-MNIST/) to learn more about T-SNE and other ways to visualize high-dimensional data. ``` %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from sklearn.manifold import TSNE viz_words = 500 tsne = TSNE() embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :]) fig, ax = plt.subplots(figsize=(14, 14)) for idx in range(viz_words): plt.scatter(*embed_tsne[idx, :], color='steelblue') plt.annotate(int_to_vocab[idx], (embed_tsne[idx, 0], embed_tsne[idx, 1]), alpha=0.7) ```
github_jupyter
# 日本語手紙文字OCRサンプル ## OpenVINOのインストールディレクトリからオリジナルのサンプルコード関連ファイルをコピー ``` !cp $INTEL_OPENVINO_DIR/inference_engine/demos/python_demos/handwritten_japanese_recognition_demo/requirements.txt . !cp $INTEL_OPENVINO_DIR/inference_engine/demos/python_demos/handwritten_japanese_recognition_demo/models.lst . !cp -r $INTEL_OPENVINO_DIR/inference_engine/demos/python_demos/handwritten_japanese_recognition_demo/utils . !cp -r $INTEL_OPENVINO_DIR/inference_engine/demos/python_demos/handwritten_japanese_recognition_demo/data . ``` ## Pythonライブラリをインストール ``` !pip install -r requirements.txt ``` ## 事前学習済みモデルをダウンロード ``` !python3 $INTEL_OPENVINO_DIR/deployment_tools/tools/model_downloader/downloader.py --list models.lst ``` ## ライブラリをインポート ``` from __future__ import print_function import os import sys import time import io import cv2 import logging as log import numpy as np from PIL import Image import PIL from openvino.inference_engine import IECore from utils.codec import CTCCodec import IPython.display from IPython.display import clear_output ``` ## 実装 ``` class JapaneseHandwrittenOCR: def __init__(self, model_path): # Plugin initialization ie = IECore() # Setup OpenVINO's IE model = model_path net = ie.read_network(model, os.path.splitext(model)[0] + ".bin") self.input_blob = next(iter(net.input_info)) self.out_blob = next(iter(net.outputs)) self.input_batch_size, self.input_channel, self.input_height, self.input_width = net.input_info[self.input_blob].input_data.shape self.exec_net = ie.load_network(network=net, device_name="CPU") # Setup codec self.codec = CTCCodec(self.__get_characters__(), None, 20) def __get_characters__(self): '''Get characters''' charlist = "data/kondate_nakayosi_char_list.txt" with open(charlist, 'r', encoding='utf-8') as f: return ''.join(line.strip('\n') for line in f) def __preprocess_input__(self, image_name, height, width): src = cv2.imread(image_name, cv2.IMREAD_GRAYSCALE) ratio = float(src.shape[1]) / float(src.shape[0]) tw = int(height * ratio) rsz = cv2.resize(src, (tw, height), interpolation=cv2.INTER_AREA).astype(np.float32) # [h,w] -> [c,h,w] img = rsz[None, :, :] _, h, w = img.shape # right edge padding pad_img = np.pad(img, ((0, 0), (0, height - h), (0, width - w)), mode='edge') return pad_img def infer(self, image_path): # Read and pre-process input image (NOTE: one image only) input_path = image_path input_image = self.__preprocess_input__(input_path, height=self.input_height, width=self.input_width)[None,:,:,:] preds = self.exec_net.infer(inputs={self.input_blob: input_image}) result = self.codec.decode(preds[self.out_blob]) return result ``` ## 実行 ``` image_path = "data/test.png" img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) f = io.BytesIO() PIL.Image.fromarray(img).save(f, 'jpeg') IPython.display.display(IPython.display.Image(data=f.getvalue())) ocr = JapaneseHandwrittenOCR("intel/handwritten-japanese-recognition-0001/FP32/handwritten-japanese-recognition-0001.xml") result = ocr.infer(image_path) print(result) ``` --- ## OpenVINO™ Model Serverを利用 ここからは手書き文字認識モデルをOpenVINO Model Serverでマイクロサービス化して外出しにします。Model ServerとはgRPCを介してコミュニケーションを取ります。 ### OpenVINO Model Serverのセットアップ OpenVINO Model ServerをホストOS上で稼働させる手順です。こちらを実行後に以降の作業を進めてください。 1. Model ServerのDockerイメージをダウンロード ```Bash docker pull openvino/model_server:latest ``` 1. 手書き文字認識用モデル(XMLファイルとBINファイル)を適当なフォルダへ格納 1. Model Serverを起動 ```Bash docker run -d --rm -v C:\Users\hiroshi\model\ocr:/models/ocr/1 -p 9000:9000 openvino/model_server:latest --model_path /models/ocr --model_name ocr --port 9000 --log_level DEBUG --shape auto ``` ※"C:\Users\hiroshi\model\ocr"にモデルが格納されているとした場合 ### モジュールのインストール ``` !pip install tensorflow-serving-api ``` ### 実装 ``` import cv2 import datetime import grpc import numpy as np import os import io from tensorflow import make_tensor_proto, make_ndarray from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2_grpc, get_model_metadata_pb2 from PIL import Image import PIL from utils.codec import CTCCodec import IPython.display from IPython.display import clear_output class RemoteJapaneseHandwrittenOCR: def __init__(self, grpc_address='localhost', grpc_port=9000, model_name='ocr', model_version=None): #Settings for accessing model server self.grpc_address = grpc_address self.grpc_port = grpc_port self.model_name = model_name self.model_version = model_version channel = grpc.insecure_channel("{}:{}".format(self.grpc_address, self.grpc_port)) self.stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) # Get input shape info from Model Server self.input_name, input_shape, self.output_name, output_shape = self.__get_input_name_and_shape__() self.input_height = input_shape[2] self.input_width = input_shape[3] # Setup codec self.codec = CTCCodec(self.__get_characters__(), None, 20) def __get_input_name_and_shape__(self): metadata_field = "signature_def" request = get_model_metadata_pb2.GetModelMetadataRequest() request.model_spec.name = self.model_name if self.model_version is not None: request.model_spec.version.value = self.model_version request.metadata_field.append(metadata_field) result = self.stub.GetModelMetadata(request, 10.0) # result includes a dictionary with all model outputs input_metadata, output_metadata = self.__get_input_and_output_meta_data__(result) input_blob = next(iter(input_metadata.keys())) output_blob = next(iter(output_metadata.keys())) return input_blob, input_metadata[input_blob]['shape'], output_blob, output_metadata[output_blob]['shape'] def __get_input_and_output_meta_data__(self, response): signature_def = response.metadata['signature_def'] signature_map = get_model_metadata_pb2.SignatureDefMap() signature_map.ParseFromString(signature_def.value) serving_default = signature_map.ListFields()[0][1]['serving_default'] serving_inputs = serving_default.inputs input_blobs_keys = {key: {} for key in serving_inputs.keys()} tensor_shape = {key: serving_inputs[key].tensor_shape for key in serving_inputs.keys()} for input_blob in input_blobs_keys: inputs_shape = [d.size for d in tensor_shape[input_blob].dim] tensor_dtype = serving_inputs[input_blob].dtype input_blobs_keys[input_blob].update({'shape': inputs_shape}) input_blobs_keys[input_blob].update({'dtype': tensor_dtype}) serving_outputs = serving_default.outputs output_blobs_keys = {key: {} for key in serving_outputs.keys()} tensor_shape = {key: serving_outputs[key].tensor_shape for key in serving_outputs.keys()} for output_blob in output_blobs_keys: outputs_shape = [d.size for d in tensor_shape[output_blob].dim] tensor_dtype = serving_outputs[output_blob].dtype output_blobs_keys[output_blob].update({'shape': outputs_shape}) output_blobs_keys[output_blob].update({'dtype': tensor_dtype}) return input_blobs_keys, output_blobs_keys def __get_characters__(self): '''Get characters''' charlist = "data/kondate_nakayosi_char_list.txt" with open(charlist, 'r', encoding='utf-8') as f: return ''.join(line.strip('\n') for line in f) def __preprocess_input__(self, image_name, height, width): src = cv2.imread(image_name, cv2.IMREAD_GRAYSCALE) ratio = float(src.shape[1]) / float(src.shape[0]) tw = int(height * ratio) rsz = cv2.resize(src, (tw, height), interpolation=cv2.INTER_AREA).astype(np.float32) # [h,w] -> [c,h,w] img = rsz[None, :, :] _, h, w = img.shape # right edge padding pad_img = np.pad(img, ((0, 0), (0, height - h), (0, width - w)), mode='edge') return pad_img def infer(self, image_path): # Read and pre-process input image (NOTE: one image only) input_path = image_path input_image = self.__preprocess_input__(input_path, height=self.input_height, width=self.input_width)[None,:,:,:] input_image = input_image.astype(np.float32) # Model ServerにgRPCでアクセスしてモデルをコール request = predict_pb2.PredictRequest() request.model_spec.name = self.model_name request.inputs[self.input_name].CopyFrom(make_tensor_proto(input_image, shape=(input_image.shape))) result = self.stub.Predict(request, 10.0) # result includes a dictionary with all model outputs preds = make_ndarray(result.outputs[self.output_name]) result = self.codec.decode(preds) return result ``` ### 実行 ``` image_path = "data/test.png" img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) f = io.BytesIO() PIL.Image.fromarray(img).save(f, 'jpeg') IPython.display.display(IPython.display.Image(data=f.getvalue())) ocr = RemoteJapaneseHandwrittenOCR(grpc_address='192.168.145.33', grpc_port='9000', model_name='ocr') result = ocr.infer(image_path) print(result) ``` --- # おしまい!
github_jupyter
# Prepare Glove vector ``` import numpy as np import codecs import pickle import operator def loadGloveModel(gloveFile): print "Loading Glove Model" f = codecs.open(gloveFile,'r') model = {} for line in f: splitLine = line.split() word = splitLine[0] embedding = [float(val) for val in splitLine[1:]] model[word] = embedding print "Done.",len(model)," words loaded!" return model f.close() def cal_coverage(voca, glove): cnt = 0 for token in voca.keys(): if glove.has_key( token ): ; else: cnt = cnt + 1 print '# missing token : ' + str(cnt) print 'coverage : ' + str( 1 - ( cnt/ float(len(voca)) ) ) def create_glove_embedding(voca, glove): # sorting voca dic by value sorted_voca = sorted(voca.items(), key=operator.itemgetter(1)) list_glove_voca = [] cnt = 0 for token, value in sorted_voca: if glove.has_key( token ): list_glove_voca.append( glove[token] ) else: if token == '_PAD_': print 'add PAD as 0s' list_glove_voca.append( np.zeros(300) ) else: list_glove_voca.append( np.random.uniform(-0.25, 0.25, 300).tolist() ) cnt = cnt + 1 print 'coverage : ' + str( 1 - ( cnt/ float(len(voca)) ) ) return list_glove_voca ``` ## 01 load glove model ``` glove = loadGloveModel('../data/raw/embedding/glove.840B.300d.txt') # glove_twit = loadGloveModel('../data/raw/embedding/glove.twitter.27B.200d.txt') ``` ## 02-A process IEMOCAP ``` dic = {} with open('../data/processed/IEMOCAP/dic.pkl') as f: dic = pickle.load(f) print 'total dic size : ' + str(len(dic)) cal_coverage(dic, glove) # cal_coverage(dic, glove_twit) list_glove_voca = create_glove_embedding(dic, glove) len(list_glove_voca) np_glove = np.asarray(list_glove_voca, dtype=np.float32) print np.shape(np_glove) np.save('../data/processed/IEMOCAP/W_embedding.npy', np_glove) ``` ## 02-B process IEMOCAP (G speech api case) ``` # dic = {} # with open('../data/processed/IEMOCAP/dic_G.pkl') as f: # dic = pickle.load(f) # print 'total dic size : ' + str(len(dic)) # cal_coverage(dic, glove) # # cal_coverage(dic, glove_twit) # list_glove_voca = create_glove_embedding(dic, glove) # len(list_glove_voca) # np_glove = np.asarray(list_glove_voca, dtype=np.float32) # print np.shape(np_glove) # np.save('../data/processed/IEMOCAP/W_embedding_G.npy', np_glove) ```
github_jupyter
# Categorical Features CV Encoding ### Explanation: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b ``` from google.colab import drive drive.mount('/content/gdrive') !pip install category_encoders # General imports import numpy as np import pandas as pd import os, sys, gc, warnings, random, datetime, time, multiprocessing import pickle from sklearn import metrics from sklearn.model_selection import train_test_split, GroupKFold from sklearn.preprocessing import LabelEncoder import category_encoders as ce from tqdm import tqdm import math warnings.filterwarnings('ignore') pd.set_option('display.max_columns', 1000) pd.set_option('display.max_rows', 500) # Seeder # :seed to make all processes deterministic # type: int def seed_everything(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) # Memory Reducer def memory_usage_mb(df, *args, **kwargs): """Dataframe memory usage in MB. """ return df.memory_usage(*args, **kwargs).sum() / 1024**2 def reduce_mem_usage(df, deep=True, verbose=False, categories=False): # All types that we want to change for "lighter" ones. # int8 and float16 are not include because we cannot reduce # those data types. # float32 is not include because float16 has too low precision. numeric2reduce = ["int16", "int32", "int64", "float64"] start_mem = 0 start_mem = memory_usage_mb(df, deep=deep) for col, col_type in df.dtypes.iteritems(): best_type = None if categories: if col_type == "object": df[col] = df[col].astype("category") best_type = "category" elif col_type in numeric2reduce: downcast = "integer" if "int" in str(col_type) else "float" df[col] = pd.to_numeric(df[col], downcast=downcast) best_type = df[col].dtype.name # Log the conversion performed. if verbose and best_type is not None and best_type != str(col_type): print(f"Column '{col}' converted from {col_type} to {best_type}") end_mem = memory_usage_mb(df, deep=deep) diff_mem = start_mem - end_mem percent_mem = 100 * diff_mem / start_mem print(f"Memory usage decreased from" f" {start_mem:.2f}MB to {end_mem:.2f}MB" f" ({diff_mem:.2f}MB, {percent_mem:.2f}% reduction)") return df # Check memory def show_mem_usage(): '''Displays memory usage from inspection of global variables in this notebook''' gl = sys._getframe(1).f_globals vars= {} for k,v in list(gl.items()): # for pandas dataframes if hasattr(v, 'memory_usage'): mem = v.memory_usage(deep=True) if not np.isscalar(mem): mem = mem.sum() vars.setdefault(id(v),[mem]).append(k) # work around for a bug elif isinstance(v,pd.Panel): v = v.values vars.setdefault(id(v),[sys.getsizeof(v)]).append(k) total = 0 for k,(value,*names) in vars.items(): if value>1e6: print(names,"%.3fMB"%(value/1e6)) total += value print("%.3fMB"%(total/1e6)) # DATA LOAD print('Load Data') train_df = pd.read_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/train.csv') test_df = pd.read_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/test.csv') test_df['isFraud'] = 0 print('Shape control:\nTrain:', train_df.shape, '\nTest:',test_df.shape) train_df = train_df.replace([np.inf, -np.inf], np.nan) train_df = train_df.fillna(-10000) test_df = test_df.replace([np.inf, -np.inf], np.nan) test_df = test_df.fillna(-10000) # Full list categorical_features = [ 'M2', 'M2__M3_0', 'M2__M3_1', 'M2__M3_2', 'M2__M3_3', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'DeviceInfo_version','DeviceInfo_device','DeviceInfo', 'ProductCD','product_type', 'card1','card2','card3', 'card4','card5','card6', 'card2__dist1','card1__card5', 'addr1','addr2', 'addr1__card1', 'R_emaildomain','P_emaildomain', 'P_emaildomain__C2','DeviceInfo__P_emaildomain', 'card5__P_emaildomain', 'card2__id_20', 'D11__DeviceInfo', 'D8__D9','M2__M3'] tokeep = ['TransactionID','isFraud'] tokeep.extend(categorical_features) print(len(tokeep)) train_df = train_df[tokeep] test_df = test_df[tokeep] test_df.drop(columns=['isFraud'],inplace=True) print('Shape control:\nTrain:', train_df.shape, '\nTest:',test_df.shape) groups = pd.read_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/groupkfolds_5.csv') train_df = train_df.merge(groups, how='left',on='TransactionID') print('Shape control:\nTrain:', train_df.shape, '\nTest:',test_df.shape) train_df.head() test_df.head() def cv_encoding(train_df, test_df, categorical_features, target='isFraud', id_col='TransactionID', encoder='CatBoostEncoder', return_fold_col=False): ''' This function encodes using CV Encoding technique link: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b. Input: - train_df: pandas df with just categorical columns, target column, id column and fold column. All numerical. - test_df: pandas df with just categorical columns and id column. All numerical. - categorical_features: list containing the categorical features to be encoded - id_col: str, specify the ID column - encoder: https://contrib.scikit-learn.org/categorical-encoding/index.html Encoding options: 'BaseNEncoder','BinaryEncoder','CatBoostEncoder','HashingEncoder', 'HelmertEncoder','JamesSteinEncoder','LeaveOneOutEncoder', 'MEstimateEncoder','OneHotEncoder','OrdinalEncoder','SumEncoder', 'PolynomialEncoder','TargetEncoder','WOEEncoder' - return_fold_col: bool, return or not the fold col in train_df Output: - new_train - new_test Prerequisite: - pandas - category_encoders (pip install category_encoders) ''' import pandas as pd import category_encoders as ce import time print('Starting DF Shapes:\nTrain:', train_df.shape, '\nTest:',test_df.shape) start = time.time() new_columns = [id_col,'fold'] new_columns.extend(categorical_features) new_train = pd.DataFrame(columns=new_columns) print('\nCV Encoding - Train set:') for i in sorted(list(train_df.fold.unique())): #------------ print('Processing Fold:',i) # will use the encoder we pass as an argument if encoder == 'BackwardDifferenceEncoder': enc = ce.BackwardDifferenceEncoder(cols=categorical_features) elif encoder == 'BaseNEncoder': enc = ce.BaseNEncoder(cols=categorical_features) elif encoder == 'BinaryEncoder': enc = ce.BinaryEncoder(cols=categorical_features) elif encoder == 'CatBoostEncoder': enc = ce.CatBoostEncoder(cols=categorical_features, sigma=2.0) elif encoder == 'HashingEncoder': enc = ce.HashingEncoder(cols=categorical_features) elif encoder == 'HelmertEncoder': enc = ce.HelmertEncoder(cols=categorical_features) elif encoder == 'JamesSteinEncoder': enc = ce.JamesSteinEncoder(cols=categorical_features) elif encoder == 'LeaveOneOutEncoder': enc = ce.LeaveOneOutEncoder(cols=categorical_features) elif encoder == 'MEstimateEncoder': enc = ce.MEstimateEncoder(cols=categorical_features) elif encoder == 'OneHotEncoder': enc = ce.OneHotEncoder(cols=categorical_features) elif encoder == 'OrdinalEncoder': enc = ce.OrdinalEncoder(cols=categorical_features) elif encoder == 'SumEncoder': enc = ce.SumEncoder(cols=categorical_features) elif encoder == 'PolynomialEncoder': enc = ce.PolynomialEncoder(cols=categorical_features) elif encoder == 'TargetEncoder': enc = ce.TargetEncoder(cols=categorical_features) elif encoder == 'WOEEncoder': enc = ce.WOEEncoder(cols=categorical_features) enc.fit(train_df[train_df['fold'] != i][categorical_features], train_df[train_df['fold'] != i][target]) trans_fold = enc.transform(train_df[train_df['fold'] == i][categorical_features]) trans_fold.reset_index(drop=True, inplace=True) trans_fold[id_col] = train_df[train_df['fold'] == i][id_col].reset_index(drop=True) trans_fold['fold'] = train_df[train_df['fold'] == i]['fold'].reset_index(drop=True) trans_fold = trans_fold[new_columns] new_train = new_train.append(trans_fold) del enc, trans_fold gc.collect() #------------ new_train_cal = new_train.merge(train_df, how='left', on=id_col) new_test = test_df print('\nCV Encoding - Test set:') for col in categorical_features: #------------ print('Column:',col) calc = new_train_cal.groupby(by=str(col)+'_y')[[str(col)+'_x']].mean() calc.reset_index(inplace=True) new_test = new_test.merge(calc, how = 'left', left_on = test_df[str(col)], right_on = calc[str(col)+'_y']) new_test.drop(columns=['key_0'],inplace=True) #------------ to_remove = [s + '_y' for s in categorical_features] to_remove.extend(categorical_features) to_remove = sorted(to_remove) new_test.drop(columns=to_remove, inplace=True) if not return_fold_col: new_train.drop(columns=['fold'],inplace=True) newtraincols = [col+'_'+str(encoder.lower()) for col in new_train.columns if col not in [id_col,'fold']] newtraincols.insert(0,id_col) new_train.columns = newtraincols newcols = [col.replace('_x','_'+str(encoder.lower())) for col in new_test.columns if '_x' in col] newcols.insert(0,id_col) new_test.columns = newcols print('\nNew DF Shapes:\nNew Train:', new_train.shape, '\nNew Test:',new_test.shape) print('Processing time (min):', round((time.time() - start)/60,2)) return new_train, new_test new_train, new_test = cv_encoding(train_df, test_df, categorical_features) new_train.head() new_test.head() # LOAD LATEST VERSION print('Load Data') train_df = pd.read_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/train_all_feat.csv') test_df = pd.read_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/test_all_feat.csv') train_df = train_df.merge(new_train, how='left', on='TransactionID') test_df = test_df.merge(new_test, how='left', on='TransactionID') train_df.drop(columns=categorical_features, inplace=True) test_df.drop(columns=categorical_features, inplace=True) print('Final DF Shapes:\nFinal Train:', train_df.shape, '\nFinal Test:',test_df.shape) train_df.to_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/train_full_catencode.csv',index=False) test_df.to_csv('../content/gdrive/My Drive/IEEE fraud Kaggle 2019/test_full_catencode.csv',index=False) ```
github_jupyter
# Simple 10-class classification ``` import keras from keras.models import Sequential from keras.layers import Dense, Activation import numpy as np import matplotlib.pyplot as plt import warnings # Suppress warkings (gets rid of some type-conversion warnings) warnings.filterwarnings("ignore") %matplotlib inline ``` ### Generate some dummy data ``` classes = 10 data = np.random.random((1000, 100)) labels = np.random.randint(classes, size=(1000, 1)) ``` ### (Optional) Visualization of the data This is not part of the Keras example, but it helps to understand what we are trying to do. ``` # Plot a 2D representation of the data, using t-SNE from sklearn.manifold import TSNE data_viz = TSNE(n_components=2).fit_transform(data) print("Data dimensions after reduction: {}".format(data_viz.shape)) plt.scatter(data_viz[:,0], data_viz[:,1], c=labels[:,0], cmap=plt.cm.get_cmap("jet", classes)) plt.colorbar(ticks=range(classes)) ``` #### Let's see what each example looks like We can think of them as the images of "digits." We will actually train character recognition in future tutorials. ``` sampleSize = 10 samples = np.random.permutation(data.shape[0])[0:sampleSize].tolist() fig=plt.figure(figsize=(15, 8)) for i in range(1, sampleSize+1): fig.add_subplot(1, sampleSize, i) plt.imshow(np.reshape(data[samples[i-1],:], (10,10)), interpolation='nearest', cmap="Blues") plt.title('Class {}'.format(labels[samples[i-1]])) plt.xlabel("Img {}".format(samples[i-1])) ``` ## Finally, let's use Keras ### Create the model ``` # For a single-input model with 10 classes (categorical classification): model = Sequential() model.add(Dense(32, activation='relu', input_dim=100)) model.add(Dense(classes, activation='softmax')) ``` ### Compile the model ``` model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ``` ### Transform labels (i.e., the outputs), to the shape expected by the model ``` # Convert labels to categorical one-hot encoding one_hot_labels = keras.utils.to_categorical(labels[:,0], num_classes=classes) # Optional: visualize the label transformation rIdx = np.random.randint(0, labels.shape[0]) print("Label shapes before: {}".format(labels.shape)) print("\tLabel at random index {}:\n\t{}\n".format(rIdx, labels[rIdx])) print("Label shapes after: {}".format(one_hot_labels.shape)) print("\tOne-hot encoded label at random index {} (same as above):\n\t{}\n".format(rIdx, one_hot_labels[rIdx, :])) print("(Pos.)\t{}".format(np.array(range(0,10),dtype="float"))) ``` ### Train the model Note how the loss decreases, while the accuracy increases, as the training goes through more and more epochs. ``` # Train the model, iterating on the data in batches of 32 samples model.fit(data, one_hot_labels, epochs=250, batch_size=32, verbose=2) predSetSize = 5 predData = np.random.random((predSetSize, 100)) samples = np.random.permutation(predData.shape[0])[0:predSetSize].tolist() fig=plt.figure(figsize=(15, 8)) results = np.round(model.predict(predData, verbose=1), decimals=2) resultLabels = np.argmax(results, axis=0) for i in range(1, predSetSize+1): fig.add_subplot(1, predSetSize, i) plt.imshow(np.reshape(predData[samples[i-1],:], (10,10)), interpolation='nearest', cmap="Blues") plt.title('Class {}'.format(resultLabels[samples[i-1]])) plt.xlabel("Img {}".format(samples[i-1])) ``` ## Conclusions This example is still abstract (i.e., we used random data), but it shows the general workflow. In the next tutorial, we will apply this to a meaningful dataset.
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # tf.data を使って NumPy データをロードする <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/beta/tutorials/load_data/numpy"><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/blob/master/site/ja/beta/tutorials/load_data/numpy.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/blob/master/site/ja/beta/tutorials/load_data/numpy.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳は**ベストエフォート**であるため、この翻訳が正確であることや[英語の公式ドキュメント](https://www.tensorflow.org/?hl=en)の 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリ[tensorflow/docs](https://github.com/tensorflow/docs)にプルリクエストをお送りください。 コミュニティによる翻訳やレビューに参加していただける方は、 [docs-ja@tensorflow.org メーリングリスト](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ja)にご連絡ください。 このチュートリアルでは、NumPy 配列から `tf.data.Dataset` にデータを読み込む例を示します。 この例では、MNIST データセットを `.npz` ファイルから読み込みますが、 NumPy 配列がどこに入っているかは重要ではありません。 ## 設定 ``` !pip install tensorflow==2.0.0-beta1 from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import tensorflow as tf import tensorflow_datasets as tfds ``` ### `.npz` ファイルからのロード ``` DATA_URL = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz' path = tf.keras.utils.get_file('mnist.npz', DATA_URL) with np.load(path) as data: train_examples = data['x_train'] train_labels = data['y_train'] test_examples = data['x_test'] test_labels = data['y_test'] ``` ## `tf.data.Dataset` を使って NumPy 配列をロード サンプルの配列と対応するラベルの配列があるとします。 `tf.data.Dataset.from_tensor_slices` にこれら2つの配列をタプルとして入力し、`tf.data.Dataset` を作成します。 ``` train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels)) test_dataset = tf.data.Dataset.from_tensor_slices((test_examples, test_labels)) ``` ## データセットの使用 ### データセットのシャッフルとバッチ化 ``` BATCH_SIZE = 64 SHUFFLE_BUFFER_SIZE = 100 train_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE) test_dataset = test_dataset.batch(BATCH_SIZE) ``` ### モデルの構築と訓練 ``` model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer=tf.keras.optimizers.RMSprop(), loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) model.fit(train_dataset, epochs=10) model.evaluate(test_dataset) ```
github_jupyter
# MODEL ANALYSIS [TEST DATA] #### Dependecies ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.metrics import brier_score_loss LEN = range(70, 260, 10) def decodePhed(x): return 10**(-x/10.0) ``` #### Load csv files ``` test_regular = list() test_mems = list() test_bow = list() test_bow_mems = list() test_mems_stat = list() orig = list() control_60 = list() reg_fn = "../data/stats/test/tstats_r_{}.tsv" m_fn = "../data/stats/test/tstats_m_{}.tsv" b_fn = "../data/stats/test/tstats_b_{}.tsv" bm_fn = "../data/stats/test/tstats_bm_{}.tsv" ms_fn = "../data/stats/test/tstats_ms_{}.tsv" for i in range(70, 260, 10): test_regular.append(pd.read_csv(reg_fn.format(i), sep='\t')) test_mems.append(pd.read_csv(m_fn.format(i), sep='\t')) test_bow.append(pd.read_csv(b_fn.format(i), sep='\t')) test_bow_mems.append(pd.read_csv(bm_fn.format(i), sep='\t')) test_mems_stat.append(pd.read_csv(ms_fn.format(i), sep='\t')) mq_size = test_regular[-1][test_regular[-1].aligner == 'recal']['aligner'].count() control_60.append(np.ones(mq_size) * 60) for i in test_regular: orig.append(i[i.aligner == 'orig']) ``` #### Counting correct and incorrect mappings ``` correct_counts = list() incorrect_counts = list() for r, m , b, bm, ms, ori in zip(test_regular, test_mems, test_bow, test_bow_mems, test_mems_stat, orig): r = r[r.aligner == 'recal'] m = m[m.aligner == 'recal'] b = b[b.aligner == 'recal'] bm = bm[bm.aligner == 'recal'] ms = ms[ms.aligner == 'recal'] rc_counts = r[r.correct == 1].correct.count() ri_counts = r[r.correct == 0].correct.count() mc_counts = m[m.correct == 1].correct.count() mi_counts = m[m.correct == 0].correct.count() bc_counts = b[b.correct == 1].correct.count() bi_counts = b[b.correct == 0].correct.count() bmc_counts = bm[bm.correct == 1].correct.count() bmi_counts = bm[bm.correct == 0].correct.count() msc_counts = ms[ms.correct == 1].correct.count() msi_counts = ms[ms.correct == 0].correct.count() oric_counts = ori[ori.correct == 1].correct.count() orii_counts = ori[ori.correct == 0].correct.count() # print("correct {}, {}, {}, {}, {}, {}".format(rc_counts, mc_counts, bc_counts, bmc_counts, msc_counts, oric_counts)) # print("incorrect {}, {}, {}, {}, {}, {}".format(ri_counts, mi_counts, bi_counts, bmi_counts, msi_counts, orii_counts)) correct_counts.append(rc_counts) incorrect_counts.append(ri_counts) incorrect_counts = np.array(incorrect_counts) correct_counts = np.array(correct_counts) plt.figure(figsize=(20,8)) plt.subplot(1, 2, 1) plt.plot(LEN, incorrect_counts) plt.xlabel('Length', fontsize=20) plt.ylabel('Incorrect amounts', fontsize=20) plt.title('DNA reads Length vs Incorrect Amount', fontsize=25); plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.subplot(1, 2, 2) plt.plot(LEN, correct_counts) plt.xlabel('Length', fontsize=20) plt.ylabel('Incorrect amounts', fontsize=20) plt.title('DNA reads Length vs Correct Amount', fontsize=25); plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.savefig("LengthVSIncorrect_test.png") plt.savefig("LengthVSIncorrect_test.pdf") plt.figure(figsize=(20,8)) plt.plot(LEN, incorrect_counts/correct_counts.astype('float')) plt.xlabel('Read Length', fontsize=20) plt.ylabel('Incorrect mapping amount %', fontsize=20) plt.title('Incorrect mapping amount % vs DNA Read Length ', fontsize=30); plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.savefig("LengthVSIncorrectPer_test.png") plt.savefig("LengthVSIncorrectPer_test.pdf") ``` #### Brier score ``` r_bc = list() m_bc = list() b_bc = list() bm_bc = list() ms_bc = list() ori_bc = list() control60_bc = list() for r, m , b, bm, ms, ori, con in zip(test_regular, test_mems, test_bow, test_bow_mems, test_mems_stat, orig, control_60): rp = 1 - decodePhed(r.mq.values) r = r.assign(p=pd.Series(rp).values) r_bc.append(brier_score_loss(r.correct.values, r.p.values)) mp = 1 - decodePhed(m.mq.values) m = m.assign(p=pd.Series(mp).values) m_bc.append(brier_score_loss(m.correct.values, m.p.values)) bp = 1 - decodePhed(b.mq.values) b = b.assign(p=pd.Series(bp).values) b_bc.append(brier_score_loss(b.correct.values, b.p.values)) bmp = 1 - decodePhed(bm.mq.values) bm = bm.assign(p=pd.Series(bmp).values) bm_bc.append(brier_score_loss(bm.correct.values, bm.p.values)) msp = 1 - decodePhed(ms.mq.values) ms = ms.assign(p=pd.Series(msp).values) ms_bc.append(brier_score_loss(ms.correct.values, ms.p.values)) orip = 1 - decodePhed(ori.mq.values) ori = ori.assign(p=pd.Series(orip).values) ori_bc.append(brier_score_loss(ori.correct.values, ori.p.values)) conp = 1 - decodePhed(con) control60_bc.append(brier_score_loss(ori.correct.values, conp)) r_bc = np.array(r_bc) m_bc = np.array(m_bc) b_bc = np.array(b_bc) bm_bc = np.array(bm_bc) ms_bc = np.array(ms_bc) ori_bc = np.array(ori_bc) control60_bc = np.array(control60_bc) plt.figure(figsize=(20,10)) plt.plot(LEN, ori_bc, c='k', label='original', linewidth=6) plt.plot(LEN, r_bc, c='b', label='mapping quality', linewidth=3) plt.plot(LEN, m_bc, c='r', label='mems', linewidth=3) plt.plot(LEN, b_bc, c='g', label='bag of words', linewidth=3) plt.plot(LEN, bm_bc, c='m', label='bag of words with mems', linewidth=3) plt.plot(LEN, ms_bc, c='y', label='mems stats', linewidth=3) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.xlabel('Length', fontsize=30) plt.xticks(fontsize=20) plt.ylabel('Brier Score', fontsize=30) plt.title('Brier Score vs DNA Read Length for model', fontsize=30); plt.legend(fontsize=20); plt.savefig("DNALengthVsBrierScore_test.png") plt.savefig("DNALengthVsBrierScore_test.pdf") ```
github_jupyter
# Imports ``` #!pip install plotly from os import listdir from os.path import isfile, join import pandas as pd import cbsodata from datetime import datetime import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import altair as alt from sklearn import preprocessing import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) ``` # Settings # Functions ``` def single_scatter(df, x, y, ymin=None, ymax=None, xmin=None, xmax=None, show=True, save=False, save_as='img', **kwargs): fig = px.scatter(df, x=x, y=y, **kwargs) suffix_datetime = datetime.strftime(datetime.now(), format='%Y%m%d%H%M') filename = f"{suffix_datetime}_scatter_x_{x}_y_{y}" if (type(ymin) == int or type(ymin) == float) and (type(ymax) == int or type(ymax) == float): fig.update_yaxes(range=[ymin, ymax], row=1, col=1) if (type(xmin) == int or type(xmin) == float) and (type(xmax) == int or type(xmax) == float): fig.update_xaxes(range=[xmin, xmax], row=1, col=1) if save: if save_as == 'html': fig.write_html(f"../img/{filename}.html") elif save_as == 'img': fig.write_image(f"../img/{filename}.jpeg") if show: fig.show() def subplot_scatter(df, xlist, y, show=True, save=False, save_as='img', **kwargs): fig = make_subplots(rows=1, cols=len(xlist), shared_yaxes=True) for i, x in enumerate(xlist): go_scatter_kwargs = {k:v for k, v in kwargs.items() if k in list(go.Scatter.__init__.__code__.co_varnames)} fig.add_trace(go.Scatter(x=df[x], y=df[y], mode="markers", name=x, **go_scatter_kwargs), row=1, col=i+1) fig.update_xaxes(title_text=x, row=1, col=i+1) update_layout_kwargs = {k:v for k, v in kwargs.items() if k not in list(kwargs.keys())} fig.update_layout(**update_layout_kwargs) fig.update_yaxes(title_text=y, row=1, col=1) if save: if save_as == 'html': fig.write_html(f"../img/{filename}.html") elif save_as == 'img': fig.write_image(f"../img/{filename}.jpeg") if show: fig.show() ``` # EDA EDA outside dataset ``` df_geslacht = pd.read_csv("../data/Cliënten huishoudelijke hulp leeftijd en geslacht Nederland Nijmegen 25 mrt 2021.csv", sep=';') df_geslacht df_manvrouw = pd.read_csv("../data/Huishoudens alleenstaand en mannen en vrouwen 2012-2020 25 mrt 2021 - Nijmegen.csv", sep=';') df_manvrouw ``` Load data ``` df = pd.read_parquet('../data/df_WMO_WIJK_HOUSEHOLDS_POP_LEVY_absolute_gemeente.parquet.gzip') ``` Omvang dataset ``` df.shape ``` Check kolommen ``` list(df.columns) ``` Tel aantal unieke gemeenten ``` df.reset_index().codering_regio.nunique() ``` Uitzoeken hoeveel gemeenten er alle jaren info hebben ``` df_gem = df.reset_index()[['codering_regio', 'interval']] df_counts = pd.DataFrame(df_gem.codering_regio.value_counts()) df_counts.head() df_counts.codering_regio.value_counts() ``` Aantal string kolommen ``` list_exclude = ['perioden', 'popcodea', 'popcodeb', 'popcodec', 'popcoded', 'popcodee', 'popcodef', 'popcodeg', 'popcodeh', 'popcodei', 'popcodej', 'popcodek', 'popcodel', 'popcodem', 'popcoden', 'popcodeo', 'popcodep', 'popcodeq', 'popcoder', 'popnaama', 'popnaamb', 'popnaamc', 'popnaamd', 'popnaame', 'popnaamf', 'popnaamg', 'popnaamh', 'popnaami', 'popnaamj', 'popnaamk', 'popnaaml', 'popnaamm', 'popnaamn', 'popnaamo', 'popnaamp', 'popnaamq', 'popnaamr', 'popkoppelvariabeleregiocode', 'typemaatwerkarrangement', 'gemeentenaam', 'meestvoorkomendepostcode'] len(list_exclude) ``` Aantal missende waarden numerieke kolommen bepalen ``` # # search certain value # df.drop(list_exclude, axis=1)[df.drop(list_exclude, axis=1) == "JZ01 "].sum()>1 # df.loc[:, df.columns != 'perioden'].columns for col in df.drop(list_exclude, axis=1).columns: # print(col) df[col] = pd.to_numeric(df[col]) s_num_missing = df.drop(list_exclude, axis=1).isnull().sum(axis=0)[df.drop(list_exclude, axis=1).isnull().sum(axis=0)>0] s_perc_missing = s_num_missing / len(df) df_missing = pd.DataFrame({'num_missing': s_num_missing,'perc_missing': s_perc_missing}) df_missing.sort_values('perc_missing', ascending=False) ``` Aantal kolommen met missing value > 25% ``` len(df_missing[df_missing['perc_missing']>0.25]) all_nan_cols = list(df_missing[df_missing['perc_missing']==1].index) all_nan_cols ``` Aantal missing values voor target variabele ``` df_missing.loc['wmoclienten'] df_missing.loc['wmoclientenper1000inwoners'] ``` # Verkennen targetvariabele _Histograms/density plots_ * [Plotly histograms ](https://plotly.com/python/histograms/) * [Plotly histrogram contour](https://plotly.com/python/2d-histogram-contour/) * [Plotly density plot](https://plotly.com/python/distplot/) ``` ## Mocht je het tof vinden, kun je ook kijken of je een mooie visualisatie in dezelfde stijl kunt krijgen ## voor de targetvariabele df['wmoclientenper1000inwoners'].hist() import plotly.figure_factory as ff import numpy as np x = df['wmoclientenper1000inwoners'].dropna() hist_data = [x] group_labels = ['wmoclientenper1000inwoners'] # name of the dataset fig = ff.create_distplot(hist_data, group_labels) fig.show() df['wmoclientenper1000inwoners'].max() import plotly.figure_factory as ff import numpy as np x = df['wmoclientenper1000inwoners'].dropna() group_labels = ['wmoclientenper1000inwoners'] # colors = ['slategray', 'magenta'] # Create distplot with curve_type set to 'normal' fig = ff.create_distplot([x], group_labels, bin_size=.5, curve_type='normal') # override default 'kde') # Add title fig.update_layout(title_text='Distplot with Normal Distribution') fig.show() ``` # Correlatie bepalen ### HIER GRAAG CORRELATIEMATRIX INVOEGEN NICK ``` corr_matrix = df.corr()['wmoclientenper1000inwoners'] sorted_pairs = corr_matrix.sort_values(kind='quicksort') strong_pairs = sorted_pairs[abs(sorted_pairs) > 0.4] print(strong_pairs) list_strong_pairs = list(strong_pairs.index) df_corr = df[list_strong_pairs].corr() f, ax = plt.subplots(figsize=(40,20)) cmap = sns.diverging_palette(230,20, as_cmap=True) sns.set(font_scale=2.0) sns.heatmap(df_corr,vmax=1 ,cmap=cmap, square=True, linewidth=.5, ax = ax) plt.title("Correlatiematrix") ``` # Verdieping middels scatterplots _Single scatterplot_ * [Plotly scatterplot](https://plotly.com/python/line-and-scatter/) * [Scatter params](https://plotly.com/python-api-reference/generated/plotly.graph_objects.Scatter.html) ``` y = 'wmoclientenper1000inwoners' x = 'vrouwen' z = 'perioden' single_scatter(df=df, x=x, y=y, color=z, opacity=0.4, size=None, hover_data=[], width=800, height=800, show=True) ``` _Single scatterplot for loop for all_ ``` # list_cols_with_interesting_corr = [df] y = 'wmoclientenper1000inwoners' z = 'perioden' for x in df.columns: single_scatter(df=df, x=x, y=y, color=z, opacity=0.4, size=None, hover_data=[], width=800, height=800, show=False, save=True) ``` # Appendix: Play with plotly ### Subplot scatterplot [Plotly subplots](https://plotly.com/python/subplots/) ``` df['leeftijd_mix_sum'] = (7.5*df['k0tot15jaar'])+(20*df['k15tot25jaar'])+(35*df['k25tot45jaar'])+(55*df['k45tot65jaar'])+(75*df['k65jaarofouder']) df['leeftijd_mix_avg'] = df['leeftijd_mix_sum'] / df['aantalinwoners'] # xlist=['k0tot15jaar', 'k15tot25jaar', 'k25tot45jaar', 'k45tot65jaar', 'k65jaarofouder'] xlist=['vrouwen', 'mannen'] # xlist = ['leeftijd_mix_sum', 'leeftijd_mix_avg'] y = 'wmoclientenper1000inwoners' subplot_scatter(df=df, xlist=xlist, y=y, opacity=0.5, height=500, width=500, title_text="Test", show=True, save=False) ```
github_jupyter
``` %matplotlib inline import pandas as pd import numpy as np import os.path import matplotlib.pyplot as plt import seaborn as sns import math from scipy.stats import poisson def ColumnNames(): return ['col1', 'col2', 'col3', 'average'] def PreProcess(filepath, skiprows, usecols): """ This function reads data and add min, max, include_mean values. Parameters ---------- filepath : filepath of the data skiprows: number of rows to skip from the csv file usecols: range of columns of data to read in. Returns ------- data : The original count data and some added columns of new stats data. """ print 'Reading Data from \"{0}\"'.format(os.path.basename(filepath)) data = pd.read_csv(filepath, skiprows=skiprows,usecols=usecols,na_values=' ', header = None, names = ColumnNames() ).dropna(axis=0) data['col_min'] = data.apply(lambda row: min(row['col1'],row['col2'],row['col3']), axis=1) data['col_max'] = data.apply(lambda row: max(row['col1'],row['col2'],row['col3']), axis=1) data['col_median'] = data.apply(lambda row: np.median([row['col1'],row['col2'],row['col3']]), axis=1) data['col_gap'] = data['col_max']-data['col_min'] data['complete'] = data['col_gap']>=2 data['include_mean'] = data.apply(lambda row: ((row['col1'] == round(row['average']) or row['col2'] == round(row['average']) or row['col3'] == round(row['average'])) and row['complete']),axis=1) return data def GetStats(data): """ This function reads data and print relevant stats. Parameters ---------- data : preprocessed data with the desired columns """ total = len(data) complete = len(data[data['complete']]) no_mean = len(data[data['include_mean'] == True]) #mid_ratio = data[data['complete']].apply(lambda row: (row['col_median']-row['col_min'])/row['col_gap'], axis=1) #plt.figure(); #sns.distplot(mid_ratio, bins=10, norm_hist=True) print 'total:{0}, number_of_complete:{1}, number_of_mean:{2}'.format(total, complete, no_mean) def MidRatioHistPlot(data): mid_ratio = data[data['complete']].apply(lambda row: (row['col_median']-row['col_min'])/row['col_gap'], axis=1) mid_ratio_value, mid_ratio_range = np.histogram(mid_ratio, bins = 10) mid_ratio_percentage = mid_ratio_value/float(len(mid_ratio)) * 100 plt.bar(np.arange(0,10), mid_ratio_percentage) plt.axis([0, 10, 0, 1.5*max(mid_ratio_percentage)]) plt.xticks(np.arange(0,10), mid_ratio_range) plt.xlabel('Mid ratio range') plt.ylabel('Percentage') plt.show() data_dir = '../data/PittHill_OSFdata_2016/csv/' rts_colony = PreProcess(os.path.join(data_dir,'Bishayee Colony Counts 10.27.97-3.8.01.csv'),3,range(3,7)) others_colony = PreProcess(os.path.join(data_dir,'Other Investigators in Lab.Colony Counts.4.23.92-11.27.02.csv'),2,range(3,7)) rts_coulter = PreProcess(os.path.join(data_dir,'Bishayee Coulter Counts.10.20.97-7.16.01.csv'),2,range(2,6)) #rts_coulter = PreProcess(os.path.join(data_dir,'Bishayee Coulter Counts.10.20.97-7.16.01.csv'),2,range(2,6)) #others_coulter = PreProcess(os.path.join(data_dir,'Other Investigators in Lab.Coulter Counts.4.15.92-5.21.05.csv'),2,range(2,6)) MidRatioHistPlot(rts_colony) MidRatioHistPlot(others_colony) GetStats(rts_colony) GetStats(others_colony) GetStats(rts_coulter) #GetStats(rts_coulter) #GetStats(others_coulter) def ChooseN(moment): MAX_N = 1000000 EPSILON = 1e-9 prob_sum = 0 for j in range(0, MAX_N): prob_sum = prob_sum + poisson.pmf(j, moment) if prob_sum >= 1-EPSILON: #print 'For moment: {0}, Choose N:{1}'.format(moment, j) return j def PoissonMidRatio(moment, left_ratio, right_ratio): prob = 0 N = ChooseN(moment) for j in list(range(2, N + 1)): for k in list(range(j, N + 1)): inner = poisson.cdf(min(k,math.floor(right_ratio*j+k-j)), moment) - poisson.cdf(max(k-j,math.floor(left_ratio*j+k-j)), moment) outer = poisson.pmf(k, moment) * poisson.pmf(k - j, moment) prob = prob + outer * inner prob = 6 * prob return(prob) leftRatio = 0.4 rightRatio = 0.6 poisMoments = range(1, 101) # each mean-variance parameter of the Poisson distribution probs = np.zeros(len(poisMoments)) # Computing the probability of the mid ratio between leftRatio and rightRatio for i in range(len(poisMoments)): if i%20 == 0: print 'Processed to moment {0}'.format(i) probs[i] = PoissonMidRatio(poisMoments[i], leftRatio, rightRatio) print 'Process Done' plt.figure(num = None, figsize=(12, 9), dpi=80) plt.plot(poisMoments, probs) plt.xlabel('$\lambda$ (moment) parameter of Poisson distribution') plt.ylabel('Probability') plt.title(r'Histogram of Mid Ratio Probabilities from Poisson Triples') plt.axis([min(poisMoments), max(poisMoments), 0, min(1.5 * max(probs), 1)]) plt.show() ```
github_jupyter
# Using Threshold - Based Source Detection and Confusion Matrix This notebook provides an example of how to run the astropy - based source detection on a fits file. This also demonstrates how to generate a confusion matrix based on the results of the source detection. ``` import astropy from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.wcs import WCS from astropy.wcs.utils import skycoord_to_pixel from astropy.stats import sigma_clipped_stats,gaussian_fwhm_to_sigma,gaussian_sigma_to_fwhm from astropy.table import Table,Column,Row,vstack,setdiff,join from astropy.nddata import Cutout2D,NDData import astropy.units as u import os import matplotlib.pyplot as plt from astropy.visualization import ZScaleInterval,simple_norm from astropy.wcs.utils import skycoord_to_pixel, pixel_to_skycoord import photutils from photutils.datasets import make_gaussian_sources_image import numpy as np import itertools import copy import matplotlib from astropy.visualization import ZScaleInterval,simple_norm zscale = ZScaleInterval() import pickle import numpy as np import diffimageml from diffimageml import fakeplanting, util ``` # Make a FitsImage class object with the desired image ``` example_file = "../test_data/sky_image_1.fits.fz" FitsImageExample = diffimageml.FitsImage(example_file) ``` # Run source detection ``` sources = FitsImageExample.detect_sources() print (sources[0]) ``` # Confusion Matrix example The confusion matrix requires a fakeplanter object, which needs to have images with fakes planted. ``` #Load examle with fakes diffim = "../test_data/diff_pydia_1_fakegrid.fits" search_im = "../test_data/sky_image_1.fits.fz" fake_sn = diffimageml.FakePlanter(diffim , searchim_fitsfilename = search_im) matrix = fake_sn.confusion_matrix() ``` The output matrix is a list of astropy tables containing the locations and magnitudes for the sources in the given categories. To simply display the resulting 2x2 matrix, use the following. ``` print (len(matrix[0]) , len(matrix[1])) print (len(matrix[2]) , 0) ##No true negatives ``` In this case we recover 440 True positives, one False negative and 588 false positives. We can also make a confusion matrix that imposes magnitude limits. For this example, the fake sources have magnitudes around 16.5, so if we limit the magnitudes to be between 18 and 22, we filter out all the true positives. ``` matrix = fake_sn.confusion_matrix(low_mag_lim = 18 , high_mag_lim = 22) print (len(matrix[0]) , len(matrix[1])) print (len(matrix[2]) , 0) ##No true negatives ```
github_jupyter
# LiH Molecule: Constructing Potential Energy Surfaces Using VQE ## Step 1: Classical calculations ``` import numpy as np import matplotlib.pyplot as plt from utility import * import tequila as tq threshold = 1e-6 #Cutoff for UCC MP2 amplitudes and QCC ranking gradients basis = 'sto-3g' ``` #### Classical Electronic Structure Methods ``` bond_lengths = np.linspace(0.7,3.0,15) #Run FCI FCI_PES = obtain_PES('lih', bond_lengths, basis, method='fci') #Run HF HF_PES = obtain_PES('lih', bond_lengths, basis, method='hf') #Run CCSD CCSD_PES = obtain_PES('lih', bond_lengths, basis, method='ccsd') #Plot LiH PESs plt.title('LiH dissociation, STO-3G') plt.xlabel('R, Angstrom') plt.ylabel('E, Hartree') plt.plot(bond_lengths, FCI_PES, label='FCI') plt.scatter(bond_lengths, HF_PES, label='HF', color='orange') plt.scatter(bond_lengths, CCSD_PES, label='CCSD', color='purple') plt.legend() ``` ## Step 2: Generating Qubit Hamiltonians ``` qubit_transf = 'jw' # Jordan-Wigner transformations lih = get_qubit_hamiltonian(mol='lih', geometry=1, basis='sto3g', qubit_transf=qubit_transf) print(lih) lih_tapered = taper_hamiltonian(lih, n_spin_orbitals=12, n_electrons=4, qubit_transf=qubit_transf) print("Effective Hamiltonian:", lih_tapered) ``` ## Step 3: Unitary Ansatz ``` trotter_steps = 1 xyz_data = get_molecular_data('lih', geometry=1.5, xyz_format=True) basis='sto-3g' lih_tq = tq.quantumchemistry.Molecule(geometry=xyz_data, basis_set=basis) print('Number of spin-orbitals (qubits): {} \n'.format(2*lih_tq.n_orbitals)) E_FCI = lih_tq.compute_energy(method='fci') print('FCI energy: {}'.format(E_FCI)) hf_reference = hf_occ(2*lih_tq.n_orbitals, lih_tq.n_electrons) H = lih_tq.make_hamiltonian() print("\nHamiltonian has {} terms\n".format(len(H))) U_UCCSD = lih_tq.make_uccsd_ansatz(initial_amplitudes='MP2',threshold=threshold, trotter_steps=trotter_steps) E = tq.ExpectationValue(H=H, U=U_UCCSD) print('\nNumber of UCCSD amplitudes: {} \n'.format(len(E.extract_variables()))) print('\nStarting optimization:\n') result = tq.minimize(objective=E, method="BFGS", initial_values={k:0.0 for k in E.extract_variables()}, tol=1e-6) print('\nObtained UCCSD energy: {}'.format(result.energy)) ``` ## Step 4: Measurement ``` comm_groups = get_commuting_group(lih) print('Number of mutually commuting fragments: {}'.format(len(comm_groups))) print('The first commuting group') print(comm_groups[1]) uqwc = get_qwc_unitary(comm_groups[1]) print('This is unitary, U * U^+ = I ') print(uqwc * uqwc) qwc = remove_complex(uqwc * comm_groups[1] * uqwc) print(qwc) uz = get_zform_unitary(qwc) print("Checking whether U * U^+ is identity: {}".format(uz * uz)) allz = remove_complex(uz * qwc * uz) print("\nThe all-z form of qwc fragment:\n{}".format(allz)) ``` ## Step 5: Circuits ``` #Define number of entanglers to enter ansatz n_ents = 1 #Rank entanglers using energy gradient criterion ranked_entangler_groupings = generate_QCC_gradient_groupings(H.to_openfermion(), 2*lih_tq.n_orbitals, hf_reference, cutoff=threshold) print('Grouping gradient magnitudes (Grouping : Gradient magnitude):') for i in range(len(ranked_entangler_groupings)): print('{} : {}'.format(i+1,ranked_entangler_groupings[i][1])) entanglers = get_QCC_entanglers(ranked_entangler_groupings, n_ents, 2*lih_tq.n_orbitals) print('\nSelected entanglers:') for ent in entanglers: print(ent) #Mean-field part of U (Omega): U_MF = construct_QMF_ansatz(n_qubits = 2*lih_tq.n_orbitals) #Entangling part of U: U_ENT = construct_QCC_ansatz(entanglers) U_QCC = U_MF + U_ENT E = tq.ExpectationValue(H=H, U=U_QCC) initial_vals = init_qcc_params(hf_reference, E.extract_variables()) #Minimize wrt the entangler amplitude and MF angles: result = tq.minimize(objective=E, method="BFGS", initial_values=initial_vals, tol=1.e-6) print('\nObtained QCC energy ({} entanglers): {}'.format(len(entanglers), result.energy)) H = tq.QubitHamiltonian.from_openfermion(get_qubit_hamiltonian('lih', 1.5, 'sto-3g', qubit_transf='jw')) a = tq.Variable("tau_0") U = construct_QMF_ansatz(8) U += tq.gates.ExpPauli(paulistring=tq.PauliString.from_string("X(2)Y(3)X(10)X(11)"), angle=a) print(U) E = tq.ExpectationValue(H=H, U=U) vars = {'beta_0': 3.141592653589793, 'gamma_0': 0.0, 'beta_1': 3.141592653589793, 'gamma_1': 0.0, 'beta_2': 3.141592653589793, 'gamma_2': 0.0, 'beta_3': 3.141592653589793, 'gamma_3': 0.0, 'beta_4': 0.0, 'gamma_4': 0.0, 'beta_5': 0.0, 'gamma_5': 0.0, 'beta_6': 0.0, 'gamma_6': 0.0, 'beta_7': 0.0, 'gamma_7': 0.0, 'beta_8': 0.0, 'gamma_8': 0.0, 'beta_9': 0.0, 'gamma_9': 0.0, 'beta_10': 3.141592653589793, 'gamma_10': 0.0, 'beta_11': 3.141592653589793, 'gamma_11': 0.0, 'tau_0': 0.0} # values obtained from step 3 print(tq.simulate(E, variables=vars)) from qiskit import IBMQ IBMQ.save_account('6f1ae0f74f3b670c62a6a7427dc22eb12f9d6eaa47e5d264218990c42e2593d029d53a92ee9260ce05f0daf11d87a8b1a1114637c90ae648bfabeddca94ae087', overwrite=True) IBMQ.enable_account('6f1ae0f74f3b670c62a6a7427dc22eb12f9d6eaa47e5d264218990c42e2593d029d53a92ee9260ce05f0daf11d87a8b1a1114637c90ae648bfabeddca94ae087') # list of devices available can be found in ibmq account page provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_qasm_simulator') tq.simulate(E, variables=vars, samples=100, backend="qiskit", device=device)#,qiskit_provider = provider) #draw circ = tq.circuit.compiler.compile_exponential_pauli_gate(U) tq.draw(circ, backend="qiskit") ```
github_jupyter
# Face Recognition for the Happy House Welcome to the first assignment of week 4! Here you will build a face recognition system. Many of the ideas presented here are from [FaceNet](https://arxiv.org/pdf/1503.03832.pdf). In lecture, we also talked about [DeepFace](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf). Face recognition problems commonly fall into two categories: - **Face Verification** - "is this the claimed person?". For example, at some airports, you can pass through customs by letting a system scan your passport and then verifying that you (the person carrying the passport) are the correct person. A mobile phone that unlocks using your face is also using face verification. This is a 1:1 matching problem. - **Face Recognition** - "who is this person?". For example, the video lecture showed a face recognition video (https://www.youtube.com/watch?v=wr4rx0Spihs) of Baidu employees entering the office without needing to otherwise identify themselves. This is a 1:K matching problem. FaceNet learns a neural network that encodes a face image into a vector of 128 numbers. By comparing two such vectors, you can then determine if two pictures are of the same person. **In this assignment, you will:** - Implement the triplet loss function - Use a pretrained model to map face images into 128-dimensional encodings - Use these encodings to perform face verification and face recognition In this exercise, we will be using a pre-trained model which represents ConvNet activations using a "channels first" convention, as opposed to the "channels last" convention used in lecture and previous programming assignments. In other words, a batch of images will be of shape $(m, n_C, n_H, n_W)$ instead of $(m, n_H, n_W, n_C)$. Both of these conventions have a reasonable amount of traction among open-source implementations; there isn't a uniform standard yet within the deep learning community. Let's load the required packages. ``` from keras.models import Sequential from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.models import Model from keras.layers.normalization import BatchNormalization from keras.layers.pooling import MaxPooling2D, AveragePooling2D from keras.layers.merge import Concatenate from keras.layers.core import Lambda, Flatten, Dense from keras.initializers import glorot_uniform from keras.engine.topology import Layer from keras import backend as K K.set_image_data_format('channels_first') import cv2 import os import numpy as np from numpy import genfromtxt import pandas as pd import tensorflow as tf from fr_utils import * from inception_blocks_v2 import * %matplotlib inline %load_ext autoreload %autoreload 2 np.set_printoptions(threshold=np.nan) ``` ## 0 - Naive Face Verification In Face Verification, you're given two images and you have to tell if they are of the same person. The simplest way to do this is to compare the two images pixel-by-pixel. If the distance between the raw images are less than a chosen threshold, it may be the same person! <img src="images/pixel_comparison.png" style="width:380px;height:150px;"> <caption><center> <u> <font color='purple'> **Figure 1** </u></center></caption> Of course, this algorithm performs really poorly, since the pixel values change dramatically due to variations in lighting, orientation of the person's face, even minor changes in head position, and so on. You'll see that rather than using the raw image, you can learn an encoding $f(img)$ so that element-wise comparisons of this encoding gives more accurate judgements as to whether two pictures are of the same person. ## 1 - Encoding face images into a 128-dimensional vector ### 1.1 - Using an ConvNet to compute encodings The FaceNet model takes a lot of data and a long time to train. So following common practice in applied deep learning settings, let's just load weights that someone else has already trained. The network architecture follows the Inception model from [Szegedy *et al.*](https://arxiv.org/abs/1409.4842). We have provided an inception network implementation. You can look in the file `inception_blocks.py` to see how it is implemented (do so by going to "File->Open..." at the top of the Jupyter notebook). The key things you need to know are: - This network uses 96x96 dimensional RGB images as its input. Specifically, inputs a face image (or batch of $m$ face images) as a tensor of shape $(m, n_C, n_H, n_W) = (m, 3, 96, 96)$ - It outputs a matrix of shape $(m, 128)$ that encodes each input face image into a 128-dimensional vector Run the cell below to create the model for face images. ``` FRmodel = faceRecoModel(input_shape=(3, 96, 96)) print("Total Params:", FRmodel.count_params()) ``` ** Expected Output ** <table> <center> Total Params: 3743280 </center> </table> By using a 128-neuron fully connected layer as its last layer, the model ensures that the output is an encoding vector of size 128. You then use the encodings the compare two face images as follows: <img src="images/distance_kiank.png" style="width:680px;height:250px;"> <caption><center> <u> <font color='purple'> **Figure 2**: <br> </u> <font color='purple'> By computing a distance between two encodings and thresholding, you can determine if the two pictures represent the same person</center></caption> So, an encoding is a good one if: - The encodings of two images of the same person are quite similar to each other - The encodings of two images of different persons are very different The triplet loss function formalizes this, and tries to "push" the encodings of two images of the same person (Anchor and Positive) closer together, while "pulling" the encodings of two images of different persons (Anchor, Negative) further apart. <img src="images/triplet_comparison.png" style="width:280px;height:150px;"> <br> <caption><center> <u> <font color='purple'> **Figure 3**: <br> </u> <font color='purple'> In the next part, we will call the pictures from left to right: Anchor (A), Positive (P), Negative (N) </center></caption> ### 1.2 - The Triplet Loss For an image $x$, we denote its encoding $f(x)$, where $f$ is the function computed by the neural network. <img src="images/f_x.png" style="width:380px;height:150px;"> <!-- We will also add a normalization step at the end of our model so that $\mid \mid f(x) \mid \mid_2 = 1$ (means the vector of encoding should be of norm 1). !--> Training will use triplets of images $(A, P, N)$: - A is an "Anchor" image--a picture of a person. - P is a "Positive" image--a picture of the same person as the Anchor image. - N is a "Negative" image--a picture of a different person than the Anchor image. These triplets are picked from our training dataset. We will write $(A^{(i)}, P^{(i)}, N^{(i)})$ to denote the $i$-th training example. You'd like to make sure that an image $A^{(i)}$ of an individual is closer to the Positive $P^{(i)}$ than to the Negative image $N^{(i)}$) by at least a margin $\alpha$: $$\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2 + \alpha < \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2$$ You would thus like to minimize the following "triplet cost": $$\mathcal{J} = \sum^{m}_{i=1} \large[ \small \underbrace{\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2}_\text{(1)} - \underbrace{\mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2}_\text{(2)} + \alpha \large ] \small_+ \tag{3}$$ Here, we are using the notation "$[z]_+$" to denote $max(z,0)$. Notes: - The term (1) is the squared distance between the anchor "A" and the positive "P" for a given triplet; you want this to be small. - The term (2) is the squared distance between the anchor "A" and the negative "N" for a given triplet, you want this to be relatively large, so it thus makes sense to have a minus sign preceding it. - $\alpha$ is called the margin. It is a hyperparameter that you should pick manually. We will use $\alpha = 0.2$. Most implementations also normalize the encoding vectors to have norm equal one (i.e., $\mid \mid f(img)\mid \mid_2$=1); you won't have to worry about that here. **Exercise**: Implement the triplet loss as defined by formula (3). Here are the 4 steps: 1. Compute the distance between the encodings of "anchor" and "positive": $\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2$ 2. Compute the distance between the encodings of "anchor" and "negative": $\mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2$ 3. Compute the formula per training example: $ \mid \mid f(A^{(i)}) - f(P^{(i)}) \mid - \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2 + \alpha$ 3. Compute the full formula by taking the max with zero and summing over the training examples: $$\mathcal{J} = \sum^{m}_{i=1} \large[ \small \mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2 - \mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2+ \alpha \large ] \small_+ \tag{3}$$ Useful functions: `tf.reduce_sum()`, `tf.square()`, `tf.subtract()`, `tf.add()`, `tf.maximum()`. For steps 1 and 2, you will need to sum over the entries of $\mid \mid f(A^{(i)}) - f(P^{(i)}) \mid \mid_2^2$ and $\mid \mid f(A^{(i)}) - f(N^{(i)}) \mid \mid_2^2$ while for step 4 you will need to sum over the training examples. ``` # GRADED FUNCTION: triplet_loss def triplet_loss(y_true, y_pred, alpha = 0.2): """ Implementation of the triplet loss as defined by formula (3) Arguments: y_true -- true labels, required when you define a loss in Keras, you don't need it in this function. y_pred -- python list containing three objects: anchor -- the encodings for the anchor images, of shape (None, 128) positive -- the encodings for the positive images, of shape (None, 128) negative -- the encodings for the negative images, of shape (None, 128) Returns: loss -- real number, value of the loss """ anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2] ### START CODE HERE ### (≈ 4 lines) # Step 1: Compute the (encoding) distance between the anchor and the positive, you will need to sum over axis=-1 pos_dist = tf.reduce_sum(tf.square(tf.subtract(y_pred[0], y_pred[1])), axis = -1) # Step 2: Compute the (encoding) distance between the anchor and the negative, you will need to sum over axis=-1 neg_dist = tf.reduce_sum(tf.square(tf.subtract(y_pred[0], y_pred[2])), axis = -1) # Step 3: subtract the two previous distances and add alpha. basic_loss = pos_dist - neg_dist + alpha # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples. loss = tf.reduce_sum(tf.maximum(basic_loss, 0)) ### END CODE HERE ### return loss with tf.Session() as test: tf.set_random_seed(1) y_true = (None, None, None) y_pred = (tf.random_normal([3, 128], mean=6, stddev=0.1, seed = 1), tf.random_normal([3, 128], mean=1, stddev=1, seed = 1), tf.random_normal([3, 128], mean=3, stddev=4, seed = 1)) loss = triplet_loss(y_true, y_pred) print("loss = " + str(loss.eval())) ``` **Expected Output**: <table> <tr> <td> **loss** </td> <td> 528.143 </td> </tr> </table> ## 2 - Loading the trained model FaceNet is trained by minimizing the triplet loss. But since training requires a lot of data and a lot of computation, we won't train it from scratch here. Instead, we load a previously trained model. Load a model using the following cell; this might take a couple of minutes to run. ``` FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy']) load_weights_from_FaceNet(FRmodel) ``` Here're some examples of distances between the encodings between three individuals: <img src="images/distance_matrix.png" style="width:380px;height:200px;"> <br> <caption><center> <u> <font color='purple'> **Figure 4**:</u> <br> <font color='purple'> Example of distance outputs between three individuals' encodings</center></caption> Let's now use this model to perform face verification and face recognition! ## 3 - Applying the model Back to the Happy House! Residents are living blissfully since you implemented happiness recognition for the house in an earlier assignment. However, several issues keep coming up: The Happy House became so happy that every happy person in the neighborhood is coming to hang out in your living room. It is getting really crowded, which is having a negative impact on the residents of the house. All these random happy people are also eating all your food. So, you decide to change the door entry policy, and not just let random happy people enter anymore, even if they are happy! Instead, you'd like to build a **Face verification** system so as to only let people from a specified list come in. To get admitted, each person has to swipe an ID card (identification card) to identify themselves at the door. The face recognition system then checks that they are who they claim to be. ### 3.1 - Face Verification Let's build a database containing one encoding vector for each person allowed to enter the happy house. To generate the encoding we use `img_to_encoding(image_path, model)` which basically runs the forward propagation of the model on the specified image. Run the following code to build the database (represented as a python dictionary). This database maps each person's name to a 128-dimensional encoding of their face. ``` database = {} database["danielle"] = img_to_encoding("images/danielle.png", FRmodel) database["younes"] = img_to_encoding("images/younes.jpg", FRmodel) database["tian"] = img_to_encoding("images/tian.jpg", FRmodel) database["andrew"] = img_to_encoding("images/andrew.jpg", FRmodel) database["kian"] = img_to_encoding("images/kian.jpg", FRmodel) database["dan"] = img_to_encoding("images/dan.jpg", FRmodel) database["sebastiano"] = img_to_encoding("images/sebastiano.jpg", FRmodel) database["bertrand"] = img_to_encoding("images/bertrand.jpg", FRmodel) database["kevin"] = img_to_encoding("images/kevin.jpg", FRmodel) database["felix"] = img_to_encoding("images/felix.jpg", FRmodel) database["benoit"] = img_to_encoding("images/benoit.jpg", FRmodel) database["arnaud"] = img_to_encoding("images/arnaud.jpg", FRmodel) ``` Now, when someone shows up at your front door and swipes their ID card (thus giving you their name), you can look up their encoding in the database, and use it to check if the person standing at the front door matches the name on the ID. **Exercise**: Implement the verify() function which checks if the front-door camera picture (`image_path`) is actually the person called "identity". You will have to go through the following steps: 1. Compute the encoding of the image from image_path 2. Compute the distance about this encoding and the encoding of the identity image stored in the database 3. Open the door if the distance is less than 0.7, else do not open. As presented above, you should use the L2 distance (np.linalg.norm). (Note: In this implementation, compare the L2 distance, not the square of the L2 distance, to the threshold 0.7.) ``` # GRADED FUNCTION: verify def verify(image_path, identity, database, model): """ Function that verifies if the person on the "image_path" image is "identity". Arguments: image_path -- path to an image identity -- string, name of the person you'd like to verify the identity. Has to be a resident of the Happy house. database -- python dictionary mapping names of allowed people's names (strings) to their encodings (vectors). model -- your Inception model instance in Keras Returns: dist -- distance between the image_path and the image of "identity" in the database. door_open -- True, if the door should open. False otherwise. """ ### START CODE HERE ### # Step 1: Compute the encoding for the image. Use img_to_encoding() see example above. (≈ 1 line) encoding = img_to_encoding(image_path, model) # Step 2: Compute distance with identity's image (≈ 1 line) dist = np.linalg.norm(database[identity]- encoding) # Step 3: Open the door if dist < 0.7, else don't open (≈ 3 lines) if dist < 0.7: print("It's " + str(identity) + ", welcome home!") door_open = True else: print("It's not " + str(identity) + ", please go away") door_open = False ### END CODE HERE ### return dist, door_open ``` Younes is trying to enter the Happy House and the camera takes a picture of him ("images/camera_0.jpg"). Let's run your verification algorithm on this picture: <img src="images/camera_0.jpg" style="width:100px;height:100px;"> ``` verify("images/camera_0.jpg", "younes", database, FRmodel) ``` **Expected Output**: <table> <tr> <td> **It's younes, welcome home!** </td> <td> (0.65939283, True) </td> </tr> </table> Benoit, who broke the aquarium last weekend, has been banned from the house and removed from the database. He stole Kian's ID card and came back to the house to try to present himself as Kian. The front-door camera took a picture of Benoit ("images/camera_2.jpg). Let's run the verification algorithm to check if benoit can enter. <img src="images/camera_2.jpg" style="width:100px;height:100px;"> ``` verify("images/camera_2.jpg", "kian", database, model) ``` **Expected Output**: <table> <tr> <td> **It's not kian, please go away** </td> <td> (0.86224014, False) </td> </tr> </table> ### 3.2 - Face Recognition Your face verification system is mostly working well. But since Kian got his ID card stolen, when he came back to the house that evening he couldn't get in! To reduce such shenanigans, you'd like to change your face verification system to a face recognition system. This way, no one has to carry an ID card anymore. An authorized person can just walk up to the house, and the front door will unlock for them! You'll implement a face recognition system that takes as input an image, and figures out if it is one of the authorized persons (and if so, who). Unlike the previous face verification system, we will no longer get a person's name as another input. **Exercise**: Implement `who_is_it()`. You will have to go through the following steps: 1. Compute the target encoding of the image from image_path 2. Find the encoding from the database that has smallest distance with the target encoding. - Initialize the `min_dist` variable to a large enough number (100). It will help you keep track of what is the closest encoding to the input's encoding. - Loop over the database dictionary's names and encodings. To loop use `for (name, db_enc) in database.items()`. - Compute L2 distance between the target "encoding" and the current "encoding" from the database. - If this distance is less than the min_dist, then set min_dist to dist, and identity to name. ``` # GRADED FUNCTION: who_is_it def who_is_it(image_path, database, model): """ Implements face recognition for the happy house by finding who is the person on the image_path image. Arguments: image_path -- path to an image database -- database containing image encodings along with the name of the person on the image model -- your Inception model instance in Keras Returns: min_dist -- the minimum distance between image_path encoding and the encodings from the database identity -- string, the name prediction for the person on image_path """ ### START CODE HERE ### ## Step 1: Compute the target "encoding" for the image. Use img_to_encoding() see example above. ## (≈ 1 line) encoding = img_to_encoding(image_path, model) ## Step 2: Find the closest encoding ## # Initialize "min_dist" to a large value, say 100 (≈1 line) min_dist = 100 # Loop over the database dictionary's names and encodings. for (name, db_enc) in database.items(): # Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line) dist = np.linalg.norm(db_enc - encoding) # If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines) if dist < min_dist: min_dist = dist identity = name ### END CODE HERE ### if min_dist > 0.7: print("Not in the database.") else: print ("it's " + str(identity) + ", the distance is " + str(min_dist)) return min_dist, identity ``` Younes is at the front-door and the camera takes a picture of him ("images/camera_0.jpg"). Let's see if your who_it_is() algorithm identifies Younes. ``` who_is_it("images/camera_0.jpg", database, FRmodel) ``` **Expected Output**: <table> <tr> <td> **it's younes, the distance is 0.659393** </td> <td> (0.65939283, 'younes') </td> </tr> </table> You can change "`camera_0.jpg`" (picture of younes) to "`camera_1.jpg`" (picture of bertrand) and see the result. Your Happy House is running well. It only lets in authorized persons, and people don't need to carry an ID card around anymore! You've now seen how a state-of-the-art face recognition system works. Although we won't implement it here, here're some ways to further improve the algorithm: - Put more images of each person (under different lighting conditions, taken on different days, etc.) into the database. Then given a new image, compare the new face to multiple pictures of the person. This would increae accuracy. - Crop the images to just contain the face, and less of the "border" region around the face. This preprocessing removes some of the irrelevant pixels around the face, and also makes the algorithm more robust. <font color='blue'> **What you should remember**: - Face verification solves an easier 1:1 matching problem; face recognition addresses a harder 1:K matching problem. - The triplet loss is an effective loss function for training a neural network to learn an encoding of a face image. - The same encoding can be used for verification and recognition. Measuring distances between two images' encodings allows you to determine whether they are pictures of the same person. Congrats on finishing this assignment! ### References: - Florian Schroff, Dmitry Kalenichenko, James Philbin (2015). [FaceNet: A Unified Embedding for Face Recognition and Clustering](https://arxiv.org/pdf/1503.03832.pdf) - Yaniv Taigman, Ming Yang, Marc'Aurelio Ranzato, Lior Wolf (2014). [DeepFace: Closing the gap to human-level performance in face verification](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf) - The pretrained model we use is inspired by Victor Sy Wang's implementation and was loaded using his code: https://github.com/iwantooxxoox/Keras-OpenFace. - Our implementation also took a lot of inspiration from the official FaceNet github repository: https://github.com/davidsandberg/facenet
github_jupyter
# CappingTransformer This notebook shows the functionality in the CappingTransformer class. This transformer caps numeric columns at either a maximum value or minimum value or both. <br> ``` import pandas as pd import numpy as np from sklearn.datasets import fetch_california_housing import tubular from tubular.capping import CappingTransformer tubular.__version__ ``` ## Load California housing dataset from sklearn ``` cali = fetch_california_housing() cali_df = pd.DataFrame(cali['data'], columns=cali['feature_names']) # add nulls cali_df['HouseAge'] = cali_df['HouseAge'].sample(frac=0.95, random_state=123) cali_df['Population'] = cali_df['Population'].sample(frac=0.99, random_state=123) cali_df.head() cali_df.describe() ``` ## Simple usage First we will demonstrate the case where the user has pre determined the values to cap at, and codes these directly into the transformer. ### Initialising CappingTransformer The `CappingTransformer` should be initialised by specifying either a `capping_values` dict or a `quantiles` dict, but not both. <br> These must be a `dict` where each key is a column to apply capping to and the items are lists of length 2, containing either `None` or numeric values; - in the case of `capping_values` the user directly specifies the values to cap at giving a lower and upper value here - or if `quantiles` is specified the values in each list should be the quantiles to cap at (these will be determined when running the `fit` method) - if a `None` value is present then the relevant min or max capping is not applied. <br> In the example below both min and max capping will be applied, if `0.66` was replaced with `None` then only min capping would be applied. ``` cap_1 = CappingTransformer(capping_values = {'AveOccup': [1, 5.5]}) ``` ### CappingTransformer fit In the case where the user specifies `capping_values` then there is no need to use the `fit` method. This is only required is the user specifies the `quantiles` argument when initialising the transformer. In fact if `capping_values` were specified and `fit` is called a warning will be generated. ### CappingTransformer transform Note, if the transformer is applied to non-numeric columns then an exception will be raised. ``` cali_df['AveOccup'].quantile([0, 0.2, 0.8, 1.0]) cali_df_2 = cap_1.transform(cali_df) cali_df_2['AveOccup'].quantile([0, 1.0]) ``` ## Transform with nulls Nulls are not imputed in the transform method. There are other transformers in the package to impute null values. ``` cap_2 = CappingTransformer({'HouseAge': [3, 50]}) cali_df['HouseAge'].isnull().sum() cali_df_3 = cap_2.transform(cali_df) cali_df_3['HouseAge'].isnull().sum() ``` ## Transforming multiple columns The specific capping values are applied to each column. The user has the option to set different combinations of min and max for each column. ``` cap_3 = CappingTransformer(capping_values = {'AveOccup': [None, 10], 'HouseAge': [None, 50]}) cali_df[['AveOccup', 'HouseAge']].max() cali_df_4 = cap_3.transform(cali_df) cali_df_4[['AveOccup', 'HouseAge']].max() ``` ## Capping at quantiles If the user does not want to pre specify quantiles up front but rather set them at quantiles in the data then the user can use the `quantiles` argument instead of `capping_values` when initialising the transformer. <br> This takes the same structure as `capping_values` but the user is specifying quantiles to cap at instead of the values directly. <br> The `fit` method of the transformer calculates the requested quantiles for each column. If the user also specified `weights_column` when initialising the transformer then weighted quantiles will be calculated using that column in `X`. <br> The user must run `fit` before running `transform` when using quantiles, otherwise and exception will be raised. ``` cap_4 = CappingTransformer(quantiles = {'HouseAge': [None, 0.8], 'AveRooms': [0.1, None], 'AveOccup': [0.2, 0.8]}) cap_4.fit(cali_df) cali_df[['HouseAge', 'AveRooms', 'AveOccup']].min() cali_df[['HouseAge', 'AveRooms', 'AveOccup']].max() cali_df_5 = cap_4.transform(cali_df) cali_df_5[['HouseAge', 'AveRooms', 'AveOccup']].min() cali_df_5[['HouseAge', 'AveRooms', 'AveOccup']].max() ``` ## Weighted quantiles The user can also specify the `weights_column` argument when initialising the transformer, so that `fit` will use the column in the input data `X` when calculating the quantiles. ### Equal weights First we will use an equal weight column and demonstrate we can recover the same quantiles from `cap_4` where no `weights_column` was specified. ``` cali_df['weights'] = 1 cap_5 = CappingTransformer(quantiles = {'AveOccup': [0.2, 0.8]}, weights_column = 'weights') cap_5.fit(cali_df) cap_5.capping_values['AveOccup'] == cap_4.capping_values['AveOccup'] ``` ### Non-equal weights Next we will set weights to zero for values that are beyond the `[0.2, 0.8]` quantiles identified previously, and check that the `[0, 1]` weighted quantiles identified are the min and max, where the weight is > 0. ``` cali_df['weights2'] = 1 cali_df.loc[cali_df['AveOccup'] < 2.338815789473684, 'weights2'] = 0 cali_df.loc[cali_df['AveOccup'] > 3.4242424242424243, 'weights2'] = 0 cap_6 = CappingTransformer(quantiles = {'AveOccup': [0.0, 1.0]}, weights_column = 'weights2') cap_6.fit(cali_df) cap_6.capping_values['AveOccup'] cali_df.loc[cali_df['weights2'] > 0, 'AveOccup'].min(), cali_df.loc[cali_df['weights2'] > 0, 'AveOccup'].max() ``` ### Weights columns restrictions The weights column can have 0 values in it, but it cannot have `null` values, `np.Inf`, `-np.Inf` or negative values. ``` cap_7 = CappingTransformer(quantiles = {'AveOccup': [0.1, 0.8]}, weights_column = 'Population') cali_df['Population'].fillna(0, inplace = True) cap_7.fit(cali_df) cap_7.capping_values['AveOccup'] ```
github_jupyter