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
Upload
uploader = PostImages() extras = [] try: with open(URLS_PATH, 'a') as f_urls: for entry in os.scandir(INPUT_DIR): if entry.is_file(): image_url, extra = uploader.upload_file(entry.path) extras.append(extra) print(entry.name, image_url, '', sep='\...
_____no_output_____
MIT
notebooks/uploader/postimages.ipynb
TheYoke/PngBin
------ Delete Uploaded Images [EXTRA]> Change below cell to code mode to run the cell.
for extra in extras: result = uploader.delete(extra['removal_link']) print(result)
_____no_output_____
MIT
notebooks/uploader/postimages.ipynb
TheYoke/PngBin
3 аттрибута тензора в pytorch:dtype - тип данных хранимых в тензоре (float32, etc.)device - на чём обрабатывается данный тензор (тензоры которые взаимодействую должны быть на одном проце/видяхе)layout - как данные расположены в памяти (не трогай это, дефолтная настройка норм) Создание тензоров (прямо как в NumPy):
# единичный тензор print(torch.eye(3)) # нулевой torch.zeros(2,2) # единичный torch.ones(2,2)
_____no_output_____
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Создание тензоров из данных:Factory function has more tweaking parameters than class constructor, so we will use them more often. They also infere the dtype (they get data in i.e. int32, they save it as int32).Beware that torch.Tensor and torch.tensor CREATE a copy of input data in memory, when torch.as_tensor and tor...
data = np.array([1,2,3]) t1 = torch.Tensor(data) # class constructor t2 = torch.tensor(data) # factory function t3 = torch.as_tensor(data) # factory function t4 = torch.from_numpy(data) # factory function
_____no_output_____
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Reshaping the the tensors, squeezing.reshape() or .view()(одно и то же, просто разные названия) - прямое изменение размеров тензора.squeeze() - удаление всех осей с длинной 1..unsqueeze() - добавляет ось с длиной 1, это позволяет изменять ранг тензора.
t = torch.tensor([ [1,1,1,1], [2,2,2,2], [3,3,3,3] ], dtype=torch.float32) t.shape # number of elements check print(torch.tensor(t.shape).prod()) print(t.numel()) print(t.reshape(2, 1, 2, 3)) # reshape to rank-4 tensor (from rank-2) print(t.reshape(2, 6)) print(t.reshape(1,12)) # tensor rank 2 print(t.resha...
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]]) tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]) tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]]) tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Flattening, Tensor size for neural network.flatten() - позволяет зарешейпить тензор любого ранга в тензор первого рангаОднако для нейросети абсолютно "плоские" данные нам не нужны, т.к. она должна различать batch (какие данные к какой введённой переменой относятся).Нейронка работает с тензорами ранга 4, вот что каждая...
# create 3 "images" 4x4 pixels, grayscale t1 = torch.tensor([ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ]) t2 = torch.tensor([ [2,2,2,2], [2,2,2,2], [2,2,2,2], [2,2,2,2] ]) t3 = torch.tensor([ [3,3,3,3], [3,3,3,3], [3,3,3,3], [3,3,3,3] ]) # stack them to make a tensor ...
_____no_output_____
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
how to use flattenWe can't flatten the whole tensor, cause it will become a simple vector and we won't be able to know where are the "start" and the "end" of each "picture". So we flatten this tensor in such a way that wa preserve the "batch" axis (flattening the color channel with hight and width axes), which tells u...
# bad idea - got vector with 48 pixel, no way to know from which picture each pixel comes from a = t.flatten() print('bad - ', a.shape) # good idea - got 3 images with 16 pixels t = t.flatten(start_dim=1) # start flattening from axis=1 (it`s an index) print('good - ', t.shape)
bad - torch.Size([48]) good - torch.Size([3, 16])
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Broadcasting for element-wise operationsBroadcasting is transforming a lower rank tensor to match the shape of the tensor with which we want it to perform an element-wise operation.All element-wise operations works with tensors due to the broadcasting.
print(t.eq(1)) # equal 1 print(t.abs()) # взятие модуля print(t + 3) print(t.neg())
tensor([[ True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True], [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, ...
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Reduction operation - .ArgMax()Reduction operation on tensor is an operation that reduced the number of elements contained within the tensor.We can use .mean(),.argmax() returns the index of the max value inside the tensor
t4 = torch.tensor([ [0,1,0], [2,0,2], [0,3,0] ], dtype=torch.float32) print(t4.shape) print(t4.sum()) # sum all elements = reduce this tensor to one axis print(t4.sum(dim=0)) print(t4.sum(dim=0).shape) # sum along axis 1 (sum columns) = reduce this tensor to one axis print('value = ', t4.max()) # MAX...
tensor(0.8889) 0.8888888955116272 tensor([0.6667, 1.3333, 0.6667]) [0.6666666865348816, 1.3333333730697632, 0.6666666865348816]
MIT
Books and Courses/PyTorch/1 - tensor creation, reshaping, squeezing, flattening.ipynb
FairlyTales/Machine_Learning_Courses
Aim and motivationThe primary reason I have chosen to create this kernel is to practice and use RNNs for various tasks and applications. First of which is time series data. RNNs have truly changed the way sequential data is forecasted. My goal here is to create the ultimate reference for RNNs here on kaggle. Things t...
# Importing the libraries import numpy as np import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout, GRU, Bidirectional from keras.optimizers import SGD import m...
_____no_output_____
MIT
05-machine-learning-nao-tabular/00-tabular-auto-correlacionado/rnns.ipynb
abefukasawa/datascience_course
Truth be told. That's one awesome score. LSTM is not the only kind of unit that has taken the world of Deep Learning by a storm. We have **Gated Recurrent Units(GRU)**. It's not known, which is better: GRU or LSTM becuase they have comparable performances. GRUs are easier to train than LSTMs. Gated Recurrent UnitsIn si...
# The GRU architecture regressorGRU = Sequential() # First GRU layer with Dropout regularisation regressorGRU.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1],1), activation='tanh')) regressorGRU.add(Dropout(0.2)) # Second GRU layer regressorGRU.add(GRU(units=50, return_sequences=True, input_shape...
_____no_output_____
MIT
05-machine-learning-nao-tabular/00-tabular-auto-correlacionado/rnns.ipynb
abefukasawa/datascience_course
The current version version uses a dense GRU network with 100 units as opposed to the GRU network with 50 units in previous version
# Preparing X_test and predicting the prices X_test = [] for i in range(60,311): X_test.append(inputs[i-60:i,0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1)) GRU_predicted_stock_price = regressorGRU.predict(X_test) GRU_predicted_stock_price = sc.inverse_transform(GRU_pr...
_____no_output_____
MIT
05-machine-learning-nao-tabular/00-tabular-auto-correlacionado/rnns.ipynb
abefukasawa/datascience_course
Sequence GenerationHere, I will generate a sequence using just initial 60 values instead of using last 60 values for every new prediction. **Due to doubts in various comments about predictions making use of test set values, I have decided to include sequence generation.** The above models make use of test set so it is...
# Preparing sequence data initial_sequence = X_train[2708,:] sequence = [] for i in range(251): new_prediction = regressorGRU.predict(initial_sequence.reshape(initial_sequence.shape[1],initial_sequence.shape[0],1)) initial_sequence = initial_sequence[1:] initial_sequence = np.append(initial_sequence,new_pre...
_____no_output_____
MIT
05-machine-learning-nao-tabular/00-tabular-auto-correlacionado/rnns.ipynb
abefukasawa/datascience_course
<h1 style="padding-top: 25px;padding-bottom: 25px;text-align: left; padding-left: 10px; background-color: DDDDDD; color: black;"> AC215: Advanced Practical Data Science, MLOps **Exercise 1 - Dask****Harvard University****Fall 2021****Instructor:**Pavlos Protopapas**Students:**Jiahui Tang, Max Li **Setup Notebook*...
!pip install dask dask[dataframe] dask-image
Requirement already satisfied: dask in /usr/local/lib/python3.7/dist-packages (2.12.0) Requirement already satisfied: dask-image in /usr/local/lib/python3.7/dist-packages (0.6.0) Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.7/dist-packages (from dask-image) (1.4.1) Requirement already satisfie...
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
**Imports**
import os import requests import zipfile import tarfile import shutil import math import json import time import sys import numpy as np import pandas as pd # Dask import dask import dask.dataframe as dd import dask.array as da from dask.diagnostics import ProgressBar
_____no_output_____
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
**Utils** Here are some util functions that we will be using for this exercise
def download_file(packet_url, base_path="", extract=False, headers=None): if base_path != "": if not os.path.exists(base_path): os.mkdir(base_path) packet_file = os.path.basename(packet_url) with requests.get(packet_url, stream=True, headers=headers) as r: r.raise_for_status() with open(os.p...
_____no_output_____
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
**Dataset** **Load Data**
start_time = time.time() download_file("https://github.com/dlops-io/datasets/releases/download/v1.0/Parking_Violations_Issued_-_Fiscal_Year_2017.csv.zip", base_path="datasets", extract=True) execution_time = (time.time() - start_time)/60.0 print("Download execution time (mins)",execution_time) parking_violation_csv = o...
_____no_output_____
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
Q1: Compute Pi with a Slowly Converging SeriesLeibniz published one of the oldest known series in 1676. While this is easy to understand and derive, it converges very slowly.https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 $$\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} ...$$While this is a genu...
# Your code here start_time = time.time() k = int(1e9*2) positive_sum = np.sum(1/np.arange(1, k ,4)) negative_sum = np.sum(-1/np.arange(3, k, 4)) pi_computed = (positive_sum + negative_sum) * 4 execution_time = time.time() - start_time # Error error = np.abs(pi_computed-np.pi) # Report Results print(f'Pi real value =...
Pi real value = 3.141592653590 Pi computed value = 3.141592652590 Error = 9.998e-10 Numpy execution time (sec) 8.094965696334839
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
**Checking 1e9 * 4 terms with Dask**
# Your code here start_time = time.time() k = int(1e9*2) positive_sum_da = da.sum(1/da.arange(1, k, 4)).compute() negative_sum_da = da.sum(-1/da.arange(3, k, 4)).compute() step3_pi = (positive_sum_da + negative_sum_da) * 4 execution_time = time.time() - start_time error = np.abs(step3_pi - np.pi) # Report Results prin...
Pi real value = 3.141592653590 Pi computed value = 3.141592652590 Error = 1.000e-09 Dask Array execution time (sec) 4.978763103485107
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
Filter Parking Tickets DatasetAccording to the parking tickets data set documentation, the column called ‘Plate Type’ consists mainly of two different types, ‘PAS’ and ‘COM’; presumably for passenger and commercial vehicles, respectively. Maybe the rest are the famous parking tickets from the UN diplomats, who take ad...
dict_1 = {'Summons Number': 'int64', 'Plate ID': 'object', 'Registration State': 'object', 'Plate Type': 'object', 'Issue Date': 'object', 'Violation Code': 'int64', 'Vehicle Body Type': 'object', 'Vehicle Make': 'object', 'Issuing Agency': 'object', 'Street Code1': 'int64', 'Street Code2': 'int64', 'Street Code3': '...
Number of NYC summonses with commercial plates in 2017 was 1838970 Percentage 17.00%
MIT
Exercise/exercise_1.ipynb
TangJiahui/AC215-Advanced_Practical_Data_Science
kNN
k=4 KNN_model = KNeighborsClassifier(n_neighbors=k) KNN_model.fit(X_train, y_train) KNN_prediction = KNN_model.predict(X_test) cm,acc,f1,macro_acc,classwise_acc = eval_metrics(y_test,KNN_prediction) print(f"Overall Accuracy Score: {acc}") print(f"Macro Accuracy: {macro_acc}") print(f"Class-wise accuracy: \n{classwise...
Overall Accuracy Score: 0.4154929577464789 Macro Accuracy: 0.42229983219064593 Class-wise accuracy: [[0.8079096 0.02824859 0.05084746 0.05084746 0.01694915 0.04519774] [0.16071429 0.46428571 0.03571429 0.07142857 0.14285714 0.125 ] [0.35483871 0.29032258 0.08064516 0.10080645 0.13306452 0.04032258] [0.07462687...
MIT
benchmark-results/6class_results/FeatureSet2.ipynb
VedantKalbag/metal-vocal-vataset
SVM
import matplotlib.pyplot as plt SVM_model = SVC(gamma='scale',C=1.0533, kernel='poly', degree=2,coef0=2.1,random_state=42) SVM_model.fit(X_train, y_train) SVM_prediction = SVM_model.predict(X_test) cm,acc,f1,macro_acc,classwise_acc = eval_metrics(y_test,SVM_prediction) print(f"Overall Accuracy Score: {acc}") print(f...
_____no_output_____
MIT
benchmark-results/6class_results/FeatureSet2.ipynb
VedantKalbag/metal-vocal-vataset
RF
RF_model = RandomForestClassifier(n_estimators=90,criterion='gini',max_depth=None,\ min_samples_split=2,min_samples_leaf=1,max_features='auto',max_leaf_nodes=None,class_weight='balanced',random_state=42) RF_model.fit(X_train, y_train) RF_prediction = RF_model.predict(X_test) cm,acc,f1,macro_acc,classwise_acc = eva...
_____no_output_____
MIT
benchmark-results/6class_results/FeatureSet2.ipynb
VedantKalbag/metal-vocal-vataset
Introduction to Xarray * **Acknowledgement**: This notebook was originally created by [Digital Eath Australia (DEA)](https://www.ga.gov.au/about/projects/geographic/digital-earth-australia) and has been modified for use in the EY Data Science Program* **Prerequisites**: Users of this notebook should have a basic unde...
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import xarray as xr
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Introduction to xarrayDEA uses `xarray` as its core data model. To better understand what it is, let's first do a simple experiment using a combination of plain `numpy` arrays and Python dictionaries.Suppose we have a satellite image with three bands: `Red`, `NIR` and `SWIR`. These bands are represented as 2-dimension...
# Create fake satellite data red = np.random.rand(250, 250) nir = np.random.rand(250, 250) swir = np.random.rand(250, 250) # Create some lats and lons lats = np.linspace(-23.5, -26.0, num=red.shape[0], endpoint=False) lons = np.linspace(110.0, 112.5, num=red.shape[1], endpoint=False) # Create metadata title = "Image ...
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
All our data is conveniently packed in a dictionary. Now we can use this dictionary to work with the data it contains:
# Date of satellite image print(image["date"]) # Mean of red values image["red"].mean()
2019-11-10
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Still, to select data we have to use `numpy` indexes. Wouldn't it be convenient to be able to select data from the images using the coordinates of the pixels instead of their relative positions? This is exactly what `xarray` solves! Let's see how it works:To explore `xarray` we have a file containing some surface refl...
ds = xr.open_dataset("../Supplementary_data/08_Intro_to_xarray/example_netcdf.nc") ds
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Xarray dataset structureA `Dataset` can be seen as a dictionary structure packing up the data, dimensions and attributes. Variables in a `Dataset` object are called `DataArrays` and they share dimensions with the higher level `Dataset`. The figure below provides an illustrative example: To access a variable we can acc...
ds["green"] # Or alternatively: ds.green
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Dimensions are also stored as numeric arrays that we can easily access:
ds["time"] # Or alternatively: ds.time
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Metadata is referred to as attributes and is internally stored under `.attrs`, but the same convenient `.` notation applies to them.
ds.attrs["crs"] # Or alternatively: ds.crs
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
`DataArrays` store their data internally as multidimensional `numpy` arrays. But these arrays contain dimensions or labels that make it easier to handle the data. To access the underlaying numpy array of a `DataArray` we can use the `.values` notation.
arr = ds.green.values type(arr), arr.shape
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Indexing`Xarray` offers two different ways of selecting data. This includes the `isel()` approach, where data can be selected based on its index (like `numpy`).
print(ds.time.values) ss = ds.green.isel(time=0) ss
['2018-01-03T08:31:05.000000000' '2018-01-08T08:34:01.000000000' '2018-01-13T08:30:41.000000000' '2018-01-18T08:30:42.000000000' '2018-01-23T08:33:58.000000000' '2018-01-28T08:30:20.000000000' '2018-02-07T08:30:53.000000000' '2018-02-12T08:31:43.000000000' '2018-02-17T08:23:09.000000000' '2018-02-17T08:35:40.000000...
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Or the `sel()` approach, used for selecting data based on its dimension of label value.
ss = ds.green.sel(time="2018-01-08") ss
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Slicing data is also used to select a subset of data.
ss.x.values[100] ss = ds.green.sel(time="2018-01-08", x=slice(2378390, 2380390)) ss
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Xarray exposes lots of functions to easily transform and analyse `Datasets` and `DataArrays`. For example, to calculate the spatial mean, standard deviation or sum of the green band:
print("Mean of green band:", ds.green.mean().values) print("Standard deviation of green band:", ds.green.std().values) print("Sum of green band:", ds.green.sum().values)
Mean of green band: 4141.488778766468 Standard deviation of green band: 3775.5536474649584 Sum of green band: 14426445446
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Plotting data with MatplotlibPlotting is also conveniently integrated in the library.
ds["green"].isel(time=0).plot()
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
...but we still can do things manually using `numpy` and `matplotlib` if you choose:
rgb = np.dstack((ds.red.isel(time=0).values, ds.green.isel(time=0).values, ds.blue.isel(time=0).values)) rgb = np.clip(rgb, 0, 2000) / 2000 plt.imshow(rgb);
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
But compare the above to elegantly chaining operations within `xarray`:
ds[["red", "green", "blue"]].isel(time=0).to_array().plot.imshow(robust=True, figsize=(6, 6));
_____no_output_____
MIT
notebooks/01_Beginners_guide/08_Intro_to_xarray.ipynb
miguelalejo/2021-Better-Working-World-Data-Challenge
Pre-Tutorial ExercisesIf you've arrived early for the tutorial, please feel free to attempt the following exercises to warm-up.
# 1. Basic Python data structures # I have a list of dictionaries as such: names = [{'name': 'Eric', 'surname': 'Ma'}, {'name': 'Jeffrey', 'surname': 'Elmer'}, {'name': 'Mike', 'surname': 'Lee'}, {'name': 'Jennifer', 'surname': 'Elmer'}] # Write a fun...
_____no_output_____
MIT
archive/0-pre-tutorial-exercises.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
Le Bloc Note pour calculer Python est un langage interprété, jupyter peut donc lui faire exécuter progressivement des calculs mathématiques entre des nombres : les opérations étant saisies dans des cellules de type code, le résultat s'affichera directement en dessous. Ainsi, cellule après cellule, notre notebook jupyt...
4+5-3*2
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Le produit est prioritaire.
4+(5-3)*2
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour ce qui est des divisions, il existe trois opérateurs :- l’opérateur de division “/”, qui donne toujours un résultat avec [virgule flottante](https://fr.wikipedia.org/wiki/Virgule_flottante) en Python 3 ;- l’opérateur de division entière “//” ;- l’opérateur modulo “%” donnant le reste de la division euclidienne.
8/2 9//2 9%2
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour élever à la puissance on utilise l'opérateur “**”
2**3
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Attention, des opérations mêlant des nombres entiers et flottant donneront des résultats flottants.
13.0//3 13.0%3
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
On peut utiliser l'écriture scientifique pour saisir des nombres flottants :
2e-3
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour convertir un flottant en entier et inversement on utilise respectivement les fonctions int() et float()
int(3.9) float(3)
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour obtenir la valeur absolue d'un nombre :
abs(-3.3)
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour arrondir un nombre flottant par exemple à deux chiffres après la virgule :
round(3.1415926535897932384626433832795,2)
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Autres fonctions mathématiques Pour faire appel à des fonctions mathématiques plus évoluées, il faut importer une bibliothèque tel que :
from numpy import *
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
L' **`*`** veut dire que nous pouvons maintenant utiliser toutes les fonctions de cette bibliothèque, telle que :
sqrt(4) sin(pi)
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
> Peut-être que le résultat de cette dernière cellule vous étonne ? Tout comme celui que produisent les cellules suivantes :
0.1+0.7 4e0+2e-1+1e-3
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
> Cet écart est du à la représentation des nombres [flottants](https://fr.wikipedia.org/wiki/Virgule_flottante) dans la mémoire de l'ordinateur, ce ne sont pas des valeurs exactes mais approchées. Il faudra donc s'en souvenir lorsqu'il s'agira d'interpréter un résultat issu d'un calcul avec des flottants, tout dépend ...
round(0.1+0.7,3) round(sin(pi),3)
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Pour générer un nombre aléatoire :
from numpy.random import * rand()
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Par exemple pour simuler un Dé à 6 faces
int(rint(rand()*5+1))
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
Représentation Graphique d'une fonction Mathématiques Pour tracer des courbes, si vous exécutez la fonction magique %pylab inline, les bibliothèques Numpy et Matplotlib sont importées et il sera possible de dessiner des graphiques de façon intégrés au notebook.
%pylab inline
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
L'exemple de code suivant sera alors exécutable.
# Fait appel à numpy (linspace et pi) x = linspace(0, 3*pi, 500) # Fait appel à matplotlib (plot et title) plot(x, sin(x)) title('Graphique sin(x)')
_____no_output_____
MIT
Arithmetique-Le_BN_pour_calculer.ipynb
ECaMorlaix-2SI-1718/CR
`파이토치(PyTorch) 기본 익히기 `_ ||`빠른 시작 `_ ||`텐서(Tensor) `_ ||`Dataset과 Dataloader `_ ||`변형(Transform) `_ ||**신경망 모델 구성하기** ||`Autograd `_ ||`최적화(Optimization) `_ ||`모델 저장하고 불러오기 `_신경망 모델 구성하기==========================================================================신경망은 데이터에 대한 연산을 수행하는 계층(layer)/모듈(module)로 구성되어 있습니다.`torch...
import os import torch from torch import nn from torch.utils.data import DataLoader from torchvision import datasets, transforms
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
학습을 위한 장치 얻기------------------------------------------------------------------------------------------가능한 경우 GPU와 같은 하드웨어 가속기에서 모델을 학습하려고 합니다.`torch.cuda `_ 를 사용할 수 있는지확인하고 그렇지 않으면 CPU를 계속 사용합니다.
device = 'cuda' if torch.cuda.is_available() else 'cpu' print('Using {} device'.format(device))
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
클래스 정의하기------------------------------------------------------------------------------------------신경망 모델을 ``nn.Module`` 의 하위클래스로 정의하고, ``__init__`` 에서 신경망 계층들을 초기화합니다.``nn.Module`` 을 상속받은 모든 클래스는 ``forward`` 메소드에 입력 데이터에 대한 연산들을 구현합니다.
class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(28*28, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linea...
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
``NeuralNetwork`` 의 인스턴스(instance)를 생성하고 이를 ``device`` 로 이동한 뒤,구조(structure)를 출력합니다.
model = NeuralNetwork().to(device) print(model)
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
모델을 사용하기 위해 입력 데이터를 전달합니다. 이는 일부`백그라운드 연산들 `_ 과 함께모델의 ``forward`` 를 실행합니다. ``model.forward()`` 를 직접 호출하지 마세요!모델에 입력을 호출하면 각 분류(class)에 대한 원시(raw) 예측값이 있는 10-차원 텐서가 반환됩니다.원시 예측값을 ``nn.Softmax`` 모듈의 인스턴스에 통과시켜 예측 확률을 얻습니다.
X = torch.rand(1, 28, 28, device=device) logits = model(X) pred_probab = nn.Softmax(dim=1)(logits) y_pred = pred_probab.argmax(1) print(f"Predicted class: {y_pred}")
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
------------------------------------------------------------------------------------------ 모델 계층(Layer)------------------------------------------------------------------------------------------FashionMNIST 모델의 계층들을 살펴보겠습니다. 이를 설명하기 위해, 28x28 크기의 이미지 3개로 구성된미니배치를 가져와, 신경망을 통과할 때 어떤 일이 발생하는지 알아보겠습니다.
input_image = torch.rand(3,28,28) print(input_image.size())
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
nn.Flatten^^^^^^^^^^^^^^^^^^^^^^`nn.Flatten `_ 계층을 초기화하여각 28x28의 2D 이미지를 784 픽셀 값을 갖는 연속된 배열로 변환합니다. (dim=0의 미니배치 차원은 유지됩니다.)
flatten = nn.Flatten() flat_image = flatten(input_image) print(flat_image.size())
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
nn.Linear^^^^^^^^^^^^^^^^^^^^^^`선형 계층 `_ 은 저장된 가중치(weight)와편향(bias)을 사용하여 입력에 선형 변환(linear transformation)을 적용하는 모듈입니다.
layer1 = nn.Linear(in_features=28*28, out_features=20) hidden1 = layer1(flat_image) print(hidden1.size())
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
nn.ReLU^^^^^^^^^^^^^^^^^^^^^^비선형 활성화(activation)는 모델의 입력과 출력 사이에 복잡한 관계(mapping)를 만듭니다.비선형 활성화는 선형 변환 후에 적용되어 *비선형성(nonlinearity)* 을 도입하고, 신경망이 다양한 현상을 학습할 수 있도록 돕습니다.이 모델에서는 `nn.ReLU `_ 를 선형 계층들 사이에 사용하지만,모델을 만들 때는 비선형성을 가진 다른 활성화를 도입할 수도 있습니다.
print(f"Before ReLU: {hidden1}\n\n") hidden1 = nn.ReLU()(hidden1) print(f"After ReLU: {hidden1}")
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
nn.Sequential^^^^^^^^^^^^^^^^^^^^^^`nn.Sequential `_ 은 순서를 갖는모듈의 컨테이너입니다. 데이터는 정의된 것과 같은 순서로 모든 모듈들을 통해 전달됩니다. 순차 컨테이너(sequential container)를 사용하여아래의 ``seq_modules`` 와 같은 신경망을 빠르게 만들 수 있습니다.
seq_modules = nn.Sequential( flatten, layer1, nn.ReLU(), nn.Linear(20, 10) ) input_image = torch.rand(3,28,28) logits = seq_modules(input_image)
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
nn.Softmax^^^^^^^^^^^^^^^^^^^^^^신경망의 마지막 선형 계층은 `nn.Softmax `_ 모듈에 전달될([-\infty, \infty] 범위의 원시 값(raw value)인) `logits` 를 반환합니다. logits는 모델의 각 분류(class)에 대한 예측 확률을 나타내도록[0, 1] 범위로 비례하여 조정(scale)됩니다. ``dim`` 매개변수는 값의 합이 1이 되는 차원을 나타냅니다.
softmax = nn.Softmax(dim=1) pred_probab = softmax(logits)
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
모델 매개변수------------------------------------------------------------------------------------------신경망 내부의 많은 계층들은 *매개변수화(parameterize)* 됩니다. 즉, 학습 중에 최적화되는 가중치와 편향과 연관지어집니다.``nn.Module`` 을 상속하면 모델 객체 내부의 모든 필드들이 자동으로 추적(track)되며, 모델의 ``parameters()`` 및``named_parameters()`` 메소드로 모든 매개변수에 접근할 수 있게 됩니다.이 예제에서는 각 매개변수들을 순회...
print("Model structure: ", model, "\n\n") for name, param in model.named_parameters(): print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")
_____no_output_____
BSD-3-Clause
docs/_downloads/68e97c325bcdbd63f73a37dc6b8c656d/buildmodel_tutorial.ipynb
YonghyunRyu/PyTorch-tutorials-kr-exercise
Multi-label classification
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.conv_learner import * PATH = 'data/planet/' # Data preparation steps if you are using Crestle: os.makedirs('data/planet/models', exist_ok=True) os.makedirs('/cache/planet/tmp', exist_ok=True) !ln -s /datasets/kaggle/planet-understanding-the-amazon-fr...
models/ test-jpg/ tmp/ train-jpg/ train_v2.csv*
Apache-2.0
DEEP LEARNING/image classification/fastai/fastai satellite multilabel classif.ipynb
Diyago/ML-DL-scripts
Multi-label versus single-label classification
from fastai.plots import * def get_1st(path): return glob(f'{path}/*.*')[0] dc_path = "data/dogscats/valid/" list_paths = [get_1st(f"{dc_path}cats"), get_1st(f"{dc_path}dogs")] plots_from_files(list_paths, titles=["cat", "dog"], maintitle="Single-label classification")
_____no_output_____
Apache-2.0
DEEP LEARNING/image classification/fastai/fastai satellite multilabel classif.ipynb
Diyago/ML-DL-scripts
In single-label classification each sample belongs to one class. In the previous example, each image is either a *dog* or a *cat*.
list_paths = [f"{PATH}train-jpg/train_0.jpg", f"{PATH}train-jpg/train_1.jpg"] titles=["haze primary", "agriculture clear primary water"] plots_from_files(list_paths, titles=titles, maintitle="Multi-label classification")
_____no_output_____
Apache-2.0
DEEP LEARNING/image classification/fastai/fastai satellite multilabel classif.ipynb
Diyago/ML-DL-scripts
In multi-label classification each sample can belong to one or more clases. In the previous example, the first images belongs to two clases: *haze* and *primary*. The second image belongs to four clases: *agriculture*, *clear*, *primary* and *water*. Multi-label models for Planet dataset
from planet import f2 metrics=[f2] f_model = resnet34 label_csv = f'{PATH}train_v2.csv' n = len(list(open(label_csv)))-1 val_idxs = get_cv_idxs(n)
_____no_output_____
Apache-2.0
DEEP LEARNING/image classification/fastai/fastai satellite multilabel classif.ipynb
Diyago/ML-DL-scripts
We use a different set of data augmentations for this dataset - we also allow vertical flips, since we don't expect vertical orientation of satellite images to change our classifications.
def get_data(sz): tfms = tfms_from_model(f_model, sz, aug_tfms=transforms_top_down, max_zoom=1.05) return ImageClassifierData.from_csv(PATH, 'train-jpg', label_csv, tfms=tfms, suffix='.jpg', val_idxs=val_idxs, test_name='test-jpg') data = get_data(256) x,y = next(iter(data.val_dl)) y list(zi...
_____no_output_____
Apache-2.0
DEEP LEARNING/image classification/fastai/fastai satellite multilabel classif.ipynb
Diyago/ML-DL-scripts
Results Classification
import os import sys sys.path.append('../') import torch import pandas as pd import numpy as np DATA_DIR = "../data" data_train = pd.read_csv(os.path.join(DATA_DIR, "train_cleaned.csv"), na_filter=False) data_val = pd.read_csv(os.path.join(DATA_DIR, "val_cleaned.csv"), na_filter=False) from transformers import AutoTo...
_____no_output_____
MIT
notebooks/3_1_classif_results.ipynb
Avditvs/sentiment-analysis-test
Results on the main languages
main_languages = ["en", "id", "ru", "ar", "fr", "es", "pt", "ko", "zh-cn", "ja", "de", "it", "th", "tr"] metric.compute(predictions=data_val[data_val.language.isin(main_languages)].predictions, references=data_val[data_val.language.isin(main_languages)].label) conf_matrix = confusion_matrix(data_val[data_val.language....
_____no_output_____
MIT
notebooks/3_1_classif_results.ipynb
Avditvs/sentiment-analysis-test
Anlayse results Let's see what element have been misclassified Positive classified as negative
for sentence in data_val[data_val.language=="en"][data_val.label==2][data_val.predictions==0].content: print(sentence)
Did you notice that zero has a karambit knife and also that they changed the number 1 in the scoreboard and timer Smackgobbed? New word for me...gonna start using all the time now. Anime Saturday about to start. New episode of bleach. Yea So tired. Finally getting some sleep. Nighty If it was up to me I would gi...
MIT
notebooks/3_1_classif_results.ipynb
Avditvs/sentiment-analysis-test
From what we can see, these wrongly classified sentences are not obviously positive. Example : "hahas sucks to be you" Negative classified as positive
for sentence in data_val[data_val.language=="en"][data_val.label==0][data_val.predictions==2].content: print(sentence)
off to college bleurgh I know, I know, it's exactly like mine craft. But, IT KEEPS FREEZING!!!!!!!!!! You might think it is just nothing, but trust me, it freezes all the time. I hardly get the time to play it. I'd give it 0 stars if I could. Rest in peace, Ping. Best hamster ever. 2007-2009 It's a fucking holiday. I...
MIT
notebooks/3_1_classif_results.ipynb
Avditvs/sentiment-analysis-test
**Guide*** Create a draw_circle function for the callback function* Use two events cv2.EVENT_LBUTTONDOWN and cv2.EVENT_LBUTTONUP* Use a boolean variable to keep track if the mouse has been clicked up and down based on the events above* Use a tuple to keep track of the x and y where the mouse was clicked.* You should be...
# Create a function based on a CV2 Event (Left button click) # mouse callback function def draw_circle(event,x,y,flags,param): global center,clicked # get mouse click on down and track center if event == cv2.EVENT_LBUTTONDOWN: center = (x, y) clicked = False # Use boolean variabl...
_____no_output_____
MIT
Neelesh_Video-Basic_opencv.ipynb
Shreyansh-Gupta/Open-contributions
**Process S1 SLC data using parallel processing** First import all necessary libraries
import ost import ost.helpers as h from ost.helpers import onda, asf_wget, vector from ost import Sentinel1_SLCBatch import os from os.path import join from pathlib import Path from pprint import pprint
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Ingest shapefile data and set start and end dates
# create a processing directory project_dir = '/home/ost/Data/jwheeler/Sydney_Fires' # apply function with buffer in meters from ost.helpers import vector input_shp = "/home/ost/Data/jwheeler/Shapefiles/Sydney_fires.shp" aoi = vector.shp_to_wkt(input_shp) #---------------------------- # Time of interest #------------...
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Initiate class with above attributes
# create s1Project class instance s1_batch = Sentinel1_SLCBatch( project_dir=project_dir, aoi=aoi, start=start, end=end, product_type='SLC', ard_type='OST Plus')
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Search for images on scihub and plot footprints
#--------------------------------------------------- # for plotting purposes we use this iPython magic %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] = (19, 19) #--------------------------------------------------- # search command s1_batch.search() # we plot the full Inventory on a map s1_batch.plot...
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Refine image search
s1_batch.refine()
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Select appropriate key and plot filtered images
pylab.rcParams['figure.figsize'] = (13, 13) key = 'DESCENDING_VVVH' s1_batch.refined_inventory_dict[key] s1_batch.plot_inventory(s1_batch.refined_inventory_dict[key], 0.3)
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Download using a selected S-1 mirror - ideally ASF (2 using request or 5 using wget) or onda (4) if accounts are set up correctly for fast, parallel downloading
s1_batch.download(s1_batch.refined_inventory_dict[key],concurrent=8)
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Create inventory of bursts in downloaded images, plot them and print information
s1_batch.create_burst_inventory(key=key, refine=True) pylab.rcParams['figure.figsize'] = (13, 13) s1_batch.plot_inventory(s1_batch.burst_inventory, transparency=0.1) print('Our burst inventory holds {} bursts to process.'.format(len(s1_batch.burst_inventory))) print('------------------------------------------') print(s...
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Uncomment the below command to view the current ard parameters
#pprint(s1_batch.ard_parameters)
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Run the s1SLCbatch class function bursts to ard to generate parameter text files for each step from burst to ard, ard to timeseries, timeseries to timescan and mosaic.**NB Use a base name for the exec file without a extension AND make sure to choose the number of cores that each process will use for parallel processing...
s1_batch.bursts_to_ard(timeseries=True, timescan=True, mosaic=True, overwrite=False, exec_file='/home/ost/Data/jwheeler/Sydney_Fires/test', ncores=2) #print(s1_batch.temp_dir)
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
Run the s1SLCbatch class function multiprocessing to run, sequentially, the parameters in the previously generated text files for each step from burst to ard, ard to timeseries, timeseries to timescan and mosaic.**NB Use the same base name for the exec file without a extension as before AND make sure to choose the numb...
s1_batch.multiprocess(timeseries=True, timescan=True, mosaic=True, overwrite=False, exec_file='/home/ost/Data/jwheeler/Sydney_Fires/test', ncores=2,multiproc=4) #burst_to_ard_batch(s1_batch.burst_inventory,s1_batch.download_dir,s1_batch.processing_dir,s1_batch.temp_dir,s1_batch.proc_file,exec_file='/home/ost/Data/jwhee...
_____no_output_____
MIT
6 Sentinel-1 SLC Parallel Processing.ipynb
jamesemwheeler/OSTParallel
PerceptronThis is a simple example illustrating the classic perceptron algorithm. A linear decision function parametrized by the weight vector "w" and bias paramter "b" is learned by making small adjustements to these parameters every time the predicted label "f_i" mismatches the true label "y_i" of an input data poi...
# Construct a simple data set based on MNIST images # This is a data set of handwritten digits 0 to 9 # Download MNIST dataset from keras from keras.datasets import mnist import numpy as np (train_X, train_y), (test_X, test_y) = mnist.load_data() print(test_X.shape) print(test_y.shape) # y are the digit labels print...
_____no_output_____
MIT
Lab 6 Perceptron/Perceptron.ipynb
xup5/Computational-Neuroscience-Class
Exercise: After trying the code for the given classes,try running the code again, but this time changing the digits of thepositive or negative class. You can do this by changing the following two lines above:pos_class = 0neg_class = 5What classes are easier to learn?
_____no_output_____
MIT
Lab 6 Perceptron/Perceptron.ipynb
xup5/Computational-Neuroscience-Class
biopythonThe [Biopython](http://biopython.org/) Project is an international association of developers of freely available [Python](http://www.python.org) tools for computational molecular biology. [documentation](http://biopython.org/wiki/Documentation) [source](https://github.com/biopython/biopython) [installation](h...
from jyquickhelper import add_notebook_menu add_notebook_menu()
_____no_output_____
MIT
_doc/notebooks/2016/pydata/im_biopython.ipynb
sdpython/jupytalk
example
from pyquickhelper.filehelper import download download("https://raw.githubusercontent.com/biopython/biopython/master/Tests/GenBank/NC_005816.gb", outfile="NC_005816.gb") from reportlab.lib import colors from reportlab.lib.units import cm from Bio.Graphics import GenomeDiagram from Bio import SeqIO record = Seq...
_____no_output_____
MIT
_doc/notebooks/2016/pydata/im_biopython.ipynb
sdpython/jupytalk
Fetching WHO's situation reports on COVID-19 as DataFrames Get the data
pdf_save_location = '../data/pdf' csv_save_location = '../data/csv' from who_covid_scraper import WHOCovidScraper scraper = WHOCovidScraper('https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports') scraper.df
_____no_output_____
Apache-2.0
covid19_who_situation_reports_importer/notebook.ipynb
aarohijohal/covid19-who-situation-reports-importer
Download report for a given date
download = scraper.download_for_date(datearg='23rd of Feb', folder=pdf_save_location)
report for the date 2020/02/23 already exists at ../data/pdf/20200223-sitrep-34-covid-19.pdf. didn't re-download
Apache-2.0
covid19_who_situation_reports_importer/notebook.ipynb
aarohijohal/covid19-who-situation-reports-importer
Send report for extraction
job = scraper.send_document_to_parsr(download['file']) job
> Polling server for the job f214dea6618020da1a446307879c1f... >> Job done!
Apache-2.0
covid19_who_situation_reports_importer/notebook.ipynb
aarohijohal/covid19-who-situation-reports-importer
Assemble the stats from the report
scraper.assemble_data(job['server_response'])
_____no_output_____
Apache-2.0
covid19_who_situation_reports_importer/notebook.ipynb
aarohijohal/covid19-who-situation-reports-importer
Pattern Generator and Trace AnalyzerThis notebook will show how to use the Pattern Generator to generate patterns on I/O pins. The pattern that will be generated is 3-bit up count performed 4 times. Step 1: Download the `logictools` overlay
from pynq.overlays.logictools import LogicToolsOverlay logictools_olay = LogicToolsOverlay('logictools.bit')
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ
Step 2: Create WaveJSON waveformThe pattern to be generated is specified in the waveJSON format The pattern is applied to the Arduino interface, pins **D0**, **D1** and **D2** are set to generate a 3-bit count. To check the generated pattern we loop them back to pins **D19**, **D18** and **D17** respectively and use...
from pynq.lib.logictools import Waveform up_counter = {'signal': [ ['stimulus', {'name': 'bit0', 'pin': 'D0', 'wave': 'lh' * 8}, {'name': 'bit1', 'pin': 'D1', 'wave': 'l.h.' * 4}, {'name': 'bit2', 'pin': 'D2', 'wave': 'l...h...' * 2}], ['analysis', {'name': 'bit2_loopbac...
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ
**Note:** Since there are no captured samples at this moment, the analysis group will be empty. Step 3: Instantiate the pattern generator and trace analyzer objectsUsers can choose whether to use the trace analyzer by calling the `trace()` method. The analyzer can be set to trace a specific number of samples using,...
pattern_generator = logictools_olay.pattern_generator pattern_generator.trace(num_analyzer_samples=16)
_____no_output_____
BSD-3-Clause
boards/Pynq-Z2/logictools/notebooks/pattern_generator_and_trace_analyzer.ipynb
jackrosenthal/PYNQ