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
4. Iterating through the fieldThe field object itself is an iterable. That means that it can be iterated through. As a result it returns a tuple, where the first element is the coordinate of the mesh point, whereas the second one is its value.
for coordinate, value in field: print(coordinate, value)
(-25.0, -25.0, -25.0) (625.0, 1250.0, -15625.0) (25.0, -25.0, -25.0) (-625.0, -1250.0, 15625.0) (-25.0, 25.0, -25.0) (-625.0, -1250.0, 15625.0) (25.0, 25.0, -25.0) (625.0, 1250.0, -15625.0) (-25.0, -25.0, 25.0) (625.0, 1250.0, 15625.0) (25.0, -25.0, 25.0) (-625.0, -1250.0, -15625.0) (-25.0, 25.0, 25.0) (-625.0, -1250.0...
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
5. Sampling the field along the lineTo sample the points of the field which are on a certain line, `discretisedfield.Field.line` method is used. It takes two points `p1` and `p2` that define the line and an integer `n` which defines how many mesh coordinates on that line are required. The default value of `n` is 100.
line = field.line(p1=(-10, 0, 0), p2=(10, 0, 0), n=5)
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
6. Intersecting the field with a planeIf we intersect the field with a plane, `discretisedfield.Field.plane` will return a new field object which contains only discretisation cells that belong to that plane. The planes allowed are the planes perpendicular to the axes of the Cartesian coordinate system. For instance, a...
field.plane(x=1)
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
If we want to cut through the middle of the mesh, we do not need to provide a particular value for a coordinate.
field.plane('x')
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
7. Cascading the operationsLet us say we want to compute the average of an $x$ component of the field on the plane $y=10$. In order to do that, we can cascade several operation in a single line.
field.plane(y=10).x.average
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
This gives the same result as for instance
field.x.plane(y=10).average
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
8. Complex fields`discretisedfield` supports complex-valued fields.
cfield = df.Field(mesh, dim=3, value=(1+1.5j, 2, 3j))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
We can extract `real` and `imaginary` part.
cfield.real((0, 0, 0)) cfield.imag((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Similarly we get `real` and `imaginary` parts of individual components.
cfield.x.real((0, 0, 0)) cfield.x.imag((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Complex conjugate.
cfield.conjugate((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Phase in the complex plane.
cfield.phase((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
9. Applying `numpys` universal functionsAll numpy universal functions can be applied to `discretisedfield.Field` objects. Below we show a different examples. For available functions please refer to the `numpy` [documentation](https://numpy.org/doc/stable/reference/ufuncs.htmlavailable-ufuncs).
import numpy as np f1 = df.Field(mesh, dim=1, value=1) f2 = df.Field(mesh, dim=1, value=np.pi) f3 = df.Field(mesh, dim=1, value=2) np.sin(f1) np.sin(f2)((0, 0, 0)) np.sum((f1, f2, f3))((0, 0, 0)) np.exp(f1)((0, 0, 0)) np.power(f3, 2)((0, 0, 0))
_____no_output_____
BSD-3-Clause
docs/field-operations.ipynb
ubermag/discretisedfield
Exercise 1 Step 1. Go to https://www.kaggle.com/openfoodfacts/world-food-facts/data Step 2. Download the dataset to your computer and unzip it.
import pandas as pd
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 3. Use the tsv file and assign it to a dataframe called food
Location = r'/Users/GregoireCourtois/Desktop/Python_programmes/Pandas exercises/pandas_exercises-master/01_Getting_&_Knowing_Your_Data/World Food Facts/en.openfoodfacts.org.products.tsv' food = pd.read_csv(Location, sep='\t') #tsv file are tabular spaced! csv fil are comma spaced
/Applications/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3146: DtypeWarning: Columns (0,3,5,19,20,24,25,26,27,28,36,37,38,39,48) have mixed types.Specify dtype option on import or set low_memory=False. has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 4. See the first 5 entries
food.head()
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 5. What is the number of observations in the dataset?
food.shape food.shape[0]
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 6. What is the number of columns in the dataset?
food.shape[1] food.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 356027 entries, 0 to 356026 Columns: 163 entries, code to water-hardness_100g dtypes: float64(107), object(56) memory usage: 442.8+ MB
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 7. Print the name of all the columns.
food.columns
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 8. What is the name of 105th column?
food.columns[104]
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 9. What is the type of the observations of the 105th column?
food['-glucose_100g'].dtype
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 10. How is the dataset indexed?
food.index
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
Step 11. What is the product name of the 19th observation?
food['product_name'][18] food.values[18][7] #way longer
_____no_output_____
BSD-3-Clause
01_Getting_&_Knowing_Your_Data/World Food Facts/Exercises.ipynb
GregoireCourtois/pandas_exercises
**Let's check out the calculation of rates of returns on single assets**The steps are as follows;1. Import Python's number crunching libraries2. Use panda's data reader to get real world stock information of Apple3. Explore the data4. Calculate rate of return using the simple returns fomula 5. Calculate rate of return...
# Step 1 (import python's number crunchers) import pandas as pd import numpy as np from pandas_datareader import data as web # Step 2 & 3 (Get Apple stock information using Pandas Datareader) data = pd.DataFrame() tickers = ['AAPL'] for item in tickers: data[item] = web.DataReader(item, data_source='yahoo', sta...
_____no_output_____
MIT
source/02-portfolios-tutorials/notebook/Returns On Single Assets.ipynb
EmanuelFontelles/machineLearningForTrading
Search with Options- Piece or Corpus- Actual or Incremental Durations- Chromatic or Diatonic- Exact or Close- Classify***
from crim_intervals import * import pandas as pd import ast import matplotlib from itertools import tee, combinations
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
The Complete Corpus
work_list = ['CRIM_Mass_0001_1.mei','CRIM_Mass_0001_2.mei','CRIM_Mass_0001_3.mei','CRIM_Mass_0001_4.mei','CRIM_Mass_0001_5.mei','CRIM_Mass_0002_1.mei','CRIM_Mass_0002_2.mei','CRIM_Mass_0002_3.mei','CRIM_Mass_0002_4.mei','CRIM_Mass_0002_5.mei','CRIM_Mass_0003_1.mei','CRIM_Mass_0003_2.mei','CRIM_Mass_0003_3.mei','CRIM_Ma...
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Short Corpus
work_list = ['CRIM_Mass_0002_1.mei', 'CRIM_Mass_0002_2.mei', 'CRIM_Mass_0002_3.mei', 'CRIM_Mass_0002_4.mei', 'CRIM_Mass_0002_5.mei', 'CRIM_Model_0001.mei'] # work_list = [ # 'CRIM_Model_0008.mei']
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Load File and Correct the MEI Metadata
work_list = [el.replace("CRIM_", "https://crimproject.org/mei/MEI_4.0/CRIM_") for el in work_list] corpus = CorpusBase(work_list) import xml.etree.ElementTree as ET import requests MEINSURI = 'http://www.music-encoding.org/ns/mei' MEINS = '{%s}' % MEINSURI for i, path in enumerate(work_list): try: i...
Requesting file from https://crimproject.org/mei/MEI_4.0/CRIM_Mass_0002_1.mei... Successfully imported. Requesting file from https://crimproject.org/mei/MEI_4.0/CRIM_Mass_0002_2.mei... Successfully imported. Requesting file from https://crimproject.org/mei/MEI_4.0/CRIM_Mass_0002_3.mei... Successfully imported. Requesti...
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Select Actual or Incremental Durations About Rhythmic Durations- For `find_close_matches` and `find_exact_matches`, rhythmic variation/duration is displayed, but **not** factored into the calculation of matching.- **Incremental Offset** calculates the intervals using a **fixed offset between notes**, no matter their a...
vectors = IntervalBase(corpus.note_list) #vectors = IntervalBase(corpus.note_list_incremental_offset(2))
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
*** Select Generic or Semitone Scale:- **Length of the Soggetto**: `into_patterns([vectors.semitone_intervals], 5)` - The **number** in this command represents the **minimum number of vectors to find**. 5 vectors is 6 notes.
patterns = into_patterns([vectors.generic_intervals], 8) #patterns = into_patterns([vectors.semitone_intervals], 4)
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
*** Select Exact Matches Here, or Close Below (Use comment feature to select screen preview or CSV output) - **Exact** is exact in *all* ways `find_exact_matches(patterns, 2)` - The **number** in this command represents the **minimum number of matching melodies needed before reporting**. This allows us to filter for co...
exact_matches = find_exact_matches(patterns, 3) # Use this for exact screen preview #for item in exact_matches: #item.print_exact_matches() output_exact = export_pandas(exact_matches) pd.DataFrame(output_exact).head() output_exact["pattern_generating_match"] = output_exact["pattern_generating_match"].apply(tuple) ...
Finding exact matches... 57 melodic intervals had more than 3 exact matches.
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
A Quick Overview of the Results
total_matches = len(output_exact) unique_sogetti = output_exact.pattern_generating_match.apply(str).nunique() summary = 'There are {} unique soggetti and {} total matches in this search'.format(unique_sogetti, total_matches) summary
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Group by the Pattern Generating Match and Check Distribution of Results- Report Top Ten and Bottom Ten Results)
pattern_inventory = pd.DataFrame(output_exact.groupby("pattern_generating_match").size().sort_values(ascending=False)[:10]) pattern_inventory pattern_inventory = pd.DataFrame(output_exact.groupby("pattern_generating_match").size().sort_values(ascending=True)[:10]) pattern_inventory
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
*** Select Close Matches Here (Comment out the 'for item iteration' in order to skip screen preview)- **Close** matches allow for melodic variation (see more below). `find_close_matches(patterns, 2, 1)`- The **first number** in this command is the **minimum number of melodies** needed before reporting- The **second num...
close_matches = find_close_matches(patterns, 2, 1) #for item in close_matches: #item.print_close_matches() #return pd.DataFrame(close_matches) output_close = export_pandas(close_matches) output_close["pattern_generating_match"] = output_close["pattern_generating_match"].apply(tuple) results = pd.DataFrame(outp...
Finding close matches... 644 melodic intervals had more than 2 exact or close matches.
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
How Many Unique Soggetti? How many instances?
total_matches = len(output_close) unique_sogetti = output_close.pattern_generating_match.apply(str).nunique() summary = 'There are {} unique soggetti and {} total matches in this search'.format(unique_sogetti, total_matches) summary
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Top and Bottom Ten Soggetti
pattern_inventory = pd.DataFrame(output_close.groupby("pattern_generating_match").size().sort_values(ascending=False)[:50]) pattern_inventory pattern_inventory = pd.DataFrame(output_close.groupby("pattern_generating_match").size().sort_values(ascending=True)[:10]) pattern_inventory
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
*** Classify Patterns Here Note: depends on choice of Close or Exact above! Must choose appropriate one below! Enable "export_to_csv" line to allow this within Notebook (must answer "Y" and provide filename)
%%capture classify_matches(close_matches, 2) #classify_matches(exact_matches, 2) cm = classify_matches(close_matches, 2) #pd.DataFrame(classified_matches) output_cm = export_pandas(cm) #pd.DataFrame(output).head() ## For CSV export, use the following (and follow prompts for file name) #export_to_csv(cm) short_out =...
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Read CSV of Classified Matches- Update file name to match the output of previous cells for Classifier
results = pd.read_csv('Sandrin_Classified.csv') results.rename(columns= {'Pattern Generating Match': 'Pattern_Generating_Match', 'Pattern matched':'Pattern_Matched', 'Classification Type': 'Classification_Type', 'Piece Title': 'Piece_Title'...
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Durational Ratios This Function Calculates the Ratios of the Durations in each Match
# makes pairs of ratio strings def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def get_ratios(input_list): ratio_pairs = [] for a, b in pairwise(input_list): ratio_pairs.append(b / a) return ratio_pairs
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Now call the function to operate on the RESULTS file from earlier
# calculates 'duration ratios' for each soggetto, then adds this to the DF results["duration_ratios"] = results.note_durations.apply(get_ratios) short_results = results.drop(columns=["ema_url"]) short_out.head(10)
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Group by the Pattern Generating Match- Each has its own string of durations, and duration ratios- and then we compare the ratios to get the differences- the "list(combinations)" method takes care of building the pairs, using data from our dataframe 'results'
def compare_ratios(ratios_1, ratios_2): ## division of lists # using zip() + list comprehension diffs = [i - j for i, j in zip(ratios_1, ratios_2)] abs_diffs = [abs(ele) for ele in diffs] sum_diffs = sum(abs_diffs) return sum_diffs #results["Pattern_Generating_Match"] = results["Patte...
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Now Run the Function to get the 'edit distances' for the durations of matching patterns
ratio_distances = get_ratio_distances(results, "pattern_generating_match", ["piece_title", "part", "start_measure", "end_measure"]) ratio_distances.head()
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
And FILTER the results according to any threshold we like
ratios_filtered = ratio_distances[ratio_distances.sum_diffs <= 1] ratios_filtered
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Now Group the Duration-Filter Results by the Pattern (which shows us very closely related soggetti in sets)
grouped = ratios_filtered.groupby("pattern") grouped.head() ratios_filtered.to_csv("filtered_sample_pair.csv")
_____no_output_____
MIT
CRIM_Intervals_Classify_12_31_20.ipynb
RichardFreedman/CRIM-notebooks
Use the Shirt ClassYou've seen what a class looks like and how to instantiate an object. Now it's your turn to write code that insantiates a shirt object. Explanation of the CodeThis Jupyter notebook is inside of a folder called 1.OOP_syntax_shirt_practice. You can see the folder if you click on the "Jupyter" logo abo...
class Shirt: def __init__(self, shirt_color, shirt_size, shirt_style, shirt_price): self.color = shirt_color self.size = shirt_size self.style = shirt_style self.price = shirt_price def change_price(self, new_price): self.price = new_price def disc...
_____no_output_____
MIT
lessons/ObjectOrientedProgramming/JupyterNotebooks/1.OOP_syntax_shirt_practice/shirt_exercise.ipynb
thomasdunlap/DSND_Term2
Test your CodeThe following code cell tests your code. There is a file called tests.py containing a function called run_tests(). The run_tests() function executes a handful of assert statements to check your work. You can see this file if you go to the Jupyter Notebook menu and click on "File->Open" and then open the ...
# Unit tests to check your solution from tests import run_tests run_tests(shirt_one, shirt_two, total, total_discount)
_____no_output_____
MIT
lessons/ObjectOrientedProgramming/JupyterNotebooks/1.OOP_syntax_shirt_practice/shirt_exercise.ipynb
thomasdunlap/DSND_Term2
______Content Copyright by Pierian Data Python DebuggerYou've probably used a variety of print statements to try to find errors in your code. A better way of doing this is by using Python's built-in debugger module (pdb). The pdb module implements an interactive debugging environment for Python programs. It includes f...
x = [1,3,4] y = 2 z = 3 result = y + z print(result) result2 = y+x print(result2)
5
DOC
Complete-Python-3-Bootcamp-master/12-Advanced Python Modules/04-Python Debugger (pdb).ipynb
davidMartinVergues/PYTHON
Hmmm, looks like we get an error! Let's implement a set_trace() using the pdb module. This will allow us to basically pause the code at the point of the trace and check if anything is wrong.
import pdb x = [1,3,4] y = 2 z = 3 result = y + z print(result) # Set a trace using Python Debugger pdb.set_trace() result2 = y+x print(result2)
5 --Return-- > <ipython-input-2-1084246755fa>(11)<module>()->None -> pdb.set_trace() (Pdb) x [1, 3, 4] (Pdb) y 2 (Pdb) result2 *** NameError: name 'result2' is not defined (Pdb) q
DOC
Complete-Python-3-Bootcamp-master/12-Advanced Python Modules/04-Python Debugger (pdb).ipynb
davidMartinVergues/PYTHON
[NTDS'19] tutorial 5: machine learning with scikit-learn[ntds'19]: https://github.com/mdeff/ntds_2019[Nicolas Aspert](https://people.epfl.ch/nicolas.aspert), [EPFL LTS2](https://lts2.epfl.ch).* Dataset: [digits](https://archive.ics.uci.edu/ml/datasets/Pen-Based+Recognition+of+Handwritten+Digits)* Tools: [scikit-learn]...
%matplotlib inline import numpy as np from matplotlib import pyplot as plt import sklearn
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Data loadingWe will use a dataset named *digits*.It is made of 1797 handwritten digits images (of size 8x8 pixels each) acquired from 44 different writers. Each image is labelled according to the digit present in the image.You can find more information about this dataset [here](https://archive.ics.uci.edu/ml/datasets/...
from sklearn.datasets import load_digits digits = load_digits()
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
The `digits` variable contains several fields.In `images` you have all samples as 2-dimensional arrays.
print(digits.images.shape) print(digits.images[0]) plt.imshow(digits.images[0], cmap=plt.cm.gray);
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
In `data`, the same samples are represented as 1-d vectors of length 64.
print(digits.data.shape) print(digits.data[0])
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
In `target` you have the label corresponding to each image.
print(digits.target.shape) print(digits.target)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Let us visualize the 20 first entries of the dataset (image display kept small on purpose)
fig = plt.figure(figsize=(15, 0.5)) for index, (image, label) in enumerate(zip(digits.images[0:20], digits.target[0:20])): ax = fig.add_subplot(1, 20, index+1) ax.imshow(image, cmap=plt.cm.gray) ax.set_title(label) ax.axis('off')
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Training/Test setBefore training our model, the [`train_test_split`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function will separate our dataset into a training set and a test set. The samples from the test set are never used during the training phase. This allow...
from sklearn.model_selection import train_test_split train_img, test_img, train_lbl, test_lbl = train_test_split( digits.data, digits.target, test_size=1/6) # keep ~300 images as test set
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
We can check that all classes are well balanced in the training and test sets.
np.histogram(train_lbl, bins=10) np.histogram(test_lbl, bins=10)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Supervised learning: logistic regression Linear regression reminderLinear regression is used to predict an dependent value $y$ from an n-dimensional vector $x$.The assumption made here is that the output depends linearly on the input components, i.e. $y = mx + b$.Given a set of input and output values, the goal is to ...
from sklearn.linear_model import LogisticRegression # All unspecified parameters are left to their default values. logisticRegr = LogisticRegression(verbose=1, solver='liblinear', multi_class='auto') # set solver and multi_class to silence warnings logisticRegr.fit(train_img, train_lbl)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Model performance evaluationFor a binary classification problem, let us denote by $TP$, $TN$, $FP$, and $FN$ the number of true positives, true negatives, false positives and false negatives. AccuracyThe *accuracy* is defined by $a = \frac{TP}{TP + TN + FP + FN}$NB: in scikit-learn, models may have different definitio...
score = logisticRegr.score(test_img, test_lbl) print(f'accuracy = {score:.4f}')
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
F1 scoreAccuracy only provides partial information about the performance of a model. Many other [metrics](https://scikit-learn.org/stable/modules/model_evaluation.htmlclassification-metrics) are part of scikit-learn.A metric that provides a more complete overview of the classification performance is the [F1 score](htt...
pred_lbl = logisticRegr.predict(test_img) from sklearn.metrics import f1_score, classification_report from sklearn.utils.multiclass import unique_labels
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
The [`f1_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.htmlsklearn.metrics.f1_score) function computes the F1 score. The `average` parameter controls whether the result is computed globally over all classes (`average='micro'`) or if the F1 score is computed for each class then avera...
f1_score(test_lbl, pred_lbl, average='micro') f1_score(test_lbl, pred_lbl, average='macro')
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
`classification_report` provides a synthetic overview of all results for each class, as well as globally.
print(classification_report(test_lbl, pred_lbl))
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Confusion matrixIn the case of a multi-class problem, the *confusion matrix* is often used to present the results.
from sklearn.metrics import confusion_matrix def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applie...
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Supervised learning: support-vector machines[Support-vector machines (SVM)](https://en.wikipedia.org/wiki/Support-vector_machine) are also used for classification tasks.For a binary classification task of $n$-dimensional feature vectors, a linear SVM try to return the ($n-1$)-dimensional hyperplane that separate the t...
from sklearn import svm
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Default parameters perform well on this dataset.It might be needed to adjust $C$ and $\gamma$ (e.g. via a grid search) for optimal performance (cf. [SVC documentation](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.htmlsklearn.svm.SVC)).
clf = svm.SVC(gamma='scale') # default kernel is RBF clf.fit(train_img, train_lbl)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
The classification accuracy improves with respect to logistic regression (here `score` also computes mean accuracy, as in logistic regression).
clf.score(test_img, test_lbl)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
The F1 score is also improved.
pred_lbl_svm = clf.predict(test_img) print(classification_report(test_lbl, pred_lbl_svm))
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Unsupervised learning: $k$-means[$k$-means](https://en.wikipedia.org/wiki/K-means_clustering) aims at partitioning a samples into $k$ clusters, s.t. each sample belongs to the cluster having the closest mean. Its implementation is iterative, and relies on a prior knowledge of the number of clusters present. One import...
from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=10) kmeans.fit(digits.data) km_labels = kmeans.predict(digits.data) digits.target km_labels
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Since we have ground truth information of classes, we can check if the $k$-means results make sense.However as you can see, the labels produced by $k$-means and the ground truth ones do not match.An agreement score based on [mutual information](https://scikit-learn.org/stable/modules/clustering.htmlclustering-evaluatio...
from sklearn.metrics import adjusted_mutual_info_score adjusted_mutual_info_score(digits.target, kmeans.labels_)
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Unsupervized learning: dimensionality reductionYou can also try to visualize the clusters as in this [scikit-learn demo](https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_digits.html). Mapping the input features to lower dimensional embeddings (2D or 3D), e.g. using PCA otr tSNE is required for visuali...
from matplotlib import offsetbox def plot_embedding(X, y, title=None): """Scale and visualize the embedding vectors.""" x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], ...
_____no_output_____
MIT
tutorials/05_scikit_learn.ipynb
sylvainlugeon/ntds_2019
Introduction to artifacts and artifact detection================================================Since MNE supports the data of many different acquisition systems, theparticular artifacts in your data might behave very differently from theartifacts you can observe in our tutorials and examples.Therefore you should be aw...
import numpy as np import mne from mne.datasets import sample from mne.preprocessing import create_ecg_epochs, create_eog_epochs # getting some data ready data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True)
_____no_output_____
BSD-3-Clause
stable/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb
drammock/mne-tools.github.io
Low frequency drifts and line noise
(raw.copy().pick_types(meg='mag') .del_proj(0) .plot(duration=60, n_channels=100, remove_dc=False))
_____no_output_____
BSD-3-Clause
stable/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb
drammock/mne-tools.github.io
we see high amplitude undulations in low frequencies, spanning across tens ofseconds
raw.plot_psd(tmax=np.inf, fmax=250)
_____no_output_____
BSD-3-Clause
stable/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb
drammock/mne-tools.github.io
On MEG sensors we see narrow frequency peaks at 60, 120, 180, 240 Hz,related to line noise.But also some high amplitude signals between 25 and 32 Hz, hinting at otherbiological artifacts such as ECG. These can be most easily detected in thetime domain using MNE helper functionsSee `tut-filter-resample`. ECG---finds ECG...
average_ecg = create_ecg_epochs(raw).average() print('We found %i ECG events' % average_ecg.nave) joint_kwargs = dict(ts_args=dict(time_unit='s'), topomap_args=dict(time_unit='s')) average_ecg.plot_joint(**joint_kwargs)
_____no_output_____
BSD-3-Clause
stable/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb
drammock/mne-tools.github.io
we can see typical time courses and non dipolar topographiesnot the order of magnitude of the average artifact related signal andcompare this to what you observe for brain signals EOG---
average_eog = create_eog_epochs(raw).average() print('We found %i EOG events' % average_eog.nave) average_eog.plot_joint(**joint_kwargs)
_____no_output_____
BSD-3-Clause
stable/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb
drammock/mne-tools.github.io
Exporting models from Caffe2 to ONNXIn this tutorial we are going to show you how to export a Caffe2 model to ONNX. You can either- Convert a Caffe2 model to an ONNX model in Pythonor - Convert a Caffe2 model file to an ONNX model file in the shellWe are going to use the squeezenet model in Caffe2 model zoo, its model...
import onnx import caffe2.python.onnx.frontend from caffe2.proto import caffe2_pb2 # We need to provide type and shape of the model inputs, # see above Note section for explanation data_type = onnx.TensorProto.FLOAT data_shape = (1, 3, 224, 224) value_info = { 'data': (data_type, data_shape) } predict_net = caff...
_____no_output_____
Apache-2.0
tutorials/Caffe2OnnxExport.ipynb
oblanchet/tutorials
Implement image blendingWe will start by importing libraries and defining a couple of functions for displaying images using matplotlib.
import cv2 import matplotlib.pyplot as plt import numpy as np %matplotlib inline plt.rcParams['figure.figsize'] = [20, 10] def showResult(title, img): # Colour images in OpenCV are given in BGR, but matplotlib expects RGB. # We therefore need to convert the OpenCV images. plt.imshow(cv2.cvtColor(img, cv2....
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
1. Load and convert the source imagesNow let's do some image processing!First, we need to read the two images we want to blend. - Read two images (choose two of the images given in the `data` directory) - Hint: [cv::imread(...)](https://docs.opencv.org/4.0.1/d4/da8/group__imgcodecs.htmlga288b8b3d...
# Load the images. img_01_fname = "data/tiger.png" img_01 = cv2.imread(img_01_fname) img_01 = np.float32(img_01) * (1.0/255.0) img_02_fname = "data/white_tiger.png" img_02 = cv2.imread(img_02_fname) img_02 = np.float32(img_02) * (1.0/255.0) # Show the loaded images. showResultsSideBySide(img_01_fname, img_01, img_02_...
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
2. Create an image with weights for blendingNow we need to define how the two images should be blended together.We will do this by constructing a weight image with weights $w(u, v) \in [0, 1].$A weight of 1 means that the blended pixel will be equal to the corresponding pixel in image 1, while a weight of 0.5 means th...
# Construct a half black, half white image. weights = np.zeros(img_01.shape, dtype=np.float32) half_image_width = int(0.5 * weights.shape[1]) weights[:, :half_image_width] = (1., 1., 1.) # Create a ramp between the two halves. ramp_width = 50 weights = cv2.blur(weights, (ramp_width+1, ramp_width+1)) # Visualise the w...
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
3. Simple linear blendingThe next step is to implement functionality for simple linear blending, where the two images are mixed according to the weight image. a) Implement linear blending of two images using the weights- $res = w \cdot img_1 + (1-w) \cdot img_2$- Tip: You can solve this step using only image operatio...
def linearBlending(img1, img2, mask): return img1 * mask + img2 * (1.-mask) # Test linear blending. linear_blend = linearBlending(img_01, img_02, weights) showResult('linear_blend', linear_blend)
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
4. Laplace blendingTo demonstrate the difference between simple linear blending, and scale-aware blending, we will now implement and test Laplace blending.We will even get to play around with scale pyramids!Recall from the lecture that Laplace blending performs linear blending at different stages in the laplacian pyra...
def constructGaussianPyramid(img): # Construct the pyramid starting with the original image. pyr = [img] # Add new downscaled images to the pyramid # until image width is <= 16 pixels while pyr[-1].shape[1] > 16: pyr.append(cv2.pyrDown(pyr[-1])) return pyr
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
b) Construct a Laplacian pyramid![Laplacian pyramid](img/thumb_pyr_laplace.png)- Hint: Use [cv::pyrUp()](https://docs.opencv.org/4.5.5/d4/d86/group__imgproc__filter.htmlgada75b59bdaaca411ed6fee10085eb784)
def constructLaplacianPyramid(img): pyr = constructGaussianPyramid(img) for i in range(len(pyr)-1): pyr[i] -= cv2.pyrUp(pyr[i+1], dstsize=pyr[i].shape[0:2]) return pyr
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
c) Implement function for collapsing the Laplacian pyramid![Collapsing the Laplacian pyramid](img/thumb_pyr_collapse.png)- Hint: Use [cv::pyrUp()](https://docs.opencv.org/4.5.5/d4/d86/group__imgproc__filter.htmlgada75b59bdaaca411ed6fee10085eb784)
def collapsePyramid(pyr): for i in range(len(pyr)-2, -1, -1): pyr[i] += cv2.pyrUp(pyr[i+1], dstsize=pyr[i].shape[0:2]) return pyr[0]
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
d) Implement Laplacian blending- Construct a Gaussian pyramid for the weights.- Construct Laplacian pyramids for the images.- Blend the images using `linearBlending()` on each pyramid level.- Reconstruct the blended image by collapsing the blended pyramid.
def laplaceBlending(img1, img2, mask): # Construct a gaussian pyramid of the mask image. pyr_mask = constructGaussianPyramid(mask) # Construct a laplacian pyramid of each of the images. pyr_img1 = constructLaplacianPyramid(img1) pyr_img2 = constructLaplacianPyramid(img2) # Blend the laplacian ...
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
e) Check that the results look reasonable- Test Laplace blending- Compare the results with linear blending.- What happens when you reduce the ramp size down to a very steep gradient?
lap_blend = laplaceBlending(img_01, img_02, weights) showResult('blend', lap_blend)
_____no_output_____
BSD-3-Clause
solution-image-blending.ipynb
tek5030/lab-image-blending-py
2D Numpy in PythonEstimated time needed: **20** minutes ObjectivesAfter completing this lab you will be able to:* Operate comfortably with `numpy`* Perform complex operations with `numpy` Table of Contents Create a 2D Numpy Array Accessing different elements of a Numpy Array Basic Oper...
# Import the libraries import numpy as np import matplotlib.pyplot as plt
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Consider the list a, which contains three nested lists **each of equal size**.
# Create a list a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]] a
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can cast the list to a Numpy Array as follows:
# Convert list to Numpy Array # Every element is the same type A = np.array(a) A
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can use the attribute ndim to obtain the number of axes or dimensions, referred to as the rank.
# Show the numpy array dimensions A.ndim
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Attribute shape returns a tuple corresponding to the size or number of each dimension.
# Show the numpy array shape A.shape
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
The total number of elements in the array is given by the attribute size.
# Show the numpy array size A.size
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Accessing different elements of a Numpy Array We can use rectangular brackets to access the different elements of the array. The correspondence between the rectangular brackets and the list and the rectangular representation is shown in the following figure for a 3x3 array: We can access the 2nd-row, 3rd column as sh...
# Access the element on the second row and third column A[1, 2]
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can also use the following notation to obtain the elements:
# Access the element on the second row and third column A[1][2]
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Consider the elements shown in the following figure We can access the element as follows:
# Access the element on the first row and first column A[0][0]
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can also use slicing in numpy arrays. Consider the following figure. We would like to obtain the first two columns in the first row This can be done with the following syntax:
# Access the element on the first row and first and second columns A[0][0:2]
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Similarly, we can obtain the first two rows of the 3rd column as follows:
# Access the element on the first and second rows and third column A[0:2, 2]
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Corresponding to the following figure: Basic Operations We can also add arrays. The process is identical to matrix addition. Matrix addition of X and Y is shown in the following figure: The numpy array is given by X and Y
# Create a numpy array X X = np.array([[1, 0], [0, 1]]) X # Create a numpy array Y Y = np.array([[2, 1], [1, 2]]) Y
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can add the numpy arrays as follows.
# Add X and Y Z = X + Y Z
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Multiplying a numpy array by a scaler is identical to multiplying a matrix by a scaler. If we multiply the matrix Y by the scaler 2, we simply multiply every element in the matrix by 2, as shown in the figure. We can perform the same operation in numpy as follows
# Create a numpy array Y Y = np.array([[2, 1], [1, 2]]) Y # Multiply Y with 2 Z = 2 * Y Z
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
Multiplication of two arrays corresponds to an element-wise product or Hadamard product. Consider matrix X and Y. The Hadamard product corresponds to multiplying each of the elements in the same position, i.e. multiplying elements contained in the same color boxes together. The result is a new matrix that is the same s...
# Create a numpy array Y Y = np.array([[2, 1], [1, 2]]) Y # Create a numpy array X X = np.array([[1, 0], [0, 1]]) X # Multiply X with Y Z = X * Y Z
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We can also perform matrix multiplication with the numpy arrays A and B as follows: First, we define matrix A and B:
# Create a matrix A A = np.array([[0, 1, 1], [1, 0, 1]]) A # Create a matrix B B = np.array([[1, 1], [1, 1], [-1, 1]]) B
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering
We use the numpy function dot to multiply the arrays together.
# Calculate the dot product Z = np.dot(A,B) Z # Calculate the sine of Z np.sin(Z)
_____no_output_____
MIT
M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb
cmaroblesg/IBM_DevOps-_and_Software_Engineering