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_se...
_____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...
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'].v...
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 LST...
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_feat...
_____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.layer...
_____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_...
_____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) cl...
_____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'] ...
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 Ep...
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 ...
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 parame...
_____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://tour...
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...
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 = ...
: 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, n...
: 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, nrou...
: 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 =...
_____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...
_____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](http...
# %%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 `...
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): ...
_____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 gra...
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 f...
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 ...
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): ...
_____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 == ...
_____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...
_____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...
_____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)#, n...
_____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")...
_____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...
_____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_cen...
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_i...
_____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): prin...
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_s...
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']...
_____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-3...
_____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 ...
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="Origina...
_____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 p...
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...
_____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 te...
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='--',c...
_____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 AC...
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_lo...
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...
#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_AR...
_____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.ex...
_____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 ...
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, ...
%%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), SpeedPe...
_____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...
# 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 sim...
%%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...
%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 *Whe...
%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), SpeedPe...
_____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...
%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...
_____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)...
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), # sma...
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 name...
# 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 ...
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 `o...
# 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 (ty...
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....
_____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(sent...
_____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 ...
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 skim...
_____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 prop...
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 Process...
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...
_____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-pas...
# 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...
_____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 ...
_____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 C...
_____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(...
_____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