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
As we did in the make blobs case, we are going to be splitting our data in train and test splits
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=0)
_____no_output_____
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
We train a KNN classifier
from sklearn.neighbors import KNeighborsClassifier k = 1 classifier = KNeighborsClassifier(n_neighbors=k,n_jobs=1) ### CELL TO BE COMPLETED - train the classifier and get the accuracy in both sets. classifier.fit(x_train,y_train) print("Accuracy on the training set {}%".format(classifier.score(x_train,y_train)*100)) p...
Accuracy on the training set 100.0% Accuracy on the test set 47.5%
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
We find the best k value for this split. Normally this would be done over the mean best k value over several train/test splits
train_acc = list() test_acc = list() # list to add the test set accuracies test_ks = range(1,25)# list containing values of k to be tested # CELL TO BE COMPLETED - Train networks with varying k for k in tqdm.tqdm(test_ks): local_classifier = KNeighborsClassifier(n_neighbors=k,n_jobs=-1) local_classifier.fit(x_...
100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 24/24 [00:07<00:00, 3.00it/s]
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
Show the classification report and confusion matrix
from sklearn.metrics import classification_report,confusion_matrix y_pred_train = classifier.predict(x_train) report = classification_report(y_true=y_train,y_pred=y_pred_train) matrix = confusion_matrix(y_true=y_train,y_pred=y_pred_train) print("Training Set:") print(report) print(matrix) plt.matshow(matrix) plt.colorb...
Training Set: precision recall f1-score support -1.0 0.57 0.73 0.64 344 0.0 0.31 0.04 0.07 99 1.0 0.63 0.61 0.62 357 avg / total 0.56 0.59 0.56 800 [[250 5 89] [ 55 4 40] [137 ...
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
Here we see that differently from the make blobs case the classes are not balanced, so even if you were correctly classyfing all of the draw examples, the color on the confusion matrix would make it seem like a bad model for that class. We have to normalize the confusion matrix by the amount of examples on each class, ...
from sklearn.metrics import classification_report,confusion_matrix y_pred_train = classifier.predict(x_train) report = classification_report(y_true=y_train,y_pred=y_pred_train) matrix = confusion_matrix(y_true=y_train,y_pred=y_pred_train) normalized_matrix = matrix/np.sum(matrix,axis=1) print("Training Set:") print(rep...
Training Set: precision recall f1-score support -1.0 0.57 0.73 0.64 344 0.0 0.31 0.04 0.07 99 1.0 0.63 0.61 0.62 357 avg / total 0.56 0.59 0.56 800 [[250 5 89] [ 55 4 40] [137 ...
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
And now the test set
### CELL TO BE COMPLETED - Generate the report and confusion matrix for the test set. y_pred_test = classifier.predict(x_test) report = classification_report(y_true=y_test,y_pred=y_pred_test) matrix = confusion_matrix(y_true=y_test,y_pred=y_pred_test) normalized_matrix = matrix/np.sum(matrix,axis=1) print("Test Set:")...
Test Set: precision recall f1-score support -1.0 0.60 0.58 0.59 96 0.0 0.33 0.05 0.08 22 1.0 0.50 0.63 0.56 82 avg / total 0.53 0.55 0.52 200 [[56 1 39] [ 9 1 12] [29 1 52]] [[ 0....
MIT
session2/Resolved TP1.ipynb
isival/IntroToAI
Peaks model
#read in sc peak table peaktable_path = '../tissue_analysis/pharynx/filtered_peaks_iqr4.0_low_cells.bow' peak_data_sparse = numpy.loadtxt(peaktable_path, dtype=int, skiprows=3) peak_data = sps.csr_matrix((peak_data_sparse[:,2], (peak_data_sparse[:,0] - 1, peak_data_sparse[:,1] - 1))) cell_names_path = '../tissue_analy...
_____no_output_____
MIT
notebooks/pharynx_analysis.primary_lda.ipynb
tdurham86/L2_sci-ATAC-seq
Analysis functions
REFDATA = 'ATAC_sequencing/2018_worm_atac/ref_data/WS235' refseq_exon_bed = os.path.join(REFDATA, 'c_elegans.WS272.canonical_geneset.genes.common_names.sorted.bed.gz') import gzip ucsc = True if peak_row_headers[0][0].startswith('chr') else False with gzip.open(refseq_exon_bed, 'rb') as lines_in: exon_locs = [] ...
_____no_output_____
MIT
notebooks/pharynx_analysis.primary_lda.ipynb
tdurham86/L2_sci-ATAC-seq
Topic Mode
doctopic_path = '../tissue_analysis/pharynx/0000_topics5_alpha3.000_beta2000.000/topic_mode.theta' doctopic_peaks = numpy.loadtxt(doctopic_path, delimiter=',', dtype=float) print(doctopic_peaks.shape) #center and scale the topic values #col_means = numpy.mean(doctopic.T, axis=0) #doctopic_norm = doctopic.T - col_means...
_____no_output_____
MIT
notebooks/pharynx_analysis.primary_lda.ipynb
tdurham86/L2_sci-ATAC-seq
Construct an AnnData object and save it in loom format
def add_lda_result_to_anndata_obj(anndata_obj, lda_base, lda_cellnames, lda_peak_bed): filt_cellnames = numpy.loadtxt(lda_cellnames, dtype=object)[:,0] filt_cellnames_set = set(filt_cellnames) filt_cellnames_map = [(True, idx, numpy.where(filt_cellnames == elt)[0][0]) if elt in fi...
_____no_output_____
MIT
notebooks/pharynx_analysis.primary_lda.ipynb
tdurham86/L2_sci-ATAC-seq
Module 5 Homework - Extracting a relational network from Reddit dataNick Lines Imports and environment set up
%pylab inline import re import os import pandas as pd import scipy.sparse as sp import networkx as nx from itertools import chain try: import datashader as ds import datashader.transfer_functions as tf from datashader.layout import random_layout, circular_layout, forceatlas2_layout from datashader.bundling impo...
Collecting datashader [?25l Downloading https://files.pythonhosted.org/packages/df/24/22f96084785d9cc424f1e70541a2803eec807c82e6bdab87c4b71fd96d10/datashader-0.12.1-py2.py3-none-any.whl (15.8MB)  |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 15.8MB 319kB/s [?25hRequirement already satisfied: param>=1.6.0 in /usr/local/...
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
This cell defines system-dependent configuration such as those different in Linux vs. Windows
if 'COLAB_GPU' in os.environ: # a hacky way of determining if you are in colab. print("Notebook is running in colab") from google.colab import drive drive.mount("/content/drive") DATA_DIR = "./drive/My Drive/Data/" else: # Get the system information from the OS PLATFORM_SYSTEM = platform.system() # Da...
Notebook is running in colab Mounted at /content/drive
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
Data extraction
comment_df = pd.read_csv(DATA_DIR + "raw/Reddit/REDDIT_COMMENTS_2021-02-03T17-02-00-0500.csv") post_df = pd.read_csv(DATA_DIR + "raw/Reddit/REDDIT_POSTS_2021-02-03T16-56-30-0500.csv") comment_posts = set(comment_df.post_id.unique()) posts = set(post_df.post_id.unique()) print(f"There are {len(comment_posts.intersection...
There are 833 posts with comments on them in the data
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
We'll now make two networkks. The first is a post-author bipartite graph pairing each post to the list of agents. The second is a comment-author-post network that pairs agents with the posts they comment on. We'll need to make indices that track which agent and which post get assigned which integer index.
agents = array(list(set(comment_df.comment_author).union(set(post_df.post_author)))) print(f"There are {agents.shape[0]} agents in the network.") all_posts = array(list(posts.union(comment_posts))) print(f"There are {all_posts.shape[0]} posts in the network.") post_author_net = nx.from_edgelist(post_df[["post_id", "pos...
True
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
Because it is convenient to do so in `networkx`, we will include both the agents and the post id's in the nodes lists (even though that is less interpretable). We've created two matrices, `X` and `Y`, which respectively represent the agents that commented on each post, and the posts that were authored by each agent. Mu...
X.shape Y.shape Z = X*Y commenter_author_net = nx.from_scipy_sparse_matrix(Z) commenter_author_net = nx.relabel.relabel_nodes(commenter_author_net, Xprime.nodes) m = nx.adjacency_matrix(commenter_author_net) mm = m.todense() pd.DataFrame(mm).to_csv(DATA_DIR+"/adjacency.csv", header=None, index=None) def hasNumbers(inpu...
_____no_output_____
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
VisualizationTo visualize our networks we will use the `networkx` and `datashader` libraries, following the documentation available at [https://datashader.org/user_guide/Networks.html](https://datashader.org/user_guide/Networks.html).
cvsopts = dict(plot_height=400, plot_width=400) def nodesplot(nodes, name=None, canvas=None, cat=None): canvas = ds.Canvas(**cvsopts) if canvas is None else canvas aggregator=None if cat is None else ds.count_cat(cat) agg=canvas.points(nodes,'x','y',aggregator) return tf.spread(tf.shade(agg, cmap=["#F...
Post Author Network 1095 Commenter Post Network 9001 Commenter Author Network 11962
MIT
Notebooks/Reddit_relational_net_extraction.ipynb
linesn/reddit_analysis
Preprocessing for numerical featuresIn this notebook, we will still use only numerical features.We will introduce these new aspects:* an example of preprocessing, namely **scaling numerical variables**;* using a scikit-learn **pipeline** to chain preprocessing and model training;* assessing the statistical performanc...
import pandas as pd adult_census = pd.read_csv("../datasets/adult-census.csv")
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We will now drop the target from the data we will use to train ourpredictive model.
target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=target_name)
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Caution!Here and later, we use the name data and target to be explicit. Inscikit-learn documentation, data is commonly named X and target iscommonly called y. Then, we select only the numerical columns, as seen in the previousnotebook.
numerical_columns = [ "age", "capital-gain", "capital-loss", "hours-per-week"] data_numeric = data[numerical_columns]
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Finally, we can divide our dataset into a train and test sets.
from sklearn.model_selection import train_test_split data_train, data_test, target_train, target_test = train_test_split( data_numeric, target, random_state=42) # ## Model fitting with preprocessing # # A range of preprocessing algorithms in scikit-learn allow us to transform # the input data before training a mo...
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We see that the dataset's features span across different ranges. Somealgorithms make some assumptions regarding the feature distributions andusually normalizing features will be helpful to address these assumptions.TipHere are some reasons for scaling features:Models that rely on the distance between a pair of samples,...
from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(data_train)
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
The `fit` method for transformers is similar to the `fit` method forpredictors. The main difference is that the former has a single argument (thedata matrix), whereas the latter has two arguments (the data matrix and thetarget).![Transformer fit diagram](../figures/api_diagram-transformer.fit.svg)In this case, the algo...
scaler.mean_ scaler.scale_
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Notescikit-learn convention: if an attribute is learned from the data, its nameends with an underscore (i.e. _), as in mean_ and scale_ for theStandardScaler. Scaling the data is applied to each feature individually (i.e. each column inthe data matrix). For each feature, we subtract its mean and divide by itsstandard d...
data_train_scaled = scaler.transform(data_train) data_train_scaled
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Let's illustrate the internal mechanism of the `transform` method and put itto perspective with what we already saw with predictors.![Transformer transform diagram](../figures/api_diagram-transformer.transform.svg)The `transform` method for transformers is similar to the `predict` methodfor predictors. It uses a predef...
data_train_scaled = scaler.fit_transform(data_train) data_train_scaled data_train_scaled = pd.DataFrame(data_train_scaled, columns=data_train.columns) data_train_scaled.describe()
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We can easily combine these sequential operations with a scikit-learn`Pipeline`, which chains together operations and is used as any otherclassifier or regressor. The helper function `make_pipeline` will create a`Pipeline`: it takes as arguments the successive transformations to perform,followed by the classifier or re...
import time from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline model = make_pipeline(StandardScaler(), LogisticRegression())
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
This predictive pipeline exposes the same methods as the final predictor:`fit` and `predict` (and additionally `predict_proba`, `decision_function`,or `score`).
start = time.time() model.fit(data_train, target_train) elapsed_time = time.time() - start
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We can represent the internal mechanism of a pipeline when calling `fit`by the following diagram:![pipeline fit diagram](../figures/api_diagram-pipeline.fit.svg)When calling `model.fit`, the method `fit_transform` from each underlyingtransformer in the pipeline will be called to: (i) learn their internalmodel states an...
predicted_target = model.predict(data_test) predicted_target[:5]
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Let's show the underlying mechanism:![pipeline predict diagram](../figures/api_diagram-pipeline.predict.svg)The method `transform` of each transformer is called to preprocess the data.Note that there is no need to call the `fit` method for these transformersbecause we are using the internal model states computed when c...
model_name = model.__class__.__name__ score = model.score(data_test, target_test) print(f"The accuracy using a {model_name} is {score:.3f} " f"with a fitting time of {elapsed_time:.3f} seconds " f"in {model[-1].n_iter_[0]} iterations")
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We could compare this predictive model with the predictive model used inthe previous notebook which did not scale features.
model = LogisticRegression() start = time.time() model.fit(data_train, target_train) elapsed_time = time.time() - start model_name = model.__class__.__name__ score = model.score(data_test, target_test) print(f"The accuracy using a {model_name} is {score:.3f} " f"with a fitting time of {elapsed_time:.3f} seconds "...
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
We see that scaling the data before training the logistic regression wasbeneficial in terms of computational performance. Indeed, the number ofiterations decreased as well as the training time. The statisticalperformance did not change since both models converged.WarningWorking with non-scaled data will potentially for...
%%time from sklearn.model_selection import cross_validate model = make_pipeline(StandardScaler(), LogisticRegression()) cv_result = cross_validate(model, data_numeric, target, cv=5) cv_result
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
The output of `cross_validate` is a Python dictionary, which by defaultcontains three entries: (i) the time to train the model on the training datafor each fold, (ii) the time to predict with the model on the testing datafor each fold, and (iii) the default score on the testing data for each fold.Setting `cv=5` created...
scores = cv_result["test_score"] print("The mean cross-validation accuracy is: " f"{scores.mean():.3f} +/- {scores.std():.3f}")
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_scaling.ipynb
glemaitre/scikit-learn-mooc
Hugging Face - Ask boolean question to T5 **Tags:** huggingface T5-base finetuned on BoolQ (superglue task)This notebook is for demonstrating the training and use of the text-to-text-transfer-transformer (better known as T5) on boolean questions (BoolQ). The example use case is a validator indicating if an idea is e...
!pip install transformers !pip install sentencepiece
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Import libraries
import json import torch from operator import itemgetter from distutils.util import strtobool from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Load model
tokenizer = AutoTokenizer.from_pretrained('mrm8488/t5-base-finetuned-boolq') model = AutoModelForSeq2SeqLM.from_pretrained('mrm8488/t5-base-finetuned-boolq').to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')) try:model.parallelize() except:pass
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Model Training> **Optional:** You can leave the following out, if you don't have custom datasets. By default the number of training epochs equals 0, so nothing is trained.> **Warning:** This option consumes a lot of runtime and thus *naas.ai* credits. Make sure to have enough credits on your account.For each dataset ...
srcs = [ { 'stream': lambda:open('boolq/train.jsonl', 'r'), 'keys': ['question', 'passage', 'answer'] }, { 'stream': lambda:open('boolq/dev.jsonl', 'r'), 'keys': ['question', 'passage', 'answer'] }, { 'stream': lambda:open('boolq-nat-perturb/train.jsonl', 'r'), 'keys': ['question', 'passag...
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Define query functionAs the model is ready, define the querying function.
def query(q='question', c='context'): return strtobool( tokenizer.decode( token_ids=model.generate( input_ids=tokenizer.encode('question:'+q+'\ncontext:'+c, return_tensors='pt') )[0], skip_special_tokens=True, max_length=3) )
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Output Querying on the taskNow the actual task begins: Query the model with your ideas (see list `ideas`).
if __name__ == '__main__': ideas = [ 'The idea is to pollute the air instead of riding the bike.', # should be false 'The idea is to go cycling instead of driving the car.', # should be true 'The idea is to put your trash everywhere.', # should be false 'The idea is to redu...
_____no_output_____
BSD-3-Clause
Hugging Face/Hugging_Face_Ask_boolean_question_to_T5.ipynb
Charles-de-Montigny/awesome-notebooks
Grid Plots Source: [https://github.com/d-insight/code-bank.git](https://github.com/d-insight/code-bank.git) License: [MIT License](https://opensource.org/licenses/MIT). See open source [license](LICENSE) in the Code Bank repository. ------------- IntroductionGrids are general types of plots that allow you to map p...
import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline iris = sns.load_dataset('iris') iris.head() iris.species.unique()
_____no_output_____
MIT
_development/tutorials/visualization/06-grid-plots.ipynb
dsfm-org/code-bank
A dataset of 150 different flowers, each from three different species of iris (*Iris setosa*, *Iris versicolor*, and *Iris virginica*).![tut4_iris](https://i.imgur.com/RcxYYBA.png) PairGridPairgrid is a subplot grid for plotting pairwise relationships in a dataset. Customize sns.pairplot()
# Just the Grid sns.PairGrid(iris) # Gives us empty an PairGrid (create subplots) # Then you map to the grid g = sns.PairGrid(iris) # Better to assign it to a variable (g) g.map(plt.scatter) # Map to upper,lower, and diagonal g = sns.PairGrid(iris) g.map_diag(plt.hist) # Can map on specif areas of the grid g.map_up...
_____no_output_____
MIT
_development/tutorials/visualization/06-grid-plots.ipynb
dsfm-org/code-bank
pairplotpairplot is a simpler version of PairGrid (you'll use quite often). More standard.
sns.pairplot(iris) sns.pairplot(iris,hue='species',palette='rainbow')
_____no_output_____
MIT
_development/tutorials/visualization/06-grid-plots.ipynb
dsfm-org/code-bank
Facet GridFacetGrid is the general way to create grids of plots based off of a feature:
# We use the tips dataset tips = sns.load_dataset('tips') tips.head() # This is Just the Grid g = sns.FacetGrid(tips, col="time", row="smoker") g = sns.FacetGrid(tips, col="time", row="smoker") g = g.map(plt.hist, "total_bill") # try with sns.distplot g = sns.FacetGrid(tips, col="time", row="smoker",hue='sex') # Noti...
_____no_output_____
MIT
_development/tutorials/visualization/06-grid-plots.ipynb
dsfm-org/code-bank
JointGridJointGrid is the general version for jointplot() type grids, for a quick example:
g = sns.JointGrid(x="total_bill", y="tip", data=tips) g = sns.JointGrid(x="total_bill", y="tip", data=tips) g = g.plot(sns.regplot, sns.distplot)
_____no_output_____
MIT
_development/tutorials/visualization/06-grid-plots.ipynb
dsfm-org/code-bank
--- Day 5: Doesn&apos;t He Have Intern-Elves For This? --- [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/oddrationale/AdventOfCode2015FSharp/master?urlpath=lab%2Ftree%2FDay05.ipynb) Santa needs help figuring out which strings in his text file are naughty or nice.A nice string is one with a...
let input = File.ReadAllLines @"input/05.txt" let containsAtLeastThreeVowels (s: string) = let vowels = [| 'a'; 'e'; 'i'; 'o'; 'u' |] s |> Seq.filter (fun c -> Array.contains c vowels) |> Seq.length >= 3 let containsDoubleLetter (s: string) = s |> Seq.windowed 2 |> Seq.exists (fun arr -> a...
_____no_output_____
MIT
Day05.ipynb
oddrationale/AdventOfCode2015FSharp
--- Part Two --- Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous.Now, a nice string is one with all of the following properties:It contains a pair of any two letters that appears at...
let containsAtLeastTwoPairs (s: string) = s |> Seq.windowed 2 |> Seq.map (fun arr -> $"{arr.[0]}{arr.[1]}") |> Seq.exists (fun pair -> pair |> s.Split |> Seq.length >= 3) let containsRepeatWithOneBetween (s: string) = s |> Seq.windowed 3 |> Seq.exists (fun arr -> arr.[0] = arr.[2]) let isR...
_____no_output_____
MIT
Day05.ipynb
oddrationale/AdventOfCode2015FSharp
8. RepetiΓ§Γ΅es (IteraΓ§Γ΅es) Condicionais
# Enquanto for verdade, repete numero = 7 while numero > 0: print(numero) numero = numero - 1 print("Acabou de repetir") # Podemos aplicar ao nosso programa repetir = True while repetir: idade = input('Digite sua idade: ') idade = int(idade) if idade >= 18 and idade < 70: print(f'Com {idade} anos, seu v...
Digite sua idade: 234567 Com 234567 anos, seu voto Γ© facultativo! Deseja repetir? (s/n)N
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
9 Listas de Dados
# lista com vΓ‘rios nΓΊmeros (idades) idades = [12, 47, 78, 8, 18] # os valores nΓ£o precisam ser do mesmo tipo miscelanea = [15, 'biscoito', True, "teste", 67.9, '78'] print(idades[3]) print(miscelanea[1]) # pode modificar um valor na lista idades[3] = 25 print(idades[3]) # adicionar elemento ao final lista idades.appe...
[0, 2, 4, 6]
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
10. IteraΓ§Γ΅es Definidas (for)
idades = [12, 47, 78, 8, 18] # variΓ‘vel idade assume valores na lista idades for idade in idades: print(idade + 2) for idade in idades: if idade >= 18 and idade < 70: print(f'Com {idade} anos, seu voto Γ© obrigatΓ³rio!') elif idade >= 16: print(f'Com {idade} anos, seu voto Γ© facultativo!') else: print...
6
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
Pedindo uma Lista
# pedindo uma lista n = int(input('Quantos elementos? ')) lista = [] for i in range(n): elemento = float(input(f'Digite o {i+1}ΒΊ elemento: ')) lista.append(elemento) print(lista)
_____no_output_____
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
Experimente* Tente pedir uma lista com *while* ao invΓ©s de *for* 11. Algumas operaΓ§Γ΅es com Strings
frase = 'Em noite de lua cheia...' # que nem as listas! print(frase[0]) print(frase[9]) # Γ­ndices negativos sΓ£o vΓ‘lidos em Python (nas listas tambΓ©m) # acessam de trΓ‘s pra frente print(frase[-4]) lista = [12, 'China', '8'] palavra = 'ninja' # listas sΓ£o mutΓ‘veis lista[1] = 5 print(lista) # strings sΓ£o imutΓ‘veis palavra...
E m n o i t e d e l u a c h e i a . . .
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
Experimente* Tente usar a funΓ§Γ£o *len* em uma string Filtrando listas e string
# filtrando os nΓΊmeros pares da lista numeros = [12, 56, 87, 23, 98, 54, 11, 7] pares = [] for num in numeros: if (num % 2) == 0: pares.append(num) print(pares) # in pode ser usado para avaliar se algo pertence Γ  lista/string print(13 in pares) print('d' in 'cabra') # nova string sem caracteres que sΓ£o vogais fra...
_____no_output_____
MIT
PJC_aula2.ipynb
angelosqr/Aprendizado
FIR Filter Class Implementation This is the final exercise for the course and will test all the knowledge that you have gathered during this semester. The final exercise consist of developing a series of functions/methods to implement a `FIR` class in Python. For this, three files were provided and are stored in the `...
import sys sys.path.insert(0, '../') import numpy as np import matplotlib.pyplot as plt from Common import fir from Common import fft from Common import auxiliary from Common import common_plots cplots = common_plots.Plot() flt = fir.FIR() fast_ft = fft.FFT()
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Part 1: Test your `common_plots.py` fileFor the first part you will test your method `plot_frequency_response` from the class `Plot` with a $sinc$ signal. The following code provides you with a test code using the numpy function `sinc`, be aware that when you implement your `shifted_sinc` method you can't use the nump...
fc = 0.20 BW = 0.04 M = int(4/BW) i = np.arange(0,M,1) h = np.sinc(2*i*fc) H = np.fft.fft(h) f = np.linspace(0,1,h.shape[0]) cplots.plot_frequency_response(np.absolute(H).reshape(-1,1), f) #Note that this is a two sided spectrum
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Part 2: Test your `fft.py` fileNow we will compare your `FFT` class against numpy, and see if both one sided and two sided results match. First run this test to see if your `fft` function works correctly:
N = h.shape[0] L = 1024 fc = 0.20 BW = 0.04 M = int(4/BW) i = np.arange(0,M,1) h = np.sinc(2*i*fc) h_zero_pad = np.append(h,np.zeros(L-N)) H_own_one_side = fast_ft.fft(h_zero_pad, one_sided=True) H_own_two_side = fast_ft.fft(h_zero_pad, one_sided=False) H_numpy = np.fft.fft(h_zero_pad) assert np.allclose(H_own_one_...
Great work! One sided implementation rocks! But is better to have a two sided implementation! Excellent work!
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Now let's run this code and see if the function `ifft` also works well:
h_own_two_side = fast_ft.ifft(H_own_two_side).astype('complex') h_own_two_side[0] = h_own_two_side[0]/2 plt.plot(np.real(h_own_two_side[0:N])) plt.plot(h) assert np.allclose(h_own_two_side[0:M], h), "It seems there is an error, check your ifft function" print("You have been doing a great work! Your IFFT is doing an a...
You have been doing a great work! Your IFFT is doing an amazing job!
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Part 3: Test your `auxiliary.py` fileAt this moment you can test your `zero_pad_fourier` method and check if both methods `DFT` and `FFT` works. The provided code test against numpy's implementation of the Fast Fourier Transform:
fc = 0.20 BW = 0.04 M = int(4/BW) i = np.arange(0,M,1) L = 1024 h = np.sinc(2*i*fc) h_zero_pad = np.append(h,np.zeros(L-N)) H_numpy = np.fft.fft(h_zero_pad).reshape(-1,1) f = np.linspace(0,0.5,L//2) H_dft, f_dft = auxiliary.zero_pad_fourier(h.reshape(-1,1), M, method='DFT') H_fft, f_fft = auxiliary.zero_pad_fourier(h...
(513, 1) Perfect! Both filters are doing an amazing job!
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Part 4: Test your `fir.py` fileThis is the last part of the Jupyter Notebook. In here you will test your window filter, then your low, high, pass band, and reject band filters. 4.1 Test your window filterThe first test we will perform is going to be on our window filters. We will check both `blackman` and `hamming` ty...
fc = 0.20 M = 103 #Now we use an odd number L = 1024 hamming = flt.window_filter(fc, M, window_type='hamming', normalized=True) blackman = flt.window_filter(fc, M, window_type='blackman', normalized=True) # Spectral inversion hamming_inverted = flt.spectral_inversion(hamming) blackman_inverted = flt.spectral_inversi...
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
4.2 Test your low pass filterNow test your low pass filters. For this case we will use both `hamming` and `blackman` windows.
fc = 0.2 M = 101 h_lp = flt.low_pass_filter(fc, M, window_type='hamming') H_lp, fh_lp = auxiliary.zero_pad_fourier(h_lp, M) b_lp = flt.low_pass_filter(fc, M, window_type='blackman') B_lp, fb_lp = auxiliary.zero_pad_fourier(b_lp, M) plt.rcParams["figure.figsize"] = (7, 5) cplots.plot_frequency_response(np.absolute(H_l...
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
4.3 Test your high pass filterIt is time to test your high pass filter, besides testing again our `hamming` and `blackman` windows, we are also going to test the `spectral_inversion` and `spectral_reversal` methods.
fc = 0.17 M = 200 h_hp = flt.high_pass_filter(fc, M, method='spectral_inversion', window_type='hamming') H_hp, fh_hp = auxiliary.zero_pad_fourier(h_hp, M) b_hp = flt.high_pass_filter(fc, M, method='spectral_reversal', window_type='blackman') B_hp, fb_hp = auxiliary.zero_pad_fourier(b_hp, M) cplots.plot_frequency_res...
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
4.2 Test your band/reject band filterFinally we will create a band pass/reject filter and test our `band_filter` function like this:
fc1 = 0.17 fc2 = 0.33 h = flt.band_filter(fc1, fc2, M, band_type='pass') H, f = auxiliary.zero_pad_fourier(h, M) g = flt.band_filter(fc1, fc2, M, band_type='reject') G, f = auxiliary.zero_pad_fourier(g, M) cplots.plot_frequency_response(np.absolute(H), f, label='Band Pass Filter') cplots.plot_frequency_response(np.a...
_____no_output_____
MIT
Project_3/.ipynb_checkpoints/Project 3-checkpoint.ipynb
mriosrivas/DSP_Student_2021
Build a neural network
# input layer: keras.layers.Input(shape(,)) # dense layer: keras.layers.Dense(#of_nodes, activation="relu")(layer_before) # output layer ? def create_nn(nodes1, nodes2): inputs = keras.layers.Input(shape=(X_data.shape[1], )) layers_dense = keras.layers.Dense(nodes1, activation='relu')(inputs) layers_dens...
_____no_output_____
CC-BY-4.0
files/weather_predictions.ipynb
escience-academy/2021-07-05-intro-deep-learning
test pyTorch source : **Twitter-roBERTa-base for Sentiment Analysis**sur [Hugging Face ](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment)
!pwd import torch torch.cuda.is_available() !pip install transformers from transformers import AutoModelForSequenceClassification from transformers import TFAutoModelForSequenceClassification from transformers import AutoTokenizer import numpy as np from scipy.special import softmax import csv import urllib.request #...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
**ATTENTION** A ne lancer qu'une fois au premier téléchargement du modèle :
task='sentiment' MODEL = f"cardiffnlp/twitter-roberta-base-{task}" print(MODEL) tokenizer = AutoTokenizer.from_pretrained(MODEL) config = AutoConfig.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) model.save_pretrained('../pretrained_models/'+MODEL) tokenizer.save_pretrained('...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
==== RECUP ML ====
!pip install nltk !pip install textblob !pip install spacy #Temps et fichiers import os import warnings import time from datetime import timedelta #Manipulation de donnΓ©es import pandas as pd import numpy as np # Text import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize nltk.download('stopwor...
[nltk_data] Downloading package punkt to /root/nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package vader_lexicon to /root/nltk_data... [nltk_data] Package ...
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
Utilisation du code du projet packagΓ©
#Cette cellule permet d'appeler la version packagΓ©e du projet et d'en assurer le reload avant appel des fonctions %load_ext autoreload %autoreload 2 from dsa_sentiment.scripts.make_dataset import load_data #from dsa_sentiment.scripts.evaluate import eval_metrics from dsa_sentiment.scripts.evaluate import eval_metrics f...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
Configuration de l'experiment MLFlow
mlflow.tracking.get_tracking_uri() exp_name="DSA_sentiment_GPU" mlflow.set_experiment(exp_name)
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
Chargement des donnΓ©es
data_folder = os.path.join('..', 'data', 'raw') all_raw_files = [os.path.join(data_folder, fname) for fname in os.listdir(data_folder)] all_raw_files random_state=42
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
Il n'est pas possible de faire de l'imputation comme avec des champs numΓ©rique. Il convient donc de supprimer les entrΓ©es vides
X_train, y_train, X_val, y_val = load_data(all_raw_files[2], split=True, test_size=0.3, random_state=random_state, dropNA=True) X_train.head() y_train.head() X_train.shape[0] + X_val.shape[0] X_test, y_test = load_data(all_raw_files[1], split=False, random_state=random_state, dropNA=True) X_test.head() X_test.info() y_...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
=== ESSAI HUGGING FACE ===
X_train.head() # X_train_txt=X_train['text'].apply(lambda x : tokenizer(preprocess(x), return_tensors='pt')) # X_train_txt.head() # output = X_train_txt.apply(lambda x : model(**x)) # output.describe() def TorchTwitterRoBERTa_Pred(text = "Good night 😊"): text = preprocess(text) otpt = nlp(text)[0] # otpt = ...
/usr/local/lib/python3.8/dist-packages/seaborn/distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms). war...
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
1) Model On commence par dΓ©finir une fonction gΓ©nΓ©rique qui sera en capacitΓ© d'ajuster, optimiser et logger dans MLFlow les rΓ©sultats de pipelines qui seront produits pour chaque essai
def trainPipelineMlFlow(xpName, pipeline, X_train, y_train, X_test, y_test, fixed_params={}, opti=False, iterable_params={}): """ Fonction générique permettant d'entrainer et d'optimiser un pipeline sklearn Les paramètres et résultats sont stockés dans MLFlow """ with mlflow.start_run(run_name=xp...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
La cellule suivante permet de crΓ©er des Γ©tapes de sΓ©lection de colonnes dans les Data Frame en entrΓ©e
from sklearn.base import BaseEstimator, TransformerMixin class TextSelector(BaseEstimator, TransformerMixin): def __init__(self, field): self.field = field def fit(self, X, y=None): return self def transform(self, X): return X[self.field] class NumberSelector(BaseEstimator, Transfo...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
roBERTa RF
roBERTa_RF_pipeline = Pipeline( steps=[ ('roBERTa', clTwitterroBERTa(field='text')), ("classifier", RandomForestClassifier(n_jobs=-1)) ] ) roBERTa_RF_Pipe = Pipeline( steps=[ ('roBERTa', roBERTa_pipe), ("classifier", RandomForestClassifier(n_jobs=-1)) ] ) random_state_p...
_____no_output_____
RSA-MD
notebooks/PyTorch.ipynb
Fabien-DS/DSA_Sentiment
In this Tutorial we will explore how to work with columnar data in HoloViews. Columnar data has a fixed list of column headings, with values stored in an arbitrarily long list of rows. Spreadsheets, relational databases, CSV files, and many other typical data sources fit naturally into this format. HoloViews defines ...
import numpy as np import pandas as pd import holoviews as hv from IPython.display import HTML hv.notebook_extension()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Simple Dataset Usually when working with data we have one or more independent variables, taking the form of categories, labels, discrete sample coordinates, or bins. These variables are what we refer to as key dimensions (or ``kdims`` for short) in HoloViews. The observer or dependent variables, on the other hand, ar...
xs = np.arange(10) ys = np.exp(xs) table = hv.Table((xs, ys), kdims=['x'], vdims=['y']) table
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
However, this data has many more meaningful visual representations, and therefore the first important concept is that Dataset objects are interchangeable as long as their dimensionality allows it, meaning that you can easily create the different objects from the same data (and cast between the objects once created):
hv.Scatter(table) + hv.Curve(table) + hv.Bars(table)
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Each of these three plots uses the same data, but represents a different assumption about the semantic meaning of that data -- the Scatter plot is appropriate if that data consists of independent samples, the Curve plot is appropriate for samples chosen from an underlying smooth function, and the Bars plot is appropria...
print(hv.Scatter({'x': xs, 'y': ys}) + hv.Scatter(np.column_stack([xs, ys])) + hv.Scatter(pd.DataFrame({'x': xs, 'y': ys})))
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
LiteralsIn addition to the main storage formats, Dataset Elements support construction from three Python literal formats: (a) An iterator of y-values, (b) a tuple of columns, and (c) an iterator of row tuples.
print(hv.Scatter(ys) + hv.Scatter((xs, ys)) + hv.Scatter(zip(xs, ys)))
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
For these inputs, the data will need to be copied to a new data structure, having one of the three storage formats above. By default Dataset will try to construct a simple array, falling back to either pandas dataframes (if available) or the dictionary-based format if the data is not purely numeric. Additionally, the ...
df = pd.DataFrame({'x': xs, 'y': ys, 'z': ys*2}) print(type(hv.Scatter(df).data))
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Dataset will attempt to parse the supplied data, falling back to each consecutive interface if the previous could not interpret the data. The default list of fallbacks and simultaneously the list of allowed datatypes is:
hv.Dataset.datatype
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Note these include grid based datatypes, which are not covered in this tutorial. To select a particular storage format explicitly, supply one or more allowed datatypes:
print(type(hv.Scatter((xs.astype('float64'), ys), datatype=['array']).data)) print(type(hv.Scatter((xs, ys), datatype=['dictionary']).data)) print(type(hv.Scatter((xs, ys), datatype=['dataframe']).data))
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Sharing Data Since the formats with labelled columns do not require any specific order, each Element can effectively become a view into a single set of data. By specifying different key and value dimensions, many Elements can show different values, while sharing the same underlying data source.
overlay = hv.Scatter(df, kdims='x', vdims='y') * hv.Scatter(df, kdims='x', vdims='z') overlay
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
We can quickly confirm that the data is actually shared:
overlay.Scatter.I.data is overlay.Scatter.II.data
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
For columnar data, this approach is much more efficient than creating copies of the data for each Element, and allows for some advanced features like linked brushing in the [Bokeh backend](Bokeh_Backend.ipynb). Converting to raw data Column types make it easy to export the data to the three basic formats: arrays, data...
table.array()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Pandas DataFrame
HTML(table.dframe().head().to_html())
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Dataset dictionary
table.columns()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Creating tabular data from Elements using the .table and .dframe methodsIf you have data in some other HoloViews element and would like to use the columnar data features, you can easily tabularize any of the core Element types into a ``Table`` Element, using the ``.table()`` method. Similarly, the ``.dframe()`` metho...
xs = np.arange(10) curve = hv.Curve(zip(xs, np.exp(xs))) curve * hv.Scatter(curve) + curve.table()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Similarly, we can get a pandas dataframe of the Curve using ``curve.dframe()``. Here we wrap that call as raw HTML to allow automated testing of this notebook, but just calling ``curve.dframe()`` would give the same result visually:
HTML(curve.dframe().to_html())
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Although 2D image-like objects are *not* inherently well suited to a flat columnar representation, serializing them by converting to tabular data is a good way to reveal the differences between Image and Raster elements. Rasters are a very simple type of element, using array-like integer indexing of rows and columns f...
%%opts Points (s=200) [size_index=None] extents = (-1.6,-2.7,2.0,3) np.random.seed(42) mat = np.random.rand(3, 3) img = hv.Image(mat, bounds=extents) raster = hv.Raster(mat) img * hv.Points(img) + img.table() + \ raster * hv.Points(raster) + raster.table()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Tabularizing space containersEven deeply nested objects can be deconstructed in this way, serializing them to make it easier to get your raw data out of a collection of specialized Element types. Let's say we want to make multiple observations of a noisy signal. We can collect the data into a HoloMap to visualize it a...
obs_hmap = hv.HoloMap({i: hv.Image(np.random.randn(10, 10), bounds=(0,0,3,3)) for i in range(3)}, kdims=['Observation']) obs_hmap
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Now we can serialize this data just as before, where this time we get a four-column (4D) table. The key dimensions of both the HoloMap and the Images, as well as the z-values of each Image, are all merged into a single table. We can visualize the samples we have collected by converting it to a Scatter3D object.
%%opts Layout [fig_size=150] Scatter3D [color_index=3 size_index=None] (cmap='hot' edgecolor='k' s=50) obs_hmap.table().to.scatter3d() + obs_hmap.table()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Here the `z` dimension is shown by color, as in the original images, and the other three dimensions determine where the datapoint is shown in 3D. This way of deconstructing will work for any data structure that satisfies the conditions described above, no matter how nested. If we vary the amount of noise while continui...
from itertools import product extents = (0,0,3,3) error_hmap = hv.HoloMap({(i, j): hv.Image(j*np.random.randn(3, 3), bounds=extents) for i, j in product(range(3), np.linspace(0, 1, 3))}, kdims=['Observation', 'noise']) noise_layout = error_hmap.layout('noise') noise_layo...
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
And again, we can easily convert the object to a ``Table``:
%%opts Table [fig_size=150] noise_layout.table()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Applying operations to the data Sorting by columns Once data is in columnar form, it is simple to apply a variety of operations. For instance, Dataset can be sorted by their dimensions using the ``.sort()`` method. By default, this method will sort by the key dimensions, but any other dimension(s) can be supplied t...
bars = hv.Bars((['C', 'A', 'B', 'D'], [2, 7, 3, 4])) bars + bars.sort() + bars.sort(['y'])
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Working with categorical or grouped data Data is often grouped in various ways, and the Dataset interface provides various means to easily compare between groups and apply statistical aggregates. We'll start by generating some synthetic data with two groups along the x-axis and 4 groups along the y axis.
n = np.arange(1000) xs = np.repeat(range(2), 500) ys = n%4 zs = np.random.randn(1000) table = hv.Table((xs, ys, zs), kdims=['x', 'y'], vdims=['z']) table
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Since there are repeat observations of the same x- and y-values, we have to reduce the data before we display it or else use a datatype that supports plotting distributions in this way. The ``BoxWhisker`` type allows doing exactly that:
%%opts BoxWhisker [aspect=2 fig_size=200 bgcolor='w'] hv.BoxWhisker(table)
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Aggregating/Reducing dimensions Most types require the data to be non-duplicated before being displayed. For this purpose, HoloViews makes it easy to ``aggregate`` and ``reduce`` the data. These two operations are simple complements of each other--aggregate computes a statistic for each group in the supplied dimensio...
%%opts Bars [show_legend=False] {+axiswise} hv.Bars(table).aggregate(function=np.mean) + hv.Bars(table).reduce(x=np.mean)
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
(**A**) aggregates over both the x and y dimension, computing the mean for each x/y group, while (**B**) reduces the x dimension leaving just the mean for each group along y. Collapsing multiple Dataset Elements When multiple observations are broken out into a HoloMap they can easily be combined using the ``collapse``...
hmap = hv.HoloMap({i: hv.Curve(np.arange(10)*i) for i in range(10)}) collapsed = hmap.collapse(function=np.mean, spreadfn=np.std) hv.Spread(collapsed) * hv.Curve(collapsed) + collapsed.table()
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Working with complex dataIn the last section we only scratched the surface of what the Dataset interface can do. When it really comes into its own is when working with high-dimensional datasets. As an illustration, we'll load a dataset of some macro-economic indicators for OECD countries from 1964-1990, cached on the...
macro_df = pd.read_csv('http://assets.holoviews.org/macro.csv', '\t') HTML(macro_df.head().to_html())
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
As we can see the data has abbreviated the names of the columns, which is convenient when referring to the variables but is often not what's desired when assigning axis labels, generating widgets, or adding titles.HoloViews dimensions provide a way to alias the variable names so you can continue to refer to the data by...
key_dimensions = [('year', 'Year'), ('country', 'Country')] value_dimensions = [('unem', 'Unemployment'), ('capmob', 'Capital Mobility'), ('gdp', 'GDP Growth'), ('trade', 'Trade')]
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
We'll also take this opportunity to set default options for all the following plots.
%output dpi=100 options = hv.Store.options() opts = hv.Options('plot', aspect=2, fig_size=250, show_frame=False, show_grid=True, legend_position='right') options.NdOverlay = opts options.Overlay = opts
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews
Loading the dataAs we saw above, we can supply a dataframe to any Dataset type. When dealing with so many dimensions it would be cumbersome to supply all the dimensions explicitly, but luckily Dataset can easily infer the dimensions from the dataframe itself. We simply supply the ``kdims``, and it will infer that all ...
macro = hv.Table(macro_df, kdims=key_dimensions, vdims=value_dimensions)
_____no_output_____
BSD-3-Clause
doc/Tutorials/Columnar_Data.ipynb
stuarteberg/holoviews