markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Slice Sessions from the Dataframe
list_sessions = [] list_last_clicked = [] list_last_clicked_temp = [] current_id = df.loc[0, 'user_session'] current_index = 0 columns = ['embedding_'+str(i) for i in range(embeddings.shape[1])] columns.append('price_standardized') columns.insert(0, 'product_id') for i in range(df.shape[0]): if df.loc[i, 'user_session'] != current_id: list_sessions.append(df.loc[current_index:i-2, columns]) list_last_clicked.append(df.loc[i-1, 'product_id']) list_last_clicked_temp.append(df.loc[i-1, columns]) current_id = df.loc[i, 'user_session'] current_index = i
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Delete Sessions with Length larger than 30
print(len(list_sessions)) list_sessions_filtered = [] list_last_clicked_filtered = [] list_last_clicked_temp_filtered = [] for index, session in enumerate(list_sessions): if not (session.shape[0] > 30): if not (session['product_id'].isin(products_to_delete).any()): list_sessions_filtered.append(session) list_last_clicked_filtered.append(list_last_clicked[index]) list_last_clicked_temp_filtered.append(list_last_clicked_temp[index]) len(list_sessions_filtered)
61295
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Slice Sessions if label and last product from session is the sameExample:- From: session: [ 1506 1506 11410 11410 2826 2826], ground truth: 2826- To: session: [ 1506 1506 11410 11410], ground truth: 2826
print("Length before", len(list_sessions_filtered)) list_sessions_processed = [] list_last_clicked_processed = [] list_session_processed_autoencoder = [] for i, session in enumerate(list_sessions_filtered): if session['product_id'].values[-1] == list_last_clicked_filtered[i]: mask = session['product_id'].values == list_last_clicked_filtered[i] if session[~mask].shape[0] > 0: list_sessions_processed.append(session[~mask]) list_last_clicked_processed.append(list_last_clicked_filtered[i]) list_session_processed_autoencoder.append(pd.concat([session[~mask], pd.DataFrame(list_last_clicked_temp_filtered[i]).T], ignore_index=True)) else: list_sessions_processed.append(session) list_last_clicked_processed.append(list_last_clicked_filtered[i]) list_session_processed_autoencoder.append(pd.concat([session, pd.DataFrame(list_last_clicked_temp_filtered[i]).T], ignore_index=True)) print("Length after", len(list_sessions_processed))
Length before 44551 Length after 30941
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Create Item IDs starting from value 1 for Embeddings and One Hot Layer
mapping = pd.read_csv('../ID_Mapping.csv')[['Item_ID', 'Mapped_ID']] dict_items = mapping.set_index('Item_ID').to_dict()['Mapped_ID'] for index, session in enumerate(list_session_processed_autoencoder): session['product_id'] = session['product_id'].map(dict_items) # Pad all Sessions with 0. Embedding Layer and LSTM will use Masking to ignore zeros. list_sessions_padded = [] window_length = 31 for df in list_session_processed_autoencoder: np_array = df.values result = np.zeros((window_length, 1), dtype=np.float32) result[:np_array.shape[0],:1] = np_array[:,:1] list_sessions_padded.append(result) # Save the results, because the slicing can take some time np.save('list_sessions_padded_autoencoder.npy', list_sessions_padded) sessions_padded = np.array(list_sessions_padded) n_output_features = int(sessions_padded.max()) n_unique_input_ids = int(sessions_padded.max()) window_length = sessions_padded.shape[1] n_input_features = sessions_padded.shape[2] print("n_output_features", n_output_features) print("n_unique_input_ids", n_unique_input_ids) print("window_length", window_length) print("n_input_features", n_input_features)
n_output_features 9494 n_unique_input_ids 9494 window_length 31 n_input_features 1
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Training: Start here if the preprocessing was already executed
sessions_padded = np.load('list_sessions_padded_autoencoder.npy') print(sessions_padded.shape) n_output_features = int(sessions_padded.max()) n_unique_input_ids = int(sessions_padded.max()) window_length = sessions_padded.shape[1] n_input_features = sessions_padded.shape[2]
(30941, 31, 1)
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Grid Search HyperparameterDictionary with different hyperparameters to train on.MLflow will track those in a database.
grid_search_dic = {'hidden_layer_size': [300], 'batch_size': [32], 'embedding_dim': [200], 'window_length': [window_length], 'dropout_fc': [0.0], #0.2 'n_output_features': [n_output_features], 'n_input_features': [n_input_features]} # Cartesian product grid_search_param = [dict(zip(grid_search_dic, v)) for v in product(*grid_search_dic.values())] grid_search_param
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
LSTM Autoencoder in functional API- Input: x rows (time steps) of Item IDs in a Session- Output: reconstructed Session
def build_autoencoder(window_length=50, units_lstm_layer=100, n_unique_input_ids=0, embedding_dim=200, n_input_features=1, n_output_features=3, dropout_rate=0.1): inputs = keras.layers.Input( shape=[window_length, n_input_features], dtype=np.float32) # Encoder # Embedding Layer embedding_layer = tf.keras.layers.Embedding( n_unique_input_ids+1, embedding_dim, input_length=window_length) # , mask_zero=True) embeddings = embedding_layer(inputs[:, :, 0]) mask = inputs[:, :, 0] != 0 # LSTM Layer 1 lstm1_output, lstm1_state_h, lstm1_state_c = keras.layers.LSTM(units=units_lstm_layer, return_state=True, return_sequences=True)(embeddings, mask=mask) lstm1_state = [lstm1_state_h, lstm1_state_c] # Decoder # input: lstm1_state_c, lstm1_state_h decoder_state_c = lstm1_state_c decoder_state_h = lstm1_state_h decoder_outputs = tf.expand_dims(lstm1_state_h, 1) list_states = [] decoder_layer = keras.layers.LSTM( units=units_lstm_layer, return_state=True, return_sequences=True, unroll=False) for i in range(window_length): decoder_outputs, decoder_state_h, decoder_state_c = decoder_layer(decoder_outputs, initial_state=[decoder_state_h, decoder_state_c]) list_states.append(decoder_state_h) stacked = tf.stack(list_states, axis=1) fc_layer = tf.keras.layers.Dense( n_output_features+1, kernel_initializer='he_normal') fc_layer_output = tf.keras.layers.TimeDistributed(fc_layer)( stacked, mask=mask) mask_softmax = tf.tile(tf.expand_dims(mask, axis=2), [1, 1, n_output_features+1]) softmax = tf.keras.layers.Softmax(axis=2, dtype=tf.float32)( fc_layer_output, mask=mask_softmax) model = keras.models.Model(inputs=[inputs], outputs=[softmax]) return model
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Convert Numpy Array to tf.data.Dataset for better training performanceThe function will return a zipped tf.data.Dataset with the following Shapes:- x: (batches, window_length)- y: (batches,)
def array_to_tf_data_api(train_data_x, train_data_y, batch_size=64, window_length=50, validate=False): """Applies sliding window on the fly by using the TF Data API. Args: train_data_x: Input Data as Numpy Array, Shape (rows, n_features) batch_size: Batch Size. window_length: Window Length or Window Size. future_length: Number of time steps that will be predicted in the future. n_output_features: Number of features that will be predicted. validate: True if input data is a validation set and does not need to be shuffled shift: Shifts the Sliding Window by this Parameter. Returns: tf.data.Dataset """ X = tf.data.Dataset.from_tensor_slices(train_data_x) y = tf.data.Dataset.from_tensor_slices(train_data_y) if not validate: train_tf_data = tf.data.Dataset.zip((X, y)).cache() \ .shuffle(buffer_size=200000, reshuffle_each_iteration=True)\ .batch(batch_size).prefetch(1) return train_tf_data else: return tf.data.Dataset.zip((X, y)).batch(batch_size)\ .prefetch(1)
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Custom TF Callback to log Metrics by MLflow
class MlflowLogging(tf.keras.callbacks.Callback): def __init__(self, **kwargs): super().__init__() # handles base args (e.g., dtype) def on_epoch_end(self, epoch, logs=None): keys = list(logs.keys()) for key in keys: mlflow.log_metric(str(key), logs.get(key), step=epoch) class CustomCategoricalCrossentropy(keras.losses.Loss): def __init__(self, **kwargs): super().__init__(**kwargs) self.bce = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=False, reduction='sum') @tf.function def call(self, y_true, y_pred): total = 0.0 for i in tf.range(y_pred.shape[1]): loss = self.bce(y_true[:, i, 0], y_pred[:, i, :]) total = total + loss return total def get_config(self): base_config = super().get_config() return {**base_config} def from_config(cls, config): return cls(**config) class CategoricalAccuracy(keras.metrics.Metric): def __init__(self, name="categorical_accuracy", **kwargs): super(CategoricalAccuracy, self).__init__(name=name, **kwargs) self.true = self.add_weight(name="true", initializer="zeros") self.count = self.add_weight(name="count", initializer="zeros") self.accuracy = self.add_weight(name="count", initializer="zeros") def update_state(self, y_true, y_pred, sample_weight=None): y_true = tf.cast(y_true, "float32") y_pred = tf.cast(y_pred, "float32") mask = y_true[:, :, 0] != 0 argmax = tf.cast(tf.argmax(y_pred, axis=2), "float32") temp = argmax == y_true[:, :, 0] true = tf.reduce_sum(tf.cast(temp[mask], dtype=tf.float32)) self.true.assign_add(true) self.count.assign_add( tf.cast(tf.shape(temp[mask])[0], dtype="float32")) self.accuracy.assign(tf.math.divide(self.true, self.count)) def result(self): return self.accuracy def reset_states(self): # The state of the metric will be reset at the start of each epoch. self.accuracy.assign(0.0) class CategoricalSessionAccuracy(keras.metrics.Metric): def __init__(self, name="categorical_session_accuracy", **kwargs): super(CategoricalSessionAccuracy, self).__init__(name=name, **kwargs) self.true = self.add_weight(name="true", initializer="zeros") self.count = self.add_weight(name="count", initializer="zeros") self.accuracy = self.add_weight(name="count", initializer="zeros") def update_state(self, y_true, y_pred, sample_weight=None): y_true = tf.cast(y_true, "float32") y_pred = tf.cast(y_pred, "float32") mask = y_true[:, :, 0] != 0 argmax = tf.cast(tf.argmax(y_pred, axis=2), "float32") temp = argmax == y_true[:, :, 0] temp = tf.reduce_all(temp, axis=1) true = tf.reduce_sum(tf.cast(temp, dtype=tf.float32)) self.true.assign_add(true) self.count.assign_add(tf.cast(tf.shape(temp)[0], dtype="float32")) self.accuracy.assign(tf.math.divide(self.true, self.count)) def result(self): return self.accuracy def reset_states(self): # The state of the metric will be reset at the start of each epoch. self.accuracy.assign(0.0)
_____no_output_____
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Training
with mlflow.start_run() as parent_run: for params in grid_search_param: batch_size = params['batch_size'] window_length = params['window_length'] embedding_dim = params['embedding_dim'] dropout_fc = params['dropout_fc'] hidden_layer_size = params['hidden_layer_size'] n_output_features = params['n_output_features'] n_input_features = params['n_input_features'] with mlflow.start_run(nested=True) as child_run: # log parameter mlflow.log_param('batch_size', batch_size) mlflow.log_param('window_length', window_length) mlflow.log_param('hidden_layer_size', hidden_layer_size) mlflow.log_param('dropout_fc_layer', dropout_fc) mlflow.log_param('embedding_dim', embedding_dim) mlflow.log_param('n_output_features', n_output_features) mlflow.log_param('n_unique_input_ids', n_unique_input_ids) mlflow.log_param('n_input_features', n_input_features) model = build_autoencoder(window_length=window_length, n_output_features=n_output_features, n_unique_input_ids=n_unique_input_ids, n_input_features=n_input_features, embedding_dim=embedding_dim, units_lstm_layer=hidden_layer_size, dropout_rate=dropout_fc) data = array_to_tf_data_api(sessions_padded, sessions_padded, window_length=window_length, batch_size=batch_size) model.compile(loss=CustomCategoricalCrossentropy(),#tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False, reduction='sum'), optimizer=keras.optimizers.Nadam(learning_rate=1e-3), metrics=[CategoricalAccuracy(), CategoricalSessionAccuracy()]) model.fit(data, shuffle=True, initial_epoch=0, epochs=20, callbacks=[MlflowLogging()]) model.compile() model.save("./tmp") model.save_weights('weights') mlflow.tensorflow.log_model(tf_saved_model_dir='./tmp', tf_meta_graph_tags='serve', tf_signature_def_key='serving_default', artifact_path='saved_model', registered_model_name='Session Based LSTM Recommender') shutil.rmtree("./tmp")
Epoch 1/20 967/967 [==============================] - 95s 70ms/step - loss: 536.0073 - categorical_accuracy: 0.0037 - categorical_session_accuracy: 0.0000e+00 Epoch 2/20 967/967 [==============================] - 65s 67ms/step - loss: 189.0837 - categorical_accuracy: 0.0097 - categorical_session_accuracy: 4.4663e-05 Epoch 3/20 967/967 [==============================] - 63s 66ms/step - loss: 174.3795 - categorical_accuracy: 0.0173 - categorical_session_accuracy: 3.9590e-04 Epoch 4/20 967/967 [==============================] - 63s 66ms/step - loss: 147.5806 - categorical_accuracy: 0.0341 - categorical_session_accuracy: 0.0023 Epoch 5/20 967/967 [==============================] - 63s 65ms/step - loss: 125.2717 - categorical_accuracy: 0.0621 - categorical_session_accuracy: 0.0089 Epoch 6/20 967/967 [==============================] - 63s 65ms/step - loss: 100.3309 - categorical_accuracy: 0.0977 - categorical_session_accuracy: 0.0234 Epoch 7/20 967/967 [==============================] - 62s 64ms/step - loss: 81.0303 - categorical_accuracy: 0.1379 - categorical_session_accuracy: 0.0440 Epoch 8/20 967/967 [==============================] - 62s 64ms/step - loss: 63.7936 - categorical_accuracy: 0.1798 - categorical_session_accuracy: 0.0692 Epoch 9/20 967/967 [==============================] - 61s 63ms/step - loss: 49.6684 - categorical_accuracy: 0.2223 - categorical_session_accuracy: 0.0991 Epoch 10/20 967/967 [==============================] - 62s 64ms/step - loss: 39.3160 - categorical_accuracy: 0.2642 - categorical_session_accuracy: 0.1321 Epoch 11/20 967/967 [==============================] - 63s 65ms/step - loss: 31.9699 - categorical_accuracy: 0.3041 - categorical_session_accuracy: 0.1679 Epoch 12/20 967/967 [==============================] - 62s 64ms/step - loss: 25.9715 - categorical_accuracy: 0.3419 - categorical_session_accuracy: 0.2051 Epoch 13/20 967/967 [==============================] - 63s 65ms/step - loss: 21.5118 - categorical_accuracy: 0.3767 - categorical_session_accuracy: 0.2418 Epoch 14/20 967/967 [==============================] - 63s 65ms/step - loss: 19.3681 - categorical_accuracy: 0.4084 - categorical_session_accuracy: 0.2759 Epoch 15/20 967/967 [==============================] - 60s 62ms/step - loss: 17.5992 - categorical_accuracy: 0.4371 - categorical_session_accuracy: 0.3075 Epoch 16/20 967/967 [==============================] - 59s 61ms/step - loss: 15.1798 - categorical_accuracy: 0.4632 - categorical_session_accuracy: 0.3369 Epoch 17/20 967/967 [==============================] - 59s 61ms/step - loss: 13.3361 - categorical_accuracy: 0.4872 - categorical_session_accuracy: 0.3641 Epoch 18/20 967/967 [==============================] - 59s 61ms/step - loss: 12.9639 - categorical_accuracy: 0.5090 - categorical_session_accuracy: 0.3889 Epoch 19/20 967/967 [==============================] - 59s 61ms/step - loss: 11.2216 - categorical_accuracy: 0.5290 - categorical_session_accuracy: 0.4118 Epoch 20/20 967/967 [==============================] - 59s 61ms/step - loss: 10.1313 - categorical_accuracy: 0.5476 - categorical_session_accuracy: 0.4333
MIT
outlier_detection/training_outlier_detection.ipynb
felix-exel/kfserving-advanced
Linear regression on Boston house prices
from keras import models from keras import layers import numpy as np import matplotlib.pyplot as plt # Download the data from keras.datasets import boston_housing (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() # Look at the dataset print train_data.shape # 404 samples, 13 features print train_targets.shape # 404 targets print test_data.shape # 102 samples, 13 features print test_targets.shape # 102 targets print train_data[10] # Each datapoint is an array with 13 entries (features) print train_targets[10] # Each target is the price of the house (in k$) # Perform feature wise normalization on the data mean = train_data.mean(axis=0) std = train_data.std(axis=0) train_data = train_data - mean train_data = train_data / std test_data = test_data - mean test_data = test_data / std print train_data[10] def build_model(): model = models.Sequential() model.add(layers.Dense(64, activation='relu',input_shape=(train_data.shape[1],))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) model.compile(optimizer='rmsprop', loss='mse', metrics=['mae']) return model # Use k-fold validation because the dataset is small k=4 num_val_samples = len(train_data) // k num_epochs = 100 all_scores = [] for i in range(k): print('processing fold #', i) val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples] val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples] partial_train_data = np.concatenate( [train_data[:i * num_val_samples],train_data[(i + 1) * num_val_samples:]], axis=0) partial_train_targets = np.concatenate( [train_targets[:i * num_val_samples],train_targets[(i + 1) * num_val_samples:]], axis=0) model = build_model() model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=1, verbose=0) history = model.history() val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0) all_scores.append(val_mae) print all_scores # Train the final model model = build_model() model.fit(train_data, train_targets,epochs=80, batch_size=8, verbose=0) test_mse_score, test_mae_score = model.evaluate(test_data, test_targets) print test_mae_score
2.8874634387446383
MIT
06_Linear_Regression_Boston_House_Prices.ipynb
alzaia/keras_projects
**Data crunch example R script**---author: sweet-richarddate: Jan 30, 2022required packages:* `tidyverse` for data handling* `feather` for efficient loading of data* `xgboost` for predictive modelling* `httr` for the automatic upload.
library(tidyverse) library(feather)
_____no_output_____
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
First, we set some **parameters**.* `is_download` controls whether you want to download data or just read prevously downloaded data* `is_upload` set this to TRUE for automatic upload.* `nrounds` is a parameter for `xgboost` that we set to 100 for illustration. You might want to adjust the paramters of xgboost.
#' ## Parameters file_name_train = "train_data.feather" file_name_test ="test_data.feather" is_download = TRUE # set this to true to download new data or to FALSE to load data in feather format is_upload = FALSE # set this to true to upload a submission nrounds = 300 # you might want to adjust this one and other parameters of xgboost
_____no_output_____
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
In the **functions** section we defined the correlation measure that we use to measure performance.
#' ## Functions #+ getCorrMeasure = function(actual, predicted) { cor_measure = cor(actual, predicted, method="spearman") return(cor_measure) }
_____no_output_____
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
Now, we either **download** the current data from the servers or load them in feather format. Furthermore, we define the features that we actually want to use. In this illustration we use all of them but `id` and `Moons`.
#' ## Download data #' after the download, data is stored in feather format to be read on demand quickly. Data is stored in integer format to save memory. #+ if( is_download ) { cat("\n start download") train_datalink_X = 'https://tournament.datacrunch.com/data/X_train.csv' train_datalink_y = 'https://tournament.datacrunch.com/data/y_train.csv' hackathon_data_link = 'https://tournament.datacrunch.com/data/X_test.csv' train_dataX = read_csv(url(train_datalink_X)) train_dataY = read_csv(url(train_datalink_y)) test_data = read_csv(url(hackathon_data_link)) train_data = bind_cols( train_dataX, train_dataY) train_data = train_data %>% mutate_at(vars(starts_with("feature_")), list(~as.integer(.*100))) feather::write_feather(train_data, path = paste0("./", file_name_train)) test_data = test_data %>% mutate_at(vars(starts_with("feature_")), list(~as.integer(.*100))) feather::write_feather(test_data, path = paste0("./", file_name_test)) names(train_data) nrow(train_data) nrow(test_data) cat("\n data is downloaded") } else { train_data = feather::read_feather(path = paste0("./", file_name_train)) test_data = feather::read_feather(path = paste0("./", file_name_test)) } ## set vars used for modelling model_vars = setdiff(names(test_data), c("id","Moons"))
start download
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
Next we fit our go-to algorithm **xgboost** with mainly default parameters, only `eta` and `max_depth` are set.
#' ## Fit xgboost #+ cache = TRUE library(xgboost, warn.conflicts = FALSE) # custom loss function for eval corrmeasure <- function(preds, dtrain) { labels <- getinfo(dtrain, "label") corrm <- as.numeric(cor(labels, preds, method="spearman")) return(list(metric = "corr", value = corrm)) } eval_metric_string = "rmse" my_objective = "reg:squarederror" tree.params = list( booster = "gbtree", eta = 0.01, max_depth = 5, tree_method = "hist", # tree_method = "auto", objective = my_objective) cat("\n starting xgboost \n")
starting xgboost
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
**First target** `target_r`
# first target target_r then g and b ################ current_target = "target_r" dtrain = xgb.DMatrix(train_data %>% select(one_of(model_vars)) %>% as.matrix(), label = train_data %>% select(one_of(current_target)) %>% as.matrix()) xgb.model.tree = xgb.train(data = dtrain, params = tree.params, nrounds = nrounds, verbose = 1, print_every_n = 50L, eval_metric = corrmeasure) xgboost_tree_train_pred1 = predict(xgb.model.tree, train_data %>% select(one_of(model_vars)) %>% as.matrix()) xgboost_tree_live_pred1 = predict(xgb.model.tree, test_data %>% select(one_of(model_vars)) %>% as.matrix()) cor_train = getCorrMeasure(train_data %>% select(one_of(current_target)), xgboost_tree_train_pred1) cat("\n : metric: ", eval_metric_string, "\n") print(paste0("Corrm on train: ", round(cor_train,4))) print(paste("xgboost", current_target, "ready"))
: metric: rmse [1] "Corrm on train: 0.0867" [1] "xgboost target_r ready"
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
**Second target** `target_g`
# second target target_g ################ current_target = "target_g" dtrain = xgb.DMatrix(train_data %>% select(one_of(model_vars)) %>% as.matrix(), label = train_data %>% select(one_of(current_target)) %>% as.matrix()) xgb.model.tree = xgb.train(data = dtrain, params = tree.params, nrounds = nrounds, verbose = 1, print_every_n = 50L, eval_metric = corrmeasure) xgboost_tree_train_pred2 = predict(xgb.model.tree, train_data %>% select(one_of(model_vars)) %>% as.matrix()) xgboost_tree_live_pred2 = predict(xgb.model.tree, test_data %>% select(one_of(model_vars)) %>% as.matrix()) cor_train = getCorrMeasure(train_data %>% select(one_of(current_target)), xgboost_tree_train_pred2) cat("\n : metric: ", eval_metric_string, "\n") print(paste0("Corrm on train: ", round(cor_train,4))) print(paste("xgboost", current_target, "ready"))
: metric: rmse [1] "Corrm on train: 0.1099" [1] "xgboost target_g ready"
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
**Third target** `target_b`
# third target target_b ################ current_target = "target_b" dtrain = xgb.DMatrix(train_data %>% select(one_of(model_vars)) %>% as.matrix(), label = train_data %>% select(one_of(current_target)) %>% as.matrix()) xgb.model.tree = xgb.train(data = dtrain, params = tree.params, nrounds = nrounds, verbose = 1, print_every_n = 50L, eval_metric = corrmeasure) xgboost_tree_train_pred3 = predict(xgb.model.tree, train_data %>% select(one_of(model_vars)) %>% as.matrix()) xgboost_tree_live_pred3 = predict(xgb.model.tree, test_data %>% select(one_of(model_vars)) %>% as.matrix()) cor_train = getCorrMeasure(train_data %>% select(one_of(current_target)), xgboost_tree_train_pred3) cat("\n : metric: ", eval_metric_string, "\n") print(paste0("Corrm on train: ", round(cor_train,4))) print(paste("xgboost", current_target, "ready"))
: metric: rmse [1] "Corrm on train: 0.1232" [1] "xgboost target_b ready"
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
Then we produce simply histogram plots to see whether the predictions are plausible and prepare a **submission file**:
#' ## Submission #' simple histograms to check the submissions #+ hist(xgboost_tree_live_pred1) hist(xgboost_tree_live_pred2) hist(xgboost_tree_live_pred3) #' create submission file #+ sub_df = tibble(target_r = xgboost_tree_live_pred1, target_g = xgboost_tree_live_pred2, target_b = xgboost_tree_live_pred3) file_name_submission = paste0("gbTree_", gsub("-","",Sys.Date()), ".csv") sub_df %>% readr::write_csv(file = paste0("./", file_name_submission)) nrow(sub_df) cat("\n submission file written")
_____no_output_____
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
Finally, we can **automatically upload** the file to the server:
#' ## Upload submission #+ if( is_upload ) { library(httr) API_KEY = "YourKeyHere" response <- POST( url = "https://tournament.crunchdao.com/api/v2/submissions", query = list(apiKey = API_KEY), body = list( file = upload_file(path = paste0("./", file_name_submission)) ), encode = c("multipart") ); status <- status_code(response) if (status == 200) { print("Submission submitted :)") } else if (status == 400) { print("ERR: The file must not be empty") print("You have send a empty file.") } else if (status == 401) { print("ERR: Your email hasn't been verified") print("Please verify your email or contact a cruncher.") } else if (status == 403) { print("ERR: Not authentified") print("Is the API Key valid?") } else if (status == 404) { print("ERR: Unknown API Key") print("You should check that the provided API key is valid and is the same as the one you've received by email.") } else if (status == 409) { print("ERR: Duplicate submission") print("Your work has already been submitted with the same exact results, if you think that this a false positive, contact a cruncher.") print("MD5 collision probability: 1/2^128 (source: https://stackoverflow.com/a/288519/7292958)") } else if (status == 422) { print("ERR: API Key is missing or empty") print("Did you forget to fill the API_KEY variable?") } else if (status == 423) { print("ERR: Submissions are close") print("You can only submit during rounds eg: Friday 7pm GMT+1 to Sunday midnight GMT+1.") print("Or the server is currently crunching the submitted files, please wait some time before retrying.") } else if (status == 423) { print("ERR: Too many submissions") } else { content <- httr::content(response) print("ERR: Server returned: " + toString(status)) print("Ouch! It seems that we were not expecting this kind of result from the server, if the probleme persist, contact a cruncher.") print(paste("Message:", content$message, sep=" ")) } # DEVELOPER WARNING: # THE API ERROR CODE WILL BE HANDLER DIFFERENTLY IN A NEAR FUTURE! # PLEASE STAY UPDATED BY JOINING THE DISCORD (https://discord.gg/veAtzsYn3M) AND READING THE NEWSLETTER EMAIL }
_____no_output_____
MIT
dcrunch_R_example.ipynb
rwarnung/datacrunch-notebooks
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.The magic command `%%capture` can be used to hide output from a specific cell. Uncomment these lines if you are running this notebook for the first time.
# %%capture # !pip install earthengine-api # !pip install geehydro
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Import libraries
import ee import folium import geehydro
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for the first time or if you are getting an authentication error.
# ee.Authenticate() ee.Initialize()
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID')
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Add Earth Engine Python script
dataset = ee.Image('CSP/ERGo/1_0/Global/SRTM_mTPI') srtmMtpi = dataset.select('elevation') srtmMtpiVis = { 'min': -200.0, 'max': 200.0, 'palette': ['0b1eff', '4be450', 'fffca4', 'ffa011', 'ff0000'], } Map.setCenter(-105.8636, 40.3439, 11) Map.addLayer(srtmMtpi, srtmMtpiVis, 'SRTM mTPI')
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Display Earth Engine data layers
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
_____no_output_____
MIT
Datasets/Terrain/srtm_mtpi.ipynb
dmendelo/earthengine-py-notebooks
Introduction to Data ScienceSee [Lesson 1](https://www.udacity.com/course/intro-to-data-analysis--ud170)You should run it in local Jupyter env as this notebook refers to local dataset
import unicodecsv from datetime import datetime as dt enrollments_filename = 'dataset/enrollments.csv' engagement_filename = 'dataset/daily_engagement.csv' submissions_filename = 'dataset/project_submissions.csv' ## Longer version of code (replaced with shorter, equivalent version below) def read_csv(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) return list(reader) enrollments = read_csv(enrollments_filename) daily_engagement = read_csv(engagement_filename) project_submissions = read_csv(submissions_filename) def renameKey(data, fromKey, toKey): for rec in data: if fromKey in rec: rec[toKey] = rec[fromKey] del rec[fromKey] renameKey(daily_engagement, 'acct', 'account_key') def cleanDataTypes(): def fixIntFloat(data, field): if field not in data: print(f'WARNING : Field {field} is not in {data}') value = data[field] if value == '': data[field] = None else: data[field] = int(float(value)) def fixFloat(data, field): if field not in data: print(f'WARNING : Field {field} is not in {data}') value = data[field] if value == '': data[field] = None else: data[field] = float(value) def fixDate(data, field): if field not in data: print(f'WARNING : Field {field} is not in {data}') value = data[field] if value == '': data[field] = None else: data[field] = dt.strptime(value, '%Y-%m-%d') def fixBool(data, field): if field not in data: print(f'WARNING : Field {field} is not in {data}') value = data[field] if value == 'True': data[field] = True elif value == 'False': data[field] = False else: print(f"WARNING: invalid boolean '{value}' value converted to False in {data}") data[field] = False def fixInt(data, field): if field not in data: print(f'WARNING : Field {field} is not in {data}') value = data[field] if value == '': data[field] = None else: data[field] = int(value) #clean data types for rec in enrollments: fixInt(rec, 'days_to_cancel') fixDate(rec, 'join_date') fixDate(rec, 'cancel_date') fixBool(rec, 'is_udacity') fixBool(rec, 'is_canceled') for rec in daily_engagement: fixDate(rec, 'utc_date') fixIntFloat(rec, 'num_courses_visited') fixFloat(rec, 'total_minutes_visited') fixIntFloat(rec, 'lessons_completed') fixIntFloat(rec, 'projects_completed') for rec in project_submissions: fixDate(rec, 'creation_date') fixDate(rec, 'completion_date') cleanDataTypes() print(f"enrollments[0] = {enrollments[0]}\n") print(f"daily_engagement[0] = {daily_engagement[0]}\n") print(f"project_submissions[0] = {project_submissions[0]}\n") from collections import defaultdict def getUniqueAccounts(data): accts = defaultdict(list) i = 0 for record in data: accountKey = record['account_key'] accts[accountKey].append(i) i+=1 return accts enrollment_num_rows = len(enrollments) enrollment_unique_students = getUniqueAccounts(enrollments) enrollment_num_unique_students = len(enrollment_unique_students) engagement_num_rows = len(daily_engagement) engagement_unique_students = getUniqueAccounts(daily_engagement) engagement_num_unique_students = len(engagement_unique_students) submission_num_rows = len(project_submissions) submission_unique_students = getUniqueAccounts(project_submissions) submission_num_unique_students = len(submission_unique_students) print(f"enrollments total={enrollment_num_rows}, unique={enrollment_num_unique_students}") print(f"engagements total={engagement_num_rows}, unique={engagement_num_unique_students}") print(f"submissions total={submission_num_rows} unique={submission_num_unique_students}") for enrollment_acct in enrollment_unique_students: if enrollment_acct not in engagement_unique_students: #print(enrollment_unique_students[enrollment]) enrollment_id = enrollment_unique_students[enrollment_acct][0] enrollment = enrollments[enrollment_id] print(f"Strange student : enrollment={enrollment}") break strange_enrollments_num_by_different_date = 0 for enrollment_acct in enrollment_unique_students: if enrollment_acct not in engagement_unique_students: for enrollment_id in enrollment_unique_students[enrollment_acct]: enrollment = enrollments[enrollment_id] if enrollment['join_date'] != enrollment['cancel_date']: strange_enrollments_num_by_different_date += 1 #print(f"Strange student with different dates : enrollments[{enrollment_id}]={enrollment}\n") print(f"Number of enrolled and cancelled at different dates but not engaged (problemactic accounts) : {strange_enrollments_num_by_different_date}\n") num_problems = 0 for enrollment in enrollments: student = enrollment['account_key'] if student not in engagement_unique_students and enrollment['join_date'] != enrollment['cancel_date']: num_problems += 1 #print(enrollment) print(f'Number of problematic account records : {num_problems}') def getRealAccounts(enrollmentData): result = [] for rec in enrollmentData: if not rec['is_udacity']: result.append(rec) return result real_enrollments = getRealAccounts(enrollments) print(f'Real account : {len(real_enrollments)}') def getPaidStudents(enrollmentData): freePeriodDays = 7 result = {} #result1 = {} for rec in enrollmentData: if rec['cancel_date'] == None or rec['days_to_cancel'] > freePeriodDays: accountKey = rec['account_key'] joinDate = rec['join_date'] if accountKey not in result or joinDate > result[accountKey]: result[accountKey] = joinDate #result1[accountKey] = joinDate ''' for accountKey, joinDate in result.items(): joinDate1 = result1[accountKey] if joinDate != joinDate1: print(f"{accountKey} : {joinDate} != {joinDate1}") ''' return result paid_students = getPaidStudents(real_enrollments) print(f'Paid students : {len(paid_students)}') def isEngagementWithingOneWeek(joinDate, engagementDate): #if joinDate > engagementDate: # print(f'WARNING: join date is after engagement date') timeDelta = engagementDate - joinDate return 0 <= timeDelta.days and timeDelta.days < 7 def collectPaidEnagagementsInTheFirstWeek(): result = [] i = 0 for engagement in daily_engagement: accountKey = engagement['account_key'] if accountKey in paid_students: joinDate = paid_students[accountKey] engagementDate = engagement['utc_date'] if isEngagementWithingOneWeek(joinDate, engagementDate): result.append(i) i+=1 return result paid_engagement_in_first_week = collectPaidEnagagementsInTheFirstWeek() print(f'Number of paid engagements in the first week : {len(paid_engagement_in_first_week)}') from collections import defaultdict import numpy as np def groupEngagementsByAccounts(engagements): result = defaultdict(list) for engagementId in engagements: engagement = daily_engagement[engagementId] accountKey = engagement['account_key'] result[accountKey].append(engagementId) return result first_week_paid_engagements_by_account = groupEngagementsByAccounts(paid_engagement_in_first_week) def sumEngagementsStatByAccount(engagements, getStatValue): result = {} for accountKey, engagementIds in engagements.items(): stat_sum = 0 for engagementId in engagementIds: engagement = daily_engagement[engagementId] stat_sum += getStatValue(engagement) result[accountKey] = stat_sum return result def printStats(getStatValue, statLabel): first_week_paid_engagements_sum_stat_by_account = sumEngagementsStatByAccount(first_week_paid_engagements_by_account, getStatValue) first_week_paid_engagements_sum_stat = list(first_week_paid_engagements_sum_stat_by_account.values()) print(f'Average {statLabel} spent by paid accounts during the first week : {np.mean(first_week_paid_engagements_sum_stat)}') print(f'StdDev {statLabel} spent by paid accounts during the first week : {np.std(first_week_paid_engagements_sum_stat)}') print(f'Min {statLabel} spent by paid accounts during the first week : {np.min(first_week_paid_engagements_sum_stat)}') print(f'Max {statLabel} spent by paid accounts during the first week : {np.max(first_week_paid_engagements_sum_stat)}') print('\n') printStats((lambda data : data['total_minutes_visited']), 'minutes') printStats((lambda data : data['lessons_completed']), 'lessons') printStats((lambda data : 1 if data['num_courses_visited'] > 0 else 0), 'days') ###################################### # 11 # ###################################### ## Create two lists of engagement data for paid students in the first week. ## The first list should contain data for students who eventually pass the ## subway project, and the second list should contain data for students ## who do not. subway_project_lesson_keys = {'746169184', '3176718735'} passing_grades = {'DISTINCTION', 'PASSED'} #{'', 'INCOMPLETE', 'DISTINCTION', 'PASSED', 'UNGRADED'} #passing_grades = {'PASSED'} #{'', 'INCOMPLETE', 'DISTINCTION', 'PASSED', 'UNGRADED'} passing_engagement = [] non_passing_engagement = [] for accountKey, engagementIds in first_week_paid_engagements_by_account.items(): if accountKey in submission_unique_students: submissionIds = submission_unique_students[accountKey] isPassed = False for submissionId in submissionIds: submission = project_submissions[submissionId] if submission['assigned_rating'] in passing_grades and submission['lesson_key'] in subway_project_lesson_keys: isPassed = True break if isPassed: passing_engagement += engagementIds else: non_passing_engagement += engagementIds else: non_passing_engagement += engagementIds print(f'First week engagements with passing grade : {len(passing_engagement)}') print(f'First week engagements with non-passing grade : {len(non_passing_engagement)}') ###################################### # 12 # ###################################### ## Compute some metrics you're interested in and see how they differ for ## students who pass the subway project vs. students who don't. A good ## starting point would be the metrics we looked at earlier (minutes spent ## in the classroom, lessons completed, and days visited). passing_engagement_by_account = groupEngagementsByAccounts(passing_engagement) non_passing_engagement_by_account = groupEngagementsByAccounts(non_passing_engagement) def getArgStatEngagements(engagementIds, getStatValue): stat_sum = 0 stat_num = 0 for engagementId in engagementIds: engagement = daily_engagement[engagementId] stat_sum += getStatValue(engagement) stat_num += 1 if stat_num > 0: return stat_sum / stat_num else: return 0 #sumEngagementsStatByAccount(first_week_paid_engagements_by_account, getStatValue) passed_minutes = list(sumEngagementsStatByAccount(passing_engagement_by_account, (lambda data : data['total_minutes_visited'])).values()) non_passed_minutes = list(sumEngagementsStatByAccount(non_passing_engagement_by_account, (lambda data : data['total_minutes_visited'])).values()) passed_lessons = list(sumEngagementsStatByAccount(passing_engagement_by_account, (lambda data : data['lessons_completed'])).values()) non_passed_lessons = list(sumEngagementsStatByAccount(non_passing_engagement_by_account, (lambda data : data['lessons_completed'])).values()) passed_days = list(sumEngagementsStatByAccount(passing_engagement_by_account, (lambda data : 1 if data['num_courses_visited'] > 0 else 0)).values()) non_passed_days = list(sumEngagementsStatByAccount(non_passing_engagement_by_account, (lambda data : 1 if data['num_courses_visited'] > 0 else 0)).values()) print(f'Passed Avg Minutes = {np.mean(passed_minutes)}') print(f'Non passed Avg Minutes = {np.mean(non_passed_minutes)}') print(f'Passed Avg Lessons = {np.mean(passed_lessons)}') print(f'Non passed Avg Lessons = {np.mean(non_passed_lessons)}') print(f'Passed Avg Days = {np.mean(passed_days)}') print(f'Non passed Avg Days = {np.mean(non_passed_days)}') ###################################### # 13 # ###################################### ## Make histograms of the three metrics we looked at earlier for both ## students who passed the subway project and students who didn't. You ## might also want to make histograms of any other metrics you examined. %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns plt.hist(passed_minutes, color ='green') plt.hist(non_passed_minutes, color ='lightblue') plt.xlabel('Number of minutes') plt.title('Passed (green) VS Non-passed (light-blue) students') #sns.displot(passed_minutes, color ='green') #sns.displot(non_passed_minutes, color ='lightblue') plt.hist(passed_lessons, color ='green') plt.hist(non_passed_lessons, color ='lightblue') plt.xlabel('Number of lessons') plt.title('Passed (green) VS Non-passed (light-blue) students') plt.hist(passed_days, color ='green', bins = 8) plt.xlabel('Number of days') plt.title('Passed students') plt.hist(non_passed_days, color ='lightblue', bins = 8) plt.xlabel('Number of days') plt.title('Non-passed students')
_____no_output_____
MIT
learning/ud170/lesson-1.ipynb
WL152/project-omega
#@title Students Grade in OOP Student_Name1= "Enter the student name"#@param{type: "string"} prelim= 90#@param{type: "number"} midterm= 95#@param{type: "number"} final= 100#@param{type: "number"} semestral_grade=(prelim+midterm+final)/3 print("The prelim grade of student 1 is"+" "+ str(prelim)) print("The midterm grade of student 1 is"+" "+ str(midterm)) print("The final grade of student 1 is"+" "+ str(final)) print("The semestral grade of student1 is " + str(semestral_grade)) #@title Gender Gender="Female" #@param["Male", "Female"] print(Gender) Birthdate= '2003-02-12' #@param{type: "date"}
The prelim grade of student 1 is 90 The midterm grade of student 1 is 95 The final grade of student 1 is 100 The semestral grade of student1 is 95.0 Female
Apache-2.0
GUI_Application.ipynb
SarahRebulado/OOP1_2
This notebook contains code for model comparison. Optimal hyperparameters for models are supposed to be already found. Imports
#imports !pip install scipydirect import math import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn import preprocessing from sklearn.preprocessing import normalize from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import NearestNeighbors from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import precision_recall_curve from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score from sklearn.metrics import average_precision_score from sklearn.metrics import confusion_matrix from sklearn.metrics import balanced_accuracy_score import collections from collections import Counter from imblearn.over_sampling import SMOTE %matplotlib inline import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from IPython import display from scipydirect import minimize # for DIvided RECTangles (DIRECT) method import time
Collecting scipydirect [?25l Downloading https://files.pythonhosted.org/packages/c2/dd/657e6c53838b3ff50e50bda4e905c8ec7e4b715f966f33d0566088391d75/scipydirect-1.3.tar.gz (49kB)  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‹ | 10kB 15.9MB/s eta 0:00:01  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ– | 20kB 21.2MB/s eta 0:00:01  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–Š | 30kB 24.8MB/s eta 0:00:01  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ– | 40kB 24.2MB/s eta 0:00:01  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 51kB 4.7MB/s [?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from scipydirect) (1.19.5) Building wheels for collected packages: scipydirect Building wheel for scipydirect (setup.py) ... [?25l[?25hdone Created wheel for scipydirect: filename=scipydirect-1.3-cp37-cp37m-linux_x86_64.whl size=119893 sha256=201aad9d5036ecc1328b332fbd9c6adc620fa9b0d03010fc0ccea07c5bea8a47 Stored in directory: /root/.cache/pip/wheels/b7/de/2b/c5550296e6dac87737c622568c6a10bc87ae76e98b52ff210e Successfully built scipydirect Installing collected packages: scipydirect Successfully installed scipydirect-1.3
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
1) Describe classes of the following models: AdaFair, SMOTEBoost, ASR 1.1) AdaFair
#AdaFair class AdaFairClassifier(AdaBoostClassifier): def __init__(self, base_estimator=None, *, n_estimators=50, learning_rate=1, algorithm='SAMME', random_state=42, protected=None, epsilon = 0): super().__init__( base_estimator=base_estimator, n_estimators=n_estimators, algorithm = algorithm, learning_rate=learning_rate, random_state=random_state) self.protected = np.array(protected) self.algorithm = algorithm self.epsilon = epsilon def _boost_discrete(self, iboost, X, y, sample_weight, random_state): """Implement a single boost using the SAMME discrete algorithm.""" estimator = self._make_estimator(random_state=random_state) estimator.fit(X, y, sample_weight=sample_weight) y_predict = estimator.predict(X) if iboost == 0: self.classes_ = getattr(estimator, 'classes_', None) self.n_classes_ = len(self.classes_) # Instances incorrectly classified incorrect = y_predict != y # Error fraction estimator_error = np.mean( np.average(incorrect, weights=sample_weight, axis=0)) # Stop if classification is perfect if estimator_error <= 0: return sample_weight, 1., 0. n_classes = self.n_classes_ # Stop if the error is at least as bad as random guessing if estimator_error >= 1. - (1. / n_classes): self.estimators_.pop(-1) if len(self.estimators_) == 0: print ("BaseClassifier in AdaBoostClassifier ensemble is worse than random, ensemble can not be fit.") raise ValueError('BaseClassifier in AdaBoostClassifier ' 'ensemble is worse than random, ensemble ' 'can not be fit.') return None, None, None if len(self.protected) != len(y): print ("Error: not given or given incorrect list of protected objects") return None, None, None #Compute fairness-related costs #CUMULATIVE prediction y_cumulative_pred = list(self.staged_predict(X))[0] u = np.array(self.get_fairness_related_costs(y, y_cumulative_pred, self.protected)) # Boost weight using multi-class AdaBoost SAMME alg estimator_weight = self.learning_rate * ( np.log((1. - estimator_error) / estimator_error) + np.log(n_classes - 1.)) # Only boost the weights if I will fit again if not iboost == self.n_estimators - 1: # Only boost positive weights sample_weight = sample_weight * np.exp(estimator_weight * incorrect * (sample_weight > 0)) * (np.ones(len(u)) + u) return sample_weight, estimator_weight, estimator_error def get_fairness_related_costs(self, y, y_pred_t, protected): y_true_protected, y_pred_protected, y_true_non_protected, y_pred_non_protected = separate_protected_from_non_protected(y, y_pred_t, protected) #Rates for non protected group tp, tn, fp, fn = tp_tn_fp_fn(y_true_non_protected, y_pred_non_protected) FPR_non_protected = fp / (fp + tn) FNR_non_protected = fn / (fn + tp) #Rates for protected group tp, tn, fp, fn = tp_tn_fp_fn(y_true_protected, y_pred_protected) FPR_protected = fp / (fp + tn) FNR_protected = fn / (fn + tp) delta_FPR = - FPR_non_protected + FPR_protected delta_FNR = - FNR_non_protected + FNR_protected self.delta_FPR = delta_FPR self.delta_FNR = delta_FNR #Compute fairness related costs u = [] for y_i, y_pred_t__i, protection in zip(y, y_pred_t, protected): if y_i == 1 and y_pred_t__i == 0 and abs(delta_FNR) > self.epsilon and protection == 1 and delta_FNR > 0: u.append(abs(delta_FNR)) elif y_i == 1 and y_pred_t__i == 0 and abs(delta_FNR) > self.epsilon and protection == 0 and delta_FNR < 0: u.append(abs(delta_FNR)) elif y_i == 0 and y_pred_t__i == 1 and abs(delta_FPR) > self.epsilon and protection == 1 and delta_FPR > 0: u.append(abs(delta_FPR)) elif y_i == 0 and y_pred_t__i == 1 and abs(delta_FPR) > self.epsilon and protection == 0 and delta_FPR < 0: u.append(abs(delta_FPR)) else: u.append(0) return u
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
1.2 SMOTEBoost
#SMOTEBoost random_state = 42 #4, y - true label def ada_boost_eps(y, y_pred_t, distribution): eps = np.sum((1 - (y == y_pred_t) + (np.logical_not(y) == y_pred_t)) * distribution) return eps #5 def ada_boost_betta(eps): betta = eps/(1 - eps) return betta def ada_boost_w(y, y_pred_t): w = 0.5 * (1 + (y == y_pred_t) - (np.logical_not(y) == y_pred_t)) return w #6 def ada_boost_distribution(distribution, betta, w): distribution = distribution * betta ** w / np.sum(distribution) return distribution def min_target(y): minority_target = min(Counter(y), key=Counter(y).get) return minority_target class SMOTEBoost(): def __init__(self, n_samples = 100, k_neighbors = 5, n_estimators = 50, #n_estimators = T base_classifier = None, random_state = 42, get_eps = ada_boost_eps, get_betta = ada_boost_betta, get_w = ada_boost_w, update_distribution=ada_boost_distribution): self.n_samples = n_samples self.k_neighbors = k_neighbors self.n_estimators = n_estimators self.base_classifier = base_classifier self.random_state = random_state self.get_eps = get_eps self.get_betta = get_betta self.get_w = get_w self.update_distribution = update_distribution def fit(self, X, y): X = np.array(X) distribution = np.ones(X.shape[0], dtype=float) / X.shape[0] self.classifiers = [] self.betta = [] y = np.array(y) for i in range(self.n_estimators): minority_class = min_target(y) X_min = X[np.where(y == minority_class)] # create a new classifier self.classifiers.append(self.base_classifier()) # SMOTE self.smote = SMOTE(n_samples=self.n_samples, k_neighbors=self.k_neighbors, random_state=self.random_state) self.smote.fit(X_min) X_syn = self.smote.sample() y_syn = np.full(X_syn.shape[0], fill_value=minority_class, dtype=np.int64) # Modify distribution distribution_syn = np.empty(X_syn.shape[0], dtype=np.float64) distribution_syn[:] = 1. / X.shape[0] mod_distribution = np.append(distribution, distribution_syn).reshape(1, -1) mod_distribution = np.squeeze(normalize(mod_distribution, axis=1, norm='l1')) # Concatenate original and synthetic datasets for training a weak learner mod_X = np.vstack((X, X_syn)) mod_y = np.append(y, y_syn) # Train a weak lerner self.classifiers[-1].fit(mod_X, mod_y, sample_weight=mod_distribution) # Make a prediction for the original dataset y_pred_t = self.classifiers[-1].predict(X) # Compute the pseudo-loss of hypothesis eps_t = ada_boost_eps(y, y_pred_t, distribution) betta_t = ada_boost_betta(eps_t) w_t = ada_boost_w(y, y_pred_t) self.betta.append(betta_t) # Update distribution and normalize distribution = ada_boost_distribution(distribution, betta_t, w_t) def predict(self, X): final_predictions_0 = np.zeros(X.shape[0]) final_predictions_1 = np.zeros(X.shape[0]) y_pred = np.empty(X.shape[0]) # get the weighted votes of the classifiers for i in range(len(self.betta)): h_i = self.classifiers[i].predict(X) final_predictions_0 = final_predictions_0 + math.log(1/self.betta[i])*(h_i == 0) final_predictions_1 = final_predictions_1 + math.log(1/self.betta[i])*(h_i == 1) for i in range(len(final_predictions_0)): if final_predictions_0[i] > final_predictions_1[i]: y_pred[i] = 0 else: y_pred[i] = 1 return y_pred class SMOTE(): def __init__(self, n_samples, k_neighbors=5, random_state=None): self.n_samples = n_samples self.k = k_neighbors self.random_state = random_state def fit(self, X): self.X = X self.n_features = self.X.shape[1] self.neigh = NearestNeighbors(n_neighbors=self.k) #k + 1 self.neigh.fit(self.X) return self def sample(self): np.random.seed(seed=self.random_state) S = np.zeros(shape=(self.n_samples, self.n_features)) for i in range(self.n_samples): j = np.random.randint(0, self.X.shape[0]) nn = self.neigh.kneighbors(self.X[j].reshape(1, -1), return_distance=False)[:, 1:] nn_index = np.random.choice(nn[0]) print (self.X[nn_index], self.X[j]) dif = self.X[nn_index] - self.X[j] gap = np.random.random() S[i, :] = self.X[j, :] + gap * dif[:] return S
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
1.3 Adaptive sensitive reweighting
#Adaptive sensitive reweighting class ReweightedClassifier: def __init__(self, baze_clf, alpha, beta, params = {}): """ Input: baze_clf - object from sklearn with methods .fit(sample_weight=), .predict(), .predict_proba() alpha - list of alphas for sensitive and non-sensitive objects [alpha, alpha'] beta - list of betss for sensitive and non-sensitive objects [beta, beta'] params - **kwargs compatible with baze_clf """ self.baze_clf = baze_clf self.model = None self.alpha = np.array(alpha) self.alphas = None self.beta = np.array(beta) self.betas = None self.weights = None self.prev_weights = None self.params = params def reweight_dataset(self, length, error, minority_idx): """ This function recalculates values of weights and saves their previous values """ if self.alphas is None or self.betas is None: # If alpha_0, alpha_1 or beta_0, beta_1 are not defined, # then define alpha_0 and beta_0 to every object from non-sensitive class, # and alpha_1 and beta_1 to every object from sensitive class (minority). self.alphas = np.ones(length) * self.alpha[0] self.betas = np.ones(length) * self.beta[0] self.alphas[minority_idx] = self.alpha[1] self.betas[minority_idx] = self.beta[1] # w_i_prev <- w_i for all i in dataset self.prev_weights = self.weights.copy() # w_i = alpha_i * L_{beta_i} (P'(y_pred_i =! y_true_i)) # + (1 - alpha_i) * L_{beta_i} (-P'(y_pred_i =! y_true_i)), # where # L_{beta_i} (x) = exp(beta_i * x) self.weights = self.alphas * np.exp(self.betas * error) \ + (1 - self.alphas) * np.exp(- self.betas * error) def pRule(self, prediction, minority_idx): """ This function calculates | P(y_pred_i = 1 | i in S) P(y_pred_i = 1 | i not in S) | pRule = min { ---------------------------- , ---------------------------- } | P(y_pred_i = 1 | i not in S) P(y_pred_i = 1 | i in S) | S - the group of sensitive objects --------- Input: prediction - labels ({0,1}) of a sample for which pRule is calculated minority_idx - indexes of objects from a sensitive group """ # majority indexes = set of all indexes / set of minority indexes, # where set of all indexes = all numbers from 0 to size of sample (=len(prediction)) majority_idx = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx) # minority = P(y_pred_i = 1 | i in minority) # majority = P(y_pred_i = 1 | i in majority) minority = prediction[minority_idx].mean() majority = prediction[list(majority_idx)].mean() minority = np.clip(minority, 1e-10, 1 - 1e-10) majority = np.clip(majority, 1e-10, 1 - 1e-10) return min(minority/majority, majority/minority) def fit(self, X_train, y_train, X_test, y_test, minority_idx, verbose=True, max_iter=30): # Initialize equal weights w_i = 1 self.weights = np.ones(len(y_train)) self.prev_weights = np.zeros(len(y_train)) # Lists for saving metrics accuracys = [] pRules = [] differences = [] accuracy_plus_prule = [] # Adaptive Sensitive Reweighting iteration = 0 while ((self.prev_weights - self.weights) ** 2).mean() > 10**(-6) and iteration < max_iter: iteration += 1 # Train classifier on X_train with weights w_i self.model = self.baze_clf(**self.params) self.model.fit(X_train, y_train, sample_weight = self.weights) # Use classifier to obtain P`(y_pred_i =! y_pred) (here it is called 'error') prediction_proba = self.model.predict_proba(X_train)[:, 1] error = (y_train == 1) * (1 - prediction_proba) + (y_train == 0) * prediction_proba # Update weights self.reweight_dataset(len(y_train), error, minority_idx) # Get metrics on X_train prediction = self.model.predict(X_train) accuracys.append(accuracy_score(prediction, y_train)) pRules.append(self.pRule(prediction, minority_idx)) accuracy_plus_prule.append(accuracys[-1] + pRules[-1]) differences.append(((self.prev_weights - self.weights)**2).mean()**0.5) # Visualize metrics if it's needed if verbose: display.clear_output(True) fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(16, 7)) metrics = [accuracys, pRules, accuracy_plus_prule, differences] metrics_names = ["Accuracy score", "pRule", "Accuracy + pRule", "Mean of weight edits"] for name, metric, ax in zip(metrics_names, metrics, axes.flat): ax.plot(metric, label='train') ax.set_title(f'{name}, iteration {iteration}') ax.legend() if name == "Mean of weight edits": ax.set_yscale('log') plt.show() return accuracys, pRules, accuracy_plus_prule def predict(self, X): return self.model.predict(X) def predict_proba(self, X): return self.model.predict_proba(X) def get_metrics_test(self, X_test, y_test, minority_idx_test): """ Obtain pRule and accuracy for trained model """ # Obtain predictions on X_test to calculate metrics prediction_test = self.model.predict(X_test) # Get metrics on test accuracy_test = accuracy_score(prediction_test, y_test) pRule_test = self.pRule(prediction_test, minority_idx_test) return accuracy_test, pRule_test def prep_train_model(X_train, y_train, X_test, y_test, minority_idx): def train_model(a): """ Function of 4 variables (a[0], a[1], a[2], a[3]) that will be minimized by DIRECT method. a[0], a[1] = alpha, alpha' a[2], a[3] = beta, beta' """ model = ReweightedClassifier(LogisticRegression, [a[0], a[1]], [a[2], a[3]], params = {"max_iter": 4000}) _, _, accuracy_plus_prule = model.fit(X_train, y_train, X_test, y_test, minority_idx) # We'll maximize [acc + pRule] which we get at the last iteration of Adaptive Sensitive Reweighting return - accuracy_plus_prule[-1] return train_model # return function for optimization
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
1.4 Some functions used for fitting models, calculating metrics, and data separation
#This function returns binary list of whether the corresponding feature is protected (1) or not (0) def get_protected_instances(X, feature, label): protected = [] for i in range(len(X)): if X.iloc[i][feature] == label: protected.append(1) else: protected.append(0) return protected #To calculate TRP and TNR for protected and non-protected groups, first separate them def separate_protected_from_non_protected(y_true, y_pred, protected): y_true_protected = [] y_pred_protected = [] y_true_non_protected = [] y_pred_non_protected = [] for true_label, pred_label, is_protected in zip(y_true, y_pred, protected): if is_protected == 1: y_true_protected.append(true_label) y_pred_protected.append(pred_label) elif is_protected == 0: y_true_non_protected.append(true_label) y_pred_non_protected.append(pred_label) else: print("Error: invalid value of in protected array ", is_protected) return 0,0,0,0 return (np.array(y_true_protected), np.array(y_pred_protected), np.array(y_true_non_protected), np.array(y_pred_non_protected)) def tp_tn_fp_fn(y_true, y_pred): matrix = confusion_matrix(y_true, y_pred) tp = matrix[1][1] tn = matrix[0][0] fp = matrix[0][1] fn = matrix[1][0] return (tp, tn, fp, fn) #same pRule as in ASR, but used for calculating this metric in others classifiers' predictions def pRule(prediction, minority_idx): """ This function calculates | P(y_pred_i = 1 | i in S) P(y_pred_i = 1 | i not in S) | pRule = min { ---------------------------- , ---------------------------- } | P(y_pred_i = 1 | i not in S) P(y_pred_i = 1 | i in S) | S - the group of sensitive objects --------- Input: prediction - labels ({0,1}) of a sample for which pRule is calculated minority_idx - indexes of objects from a sensitive group """ # majority indexes = set of all indexes / set of minority indexes, # where set of all indexes = all numbers from 0 to size of sample (=len(prediction)) majority_idx = set(np.linspace(0, len(prediction) - 1, len(prediction), dtype = int)).difference(minority_idx) # minority = P(y_pred_i = 1 | i in minority) # majority = P(y_pred_i = 1 | i in majority) minority = prediction[minority_idx].mean() majority = prediction[list(majority_idx)].mean() minority = np.clip(minority, 1e-10, 1 - 1e-10) majority = np.clip(majority, 1e-10, 1 - 1e-10) return min(minority/majority, majority/minority)
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
2) Download datasets (run one cell for one dataset) Adult census
#Adult census #adult_census_names = ['old_id' ,'age','workclass','fnlwgt','education','education_num','marital_status','occupation','relationship','race','sex','capital_gain','capital_loss','hours_per_week','native_country'] X_train = pd.read_csv("splits/X_train_preprocessed_adult.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] X_test = pd.read_csv("splits/X_test_preprocessed_adult.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] y_train = pd.read_csv("splits/y_train_preprocessed_adult.csv")['income'] y_test = pd.read_csv("splits/y_test_preprocessed_adult.csv")['income'] reweight_prediction = "/content/predictions/y_pred_test_adult.csv" #X_test, X_train = preprocess_adult_census(X_test.drop('old_id', axis = 1)), preprocess_adult_census(X_train.drop('old_id', axis = 1)) #y_test, y_train = adult_label_transform(y_test)['income'], adult_label_transform(y_train)['income'] #Obtain protected group (used in AdaFair) protected_test = get_protected_instances(X_test, 'gender', 1) protected_train = get_protected_instances(X_train, 'gender', 1) # Obtain indexes of sensitive class (for regression algorithm) minority_idx = X_train.reset_index(drop=True).index.values[X_train["gender"] == 1] minority_idx_test = X_test.reset_index(drop=True).index.values[X_test["gender"] == 1] #best hyperparameters for AdaFair adafair_max_depth = 2 adafair_n_estimators = 20 #result of ASR optimizing a_1 = [0.01851852, 0.99382716, 1.16666667, 2.94444444] #print(len(X_train),len(y_train)) #X_train.head()
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
Bank
X_train = pd.read_csv("splits/X_train_preprocessed_bank.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] X_test = pd.read_csv("splits/X_test_preprocessed_bank.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] y_train = pd.read_csv("splits/y_train_preprocessed_bank.csv")['y'] y_test = pd.read_csv("splits/y_test_preprocessed_bank.csv")['y'] reweight_prediction = "/content/predictions/y_pred_test_bank.csv" #X_test, X_train = preprocess_adult_census(X_test.drop('old_id', axis = 1)), preprocess_adult_census(X_train.drop('old_id', axis = 1)) #y_test, y_train = adult_label_transform(y_test)['income'], adult_label_transform(y_train)['income'] #Obtain protected group (used in AdaFair) protected_test = get_protected_instances(X_test, 'age', 1) protected_train = get_protected_instances(X_train, 'age', 1) # Obtain indexes of sensitive class (for regression algorithm) minority_idx = X_train.reset_index(drop=True).index.values[X_train["age"] == 1] minority_idx_test = X_test.reset_index(drop=True).index.values[X_test["age"] == 1] #best hyperparameters for AdaFair adafair_max_depth = 2 adafair_n_estimators = 9 #result of ASR optimizing a_1 = [0.87037037, 0.01851852, 2.72222222, 1.57407407] #print(len(X_train),len(y_train)) #X_train.head()
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
Compass
X_train = pd.read_csv("splits/X_train_preprocessed_compas.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] X_test = pd.read_csv("splits/X_test_preprocessed_compas.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] y_train = pd.read_csv("splits/y_train_preprocessed_compas.csv")['two_year_recid'] y_test = pd.read_csv("splits/y_test_preprocessed_compas.csv")['two_year_recid'] reweight_prediction = "/content/predictions/y_pred_test_compas.csv" #X_test, X_train = preprocess_adult_census(X_test.drop('old_id', axis = 1)), preprocess_adult_census(X_train.drop('old_id', axis = 1)) #y_test, y_train = adult_label_transform(y_test)['income'], adult_label_transform(y_train)['income'] #Obtain protected group (used in AdaFair) protected_test = get_protected_instances(X_test, 'race', 0) protected_train = get_protected_instances(X_train, 'race', 0) # Obtain indexes of sensitive class (for regression algorithm) minority_idx = X_train.reset_index(drop=True).index.values[X_train["race"] == 0] minority_idx_test = X_test.reset_index(drop=True).index.values[X_test["race"] == 0] #best hyperparameters for AdaFair adafair_max_depth = 4 adafair_n_estimators = 5 #result of ASR optimizing a_1 = [0.0308642, 0.72222222, 0.5, 0.45061728] #print(len(X_train),len(y_train)) #y_train.head()
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
KDD Census
#adult_census_names = ['old_id' ,'age','workclass','fnlwgt','education','education_num','marital_status','occupation','relationship','race','sex','capital_gain','capital_loss','hours_per_week','native_country'] X_train = pd.read_csv("splits/X_train_preprocessed_kdd.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] X_test = pd.read_csv("splits/X_test_preprocessed_kdd.csv").drop("Unnamed: 0", axis = 1)#, names = adult_census_names).iloc[1:] y_train = pd.read_csv("splits/y_train_preprocessed_kdd.csv")['income_50k'] y_test = pd.read_csv("splits/y_test_preprocessed_kdd.csv")['income_50k'] reweight_prediction = "/content/predictions/y_pred_test_kdd.csv" #X_test, X_train = preprocess_adult_census(X_test.drop('old_id', axis = 1)), preprocess_adult_census(X_train.drop('old_id', axis = 1)) #y_test, y_train = adult_label_transform(y_test)['income'], adult_label_transform(y_train)['income'] #Obtain protected group (used in AdaFair) protected_test = get_protected_instances(X_test, 'sex', 1) protected_train = get_protected_instances(X_train, 'sex', 1) # Obtain indexes of sensitive class (for regression algorithm) minority_idx = X_train.reset_index(drop=True).index.values[X_train["sex"] == 1] minority_idx_test = X_test.reset_index(drop=True).index.values[X_test["sex"] == 1] #best hyperparameters for AdaFair adafair_max_depth = 5 adafair_n_estimators = 11 #result of ASR optimizing a_1 = [0.01851852, 0.99382716, 1.16666667, 2.94444444] #print(len(X_train),len(y_train)) #X_train.head()
98147 98147
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
3) Create models, train classifiers
#Regression # Create model with obtained hyperparameters alpha, alpha', beta, beta' model_reweighted_classifier = ReweightedClassifier(LogisticRegression, [a_1[0], a_1[1]], [a_1[2], a_1[3]], params = {"max_iter": 4}) # Train model on X_train model_reweighted_classifier.fit(X_train, y_train, X_test, y_test, minority_idx, verbose=False) # Calculate metrics (pRule, accuracy) on X_test accuracy_test, pRule_test = model_reweighted_classifier.get_metrics_test(X_test, y_test, minority_idx_test) #print('ASR+CULEP for X_test') #print(f"prule = {pRule_test:.6}, accuracy = {accuracy_test:.6}") #print(f"prule + accuracy = {(pRule_test + accuracy_test):.6}") #SMOTEBOOST max_depth = 2 n_samples = 100 k_neighbors = 5 n_estimators = 5 # T random_state = 42 get_base_clf = lambda: DecisionTreeClassifier(max_depth = max_depth) smoteboost1 = SMOTEBoost(n_samples = n_samples, k_neighbors = k_neighbors, n_estimators = n_estimators, base_classifier = get_base_clf, random_state = random_state) smoteboost1.fit(X_train, y_train) #smote_boost = smoteboost1.predict(X_test) #AdaFair #Tolerance to unfairness epsilon = 0 get_base_clf = lambda: DecisionTreeClassifier(max_depth=adafair_max_depth) ada_fair = AdaFairClassifier(DecisionTreeClassifier(max_depth=adafair_max_depth), algorithm="SAMME", n_estimators=adafair_n_estimators, protected = protected_train, epsilon = epsilon) ada_fair.fit(X_train, y_train) #Adaboost ada_boost_sklearn = AdaBoostClassifier(DecisionTreeClassifier(max_depth=max_depth), algorithm="SAMME", n_estimators=n_estimators) ada_boost_sklearn.fit(X_train, y_train)
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
4) Compute and plot metrics 4.1 Compute
names = ['ada_fair','ada_boost_sklearn', 'smoteboost', "reweighted_classifier"] classifiers = [ada_fair, ada_boost_sklearn, smoteboost1, model_reweighted_classifier] accuracy = {} bal_accuracy = {} TPR = {} TNR = {} eq_odds = {} p_rule = {} #DELETA #y_test = y_test[:][1] for i, clf in enumerate(classifiers): print(names[i]) prediction = clf.predict(X_test) if i == 3: prediction = np.array(pd.read_csv(reweight_prediction, names = ['idx', 'pred'])['pred'][1:]) print((prediction), (y_test)) print(len(prediction), len(y_test)) accuracy[names[i]] = (prediction == y_test).sum() * 1. / len(y_test) bal_accuracy[names[i]] = balanced_accuracy_score(y_test, prediction) print('accuracy {}: {}'.format(names[i], (prediction == y_test).sum() * 1. / len(y_test))) print('balanced accuracy {}: {}'.format(names[i], balanced_accuracy_score(y_test, prediction))) y_true_protected, y_pred_protected, y_true_non_protected, y_pred_non_protected = separate_protected_from_non_protected(y_test, prediction, protected_test) #TPR for protected group tp, tn, fp, fn = tp_tn_fp_fn(y_true_protected, y_pred_protected) TPR_protected = tp / (tp + fn) TNR_protected = tn / (tn + fp) FPR_protected = fp / (fp + tn) FNR_protected = fn / (fn + tp) print('TPR protected {}: {}'.format(names[i], TPR_protected)) print('TNR protected {}: {}'.format(names[i], TNR_protected)) TPR[names[i] + ' protected'] = TPR_protected TNR[names[i] + ' protected'] = TNR_protected #TPR for non protected group tp, tn, fp, fn = tp_tn_fp_fn(y_true_non_protected, y_pred_non_protected) TPR_non_protected = tp / (tp + fn) TNR_non_protected = tn / (tn + fp) FPR_non_protected = fp / (fp + tn) FNR_non_protected = fn / (fn + tp) print('TPR non protected {}: {}'.format(names[i], TPR_non_protected)) print('TNR non protected {}: {}'.format(names[i], TNR_non_protected)) delta_FPR = -FPR_non_protected + FPR_protected delta_FNR = -FNR_non_protected + FNR_protected eq_odds[names[i]] = abs(delta_FPR) + abs(delta_FNR) TPR[names[i] + ' non protected'] = TPR_non_protected TNR[names[i] + ' non protected'] = TNR_non_protected p_rule[names[i]] = pRule(prediction, minority_idx_test) print('pRule {}: {}'.format(names[i],p_rule[names[i]]))
ada_fair accuracy ada_fair: 0.9228809846454807 balanced accuracy ada_fair: 0.7176952582693732 TPR protected ada_fair: 0.6626686656671664 TNR protected ada_fair: 0.9330514588008977 TPR non protected ada_fair: 0.4335117332235488 TNR non protected ada_fair: 0.9756010558607405 pRule ada_fair: 0.8097128558491885 ada_boost_sklearn accuracy ada_boost_sklearn: 0.946417109030332 balanced accuracy ada_boost_sklearn: 0.6529104164181531 TPR protected ada_boost_sklearn: 0.08320839580209895 TNR protected ada_boost_sklearn: 0.9992385379929465 TPR non protected ada_boost_sklearn: 0.3812268423219432 TNR non protected ada_boost_sklearn: 0.976409597869254 pRule ada_boost_sklearn: 0.047964583961589244 smoteboost accuracy smoteboost: 0.9368192609045616 balanced accuracy smoteboost: 0.5606524639130167 TPR protected smoteboost: 0.13793103448275862 TNR protected smoteboost: 0.984550336646361 TPR non protected smoteboost: 0.12803622890078223 TNR non protected smoteboost: 0.9989536515183943 pRule smoteboost: 0.7617401588170212 reweighted_classifier [0 0 0 ... 0 0 0] 0 0 1 0 2 0 3 0 4 0 .. 98142 0 98143 0 98144 0 98145 0 98146 0 Name: income_50k, Length: 98147, dtype: int64 98147 98147 accuracy reweighted_classifier: 0.9402528859771567 balanced accuracy reweighted_classifier: 0.5368035200272799 TPR protected reweighted_classifier: 0.08095952023988005 TNR protected reweighted_classifier: 0.9981965373517153 TPR non protected reweighted_classifier: 0.07348703170028818 TNR non protected reweighted_classifier: 0.9988823095764666 pRule reweighted_classifier: 0.4486914878692678
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
4.2 Plot
labels = ['Accuracy', 'Bal. accuracy', 'Eq. odds','TPR prot.', 'TPR non-prot', 'TNR prot.', 'TNR non-prot.', 'pRule'] adaFair_metrics = [accuracy['ada_fair'], bal_accuracy['ada_fair'], eq_odds['ada_fair'], TPR['ada_fair protected'], TPR['ada_fair non protected'], TNR['ada_fair protected'], TNR['ada_fair non protected'], p_rule['ada_fair']] adaBoost_metrics = [accuracy['ada_boost_sklearn'], bal_accuracy['ada_boost_sklearn'], eq_odds['ada_boost_sklearn'], TPR['ada_boost_sklearn protected'], TPR['ada_boost_sklearn non protected'], TNR['ada_boost_sklearn protected'], TNR['ada_boost_sklearn non protected'], p_rule['ada_boost_sklearn']] SMOTEBoost_metrics = [accuracy['smoteboost'], bal_accuracy['smoteboost'], eq_odds['smoteboost'], TPR['smoteboost protected'], TPR['smoteboost non protected'], TNR['smoteboost protected'], TNR['smoteboost non protected'], p_rule['smoteboost']] reweighted_class_metrics = [accuracy['reweighted_classifier'], bal_accuracy['reweighted_classifier'], eq_odds['reweighted_classifier'], TPR['reweighted_classifier protected'], TPR['reweighted_classifier non protected'], TNR['reweighted_classifier protected'], TNR['reweighted_classifier non protected'],p_rule['reweighted_classifier']] x = np.arange(len(labels)) # the label locations width = 0.20 # the width of the bars font = {'family' : 'normal', 'weight' : 'normal', 'size' : 19} matplotlib.rc('font', **font) fig, ax = plt.subplots(figsize = [15, 5]) rects1 = ax.bar(x - 1.5*width, adaBoost_metrics, width, label='AdaBoost', color='gray') rects2 = ax.bar(x - width/2 , SMOTEBoost_metrics, width, label='SMOTEBoost', color='red') rects3 = ax.bar(x + width/2, adaFair_metrics, width, label='AdaFair', color='green') rects4 = ax.bar(x + 1.5*width, reweighted_class_metrics, width, label='ASR', color='blue') ax.set_ylabel('Scores') #ax.set_title('Scores by algoritms') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend(loc=9, ncol = 4, bbox_to_anchor=(0.5, 1.15)) ax.grid() fig.tight_layout() plt.show()
_____no_output_____
MIT
Model Comparison/Model_comparison.ipynb
asmolina/ML-project-fairness-aware-classification
Apple and Tesla Split on 8/31
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import math import warnings warnings.filterwarnings("ignore") # for fetching data import yfinance as yf # input # Coronavirus 2nd Wave title = "Apple and Tesla" symbols = ['AAPL', 'TSLA'] start = '2020-01-01' end = '2020-08-31' df = pd.DataFrame() for symbol in symbols: df[symbol] = yf.download(symbol, start, end)['Adj Close'] from datetime import datetime from dateutil import relativedelta d1 = datetime.strptime(start, "%Y-%m-%d") d2 = datetime.strptime(end, "%Y-%m-%d") delta = relativedelta.relativedelta(d2, d1) print('How many years of investing?') print('%s years' % delta.years) number_of_years = delta.years days = (df.index[-1] - df.index[0]).days days df.head() df.tail() df.min() df.max() df.describe() plt.figure(figsize=(12,8)) plt.plot(df) plt.title(title + ' Closing Price') plt.legend(labels=df.columns) plt.show() # Normalize the data normalize = (df - df.min())/ (df.max() - df.min()) plt.figure(figsize=(18,12)) plt.plot(normalize) plt.title(title + ' Stocks Normalize') plt.legend(labels=normalize.columns) plt.show() stock_rets = df.pct_change().dropna() plt.figure(figsize=(12,8)) plt.plot(stock_rets) plt.title(title + ' Stocks Returns') plt.legend(labels=stock_rets.columns) plt.show() plt.figure(figsize=(12,8)) plt.plot(stock_rets.cumsum()) plt.title(title + ' Stocks Returns Cumulative Sum') plt.legend(labels=stock_rets.columns) plt.show() sns.set(style='ticks') ax = sns.pairplot(stock_rets, diag_kind='hist') nplot = len(stock_rets.columns) for i in range(nplot) : for j in range(nplot) : ax.axes[i, j].locator_params(axis='x', nbins=6, tight=True) ax = sns.PairGrid(stock_rets) ax.map_upper(plt.scatter, color='purple') ax.map_lower(sns.kdeplot, color='blue') ax.map_diag(plt.hist, bins=30) for i in range(nplot) : for j in range(nplot) : ax.axes[i, j].locator_params(axis='x', nbins=6, tight=True) plt.figure(figsize=(10,10)) corr = stock_rets.corr() # plot the heatmap sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap="Reds") # Box plot stock_rets.plot(kind='box',figsize=(24,8)) rets = stock_rets.dropna() plt.figure(figsize=(16,8)) plt.scatter(rets.std(), rets.mean(),alpha = 0.5) plt.title('Stocks Risk & Returns') plt.xlabel('Risk') plt.ylabel('Expected Returns') plt.grid(which='major') for label, x, y in zip(rets.columns, rets.std(), rets.mean()): plt.annotate( label, xy = (x, y), xytext = (50, 50), textcoords = 'offset points', ha = 'right', va = 'bottom', arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3')) rets = stock_rets.dropna() area = np.pi*20.0 sns.set(style='darkgrid') plt.figure(figsize=(16,8)) plt.scatter(rets.std(), rets.mean(), s=area) plt.xlabel("Risk", fontsize=15) plt.ylabel("Expected Return", fontsize=15) plt.title("Return vs. Risk for Stocks", fontsize=20) for label, x, y in zip(rets.columns, rets.std(), rets.mean()) : plt.annotate(label, xy=(x,y), xytext=(50, 0), textcoords='offset points', arrowprops=dict(arrowstyle='-', connectionstyle='bar,angle=180,fraction=-0.2'), bbox=dict(boxstyle="round", fc="w")) def annual_risk_return(stock_rets): tradeoff = stock_rets.agg(["mean", "std"]).T tradeoff.columns = ["Return", "Risk"] tradeoff.Return = tradeoff.Return*252 tradeoff.Risk = tradeoff.Risk * np.sqrt(252) return tradeoff tradeoff = annual_risk_return(stock_rets) tradeoff import itertools colors = itertools.cycle(["r", "b", "g"]) tradeoff.plot(x = "Risk", y = "Return", kind = "scatter", figsize = (13,9), s = 20, fontsize = 15, c='g') for i in tradeoff.index: plt.annotate(i, xy=(tradeoff.loc[i, "Risk"]+0.002, tradeoff.loc[i, "Return"]+0.002), size = 15) plt.xlabel("Annual Risk", fontsize = 15) plt.ylabel("Annual Return", fontsize = 15) plt.title("Return vs. Risk for " + title + " Stocks", fontsize = 20) plt.show() rest_rets = rets.corr() pair_value = rest_rets.abs().unstack() pair_value.sort_values(ascending = False) # Normalized Returns Data Normalized_Value = ((rets[:] - rets[:].min()) /(rets[:].max() - rets[:].min())) Normalized_Value.head() Normalized_Value.corr() normalized_rets = Normalized_Value.corr() normalized_pair_value = normalized_rets.abs().unstack() normalized_pair_value.sort_values(ascending = False) print("Stock returns: ") print(rets.mean()) print('-' * 50) print("Stock risks:") print(rets.std()) table = pd.DataFrame() table['Returns'] = rets.mean() table['Risk'] = rets.std() table.sort_values(by='Returns') table.sort_values(by='Risk') rf = 0.01 table['Sharpe Ratio'] = (table['Returns'] - rf) / table['Risk'] table table['Max Returns'] = rets.max() table['Min Returns'] = rets.min() table['Median Returns'] = rets.median() total_return = stock_rets[-1:].transpose() table['Total Return'] = 100 * total_return table table['Average Return Days'] = (1 + total_return)**(1 / days) - 1 table initial_value = df.iloc[0] ending_value = df.iloc[-1] table['CAGR'] = ((ending_value / initial_value) ** (252.0 / days)) -1 table table.sort_values(by='Average Return Days')
_____no_output_____
MIT
Python_Stock/Portfolio_Strategies/Apple_Tesla_Split.ipynb
linusqzdeng/Stock_Analysis_For_Quant
- A stationary time series is one whose statistical properties such as mean, variance, autocorrelation, etc. are all constant over time. Most statistical forecasting methods are based on the assumption that the time series can be rendered approximately stationary (i.e., "stationarized") through the use of mathematical transformations. A stationarized series is relatively easy to predict: you simply predict that its statistical properties will be the same in the future as they have been in the past! - We can check stationarity using the following:- - Plotting Rolling Statistics: We can plot the moving average or moving variance and see if it varies with time. This is more of a visual technique.- - Dickey-Fuller Test: This is one of the statistical tests for checking stationarity. Here the null hypothesis is that the TimeSeries is non-stationary. The test results comprise of a Test Statistic and some Critical Values for difference confidence levels. If the β€˜Test Statistic’ is less than the β€˜Critical Value’, we can reject the null hypothesis and say that the series is stationary.
from statsmodels.tsa.stattools import adfuller def test_stationary(timeseries): #Determing rolling statistics moving_average=timeseries.rolling(window=12).mean() standard_deviation=timeseries.rolling(window=12).std() #Plot rolling statistics: plt.plot(timeseries,color='blue',label="Original") plt.plot(moving_average,color='red',label='Mean') plt.plot(standard_deviation,color='black',label='Standard Deviation') plt.legend(loc='best') #best for axes plt.title('Rolling Mean & Deviation') # plt.show() plt.show(block=False) #Perform Dickey-Fuller test: print('Results Of Dickey-Fuller Test') tstest=adfuller(timeseries['MONSOON'],autolag='AIC') tsoutput=pd.Series(tstest[0:4],index=['Test Statistcs','P-value','#Lags used',"#Obs. used"]) #Test Statistics should be less than the Critical Value for Stationarity #lesser the p-value, greater the stationarity # print(list(dftest)) for key,value in tstest[4].items(): tsoutput['Critical Value (%s)'%key]=value print((tsoutput)) test_stationary(indexedDataset)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- There are 2 major reasons behind non-stationaruty of a TS:- - Trend – varying mean over time. For eg, in this case we saw that on average, the number of passengers was growing over time.- - Seasonality – variations at specific time-frames. eg people might have a tendency to buy cars in a particular month because of pay increment or festivals. Indexed Dataset Logscale
indexedDataset_logscale=np.log(indexedDataset) test_stationary(indexedDataset_logscale)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Dataset Log Minus Moving Average (dl_ma)
rolmeanlog=indexedDataset_logscale.rolling(window=12).mean() dl_ma=indexedDataset_logscale-rolmeanlog dl_ma.head(12) dl_ma.dropna(inplace=True) dl_ma.head(12) test_stationary(dl_ma)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Exponential Decay Weighted Average (edwa)
edwa=indexedDataset_logscale.ewm(halflife=12,min_periods=0,adjust=True).mean() plt.plot(indexedDataset_logscale) plt.plot(edwa,color='red')
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Dataset Logscale Minus Moving Exponential Decay Average (dlmeda)
dlmeda=indexedDataset_logscale-edwa test_stationary(dlmeda)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Eliminating Trend and Seasonality - Differencing – taking the differece with a particular time lag- Decomposition – modeling both trend and seasonality and removing them from the model. Differencing Dataset Log Div Shifting (dlds)
#Before Shifting indexedDataset_logscale.head() #After Shifting indexedDataset_logscale.shift().head() dlds=indexedDataset_logscale-indexedDataset_logscale.shift() dlds.dropna(inplace=True) test_stationary(dlds)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Decomposition
from statsmodels.tsa.seasonal import seasonal_decompose decompostion= seasonal_decompose(indexedDataset_logscale,freq=10) trend=decompostion.trend seasonal=decompostion.seasonal residual=decompostion.resid plt.subplot(411) plt.plot(indexedDataset_logscale,label='Original') plt.legend(loc='best') plt.subplot(412) plt.plot(trend,label='Trend') plt.legend(loc='best') plt.subplot(413) plt.plot(seasonal,label='Seasonal') plt.legend(loc='best') plt.subplot(414) plt.plot(residual,label='Residual') plt.legend(loc='best') plt.tight_layout() #To Show Multiple Grpahs In One Output, Use plt.subplot(abc)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- Here trend, seasonality are separated out from data and we can model the residuals. Lets check stationarity of residuals:
decomposedlogdata=residual decomposedlogdata.dropna(inplace=True) test_stationary(decomposedlogdata)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Forecasting a Time Series - ARIMA stands for Auto-Regressive Integrated Moving Averages. The ARIMA forecasting for a stationary time series is nothing but a linear (like a linear regression) equation. The predictors depend on the parameters (p,d,q) of the ARIMA model:- - Number of AR (Auto-Regressive) terms (p): AR terms are just lags of dependent variable. For instance if p is 5, the predictors for x(t) will be x(t-1)….x(t-5).- - Number of MA (Moving Average) terms (q): MA terms are lagged forecast errors in prediction equation. For instance if q is 5, the predictors for x(t) will be e(t-1)….e(t-5) where e(i) is the difference between the moving average at ith instant and actual value.- - Number of Differences (d): These are the number of nonseasonal differences, i.e. in this case we took the first order difference. So either we can pass that variable and put d=0 or pass the original variable and put d=1. Both will generate same results.- An importance concern here is how to determine the value of β€˜p’ and β€˜q’. We use two plots to determine these numbers.- - Autocorrelation Function (ACF): It is a measure of the correlation between the the TS with a lagged version of itself-. For instance at lag 5, ACF would compare series at time instant β€˜t1’…’t2’ with series at instant β€˜t1-5’…’t2-5’ (t1-5 and t2 being end points).- - Partial Autocorrelation Function (PACF): This measures the correlation between the TS with a lagged version of itself but after eliminating the variations already explained by the intervening comparisons. Eg at lag 5, it will check the correlation but remove the effects already explained by lags 1 to 4. ACF & PACF Plots
from statsmodels.tsa.stattools import acf,pacf lag_acf=acf(dlds,nlags=20) lag_pacf=pacf(dlds,nlags=20,method='ols') plt.subplot(121) plt.plot(lag_acf) plt.axhline(y=0, linestyle='--',color='gray') plt.axhline(y=1.96/np.sqrt(len(dlds)),linestyle='--',color='gray') plt.axhline(y=-1.96/np.sqrt(len(dlds)),linestyle='--',color='gray') plt.title('AutoCorrelation Function') plt.subplot(122) plt.plot(lag_pacf) plt.axhline(y=0, linestyle='--',color='gray') plt.axhline(y=1.96/np.sqrt(len(dlds)),linestyle='--',color='gray') plt.axhline(y=-1.96/np.sqrt(len(dlds)),linestyle='--',color='gray') plt.title('PartialAutoCorrelation Function') plt.tight_layout()
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- In this plot, the two dotted lines on either sides of 0 are the confidence interevals. These can be used to determine the β€˜p’ and β€˜q’ values as:- - p – The lag value where the PACF chart crosses the upper confidence interval for the first time. If we notice closely, in this case p=2.- - q – The lag value where the ACF chart crosses the upper confidence interval for the first time. If we notice closely, in this case q=2.
from statsmodels.tsa.arima_model import ARIMA model=ARIMA(indexedDataset_logscale,order=(5,1,0)) results_AR=model.fit(disp=-1) plt.plot(dlds) plt.plot(results_AR.fittedvalues,color='red') plt.title('RSS: %.4f'%sum((results_AR.fittedvalues-dlds['MONSOON'])**2)) print('Plotting AR Model') model = ARIMA(indexedDataset_logscale, order=(0, 1, 2)) #0,1,2 results_MA = model.fit(disp=-1) plt.plot(dlds) plt.plot(results_MA.fittedvalues, color='red') plt.title('RSS: %.4f'%sum((results_MA.fittedvalues-dlds['MONSOON'])**2)) print('Plotting MA Model') import itertools a={} p=d=q=range(0,6) pdq=list(itertools.product(p,d,q)) for i in pdq: try: model_arima=(ARIMA(indexedDataset_logscale,order=i)).fit() a[i]=model_arima.aic except: continue # min(a, key=a.get) RSS=[] RSS1=[] for i in a.keys(): model = ARIMA(indexedDataset_logscale, order=i) results_ARIMA = model.fit(disp=-1) RSS.append(sum((results_ARIMA.fittedvalues-dlds['MONSOON'])**2)) for i in range(0,len(RSS)): if(~np.isnan(RSS[i])): RSS1.append(RSS[i]) min(RSS1) model = ARIMA(indexedDataset_logscale, order=(5, 1, 2)) results_ARIMA = model.fit(disp=-1) plt.plot(dlds) plt.plot(results_ARIMA.fittedvalues, color='red') plt.title('RSS: %.4f'%sum((results_ARIMA.fittedvalues-dlds['MONSOON'])**2)) print('Plotting Combined Model')
Plotting Combined Model
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
Taking it back to original scale from residual scale
#storing the predicted results as a separate series predictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True) predictions_ARIMA_diff.head()
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- Notice that these start from β€˜1949-02-01’ and not the first month. Why? This is because we took a lag by 1 and first element doesn’t have anything before it to subtract from. The way to convert the differencing to log scale is to add these differences consecutively to the base number. An easy way to do it is to first determine the cumulative sum at index and then add it to the base number.
#convert to cummuative sum predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum() predictions_ARIMA_diff_cumsum predictions_ARIMA_log = pd.Series(indexedDataset_logscale['MONSOON'].ix[0], index=indexedDataset_logscale.index) predictions_ARIMA_log predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum,fill_value=0) predictions_ARIMA_log
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- Here the first element is base number itself and from there on the values cumulatively added.
#Last step is to take the exponent and compare with the original series. predictions_ARIMA = np.exp(predictions_ARIMA_log) plt.plot(indexedDataset) plt.plot(predictions_ARIMA) plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-indexedDataset['MONSOON'])**2)/len(indexedDataset)))
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
- Finally we have a forecast at the original scale.
results_ARIMA.plot_predict(1,26) #start = !st month #end = 10yrs forcasting = 144+12*10 = 264th month #Two models corresponds to AR & MA x=results_ARIMA.forecast(steps=5) print(x) #values in residual equivalent for i in range(0,5): print(x[0][i],end='') print('\t',x[1][i],end='') print('\t',x[2][i]) np.exp(results_ARIMA.forecast(steps=5)[0]) predictions_ARIMA_diff = pd.Series(results_ARIMA.forecast(steps=5)[0], copy=True) predictions_ARIMA_diff.head() predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum() predictions_ARIMA_diff_cumsum.head() predictions_ARIMA_log=[] for i in range(0,len(predictions_ARIMA_diff_cumsum)): predictions_ARIMA_log.append(predictions_ARIMA_diff_cumsum[i]+3.411478) predictions_ARIMA_log #Last step is to take the exponent and compare with the original series. predictions_ARIMA = np.exp(predictions_ARIMA_log) plt.subplot(121) plt.plot(indexedDataset) plt.subplot(122) plt.plot(predictions_ARIMA) plt.tight_layout() # plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-indexedDataset['MONSOON'])**2)/len(indexedDataset))) np.exp(predictions_ARIMA_log)
_____no_output_____
MIT
ML-Predictions/.ipynb_checkpoints/Water-Level TSF - Copy (2)-checkpoint.ipynb
romilshah525/SIH-2019
1. Create an assert statement that throws an AssertionError if the variable spam is a negative integer.
import pyinputplus as pyip def is_pos_integer(): n = pyip.inputInt(prompt='Enter a positive integer: ') assert n > 0, 'This is a negative integer' is_pos_integer()
Enter a positive integer: -1
MIT
Python_Basic_Assignments/Assignment_11.ipynb
dataqueenpend/-Assignments_fsDS_OneNeuron
2. Write an assert statement that triggers an AssertionError if the variables eggs and bacon contain strings that are the same as each other, even if their cases are different (that is, &39;hello&39; and &39;hello&39; are considered the same, and &39;goodbye&39; and &39;GOODbye&39; are also considered the same).
import re import pyinputplus as pyip def same_or_different(): eggs = pyip.inputStr(prompt='What is eggs: ') bacon = pyip.inputStr(prompt='What is bacon: ') assert eggs.lower() != bacon.lower(), 'Strings are the same!' same_or_different()
What is eggs: hello What is bacon: Hello
MIT
Python_Basic_Assignments/Assignment_11.ipynb
dataqueenpend/-Assignments_fsDS_OneNeuron
3. Create an assert statement that throws an AssertionError every time.
assert 0 !=0 , 'Assertion Error every time!'
_____no_output_____
MIT
Python_Basic_Assignments/Assignment_11.ipynb
dataqueenpend/-Assignments_fsDS_OneNeuron
2 Dead reckoning*Dead reckoning* is a means of navigation that does not rely on external observations. Instead, a robot’s position is estimated by summing its incremental movements relative to a known starting point.Estimates of the distance traversed are usually obtained from measuring how many times the wheels have turned, and how many times they have turned in relation to each other. For example, the wheels of the robot could be attached to an odometer, similar to the device that records the mileage of a car.In RoboLab we will calculate the position of a robot from how long it moves in a straight line or rotates about its centre. We will assume that the length of time for which the motors are switched on is directly related to the distance travelled by the wheels. *By design, the simulator does not provide the robot with access to any magical GPS-style service. In principle, we could create a magical β€˜simulated-GPS’ sensor that would allow the robot to identify its location from the simulator’s point of view; but in the real world we can’t always guarantee that external location services are available. For example, GPS doesn’t work indoors or underground, or even in many cities where line-of-sight access to four or more GPS satellites is not available.**Furthermore, the robot cannot magically teleport itself to a new location from within a program. Only the magics can teleport the robot to a specific location...**Although the simulator is omniscient and does keep track of where the robot is, the robot must figure out for itself where it is based on things like how far the motors have turned, or from its own sensor readings (ultrasound-based distance to a target, for example, or gyroscope heading); you will learn how to make use of sensors for navigation in later notebooks.* 2.1 Activity – Dead reckoningAn environment for the simulated robot to navigate is shown below, based on the 2018 First Lego League β€˜Into Orbit’ challenge.The idea is that the robot must get to the target satellite from its original starting point by avoiding the obstacles in its direct path.![Space scene showing the robot, some satellites against a β€˜space’ background, and some wall-like obstacles between the robot’s starting point and a target satellite.](../images/Section_00_02_-_Jupyter_Notebook.png) The [First Lego League (FLL)](https://www.firstlegoleague.org/) is a friendly international youth-based robot competition in which teams compete at national and international level on an annual basis. School teams are often coached by volunteers. In the UK, volunteers often coach teams under the auspices of the [STEM Ambassadors Scheme](https://www.stem.org.uk/stem-ambassadors). Many companies run volunteering schemes that allow employees to volunteer their skills in company time using schemes such as STEM Ambassadors. Load in the simulator in the usual way:
from nbev3devsim.load_nbev3devwidget import roboSim, eds %load_ext nbev3devsim
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
To navigate the environment, we will use a small robot configuration within the simulator. The robot configuration can be set via the simulator user interface, or by passing the `-r Small_Robot` parameter setting in the simulator magic.The following program should drive the robot from its starting point to the target, whilst avoiding the obstacles. We define the obstacle as being avoided if it is not crossed by the robot’s *pen down* trail.Load the *FLL_2018_Into_Orbit* background into the simulator. Run the following code cell to download the program to the simulator and then, with the *pen down*, run the program in the simulator. Remember, you can use the `-P / --pencolor` flag to change the pen colour and the `-C / --clear` option to clear the pen trace. Does the robot reach the target satellite without encountering any obstacles?
%%sim_magic_preloaded -b FLL_2018_Into_Orbit -p -r Small_Robot # Turn on the spot to the right tank_turn.on_for_rotations(100, SpeedPercent(70), 1.7 ) # Go forwards tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 20) # Slight graceful turn to left tank_drive.on_for_rotations(SpeedPercent(35), SpeedPercent(50), 8.5) # Turn on the spot to the left tank_turn.on_for_rotations(-100, SpeedPercent(75), 0.8) # Forwards a bit tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 2.0) # Turn on the spot a bit more to the right tank_turn.on_for_rotations(100, SpeedPercent(60), 0.4 ) # Go forwards a bit more and dock on the satellite tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 1.0) say("Hopefully I have docked with the satellite...")
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
*Add your notes on how well the simulated robot performed the task here.* To set the speeds and times, I used a bit of trial and error.If the route had been much more complex, then I would have been tempted to comment out the steps up I had already run and add new steps that would be applied from wherever the robot was currently located.Note that the robot could have taken other routes to get to the satellite – I just thought I should avoid the asteroid! 2.1.1 Using motor tacho counts to identify how far the robot has travelledIn the above example, the motors were turned on for a specific amount of time to move the robot on each leg of its journey. This would not be an appropriate control strategy if we wanted to collect sensor data along the route, because the `on_for_X()` motor commands are blocking commands.However, suppose we replaced the forward driving `tank_drive.on_for_rotations()` commands with commands of the form:```pythonfrom time import sleeptank_drive.on(SPEED)while int(tank_drive.left_motor.position) < DISTANCE: We need something that takes a finite time to run in the loop or the program will hang sleep(0.1)```Now we could drive the robot forwards until the motor tacho count exceeds a specified `DISTANCE` and at the same time, optionally include additional commands, such as sensor data-logging commands, inside the body of each `while` loop.*As well as `tank_drive.left_motor.position` we can also refer to `tank_drive.right_motor.position`. Also note that these values are returned as strings and need to be cast to integers for numerical comparisons.* 2.1.2 Activity – Dead reckoning over distances (optional)Use the `.left_motor.position` and/or `.right_motor.position` motor tacho counts in a program that allows the robot to navigate from its home base to the satellite rendezvous. *Your design notes here.*
# YOUR CODE HERE
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
*Your notes and observations here.* 2.2 Challenge – Reaching the moon base In the following code cell, write a program to move the simulated robot from its location servicing the satellite to the moon base identified as the circular area marked on the moon in the top right-hand corner of the simulated world.In the simulator, set the robot’s *x* location to `1250` and *y* location to `450`.Use the following code cell to write your own dead-reckoning program to drive the robot to the moon base at location `(2150, 950)`.
%%sim_magic_preloaded # YOUR CODE HERE
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
2.3 Dead reckoning with noiseThe robot traverses its path using timing information for dead reckoning. In principle, if the simulated robot had a map then it could calculate all the distances and directions for itself, convert these to times, and dead reckon its way to the target. However, there is a problem with dead reckoning: *noise*.In many physical systems, a perfect intended behaviour is subject to *noise* – random perturbations that arise within the system as time goes on as a side effect of its operation. In a robot, noise might arise in the behaviour of the motors, the transmission or the wheels. The result is that the robot does not execute its motion without error. We can model noise effects in the mobility system of our robot by adding a small amount of noise to the motor speeds as the simulator runs. This noise component may speed up or slow down the speed of each motor, in a random way. As with real systems, the noise represents slight random deviations from the theoretical, ideal behaviour.For the following experiment, create a new, empty background cleared of pen traces.
%sim_magic -b Empty_Map --clear
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
Run the following code cell to download the program to the simulator using an empty background (select the *Empty_Map*) and the *Pen Down* mode selected. Also reset the initial location of the robot to an *x* value of `150` and *y* value of `400`.Run the program in the simulator and observe what happens.
%%sim_magic_preloaded -b Empty_Map -p -x 150 -y 400 -r Small_Robot --noisecontrols tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 10)
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
*Record your observations here describing what happens when you run the program.* When you run the program, you should see the robot drive forwards a short way in a straight line, leaving a straight line trail behind it.Reset the location of the robot. Within the simulator, use the *Noise controls* to increase the *Wheel noise* value from zero by dragging the slider to the right a little way. Alternatively, add noise in the range `0...500` using the `--motornoise / -M` magic flag. Run the program in the simulator again.You should notice this time that the robot does not travel in a straight line. Instead, it drifts from side to side, although possibly to one side of the line.Move the robot back to the start position, or rerun the previous code cell to do so, and run the program in the simulator again. This time, you should see it follows yet another different path.Depending on how severe the noise setting is, the robot will travel closer (low noise) to the original straight line, or follow an ever-more erratic path (high noise). *Record your own notes and observations here describing the behaviour of the robot for different levels of motor noise.* Clear the pen traces from the simulator by running the following line magic:
%sim_magic -C
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
Now run the original satellite-finding dead-reckoning program again, using the *FLL_2018_Into_Orbit* background, but in the presence of *Wheel noise*. How well does it perform this time compared to previously?
%%sim_magic_preloaded -b FLL_2018_Into_Orbit -p -r Small_Robot # Turn on the spot to the right tank_turn.on_for_rotations(100, SpeedPercent(70), 1.7 ) # Go forwards tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 20) # Slight graceful turn to left tank_drive.on_for_rotations(SpeedPercent(35), SpeedPercent(50), 8.5) # Turn on the spot to the left tank_turn.on_for_rotations(-100, SpeedPercent(75), 0.8) # Forwards a bit tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 2.0) # Turn on the spot a bit more to the right tank_turn.on_for_rotations(100, SpeedPercent(60), 0.4 ) # Go forwards a bit more and dock on the satellite tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), 1.0) say("Did I avoid crashing and dock with the satellite?")
_____no_output_____
OML
content/04. Not quite intelligent robots/04.2 Robot navigation using dead reckoning.ipynb
mmh352/tm129-robotics2020
What this code doesIn short, it is a reverse meme search, that identifies the source of the meme. It takes an image copypasta, extracts the individual *subimages* and compares it with a database of pictures (the database should be made up of copypastas, which is in TODO) TODO Clean up the codeThere are many repetitive import statements. The code is saving the picture as file so that you can load it into model. Anything that you cannot explain in this code Change VGG16 to Xception (because I can't upgrade both TF and keras for reasons) Feature vector robustness checkTo what extent the following transformations affects the feature vector?- crop (a little, add bounding boxes)- photoshop - e.g. cropping a face onto a body- rotate the image (a little, a lot)- add text (different sizes)- vandalised - scribbling markers over - add noise (Gaussian etc)- compression changes- recoloring - grey-scale- picture effects - e.g. twisted picture meme- special effects - e.g. shining eyes meme Image separation testingWe need to ensure the individual pictures are separated correctly.- pictures now don't have borders- pictures are no longer rectangular- whether does it identify the source of the cropped face Database managementWe need to do preprocessing of the database. Currently the feature vector is only calculated when you start this notebook. Moreover, since the database of copypasta will not be single images, we need to process that aspect as well. From the copypastas we need to identify its subimages and then calculate their feature vector. There also needs to be some way to associate the feature vector and the location of the subimages to the image copypasta, together with its metadata - in a manner that is scalable. import imagenet model
%run image_database_helper.ipynb model = init_model()
_____no_output_____
MIT
database_updater.ipynb
tlkh/reverse-image-search
making a list of all the files
!rm 'imgs/.DS_Store' images = findfiles("new/") print(len(images))
24
MIT
database_updater.ipynb
tlkh/reverse-image-search
Processing pictures
from PIL import Image from matplotlib.pyplot import imshow import matplotlib.pyplot as plt import cv2 import csv fieldnames = ['img_file_name', 'number_of_subimages', 'subimage_number', 'x', 'y', 'w', 'h', 'feature_vector'] import os if not os.path.exists('index_subimage.csv'): with open('index_subimage.csv', 'w') as csvfile: db = csv.DictWriter(csvfile, fieldnames=fieldnames) db.writeheader() import subprocess import csv for img_name in images: path_image_to_analyse = "./new/"+img_name print(img_name) img = cv2.imread(path_image_to_analyse) output_boxes = get_bounding_boxes(img) for i, box in enumerate(output_boxes): [x,y,w,h] = box output_img = np.array(img[y:y+h, x:x+w]) cv2.imwrite("temp.jpg",output_img) feature_vector = calc_feature_vector(model, "temp.jpg") dict_to_write = {'img_file_name':img_name, 'number_of_subimages':len(output_boxes), 'subimage_number':i, 'x':x, 'y':y, 'w':w, 'h':h, 'feature_vector':feature_vector} with open('index_subimage.csv', 'a') as csvfile: db = csv.DictWriter(csvfile, fieldnames=fieldnames) db.writerow(dict_to_write) subprocess.run("mv ./new/{} ./database/{}".format(img_name,img_name),shell=True) !cp ./database/* ./new/
_____no_output_____
MIT
database_updater.ipynb
tlkh/reverse-image-search
Computer Vision Nanodegree Project: Image Captioning---In this notebook, you will use your trained model to generate captions for images in the test dataset.This notebook **will be graded**. Feel free to use the links below to navigate the notebook:- [Step 1](step1): Get Data Loader for Test Dataset - [Step 2](step2): Load Trained Models- [Step 3](step3): Finish the Sampler- [Step 4](step4): Clean up Captions- [Step 5](step5): Generate Predictions! Step 1: Get Data Loader for Test DatasetBefore running the code cell below, define the transform in `transform_test` that you would like to use to pre-process the test images. Make sure that the transform that you define here agrees with the transform that you used to pre-process the training images (in **2_Training.ipynb**). For instance, if you normalized the training images, you should also apply the same normalization procedure to the test images.
import sys sys.path.append('/opt/cocoapi/PythonAPI') from pycocotools.coco import COCO from data_loader import get_loader from torchvision import transforms # TODO #1: Define a transform to pre-process the testing images. transform_test = transforms.Compose([ transforms.Resize(256), # smaller edge of image resized to 256 transforms.RandomCrop(224), # get 224x224 crop from random location transforms.RandomHorizontalFlip(), # horizontally flip image with probability=0.5 transforms.ToTensor(), # convert the PIL Image to a tensor transforms.Normalize((0.485, 0.456, 0.406), # normalize image for pre-trained model (0.229, 0.224, 0.225))]) #-#-#-# Do NOT modify the code below this line. #-#-#-# # Create the data loader. data_loader = get_loader(transform=transform_test, mode='test')
Vocabulary successfully loaded from vocab.pkl file!
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Run the code cell below to visualize an example test image, before pre-processing is applied.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Obtain sample image before and after pre-processing. orig_image, image = next(iter(data_loader)) # Visualize sample image, before pre-processing. plt.imshow(np.squeeze(orig_image)) plt.title('example image') plt.show()
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Step 2: Load Trained ModelsIn the next code cell we define a `device` that you will use move PyTorch tensors to GPU (if CUDA is available). Run this code cell before continuing.
import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Before running the code cell below, complete the following tasks. Task 1In the next code cell, you will load the trained encoder and decoder from the previous notebook (**2_Training.ipynb**). To accomplish this, you must specify the names of the saved encoder and decoder files in the `models/` folder (e.g., these names should be `encoder-5.pkl` and `decoder-5.pkl`, if you trained the model for 5 epochs and saved the weights after each epoch). Task 2Plug in both the embedding size and the size of the hidden layer of the decoder corresponding to the selected pickle file in `decoder_file`.
# Watch for any changes in model.py, and re-load it automatically. % load_ext autoreload % autoreload 2 import os import torch from model import EncoderCNN, DecoderRNN # TODO #2: Specify the saved models to load. encoder_file = "encoder-1.pkl" decoder_file = "decoder-1.pkl" # TODO #3: Select appropriate values for the Python variables below. embed_size = 256 #512 #300 hidden_size = 512 # The size of the vocabulary. vocab_size = len(data_loader.dataset.vocab) # Initialize the encoder and decoder, and set each to inference mode. encoder = EncoderCNN(embed_size) encoder.eval() decoder = DecoderRNN(embed_size, hidden_size, vocab_size) decoder.eval() # Load the trained weights. encoder.load_state_dict(torch.load(os.path.join('./models', encoder_file))) decoder.load_state_dict(torch.load(os.path.join('./models', decoder_file))) # Move models to GPU if CUDA is available. encoder.to(device) decoder.to(device)
Downloading: "https://download.pytorch.org/models/resnet50-19c8e357.pth" to /root/.torch/models/resnet50-19c8e357.pth 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 102502400/102502400 [00:01<00:00, 58944421.27it/s]
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Step 3: Finish the SamplerBefore executing the next code cell, you must write the `sample` method in the `DecoderRNN` class in **model.py**. This method should accept as input a PyTorch tensor `features` containing the embedded input features corresponding to a single image.It should return as output a Python list `output`, indicating the predicted sentence. `output[i]` is a nonnegative integer that identifies the predicted `i`-th token in the sentence. The correspondence between integers and tokens can be explored by examining either `data_loader.dataset.vocab.word2idx` (or `data_loader.dataset.vocab.idx2word`).After implementing the `sample` method, run the code cell below. If the cell returns an assertion error, then please follow the instructions to modify your code before proceeding. Do **not** modify the code in the cell below.
# Move image Pytorch Tensor to GPU if CUDA is available. image = image.to(device) # Obtain the embedded image features. features = encoder(image).unsqueeze(1) # Pass the embedded image features through the model to get a predicted caption. output = decoder.sample(features) print('example output:', output) assert (type(output)==list), "Output needs to be a Python list" assert all([type(x)==int for x in output]), "Output should be a list of integers." assert all([x in data_loader.dataset.vocab.idx2word for x in output]), "Each entry in the output needs to correspond to an integer that indicates a token in the vocabulary."
example output: [0, 3, 2436, 170, 77, 3, 204, 21, 3, 769, 77, 32, 297, 18, 1, 1, 18, 1, 1, 18]
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Step 4: Clean up the CaptionsIn the code cell below, complete the `clean_sentence` function. It should take a list of integers (corresponding to the variable `output` in **Step 3**) as input and return the corresponding predicted sentence (as a single Python string).
# TODO #4: Complete the function. def clean_sentence(output): seperator = " " word_list = []; for word_index in output: if word_index not in [0,2]: # 0: '<start>', 1: '<end>', 2: '<unk>', 18: '.' if word_index == 1: break word = data_loader.dataset.vocab.idx2word[word_index] word_list.append(word) sentence = seperator.join(word_list) return sentence
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
After completing the `clean_sentence` function above, run the code cell below. If the cell returns an assertion error, then please follow the instructions to modify your code before proceeding.
sentence = clean_sentence(output) print('example sentence:', sentence) assert type(sentence)==str, 'Sentence needs to be a Python string!'
example sentence: a giraffe standing in a field with a tree in the background .
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Step 5: Generate Predictions!In the code cell below, we have written a function (`get_prediction`) that you can use to use to loop over images in the test dataset and print your model's predicted caption.
def get_prediction(): orig_image, image = next(iter(data_loader)) plt.imshow(np.squeeze(orig_image)) plt.title('Sample Image') plt.show() image = image.to(device) features = encoder(image).unsqueeze(1) output = decoder.sample(features) sentence = clean_sentence(output) print(sentence)
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Run the code cell below (multiple times, if you like!) to test how this function works.
get_prediction()
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
As the last task in this project, you will loop over the images until you find four image-caption pairs of interest:- Two should include image-caption pairs that show instances when the model performed well.- Two should highlight image-caption pairs that highlight instances where the model did not perform well.Use the four code cells below to complete this task. The model performed well!Use the next two code cells to loop over captions. Save the notebook when you encounter two images with relatively accurate captions.
get_prediction() get_prediction()
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
The model could have performed better ...Use the next two code cells to loop over captions. Save the notebook when you encounter two images with relatively inaccurate captions.
get_prediction() get_prediction()
_____no_output_____
MIT
3_Inference.ipynb
mohamed11981198/udacity-CVND-Image-Captioning
Purpose: To run the full segmentation using the best scored method from 2_compare_auto_to_manual_threshold Date Created: January 7, 2022 Dates Edited: January 26, 2022 - changed the ogd severity study to be the otsu data as the yen data did not run on all samples. *Step 1: Import Necessary Packages*
# import major packages import numpy as np import matplotlib.pyplot as plt import skimage import PIL as Image import os import pandas as pd # import specific package functions from skimage.filters import threshold_otsu from skimage import morphology from scipy import ndimage from skimage.measure import label from skimage import io from skimage import measure
_____no_output_____
MIT
1_microglia_segmentation/OGD_3_full_segmentation_pipeline-Copy1.ipynb
Nance-Lab/microFIBER
__OGD Severity Study__
im_folder_location = '/Users/hhelmbre/Desktop/ogd_severity_undergrad/10_4_21_redownload/' im_paths = [] files = [] for file in os.listdir(im_folder_location): if file.endswith(".tif"): file_name = os.path.join(im_folder_location, file) files.append(file) im_paths.append(file_name) files properties_list = ('area', 'bbox_area', 'centroid', 'convex_area', 'eccentricity', 'equivalent_diameter', 'euler_number', 'extent', 'filled_area', 'major_axis_length', 'minor_axis_length', 'orientation', 'perimeter', 'solidity') source_dir = '/Users/hhelmbre/Desktop/microfiber/ogd_severity_segmentations/' j = 0 for image in im_paths: short_im_name = image.rsplit('/', 1) short_im_name = short_im_name[1] im = io.imread(image) microglia_im = im[:,:,1] #otsu threshold thresh_otsu = skimage.filters.threshold_otsu(microglia_im) binary_otsu = microglia_im > thresh_otsu new_binary_otsu = morphology.remove_small_objects(binary_otsu, min_size=71) new_binary_otsu = ndimage.binary_fill_holes(new_binary_otsu) label_image = measure.label(new_binary_otsu) props = measure.regionprops_table(label_image, properties=(properties_list)) np.save(str(source_dir + short_im_name[:-4] + '_otsu_thresh'), new_binary_otsu) if j == 0: df = pd.DataFrame(props) df['filename'] = image else: df2 = pd.DataFrame(props) df2['filename'] = image df = df.append(df2) j = 1 df['circularity'] = 4*np.pi*df.area/df.perimeter**2 df['aspect_ratio'] = df.major_axis_length/df.minor_axis_length df df.to_csv('/Users/hhelmbre/Desktop/microfiber/ogd_severity_study_features_otsu.csv' ) %load_ext watermark %watermark -v -m -p numpy,pandas,scipy,skimage,matplotlib,wget %watermark -u -n -t -z
Python implementation: CPython Python version : 3.7.4 IPython version : 7.8.0 numpy : 1.21.5 pandas : 1.3.5 scipy : 1.3.1 skimage : 0.17.2 matplotlib: 3.1.1 wget : 3.2 Compiler : Clang 4.0.1 (tags/RELEASE_401/final) OS : Darwin Release : 20.6.0 Machine : x86_64 Processor : i386 CPU cores : 8 Architecture: 64bit Last updated: Wed Jan 26 2022 14:39:49PST
MIT
1_microglia_segmentation/OGD_3_full_segmentation_pipeline-Copy1.ipynb
Nance-Lab/microFIBER
Basic Workflow
# Always have your imports at the top import pandas as pd from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.ensemble import RandomForestClassifier from sklearn.base import TransformerMixin from hashlib import sha1 # just for grading purposes import json # just for grading purposes def _hash(obj, salt='none'): if type(obj) is not str: obj = json.dumps(obj) to_encode = obj + salt return sha1(to_encode.encode()).hexdigest()
_____no_output_____
MIT
stats-279/SLU19 - Workflow/Exercise notebook.ipynb
hershaw/stats-279
Workflow stepsWhat are the basic workflow steps?It's incredibly obvious what the steps are since you can see them graded in plain text. However we deem it worth actually making you type each one of the steps and take a moment to think about it and internalize them.Please do actually type them rather than just copy-pasting as fast as you can. Type it out character by character and internalize.
# step_1 = ... # step_2 = ... # step_2_a = ... # step_2_b = ... # step_2_c = ... # step_2_d = ... # step_3 = ... # step_4 = ... # step_5 = ... # YOUR CODE HERE raise NotImplementedError() ### BEGIN TESTS assert step_1 == 'Get the data' assert step_2 == 'Data analysis and preparation' assert step_2_a == 'Data analysis' assert step_2_b == 'Dealing with data problems' assert step_2_c == 'Feature engineering' assert step_2_d == 'Feature selection' assert step_3 == 'Train model' assert step_4 == 'Evaluate results' assert step_5 == 'Iterate' ### END TESTS
_____no_output_____
MIT
stats-279/SLU19 - Workflow/Exercise notebook.ipynb
hershaw/stats-279
Specific workflow questionsHere are some more specific questions about individual workflow steps.
# True or False, it's super easy to gather your dataset in a production environment # real_world_dataset_gathering_easy = ... # True or False, it's super easy to gather your dataset in the context of the academy # academy_dataset_gathering_easy = ... # True or False, you should try as hard as you can to get the best possible score # on your test set by iterating until you can't get your test set score any higher # by any means possible # test_set_optimization_is_good = ... # True or False, you should choose one metric by which to evaluate your model and # never consider using another one # one_metric_should_rule_them_all = ... # YOUR CODE HERE raise NotImplementedError() ### BEGIN TESTS assert _hash(real_world_dataset_gathering_easy, 'salt1') == '63b5b9a8f2d359e1fc175c3b01b907ef87590484' assert _hash(academy_dataset_gathering_easy, 'salt2') == 'dd7dee495a153c95d28c7aa95289c0415242f5d8' assert _hash(test_set_optimization_is_good, 'salt3') == 'f24a294afb4a09f7f9df9ee13eb18e7d341c439d' assert _hash(one_metric_should_rule_them_all, 'salt4') == '2360691a582e4f0fbefa238ab6ced1cbfbfe8a50' ### END TESTS
_____no_output_____
MIT
stats-279/SLU19 - Workflow/Exercise notebook.ipynb
hershaw/stats-279
scikit pipelinesMake a simple pipeline that1. Drops all columns that start with the string `evil`1. Fills all nulls with the median
# Create a pipeline step called RemoveEvilColumns the removed any # column whose name starts with the string 'evil' # YOUR CODE HERE raise NotImplementedError() # Create an pipeline using make_pipeline # 1. removes evil columns # 2. imputes with the mean # 3. has a random forest classifier as the last step # YOUR CODE HERE raise NotImplementedError() X = pd.DataFrame({ 'evil_1': ['a'] * 100, 'evil_2': ['b'] * 100, 'not_so_evil': list(range(0, 100)) }) y = pd.Series([x % 2 for x in range(0, 100)]) pipeline.fit(X, y) ### BEGIN TESTS assert pipeline.steps[0][0] == 'removeevilcolumns', pipeline.steps[0][0] assert pipeline.steps[1][0] == 'simpleimputer', pipeline.steps[1][0] assert pipeline.steps[2][0] == 'randomforestclassifier', pipeline.steps[2][0] ### END TESTS
_____no_output_____
MIT
stats-279/SLU19 - Workflow/Exercise notebook.ipynb
hershaw/stats-279
import pandas as pd path="https://raw.githubusercontent.com/Sarbajit097/Assignment/main/Toyota.csv" data =pd.read_csv(path) data type(data) data.shape data.info() data.index data.columns data.head() data.tail() data.head(5) data[['Price',"Age"]].head(10) data.isnull().sum() data.dropna(inplace=True) data.isnull().sum() data.shape data.head(10) data['MetColor'].mean() data['MetColor'].head() import numpy as np data['MetColor'].replace(np.NaN,data['MetColor'].mean()).head() data.head(10) data['CC'].mean() data['CC'].head() data[['Age',"KM"]].head(20)
_____no_output_____
Apache-2.0
Assignment_3.ipynb
Sarbajit097/Assignment
For Loop
week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] for x in week: print(x)
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
The Break Statement
week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] for x in week: print(x) if x=="Thursday": break week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] for x in week: if x=="Thursday": break print(x)
Sunday Monday Tuesday Wednesday
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
Looping through string
for x in "Python Programming": print(x)
P y t h o n P r o g r a m m i n g
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
The range () function
for x in range(16): print(x) for x in range(2,16): print(x)
2 3 4 5 6 7 8 9 10 11 12 13 14 15
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
Nested Loops
adjective=["red","big","tasty"] fruits = ["apple","banana","cherry"] for x in adjective: for y in fruits: print(x,y)
red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
While Loop
i=1 while i<=6: print(i) i+=1 #Assignment operator for addition
1 2 3 4 5 6
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
The break statement
i=1 while i<6: print(i) if i==3: break i+=1
1 2 3
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
The continue statement
i = 0 while i<6: i+=1 #Assignment operator for addition if i==3: continue print(i)
1 2 4 5 6
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
The else statement
i = 1 while i<=6: print(i) i+=1 else: print("i is no longer less than 6")
1 2 3 4 5 6 i is no longer less than 6
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
Application 1
#Create a Python program that displays Hello 0 to Hello 10 in vertical sequence hello=["Hello"] num=["0","1","2","3","4","5","6","7","8","9","10"] #for loop for x in hello: for y in num: print(x,y) #while loop i=0 while i<=10: print("Hello",i) i+=1 #Assignment operator to increment i
Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
Application 2
#Create a Python program that displays integers less than 10 but not less than 3 i = 0 while i<10: i+=1 #Assignment operator to increment i if i<3: continue if i==10: break print(i)
3 4 5 6 7 8 9
Apache-2.0
Loop_Statement.ipynb
kathleenmei/CPEN-21A-ECE-2-1
Lab 11: MLP -- exercise Understanding the training loop
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from random import randint import utils
_____no_output_____
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018