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
Train multi-class multi-label model
clf = OneVsRestClassifier(RandomForestClassifier(n_jobs=-1, n_estimators=100, max_depth=10, random_state=42)) clf.fit(X_train, y_train_genres) y_pred_genres = clf.predict_proba(X_test) roc_auc_score(y_test_genres, y_pred_genres, average='macro')
_____no_output_____
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass
Apply models to kaggle test
X_test_dtm = vect.transform(dataTesting['plot']) cols = ['p_Action', 'p_Adventure', 'p_Animation', 'p_Biography', 'p_Comedy', 'p_Crime', 'p_Documentary', 'p_Drama', 'p_Family', 'p_Fantasy', 'p_Film-Noir', 'p_History', 'p_Horror', 'p_Music', 'p_Musical', 'p_Mystery', 'p_News', 'p_Romance', 'p_Sci-Fi', '...
_____no_output_____
MIT
finalProject/ExampleTextRF.ipynb
Tionick/AppliedDeepLearningClass
Classification
from nltk.corpus import reuters import spacy import re import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import MultiLabelBinarizer from sklearn.svm import LinearSVC from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import f1_score, precisio...
_____no_output_____
Apache-2.0
Classification_Reuters.ipynb
miguelmalvarez/reuters-tc
This notebook contains Hovmoller plots that compare the model output over many different depths to the results from the ORCA Buoy data.
import sys sys.path.append('/ocean/kflanaga/MEOPAR/analysis-keegan/notebooks/Tools') import numpy as np import matplotlib.pyplot as plt import os import pandas as pd import netCDF4 as nc import xarray as xr import datetime as dt from salishsea_tools import evaltools as et, viz_tools, places import gsw import matplotli...
_____no_output_____
Apache-2.0
notebooks/Evaluations/Continuous_Timeseries/All_Depths_ORCA/Hansville/201905_Hindcast/2015_Hansville_Evaluations.ipynb
SalishSeaCast/analysis-keegan
Map of Buoy Location.
lon,lat=places.PLACES[mooring]['lon lat'] fig, ax = plt.subplots(1,1,figsize = (6,6)) with nc.Dataset('/data/vdo/MEOPAR/NEMO-forcing/grid/bathymetry_201702.nc') as bathy: viz_tools.plot_coastline(ax, bathy, coords = 'map',isobath=.1) color=('firebrick') ax.plot(lon, lat,'o',color = 'firebrick', label=mooring) ax.s...
_____no_output_____
Apache-2.0
notebooks/Evaluations/Continuous_Timeseries/All_Depths_ORCA/Hansville/201905_Hindcast/2015_Hansville_Evaluations.ipynb
SalishSeaCast/analysis-keegan
Temperature
df,dep,tim= Process_ORCA(orca_dict['Btemp'],obs_dep,YD_rounded,year) date_range=(dt.datetime(year,1,1),dt.datetime(year,12,31)) ax=ket.hovmoeller(df,dep,tim,(2,15),date_range,title='Observed Temperature Series', var_title='Temperature (C$^0$)',vmax=23,vmin=8,cmap=cmo.cm.thermal) ax=ket.hovmoeller(mod...
/ocean/kflanaga/MEOPAR/analysis-keegan/notebooks/Tools/Keegan_eval_tools.py:816: UserWarning: 'set_params()' not defined for locator of type <class 'matplotlib.dates.AutoDateLocator'> plt.locator_params(axis="x", nbins=20)
Apache-2.0
notebooks/Evaluations/Continuous_Timeseries/All_Depths_ORCA/Hansville/201905_Hindcast/2015_Hansville_Evaluations.ipynb
SalishSeaCast/analysis-keegan
Salinity
df,dep,tim= Process_ORCA(orca_dict['Bsal'],obs_dep,YD_rounded,year) ax=ket.hovmoeller(df,dep,tim,(2,15),date_range,title='Observed Absolute Salinity Series', var_title='SA (g/kg)',vmax=31,vmin=14,cmap=cmo.cm.haline) ax=ket.hovmoeller(mod_vosaline, mod_depth, tt, (2,15),date_range,title='Modeled Absolute...
_____no_output_____
Apache-2.0
notebooks/Evaluations/Continuous_Timeseries/All_Depths_ORCA/Hansville/201905_Hindcast/2015_Hansville_Evaluations.ipynb
SalishSeaCast/analysis-keegan
** Iniciando a contrução do pipeline do algoritmo **
# aplicando o modelo de validação cruzada # divide o dataset entre 5 diferentes grupos kfold = KFold(n_splits=5, shuffle=True, random_state=42) print(kfold.get_n_splits()) # construindo os modelos de classificação modelos = [LogisticRegression(solver='liblinear'), RandomForestClassifier(n_estimators=400, random_state=4...
_____no_output_____
CC0-1.0
Mod1/app_comparacao_modelo_cap_4/cap4FAM.ipynb
spedison/Curso_igti_ML
**Realizando a previsão dos classificadores** ** Quais algoritmos escollher?**
# Dividindo o dataset entre treinamento 80% e teste 20% x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, stratify=y, shuffle=True, random_state=42) #escolhendo o svm e a floresta randomica svm_clf = svm.SVC(C=0.9, gamma=0.1, kernel='rbf', prob...
_____no_output_____
CC0-1.0
Mod1/app_comparacao_modelo_cap_4/cap4FAM.ipynb
spedison/Curso_igti_ML
Blue Food Visualizing protein supply and how the practices generating that protein supply affect the ocean using a heirarchical relationship.Note that this is a parameterized widget; the specification passed to the API will not be renderable without the geostore identifier being inserted. *Author: Rachel ThomsCreated...
import json from vega import Vega from IPython.display import display def Vega(spec): bundle = {} bundle['application/vnd.vega.v5+json'] = spec display(bundle, raw=True) widget_width = 600 widget_height = 600
_____no_output_____
MIT
widgets/ocn_calcs_015_blue_food_protein_supply/blue_food_visulization.ipynb
resource-watch/ocean-watch-data
Visualization Queries Testing ``` gid_0 = 'JPN' ``` used as stand-in for parameterized ```geostore_id={{geostore_id}}``` in production version ```sqlSELECT alias.iso as gid_0, data.area, year, item as id, parent, size, value as protein, analysis_category, product FROM (SELECT * FROM foo_061_rw1_blue_food_supply_...
spec=json.loads("""{ "$schema": "https://vega.github.io/schema/vega/v5.json", "padding": 5, "autosize": "pad", "signals": [ { "name": "year", "value": 2018, "bind": {"input": "range", "min": 1961, "max": 2018, "step": 1} } ], "data": [ { "name": "table", "url": "htt...
_____no_output_____
MIT
widgets/ocn_calcs_015_blue_food_protein_supply/blue_food_visulization.ipynb
resource-watch/ocean-watch-data
Rossler performance experiments
import numpy as np import torch import sys sys.path.append("../") import utils as utils import NMC as models import importlib
_____no_output_____
MIT
experiments/Paper_experiments_Rossler.ipynb
vanderschaarlab/Graphical-modelling-continuous-time
SVAM
# LiNGAM / SVAM performance with sparse data import warnings warnings.filterwarnings("ignore") for p in [10, 50]: perf = [] for i in range(20): # Simulate data T = 1000 num_points = T data, GC = utils.simulate_rossler(p=p, a=0, T=T, delta_t=0.1, sd=0.05, burn_in=0, sigma=0.0) ...
Means and standard deviations for TPR, FDR and AUC with 10 dimensions [0.77368421 0.53953499 0.49996751] [0.10273274 0.06081473 0.02438485] Means and standard deviations for TPR, FDR and AUC with 50 dimensions [0.59141414 0.66847463 0.49049291] [0.10153776 0.06151317 0.02785143]
MIT
experiments/Paper_experiments_Rossler.ipynb
vanderschaarlab/Graphical-modelling-continuous-time
DCM
# DCM performance with sparse data for p in [10, 50]: perf = [] for i in range(10): # Simulate data T = 1000 num_points = T data, GC = utils.simulate_rossler(p=p, a=0, T=T, delta_t=0.1, sd=0.05, burn_in=0, sigma=0.0) from benchmarks.DCM import DCM_full graph = D...
Means and standard deviations for TPR, FDR and AUC with 10 dimensions [0.779 0.452 0.864] [0.135 0.115 0.092] Means and standard deviations for TPR, FDR and AUC with 50 dimensions [0.97 0.716 0.983] [2.220e-16 1.151e-01 8.450e-04]
MIT
experiments/Paper_experiments_Rossler.ipynb
vanderschaarlab/Graphical-modelling-continuous-time
PCMCI
# pcmci performance with sparse data for p in [10, 50]: perf = [] for i in range(5): # Simulate data T = 1000 num_points = T data, GC = utils.simulate_rossler(p=p, a=0, T=T, delta_t=0.1, sd=0.05, burn_in=0, sigma=0.0) from benchmarks.pcmci import pcmci importlib...
Could not import packages for CMIknn and GPDC estimation Could not import r-package RCIT Means and standard deviations for TPR, FDR and AUC with 10 dimensions [0.768 0.76 0.597] [0.123 0.041 0.083] Means and standard deviations for TPR, FDR and AUC with 50 dimensions [0.685 0.925 0.668] [0.068 0.006 0.018]
MIT
experiments/Paper_experiments_Rossler.ipynb
vanderschaarlab/Graphical-modelling-continuous-time
NGM
# NGM performance with sparse data import warnings warnings.filterwarnings("ignore") for p in [10, 50]: perf = [] for i in range(5): # Simulate data T = 1000 num_points = T data, GC = utils.simulate_rossler(p=p, a=0, T=T, delta_t=0.1, sd=0.05, burn_in=0, sigma=0.0) # fo...
Means and standard deviations for TPR, FDR and AUC with 10 dimensions [0.863 0. 0.932] [0.026 0. 0.013] Means and standard deviations for TPR, FDR and AUC with 50 dimensions [0.974 0.11 0.987] [0.005 0.043 0.002]
MIT
experiments/Paper_experiments_Rossler.ipynb
vanderschaarlab/Graphical-modelling-continuous-time
Copyright 2019 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License");
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
探索 TF-Hub CORD-19 Swivel 嵌入向量 在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 中查看源代码 {img1下载笔记本 TF-Hub (https://tfhub.dev/tensorflow/cord-19/swivel-128d/3) 上的 CORD-19 Swivel 文本嵌入向量模块旨在支持研究员分析与 COVID-19 相关的自然语言文本。这些嵌入针对 [CORD-19 数据集](https://pages.semanticscholar.org/coronavirus-research)中文章的标题、作者、摘要、正文文本和参考文献标...
import functools import itertools import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_hub as hub from tqdm import trange
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
分析嵌入向量首先,我们通过计算和绘制不同术语之间的相关矩阵来分析嵌入向量。如果嵌入向量学会了成功捕获不同单词的含义,则语义相似的单词的嵌入向量应相互靠近。我们来看一些与 COVID-19 相关的术语。
# Use the inner product between two embedding vectors as the similarity measure def plot_correlation(labels, features): corr = np.inner(features, features) corr /= np.max(corr) sns.heatmap(corr, xticklabels=labels, yticklabels=labels) # Generate embeddings for some terms queries = [ # Related viruses 'corona...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
可以看到,嵌入向量成功捕获了不同术语的含义。每个单词都与其所在簇的其他单词相似(即“coronavirus”与“SARS”和“MERS”高度相关),但与其他簇的术语不同(即“SARS”与“Spain”之间的相似度接近于 0)。现在,我们来看看如何使用这些嵌入向量解决特定任务。 SciCite:引用意图分类本部分介绍了将嵌入向量用于下游任务(如文本分类)的方法。我们将使用 TensorFlow 数据集中的 [SciCite 数据集](https://tensorflow.google.cn/datasets/catalog/scicite)对学术论文中的引文意图进行分类。给定一个带有学术论文引文的句子,对引文的主要意图进行分类:是背...
builder = tfds.builder(name='scicite') builder.download_and_prepare() train_data, validation_data, test_data = builder.as_dataset( split=('train', 'validation', 'test'), as_supervised=True) #@title Let's take a look at a few labeled examples from the training set NUM_EXAMPLES = 10#@param {type:"integer"} TEX...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
训练引用意图分类器我们将使用 Keras 在 [SciCite 数据集](https://tensorflow.google.cn/datasets/catalog/scicite)上对分类器进行训练。我们构建一个模型,该模型使用 CORD-19 嵌入向量,并在顶部具有一个分类层。
#@title Hyperparameters { run: "auto" } EMBEDDING = 'https://tfhub.dev/tensorflow/cord-19/swivel-128d/3' #@param {type: "string"} TRAINABLE_MODULE = False #@param {type: "boolean"} hub_layer = hub.KerasLayer(EMBEDDING, input_shape=[], dtype=tf.string, trainable=TRAINABLE_MODULE) model =...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
训练并评估模型让我们训练并评估模型以查看在 SciCite 任务上的性能。
EPOCHS = 35#@param {type: "integer"} BATCH_SIZE = 32#@param {type: "integer"} history = model.fit(train_data.shuffle(10000).batch(BATCH_SIZE), epochs=EPOCHS, validation_data=validation_data.batch(BATCH_SIZE), verbose=1) from matplotlib import pyplot as plt ...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
评估模型我们来看看模型的表现。模型将返回两个值:损失(表示错误的数字,值越低越好)和准确率。
results = model.evaluate(test_data.batch(512), verbose=2) for name, value in zip(model.metrics_names, results): print('%s: %.3f' % (name, value))
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
可以看到,损失迅速减小,而准确率迅速提高。我们绘制一些样本来检查预测与真实标签的关系:
prediction_dataset = next(iter(test_data.batch(20))) prediction_texts = [ex.numpy().decode('utf8') for ex in prediction_dataset[0]] prediction_labels = [label2str(x) for x in prediction_dataset[1]] predictions = [label2str(x) for x in model.predict_classes(prediction_texts)] pd.DataFrame({ TEXT_FEATURE_NAME: pr...
_____no_output_____
Apache-2.0
site/zh-cn/hub/tutorials/cord_19_embeddings_keras.ipynb
NarimaneHennouni/docs-l10n
Polynomial Regression and Cross ValidationFor the first assignment we will do something that might seem familiar from *Probability Theory for Machine Learning*; try to fit a polynomial function to a provided dataset. Fitting a function is a quintessential example of *supervised learning*, specifically *regression*, ma...
%matplotlib inline import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt from IPython.display import YouTubeVideo
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Loading the data [1 pt]Write a function to read the data stored in the file `points.csv` and convert it to a *Numpy* array. Each line in the file is a data point consisting of an **x**-value and **r**-value, separated by a comma. You could use Numpy's [loadtxt](https://docs.scipy.org/doc/numpy/reference/generated/nump...
# YOUR SOLUTION HERE data = np.loadtxt('points.csv', delimiter=',') data
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Plotting the points [2 pt]Write a function `split_X_r` to separate your `data` into an X matrix and a R matrix using [slicing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html).Using both vectors, create a graph containing the plotted points you just read from the file. For this you can use the *matplot...
def split_X_R(data): # YOUR SOLUTION HERE X = np.array([data[:,0]]).T R = np.array([data[:,1]]).T return X, R # YOUR SOLUTION HERE X, R = split_X_R(data) plt.scatter(X, R) plt.show()
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Defining the linear model [1 pt]Now we are going to try to find the function which best relates these points. We will start by fitting a simple linear function of the form(2.15) $$g(x) = w_1x + w_0$$*For more detailed description of linear regression, watch Andrew's videos on the topic. The notation is slightly differ...
display(YouTubeVideo('ls7Ke48jCt8')) display(YouTubeVideo('PBZUjnGuXjA'))
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Now write a function that computes the predicted output value $g(x)$ given a value of $x$ and the parameters $w_0$ and $w_1$. This should be very straightforward, but make sure you understand what part this plays in our supervised learning problem before moving on.
def linear_model(w0, w1, x): # YOUR SOLUTION HERE return w0+w1*x
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Creating the cost function [2 pt]The cost function is defined as the sum of the squared errors of each prediction(2.16) $$E(w_1, w_0|X) = \frac{1}{N}\sum^N_{t=1} [r^t - (w_1x^t + w_0)]^2$$*These videos are great for building intuition on the relation between the hypothesis function and the associated cost of that hypo...
display(YouTubeVideo('EANr4YttXIQ')) display(YouTubeVideo('J5vJFwQWOaY'))
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Write a function to compute the cost based on the dataset $X$, $R$ and parameters $w_0$ and $w_1$. Based on your plot of the data, try to estimate some sensible values for $w_0$ and $w_1$ and compute the corresponding cost. Try at least 3 different guesses and print their cost. Order the prints of your guesses from hig...
def linear_cost(w0, w1, X, R): # YOUR SOLUTION HERE return np.sum((w0+w1*X-R)**2)/len(R) # Guess 1 w0=-200, w1=100 print(linear_cost(-200, 100, X, R)) # Guess 2 w0=-100, w1=10 print(linear_cost(-100, 10, X, R)) # Guess 3 w0=0, w1=0 print(linear_cost(0, 0, X, R))
125813.8834593852 74055.22824945165 55279.41576950028
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Fitting the linear model [4 pt]We can find the minimum value of the cost function by taking the partial derivatives of that cost function for both of the weights $w_0$ and $w_1$ and setting them equal to $0$, resulting in the equations(2.17a) $$w_1 = \frac{\sum_tx^tr^t - \bar{x}\bar{r}N}{\sum_t(x^t)^2 - N\bar{x}^2}$$(...
def linear_fit(X, R, N): # YOUR SOLUTION HERE xbar = np.mean(X) rbar = np.mean(R) w1 = (np.sum(X*R) - xbar*rbar*N) / (np.sum(X**2) - N*xbar**2) w0 = rbar - w1*xbar return w0,w1 # YOUR SOLUTION HERE plt.scatter(X, R) w0,w1 = linear_fit(X, R, len(R)) y1 = linear_model(w0, w1, -5) y2 = linear_model...
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Polynomial data [3 pt]The linear model can easily be extended to polynomials of any order by expanding the original input with the squared input $x^2$, the cubed input $x^3$, etc and adding additional weights to the model. For ease of calculation, the input is also expanded with a vector of $1$'s, to represent the inp...
def create_D_matrix(X, k): # YOUR SOLUTION HERE return np.array([X.reshape(len(X),)**i for i in range(k+1)]).T D = create_D_matrix(X, 2)
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Polynomial model [2 pt]The parameters can now be represented as$$ w = \left[\begin{array}{c} w_0 \\ w_1 \\ \vdots \\ w_k \end{array} \right]$$The hypothesis for a single input then just becomes$$ g(x^1) = \sum_{i=0}^k D^1_iw_i $$Which can write as a matrix multiplication for all inputs in a single equation$$ \left[\be...
def poly_val(x, W): # YOUR SOLUTION HERE return np.dot(np.array([x**i for i in range(len(W))]),W) def poly_model(D, W): # YOUR SOLUTION HERE return np.dot(D, W)
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Polynomial cost function and model fitting [3 pts]And for the cost function we can now use$$ E(w|X) = \frac{1}{2N} \sum_{t=1}^N [r^t - D^tw]^2$$Here, we compute the hypothesis $g(x)$ for every example using $D^tw$, take the difference with the actual output $r$ and finally square and sum each difference. Note that thi...
def poly_cost(W, D, R): # YOUR SOLUTION HERE return np.sum((R - np.dot(D,W))**2) / (2*len(R)) def poly_fit(D, R): # YOUR SOLUTION HERE return np.dot(np.dot(inv(np.dot(np.transpose(D),D)),np.transpose(D)),R) # YOUR SOLUTION HERE W = poly_fit(D, R) print(W)
[[-56.87348684] [ 52.14107002] [ 16.02439317]]
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Plotting polynomials [1 pt]Now lets try and figure out what our fitted quadratic polynomial looks like. As the function is not linear, we will need more than just 2 points to actually plot the line. The easiest solution is to create a whole bunch of x-values as samples, compute the corresponding y-values and plot thos...
def poly_plot(W, X, R): # YOUR SOLUTION HERE x = np.linspace(-5,5,100) y = [poly_val(xi, W) for xi in x] plt.scatter(X,R) plt.plot(x, y) plt.show() poly_plot(W, X, R)
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Polynomial order [1 pt]You can now create a polynomial fit on the data for a polynomial of any order. The next question then becomes: *What order polynomial fits the data the best?*Using the `create_D_matrix`, `poly_fit` and `poly_plot`, try to fit different order polynomials to the data. Show the plot for the order p...
# YOUR SOLUTION HERE D = create_D_matrix(X, 4) W = poly_fit(D, R) poly_plot(W, X, R)
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Cross validation [2 pt]Another way to answer this same question is to use cross validation. With cross validation you split the data into 2 parts and use one part to fit the model (training set) and the other part to see how well the model fits the remaining data (validation set). This way, we can select a model that ...
def validation_split(data, ratio): # YOUR SOLUTION HERE np.random.shuffle(data) n = int(ratio*len(data)) training_set = data[:n, :] validation_set = data[n:, :] return training_set, validation_set # YOUR SOLUTION HERE training_set, validation_set = validation_split(data, 0.6) train_x, train_r = ...
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Model selection [5 pt]With this new split of the data you can just repeatedly fit different order polynomials to the training set and see which produces the lowest cost on the validation set. The set of weights with the lowests cost on the validation set generalizes the best to new data and is thus the best overal fit...
def best_poly_fit(train_x, train_r, val_x, val_r): # YOUR SOLUTION HERE lowest_cost = float('inf') best_w = 0 for k in range(1,51): train_D = create_D_matrix(train_x, k) W = poly_fit(train_D, train_r) val_D = create_D_matrix(val_x, k) cost = poly_cost(W, val_D, val_r) ...
_____no_output_____
MIT
Jiang_Assignment_1/Jiang_Assignment_1.ipynb
snowhite2018/Leren
Exploring Reddit with the pushshift APIThis notebook give you examples of how to use the pushshift API for querying Reddit data.* Pushshift doc: https://github.com/pushshift/api* FAQ about Pushshift: https://www.reddit.com/r/pushshift/comments/bcxguf/new_to_pushshift_read_this_faq/
import requests import pandas as pd
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
We define a convenient function to get data from Pushshift:
def get_pushshift_data(data_type, params): """ Gets data from the pushshift api. data_type can be 'comment' or 'submission' The rest of the args are interpreted as payload. Read more: https://github.com/pushshift/api This function is inspired from: https://www.jcchouinard.com/how-to...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
This function accepts the parameters of the pushshift API detailed in the doc at https://github.com/pushshift/api. An example is given below. Example of request to the APILet us collect the comments written in the last 2 day in the subreddit `askscience`. The number of results returned is limited to 100, the upper lim...
# parameters for the pushshift API data_type = "comment" # accept "comment" or "submission", search in comments or submissions params = { "subreddit" : "askscience", # limit to one or a list of subreddit(s) "after" : "2d", # Select the timeframe. Epoch value or Integer + "s,m,h,d" (i.e. "second", "minute", "...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
Authors of commentsLet us collect the authors of comments in a subreddit during the last days. The next function helps bypassing the limit of results by sending queries multiple times, avoiding collecting duplicate authors.
# Get the list of unique authors of comments in the API results # bypass the limit of 100 results by sending multiple queries def get_unique_authors(n_results, params): results_per_request = 100 # default nb of results per query n_queries = n_results // results_per_request + 1 author_list = [] author_ne...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
Network of subreddits (ego-graph)Let us build the ego-graph of the subreddit. Other subreddits will be connected to the main one if the users commented in the other subreddits as well.
# module for networks import networkx as nx threshold = 0.05 G = nx.Graph() G.add_node(subreddit) self_refs = subreddits_count[subreddit] for sub,value in subreddits_count.items(): post_ratio = value/self_refs if post_ratio >= threshold: G.add_edge(subreddit,sub, weight=post_ratio) print("Total number o...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
Here is an alternative way of generating the graph using pandas dataframes instead of a for loop (it might scale better on bigger graphs).
threshold = 0.05 subreddits_count_df = pd.DataFrame.from_dict(subreddits_count, orient='index', columns=['total']) subreddits_ratio_df = subreddits_count_df/subreddits_count_df.loc[subreddit] subreddits_ratio_df.rename(columns={'total': 'weight'}, inplace=True) filtered_sr_df = subreddit_ratio_df[subreddits_ratio_df['w...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
Network of subreddit neighborsThis second collection makes a distinction between the related subreddits. For each author, all the subreddits where he/she commented will be connected together. The weight of each connection will be proportional to the number of users commenting in both subreddits joined by the connectio...
data_type = "comment" params = { "size" : 100 } count_list = [] for author in author_list: params["author"] = author print(params["author"]) data = get_pushshift_data(data_type=data_type, params=params) if data: df = pd.DataFrame.from_records(data) count_list.append(Counter(dict(df['...
_____no_output_____
MIT
05_Reddit_Pushshift_API.ipynb
mizvol/GraphMining-TheWebConf2021
PyTorch: Tensors----------------A fully-connected ReLU network with one hidden layer and no biases, trained topredict y from x by minimizing squared Euclidean distance.This implementation uses PyTorch tensors to manually compute the forward pass,loss, and backward pass.A PyTorch Tensor is basically the same as a numpy ...
import torch dtype = torch.float # device = torch.device("cpu") device = torch.device("cuda:1") # Uncomment this to run on GPU # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data x = torch.randn(N...
0 29266960.0 1 25477014.0 2 27260208.0 3 30241428.0 4 30207164.0 5 25019268.0 6 16550626.0 7 9194384.0 8 4705195.0 9 2503613.25 10 1491022.125 11 1013848.625 12 764834.1875 13 615944.9375 14 514465.5625 15 438525.125 16 378407.875 17 329093.71875 18 287852.5 19 252939.140625 20 223106.5625 21 197447.125 22 175266.23437...
MIT
examples/2_two_layer_net_tensor.ipynb
spencerpomme/torchlight
CME Smart Stream on Google Cloud Platform Tutorials Getting CME Binary Data from CME Smart Stream on Google Cloud Platform (GCP)This workbook demonstrates the ability to quickly use the CME Smart Stream on GCP solution. Through the examples, we will - Authenticate using GCP IAM information- Configure which CME Smart ...
#import packages. These are outlined in the environment.ymal file as part of this project. #these can also be directly imported. # Google SDK: https://cloud.google.com/sdk/docs/quickstarts # Google PubSub: https://cloud.google.com/pubsub/docs/reference/libraries from google.cloud import pubsub_v1 import os import g...
_____no_output_____
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Authentication using Google IAMCME Smart Stream uses Google Cloud native Idenity and Accesss Management (IAM) solutions. Using this approach, customers are able to natively access CME Smart Stream solution without custom SDK's or authentication routines. All the code in this workboard is native Google Python SDK. W...
## Authentication Method Options -- SERVICE ACCOUNT JSON FILE # This should point to the file location of the json file downloaded from GCP console. This will load it into your os variables and be automtically leverage when your system interacts with GCP. #os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "./gcp-auth.js...
_____no_output_____
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Authentication for User AccountThis section is for customers that registered thier GCP User Account (i.e. user@domain.com). This routine will launch the OS SDK to authenticate you as that user and then set it as your default credentials for the rest of the workflow when interacting with GCP. IN OS TERMINAL: 'gcloud ...
## Authentication Method User Machine Defaults # #Run "gcloud auth login" in command line and login as the user. The code below will do that automatically. #It should laucnh a browser to authenticate into GCP that user name and associated permissions will be used in the remaining of the code below # This code will p...
/anaconda3/envs/python3/lib/python3.7/site-packages/google/auth/_default.py:66: UserWarning: Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud ...
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Set Your Smart Stream on GCP Projects and Topics Set CME Smart Stream Project CME Smart Stream on GCP data is avaliable in two GCP Projects based upon Production and Non-Production (i.e. certification and new release) data. Customers are granted access to projects through the onboarding process. The example below se...
#This is the project at CME os.environ['GOOGLE_CLOUD_PROJECT_CME'] = "cmegroup-marketdata-newrel" #CERT and NEW RELEASE #os.environ['GOOGLE_CLOUD_PROJECT_CME'] = "cmegroup-marketdata" #PRODUCTION
_____no_output_____
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Set CME Smart Stream TopicsCME Smart Stream on GCP follows the traditional data segmentation of the CME Multicast solution. Each channel on Multicast is avaliable as a Topic in Google Cloud PubSub. This workbook will create 1 subscription in the customer's account against 1 Topic from the CME project. Clearly, custo...
# The CME TOPIC that a Subscription will be created against os.environ['GOOGLE_CLOUD_TOPIC_CME'] = "CERT.SSCL.GCP.MD.RT.CMEG.FIXBIN.v01000.INCR.310" #CERT #s.environ['GOOGLE_CLOUD_TOPIC_CME'] = "NR.SSCL.GCP.MD.RT.CMEG.FIXBIN.v01000.INCR.310" #NEW RELEASE #os.environ['GOOGLE_CLOUD_TOPIC_CME'] = "CERT.SSCL.GCP.MD.RT.CME...
_____no_output_____
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Set Customer Configurations Set Customer Project & Subscription NameSmart Stream on GCP solution requires that the customer create a Cloud Pub/Sub Subscription in thier account. This subscription will automatically collect data from the CME Smart Stream Pub/Sub Topic. Since the Subscriptin is in the customer account...
#Your Configurations for the project you want to have access; #will use the defaults from credentials os.environ['GOOGLE_CLOUD_PROJECT'] = "prefab-rampart-794" #My Subscipription Name -- Take the CME Topic Name and prepend 'MY_' -- Can be any thing the customer wants os.environ['MY_SUBSCRIPTION_NAME'] = 'MY_'+os.env...
_____no_output_____
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Final ConfigurationThe following is the final configuration for your setup.
print ('Target Project: \t',os.environ['GOOGLE_CLOUD_PROJECT_CME'] ) print ('Target Topic: \t\t', os.environ['GOOGLE_CLOUD_TOPIC_CME'] , '\n' ) print ('My Project: \t\t',os.environ['GOOGLE_CLOUD_PROJECT']) print ('My Subscriptions: \t',os.environ['MY_SUBSCRIPTION_NAME'] )
Target Project: cmegroup-marketdata-newrel Target Topic: CERT.SSCL.GCP.MD.RT.CMEG.FIXBIN.v01000.INCR.310 My Project: prefab-rampart-794 My Subscriptions: MY_CERT.SSCL.GCP.MD.RT.CMEG.FIXBIN.v01000.INCR.310
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Create Your Subscription to CME Smart Stream Data TopicsWe have all the main variables set and can pass them to the Cloud Pub/Sub Python SDK. The following attempts to create a Subscription (MY_SUBSCRIPTION_NAME) in your specified project (GOOGLE_CLOUD_PROJECT) that points to the CME Topic (GOOGLE_CLOUD_TOPIC_CME) an...
#https://googleapis.github.io/google-cloud-python/latest/pubsub/#subscribing #Create Topic Name from Config Above topic_name = 'projects/{cme_project_id}/topics/{cme_topic}'.format( cme_project_id=os.getenv('GOOGLE_CLOUD_PROJECT_CME'), cme_topic=os.getenv('GOOGLE_CLOUD_TOPIC_CME'), ) #Create Subscription Name from ...
Created Subscriptions in Project Listing Subscriptions in Your Project prefab-rampart-794 : projects/prefab-rampart-794/subscriptions/ALEXDEMO_CERT.SSCL.GCP.MD.RT.CMEG.FIXBIN.v01000.INCR.310
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Subscription View in Google Cloud ConsoleSubscriptions are also avaliable for viewing in Google Cloud Console (https://console.cloud.google.com/). Navigate to Cloud Pub/Sub and click Subscription. If you click your Subscription Name, it will open up the details about that Subscription. You can see the all queued me...
#Pull 1 Message print ('Pulling a Single Message and Displaying:') CME_DATA = subscriber.pull(subscription_name, max_messages=1) #Print that Message print (CME_DATA)
Pulling a Single Message and Displaying: received_messages { ack_id: "TgQhIT4wPkVTRFAGFixdRkhRNxkIaFEOT14jPzUgKEURAQgUBXx9cUFPdVVeGgdRDRlyfGcjbAkXUgRGVnlVWRENem1cVzhYDxl7e2F2bl4VAwpHUn13wszCqPLBIR1tNY2h8KFASony3-N2Zho9XxJLLD5-PT1FQV5AEkw2CERJUytDCypYEQ" message { data: ":|\027\000\353\336\260\266\260n\346\025@\...
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Delete SubscriptionsYou can also use the Python SDK to delete your Cloud Pub/Sub Subscriptions. The following will attempt to delete ALL the subscriptions in your Project.
#List Subscriptions in My Project / Delete Subscription delete = True subscriber = pubsub_v1.SubscriberClient() project_path = subscriber.project_path(os.environ['GOOGLE_CLOUD_PROJECT']) if not delete: print ('Did you mean to Delete all Subscriptions? If yes, then set delete = True') for subscription in subsc...
/anaconda3/envs/python3/lib/python3.7/site-packages/google/auth/_default.py:66: UserWarning: Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud ...
BSD-3-Clause
Tutorials/GooglePubSubGetCMEBinaryData.ipynb
CMEGroup/CMESmartStream-on-GCP-Tutorial
Load paradigm parameters
prdm_fname = os.path.join(sbj_dir,'03_events',SBJ+'_prdm_vars.pkl') with open(prdm_fname, 'rb') as f: prdm = pickle.load(f)
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Load Log Info
behav_fname = os.path.join(sbj_dir,'03_events',SBJ+'_behav.csv') data = pd.read_csv(behav_fname) # Remove second set of training trials in restarted runs (EEG12, EEG24, EEG25) if len(data[(data['Trial']==0) & (data['Block']==-1)])>1: train_start_ix = data[(data['Trial']==0) & (data['Block']==-1)].index train_ix...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Add specific analysis computations
# Find middle of blocks to plot accuracy block_start_ix = data[data['Trial']==0].index if SBJ=='EP11':#deal with missing BT_T0 block_mid_ix = [ix+prdm['n_trials']/2 for ix in block_start_ix] else: block_mid_ix = [ix+prdm['n_trials']/2 for ix in block_start_ix[1:]] # Add in full_vis + E/H training: 0:4 + 5:19 =...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Plot Full Behavior Across Dataset
# Accuracy, Ratings, and Tolerance f, ax1 = plt.subplots() x = range(len(data)) plot_title = '{0} Tolerance and Accuracy: easy={1:0.3f}; hard={2:0.3f}'.format( SBJ, data[data['Condition']=='easy']['Hit'].mean(), data[data['Condition']=='hard']['Hit'].mean()) colors = {'easy': [0.5, ...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Plot only real data (exclude examples + training)
data_all = data # Exclude: Training/Examples, non-responses, first trial of each block if data[data['RT']<0].shape[0]>0: print 'WARNING: '+str(data[data['RT']<0].shape[0])+' trials with no response!' data = data[(data['Block']!=-1) & (data['RT']>0) & (data['ITI']>0)]
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Histogram of ITIs
# ITI Histogram f,axes = plt.subplots(1,2) bins = np.arange(0,1.1,0.01) hist_real = sns.distplot(data['ITI'],bins=bins,kde=False,label=SBJ,ax=axes[0]) hist_adj = sns.distplot(data['ITI type'],bins=bins,kde=False,label=SBJ,ax=axes[1]) axes[0].set_xlim([0, 1.1]) axes[1].set_xlim([0, 1.1]) plt.subplots_adjust(top=0.93) f...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Histogram of all RTs
# RT Histogram f,ax = plt.subplots() hist = sns.distplot(data['RT'],label=SBJ) plt.subplots_adjust(top=0.9) hist.legend() # can also get the figure from plt.gcf() plt.savefig(results_dir+'BHV/RTs/histograms/'+SBJ+'_RT_hist'+fig_type)
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
RT Histograms by ITI
# ANOVA for RT differences across ITI itis = np.unique(data['ITI type']) if len(prdm['ITIs'])==4: f,iti_p = scipy.stats.f_oneway(data.loc[data['ITI type']==itis[0],('RT')].values, data.loc[data['ITI type']==itis[1],('RT')].values, data.loc[data['ITI type...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
RT adjustment after being short vs. long
# t test for RT differences across ITI itis = np.unique(data['ITI type']) f,postlong_p = scipy.stats.ttest_ind(data.loc[data['postlong']==True,('dRT')].values, data.loc[data['postlong']==False,('dRT')].values) f, axes = plt.subplots(1,2) # RT Histogram drt_bins = np.arange(-0.6,0.6,0.025) s...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
RT and Accuracy Effects by ITI and across post-error
# RTs by condition # if len(prdm_params['ITIs'])==4: # target_time v1.8.5+ # data['ITI type'] = ['short' if data['ITI'][ix]<0.5 else 'long' for ix in range(len(data))] # ITI_plot_order = ['short','long'] # elif len(prdm_params['ITIs'])==3: # target_time v1.8.4 and below # data['ITI type'] = ['short' if ...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
Look for behavioral adjustments following short and long responses
plot = sns.factorplot(data=data_PL,x='ITI type',y='RT',hue='PE',col='Condition',kind='point', ci=95,order=prdm['ITIs']); plt.subplots_adjust(top=0.9) plot.fig.suptitle(SBJ+'_post-long') # can also get the figure from plt.gcf() # plt.savefig(results_dir+'RT_plots/'+SBJ+'_RT_PE_ITI_hit'+fig_type) plot2 = ...
_____no_output_____
MIT
.ipynb_checkpoints/BHV01_ratings_prelim_analysis-checkpoint.ipynb
hoycw/PRJ_Error_eeg
_Speech Processing Labs 2021: SIGNALS 1: Digital Signals: Sampling and Superposition_
## Run this first! %matplotlib inline import sys import matplotlib.pyplot as plt import numpy as np import cmath from matplotlib.animation import FuncAnimation from IPython.display import HTML plt.style.use('ggplot') from dspMisc import *
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Digital Signals: Sampling and Superposition Learning Outcomes* Understand how we can approximate a sine wave with a specific frequency, given a specific sampling rate* Understand how sampling rate limits the frequencies of sinusoids we can describe with discrete sequences* Explain when aliasing will occurr and how th...
## Our parameters: Tmin = 0 Tmax = 4 freq = 2 # cycles/second sampling_rate = 16 # i.e, f_s above t_step=1/sampling_rate # i.e., t_s above ## Get our complex values corresponding to the phasor with frequency freq zs, thetas, tsteps = gen_phasor_vals_freq(Tmin=Tmin, Tmax=Tmax, t_step=t_step, fre...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
You should see two graphs above:* On the left is the phasor diagram: the grey circle represents a phasor with magnitude 1, the red dots represents the points on the circle that the phasor samples between `tmin` and `tmax` given the `sampling_rate`. * On the right is the time versus amplitude graph: The grey line shows ...
## Now let's animate it! ## a helper to draw the 'clockhand' line X, Y, n_samples = get_line_coords(Xs, Ys) ## initialize the animation line = phasor.plot([], [], color='b', lw=3)[0] sin_t = sinusoid.plot([], [], 'o', color='b')[0] figs = (line, sin_t) anim = FuncAnimation( fig, lambda x: anim_sinusoid(x, X=X, Y=...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Exercise Change the `freq` variable in the code below to investigate: * What happens when the sine wave frequency (cycles/second) `freq` is set to `sampling_rate/2`?* What happens when the frequency `freq` approaches the half the `sampling_rate`? * What happens when the frequency `freq` equals the half the `sampling_r...
## Example: Play around with these values Tmax = 1 Tmin = 0 freq = 15 # cycles/second sampling_rate = 16 # f_s above t_step=1/sampling_rate print("freq=%.2f cycles/sec, sampling rate=%.2f samples/sec, sampling period=%.2f sec" % (freq, sampling_rate, t_step) ) ## Get our complex values corresponding to the sine wa...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Notes AliasingIf you change the frequency (`freq`) for the phasor to be higher than half the sampling rate , you'll see that the actual frequency of the sinusoid doesn't actually keep getting higher. In fact, with `freq=8` the sine wave (i.e. projection of the vertical (imaginary) component) doesn't appear to have ...
## Some parameters to play with Tmax = 2 Tmin = 0 sampling_rate = 16 t_step=1/sampling_rate
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Now, let's create some phasors with different magnitudes, frequencies and phases. Here we create 2 phasors with magnitude 1 and no phase shift, one with `freq=2` Hz and another phasor with frequency `2*freq`. We then add the two phasors values together at each timestep (`zs_sum` in the code below):
## Define a bunch of sinusoids. We can do this in terms of 3 parameters: ## (magnitude, frequency, phase) ## The following defines two sinusoids, both with magnitude (peak amplitude) 1 and the same phase (no phase shift) ## The second has double the frequency of the first: freq=2 params = [(1, freq, 0), (1, 2*freq...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Now, we can plot the sine (vertical) component of the individual phasors (on the right), ignoring the cosine (horizontal) component for the moment.
## Plot the phasor (left) and the projection of the imaginary (vertical) component (right) ## cosproj would be the projection to the real axis, but let's just ignore that for now fig, phasor, sinproj, cosproj = create_phasor_sinusoid_bkg(Tmin, Tmax, ymax=3, plot_phasor=True, plot_real=False, plot_imag=True,) dense_ts...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Now plot the sum of the phasors (left) and the projected imaginary component in magenta (right) - that is, the sum of the sine components (in grey)
## Plot sinusoids as sampled Xlist = [] Ylist = [] ## some hacks to get to represent the individual phasors as lines from the centre of a circle as well as points for i, zs in enumerate(phasor_list): Xs_ = np.real(zs) Ys_ = np.imag(zs) X_, Y_, _ = get_line_coords(Xs_, Ys_) Xlist.append(X_) Ylist.ap...
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
Now let's see an animation of how we're adding these phasors together!
anim = get_phasor_animation(Xline, Yline, tsteps, phasor, sinproj, cosproj, fig, Xlist=Xlist, Ylist=Ylist, params=params) anim
_____no_output_____
MIT
signals/signals-lab-1/signals-1-2-sampling-sinusoids.ipynb
laic/uoe_speech_processing_course
AmsterdamUMCdb - Freely Accessible ICU Databaseversion 1.0.2 March 2020 Copyright &copy; 2003-2020 Amsterdam UMC - Amsterdam Medical Data Science Sequential Organ Failure Assessment (SOFA)The sequential organ failure assessment score (SOFA score), originally published as as the Sepsis-related Organ Failure Assessmen...
%matplotlib inline import amsterdamumcdb import psycopg2 import pandas as pd import numpy as np import re import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib as mpl import io from IPython.display import display, HTML, Markdown sofa = pd.read_csv('sofa/sofa.csv') oxy_flow = pd.read...
_____no_output_____
MIT
sepsis/extract_data.ipynb
yinchangchang/AmsterdamUMCdb
Train Tensorflow Faster-RCNN and SSD models to detect bats (Chiroptera) from EOL images--- *Last Updated 19 Oct 2021* -Now runs in Python 3 with Tensorflow 2.0- Use EOL user generated cropping coordinates to train Faster-RCNN and SSD Object Detection Models implemented in Tensorflow to detect bats from EOL ima...
# Mount google drive to import/export files from google.colab import drive drive.mount('/content/drive', force_remount=True) # For running inference on the TF-Hub module import tensorflow as tf import tensorflow_hub as hub # For downloading and displaying images import matplotlib import matplotlib.pyplot as plt import...
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Model preparation (only run once)---These blocks download and set-up files needed for training object detectors. After running once, you can train and re-train as many times as you'd like. Download and extract pre-trained models
# Download pre-trained models from Tensorflow Object Detection Model Zoo # https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md # SSD and Faster-RCNN used as options below # modified from https://github.com/RomRoc/objdet_train_tensorflow_colab/blob/master/objdet_custom_t...
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Convert training data to tf.record format 1) Download generate_tfrecord.py using code block below2) Open the Colab file explorer on the right and navigate to your current working directory3) Double click on generate_tfrecord.py to open it in the Colab text editor.4) Modify the file for your train dataset: * update l...
# Download chiroptera_generate_tfrecord.py to your wd in Google Drive # Follow directions above to modify the file for your dataset !gdown --id 1fVXeuk7ALHTlTLK3GGH8p6fMHuuWt1Sr # Convert crops_test to tf.record format for test data # Modified from https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/late...
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Make label map for class Chiroptera
%%writefile labelmap.pbtxt item { id: 1 name: 'Chiroptera' }
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Modify model config files for training Faster-RCNN and SSD with your dataset If you have errors with training, check the pipline_config_path and model_dir in the config files for R-FCN or Faster-RCNN model
# Adjust model config file based on training/testing datasets # Modified from https://stackoverflow.com/a/63645324 from google.protobuf import text_format from object_detection.protos import pipeline_pb2 %cd $wd # TO DO: Adjust parameters ## add form fields here filter = "Chiroptera" #@param {type:"string"} config_ba...
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Train---
# Determine how many train and eval steps to use based on dataset size # TO DO: Only need to update path if you didn't just run "Model Preparation" block above try: train_image_dir except NameError: train_image_dir = "/content/drive/MyDrive/train/tf2/images" #@param {type:"string"} examples = len(os.listdir(t...
_____no_output_____
MIT
object_detection_for_image_cropping/chiroptera/chiroptera_train_tf2_ssd_rcnn.ipynb
aubricot/computer_vision_with_eol_images
Copyright (c) 2021, 2022 Oracle and/or its affiliates.Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ Unix Operations _Important: The ocifs SDK isn't a one-to-one adaptor of OCI Object Storage and UNIX filesystem operations. It's a set of convenient wrappings to a...
from ocifs import OCIFileSystem fs = OCIFileSystem(config="~/.oci/config")
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
Filesystem Operations listList the files in a bucket or subdirectory using `ls`:
fs.ls("bucket@namespace/") # ['bucket@namespace/file.txt', # 'bucket@namespace/data.csv', # 'bucket@namespace/folder1/', # 'bucket@namespace/folder2/']
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
`list` has the following args: 1) `compartment_id`: a specific compartment from which to list. 2)`detail`: If true, return a list of dictionaries with various details about each object. 3)`refresh`: If true, ignore the cache and pull fresh.
fs.ls("bucket@namespace/", detail=True) # [{'name': 'bucket@namespace/file.txt', # 'etag': 'abcdefghijklmnop', # 'type': 'file', # 'timeCreated': <timestamp when artifact created>, # ... }, # ... # ]
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
touchThe UNIX `touch` command creates empty files in Object Storage. The `data` parameter accepts a bytestream and writes it to the new file.
fs.touch("bucket@namespace/newfile", data=b"Hello World!") fs.cat("bucket@namespace/newfile") # "Hello World!"
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
copyThe `copy` method is a popular UNIX method, and it has a special role in ocifs as the only method capable of cross-tenancy calls. Your IAM Policy must permit you to read and write cross-region to use the `copy` method cross-region. Note: Another benefit of `copy` is that it can move large data between locations in...
fs.copy("bucket@namespace/newfile", "bucket@namespace/newfile-sydney", destination_region="ap-sydney-1")
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
rmThe `rm` method is another essential UNIX filesystem method. It accepts one additional argument (beyond the path), `recursive`. When `recursive=True`, it is equivalent to an `rm -rf` command. It deletes all files underneath the prefix.
fs.exists("oci://bucket@namespace/folder/file") # True fs.rm("oci://bucket@namespace/folder", recursive=True) fs.exists("oci://bucket@namespace/folder/file") # False
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
globFsspec implementations, including ocifs, support UNIX glob patterns, see [Globbing](https://man7.org/linux/man-pages/man7/glob.7.html).
fs.glob("oci://bucket@namespace/folder/*.csv") # ["bucket@namespace/folder/part1.csv", "bucket@namespace/folder/part2.csv"]
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
Dask has special support for reading from and writing to a set of files using glob expressions (Pandas doesn't support glob), see [Dask's Glob support](https://docs.dask.org/en/latest/remote-data-services.html).
from dask import dataframe as dd ddf = dd.read_csv("oci://bucket@namespace/folder/*.csv") ddf.to_csv("oci://bucket@namespace/folder_copy/*.csv")
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
walkUse the UNIX `walk` method for iterating through the subdirectories of a given path. This is a valuable method for determining every file within a bucket or folder.
fs.walk("oci://bucket@namespace/folder") # ["bucket@namespace/folder/part1.csv", "bucket@namespace/folder/part2.csv", # "bucket@namespace/folder/subdir/file1.csv", "bucket@namespace/folder/subdir/file2.csv"]
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
openThis method opens a file and returns an `OCIFile` object. There are examples of what you can do with an `OCIFile` in the next section. File OperationsAfter calling open, you get an `OCIFile` object, which is subclassed from fsspec's `AbstractBufferedFile`. This file object can do almost everything a UNIX file can...
import fsspec with fsspec.open("oci://bucket@namespace/folder/file", 'rb') as f: buffer = f.read() with fs.open("oci://bucket@namespace/folder/file", 'rb') as f: buffer = f.read() file = fs.open("oci://bucket@namespace/folder/file") buffer = file.read() file.close()
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
seekThe `seek` method is also valuable in navigating files:
fs.touch("bucket@namespace/newfile", data=b"Hello World!") with fs.open("bucket@namespace/newfile") as f: f.seek(3) print(f.read(1)) f.seek(0) print(f.read(1)) # l # H
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
writeYou can use the `write` operation:
with fsspec.open("oci://bucket@namespace/newfile", 'wb') as f: buffer = f.write(b"new text") with fsspec.open("oci://bucket@namespace/newfile", 'rb') as f: assert f.read() == b"new text"
_____no_output_____
UPL-1.0
docs/source/unix-operations.ipynb
LaudateCorpus1/ocifs
**Yolov3 Algorithm**
import struct import numpy as np import pandas as pd import os from keras.layers import Conv2D from keras.layers import Input from keras.layers import BatchNormalization from keras.layers import LeakyReLU from keras.layers import ZeroPadding2D from keras.layers import UpSampling2D from keras.layers.merge import add, co...
_____no_output_____
MIT
experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb
moeraza/juice-box
**Access Google Drive**
# Load the Drive helper and mount from google.colab import drive drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
MIT
experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb
moeraza/juice-box
**Residual Block** formula: y=F(x) + x
def _conv_block(inp, convs, skip=True): x = inp count = 0 for conv in convs: if count == (len(convs) - 2) and skip: skip_connection = x count += 1 if conv['stride'] > 1: x = ZeroPadding2D(((1,0),(1,0)))(x) #padding as darknet prefer left and top x = Conv2D(conv['filter'], conv['kernel'], str...
_____no_output_____
MIT
experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb
moeraza/juice-box
**Create Yolov3 Architecture**Three output layers: 82, 94, 106
def make_yolov3_model(): input_image = Input(shape=(None, None, 3)) # Layer 0 => 4 x = _conv_block(input_image, [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0}, {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 1}, {'filte...
_____no_output_____
MIT
experiments/YOLOv3/PART2_Yolov3_Object_Detection.ipynb
moeraza/juice-box