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 |
|---|---|---|---|---|---|
So df3 has 500 records and 3 columns. The data represents factory production numbers and reported numbers of defects on certain days of the week. 1. Recreate this scatter plot of 'produced' vs 'defective'. Note the color and size of the points. Also note the figure size. See if you can figure out how to stretch it in ... | # 1. Recrie este gráfico de dispersão de 'produzido' vs 'defeituoso'. Observe a cor e o tamanho dos pontos.
# Observe também o tamanho da figura. Veja se você pode descobrir como esticá-lo de forma semelhante.
# CODE HERE
df3.plot.scatter(x='produced', y='defective', c='red', figsize=(12,3), s=20)
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
2. Create a histogram of the 'produced' column. | # 2. Crie um histograma da coluna 'produzida'.
df3['produced'].plot.hist()
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
3. Recreate the following histogram of 'produced', tightening the x-axis and adding lines between bars. | # 3. Recrie o seguinte histograma de 'produzido', apertando o eixo x e adicionando linhas entre as barras.
df3['produced'].plot.hist(edgecolor='k').autoscale(axis='x', tight=True)
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
4. Create a boxplot that shows 'produced' for each 'weekday' (hint: this is a groupby operation) | # 4. Crie um boxplot que mostre 'produzido' para cada 'dia da semana' (dica: esta é uma operação groupby)
df3[['weekday','produced']].boxplot(by='weekday', figsize=(12,5))
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
5. Create a KDE plot of the 'defective' column | # 5. Crie um gráfico KDE da coluna 'defeituoso'
df3['defective'].plot.kde()
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
6. For the above KDE plot, figure out how to increase the linewidth and make the linestyle dashed.(Note: You would usually not dash a KDE plot line) | # 6. Para o gráfico do KDE acima, descubra como aumentar a largura da linha e tornar o estilo de linha tracejada.
# (Nota: Você normalmente não traçou uma linha de plotagem do KDE)
df3['defective'].plot.kde(ls='--', lw=5)
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
7. Create a blended area plot of all the columns for just the rows up to 30. (hint: use .loc) | # 7. Crie um gráfico de área combinada de todas as colunas apenas para as linhas até 30. (dica: use .loc)
ax = df3.loc[0:30].plot.area(stacked=False, alpha=0.4)
ax.legend(loc=0)
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
Bonus Challenge!Notice how the legend in our previous figure overlapped some of actual diagram. Can you figure out how to display the legend outside of the plot as shown below? | ax = df3.loc[0:30].plot.area(stacked=False, alpha=0.4)
ax.legend(loc=0, bbox_to_anchor=(1.3,0.5))
# DON'T WRITE HERE | _____no_output_____ | MIT | pacote-download/02-Pandas-Data-Visualization-Exercise.ipynb | stephacastro/Coleta_dados |
Disk Stacking[link](https://www.algoexpert.io/questions/Disk%20Stacking) My Solution | def diskStacking(disks):
# Write your code here.
disks.sort(key=lambda x: x[1])
globalMaxHeight = 0
prevDiskIdx = [None for _ in range(len(disks) + 1)]
opt = [0 for _ in range(len(disks) + 1)]
for i in range(len(disks)):
opt[i + 1] = disks[i][2]
for i in range(len(opt)):
maxH... | _____no_output_____ | MIT | algoExpert/disk_stacking/solution.ipynb | maple1eaf/learning_algorithm |
Expert Solution | # O(n^2) time | O(n) space
def diskStacking(disks):
disks.sort(key=lambda disk:disk[2])
heights = [disk[2] for disk in disks]
sequences = [None for disk in disks]
maxHeightIdx = 0
for i in range(1, len(disks)):
currentDisk = disks[i]
for j in range(0, i):
otherDisk = disk... | _____no_output_____ | MIT | algoExpert/disk_stacking/solution.ipynb | maple1eaf/learning_algorithm |
Active Contour ModelThe active contour model is a method to fit open or closed splines to lines oredges in an image [1]_. It works by minimising an energy that is in partdefined by the image and part by the spline's shape: length and smoothness. Theminimization is done implicitly in the shape energy and explicitly in ... | import numpy as np
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage import data
from skimage.filters import gaussian
from skimage.segmentation import active_contour
img = data.astronaut()
img = rgb2gray(img)
s = np.linspace(0, 2*np.pi, 400)
r = 100 + 100*np.sin(s)
c = 220 + 100*np.cos(... | _____no_output_____ | MIT | digital-image-processing/notebooks/edges/plot_active_contours.ipynb | sinamedialab/courses |
Here we initialize a straight line between two points, `(5, 136)` and`(424, 50)`, and require that the spline has its end points there by givingthe boundary condition `boundary_condition='fixed'`. We furthermoremake the algorithm search for dark lines by giving a negative `w_line` value. | img = data.text()
r = np.linspace(136, 50, 100)
c = np.linspace(5, 424, 100)
init = np.array([r, c]).T
snake = active_contour(gaussian(img, 1), init, boundary_condition='fixed',
alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1,
coordinates='rc')
fig, ax = plt.subplots... | _____no_output_____ | MIT | digital-image-processing/notebooks/edges/plot_active_contours.ipynb | sinamedialab/courses |
Question1 | df0 = df[df.DEATH_EVENT == 0]
df0Feature = df0[['creatinine_phosphokinase', 'serum_creatinine', 'serum_sodium', 'platelets']]
df1 = df[df.DEATH_EVENT == 1]
df1Feature = df1[['creatinine_phosphokinase', 'serum_creatinine', 'serum_sodium', 'platelets']]
# corr matrix for death_event 0
sn.heatmap(df0Feature.corr(), annot=... | _____no_output_____ | MIT | Assignment_7/heart_failure_linear_model/HeartFali.ipynb | KyleLeePiupiupiu/CS677_Assignment |
Question2Group3--> X = serum sodium, Y = serum creatinine | def residual(yTest, yPredict):
temp = 0
for (a, b) in zip(yTest, yPredict):
temp += (a-b) * (a - b)
return temp
zeroSet = df0[[ 'serum_creatinine', 'serum_sodium']]
oneSet = df1[[ 'serum_creatinine', 'serum_sodium']]
# for death_evetn = 0
# simple linear regression
x = zeroSet['serum_sodium']
y = ze... | [-0.01236989 3.8018824 ]
38.63069354525988
[ 9.69912611e-03 -2.65111621e+00 1.83120347e+02]
61.60974727399684
[ 6.93416020e-03 -2.82186374e+00 3.82460077e+02 -1.72620285e+04]
2607.9355538202913
[-1.80477484 10.98470858]
38.58311899419233
[-3.18264613 16.14955754]
22.58026509775523
| MIT | Assignment_7/heart_failure_linear_model/HeartFali.ipynb | KyleLeePiupiupiu/CS677_Assignment |
Functions | #function: gaussian kernel 1d
#input: sigma: std
# order: A positive order corresponds to convolution with
# that derivative of a Gaussian, use 0 here
# radius: radius of the filter
def my_gaussian_kernel1d(sigma, order, radius):
"""
Computes a 1D Gaussian convolution kernel.
"""
... | _____no_output_____ | MIT | code/image_analysis_twilight.ipynb | yongrong-qiu/mouse-scene-cam |
Sunrise: Intensity profile in the dome, radiated from the sun | def createLineIterator(P1, P2, img):
"""
Produces and array that consists of the coordinates and intensities of each pixel in a line between two points
Parameters:
-P1: a numpy array that consists of the coordinate of the first point (x,y)
-P2: a numpy array that consists of the coordinate ... | _____no_output_____ | MIT | code/image_analysis_twilight.ipynb | yongrong-qiu/mouse-scene-cam |
Sunrise: Dome and tree intensity change along time points | temp=img_real2view(img_sunrises[5])
recteg=cv2.rectangle(temp,(168,35),(228,55),(255,255,255),1)
plt.imshow(recteg[...,::-1])
#dome intensity
domeinten_median=np.zeros((6,2)) #6 time points, 2 color channel (UV and G)
domeinten_std=np.zeros((6,2))
domeinten_lowq_higq=np.zeros((6,2,2)) #6 time points, 2 color channel (U... | _____no_output_____ | MIT | code/image_analysis_twilight.ipynb | yongrong-qiu/mouse-scene-cam |
Sunrise: Crms change along time points | #pick a rectangular area for the tree, not close to the sun, near the edge
temp=img_real2view(img_sunrises[5])
recteg=cv2.rectangle(temp,(160,50),(340,100),(0,0,255),5)
plt.imshow(recteg[...,::-1])
#RF: 2,10 degrees
RFradius=np.array([2,12])
onoff_num=100
#Crms
rms2_time=np.zeros((6,2,2,onoff_num))#6 time points, 2 col... | _____no_output_____ | MIT | code/image_analysis_twilight.ipynb | yongrong-qiu/mouse-scene-cam |
Sunset: Conoff and Crms of tree | #pick a rectangular area for the tree
temp=img_real2view(img_sunsets[1])
recteg=cv2.rectangle(temp,(130,50),(340,200),(0,0,255),5)
plt.imshow(recteg[...,::-1])
RFradius=np.array([2,7,12,16])
onoff_num=200
#upper visual field, UV channel
upper_UV_RF_rms2s=np.zeros((4,onoff_num))
for ii in range(4):
temp=img_sunsets[... | _____no_output_____ | MIT | code/image_analysis_twilight.ipynb | yongrong-qiu/mouse-scene-cam |
How to export 🤗 Transformers Models to ONNX ? [ONNX](http://onnx.ai/) is open format for machine learning models. It allows to save your neural network's computation graph in a framework agnostic way, which might be particulary helpful when deploying deep learning models.Indeed, businesses might have other requirement... | import sys
!{sys.executable} -m pip install --upgrade git+https://github.com/huggingface/transformers
!{sys.executable} -m pip install --upgrade torch==1.6.0+cpu torchvision==0.7.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
!{sys.executable} -m pip install --upgrade onnxruntime==1.4.0
!{sys.executable} -... | loading configuration file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-config.json from cache at /home/mfuntowicz/.cache/torch/transformers/b945b69218e98b3e2c95acf911789741307dec43c698d35fad11c1ae28bda352.9da767be51e1327499df13488672789394e2ca38b877837e52618a67d7002391
Model config BertConfig {
... | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
How to leverage runtime for inference over an ONNX graph---As mentionned in the introduction, **ONNX** is a serialization format and many side projects can load the saved graph and run the actual computations from it. Here, we'll focus on the official [onnxruntime](https://microsoft.github.io/onnxruntime/). The runtim... | !pip install transformers onnxruntime-gpu onnx psutil matplotlib | Requirement already satisfied: transformers in /home/mfuntowicz/miniconda3/envs/pytorch/lib/python3.8/site-packages (3.0.2)
Requirement already satisfied: onnxruntime-gpu in /home/mfuntowicz/miniconda3/envs/pytorch/lib/python3.8/site-packages (1.3.0)
Requirement already satisfied: onnx in /home/mfuntowicz/miniconda3/en... | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Preparing for an Inference Session---Inference is done using a specific backend definition which turns on hardware specific optimizations of the graph. Optimizations are basically of three kinds: - **Constant Folding**: Convert static variables to constants in the graph - **Deadcode Elimination**: Remove nodes never a... | # # An optional step unless
# # you want to get a model with mixed precision for perf accelartion on newer GPU
# # or you are working with Tensorflow(tf.keras) models or pytorch models other than bert
# !pip install onnxruntime-tools
# from onnxruntime_tools import optimizer
# # Mixed precision conversion for bert-ba... | _____no_output_____ | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Forwarding through our optimized ONNX model running on CPU---When the model is loaded for inference over a specific provider, for instance **CPUExecutionProvider** as above, an optimized graph can be saved. This graph will might include various optimizations, and you might be able to see some **higher-level** operatio... | from transformers import BertTokenizerFast
tokenizer = BertTokenizerFast.from_pretrained("bert-base-cased")
cpu_model = create_model_for_provider("onnx/bert-base-cased.onnx", "CPUExecutionProvider")
# Inputs are provided through numpy array
model_inputs = tokenizer("My name is Bert", return_tensors="pt")
inputs_onnx ... | loading file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt from cache at /home/mfuntowicz/.cache/torch/transformers/5e8a2b4893d13790ed4150ca1906be5f7a03d6c4ddf62296c383f6db42814db2.e13dbb970cb325137104fb2e5f36fe865f27746c6b526f6352861b1980eb80b1
| MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Benchmarking PyTorch model_Note: PyTorch model benchmark is run on CPU_ | from transformers import BertModel
PROVIDERS = {
("cpu", "PyTorch CPU"),
# Uncomment this line to enable GPU benchmarking
# ("cuda:0", "PyTorch GPU")
}
results = {}
for device, label in PROVIDERS:
# Move inputs to the correct device
model_inputs_on_device = {
arg_name: tensor.to(device)
... | loading configuration file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-config.json from cache at /home/mfuntowicz/.cache/torch/transformers/b945b69218e98b3e2c95acf911789741307dec43c698d35fad11c1ae28bda352.9da767be51e1327499df13488672789394e2ca38b877837e52618a67d7002391
Model config BertConfig {
... | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Benchmarking PyTorch & ONNX on CPU_**Disclamer: results may vary from the actual hardware used to run the model**_ | PROVIDERS = {
("CPUExecutionProvider", "ONNX CPU"),
# Uncomment this line to enable GPU benchmarking
# ("CUDAExecutionProvider", "ONNX GPU")
}
for provider, label in PROVIDERS:
# Create the model with the specified provider
model = create_model_for_provider("onnx/bert-base-cased.onnx", provider)
... | _____no_output_____ | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Quantization support from transformersQuantization enables the use of integers (_instead of floatting point_) arithmetic to run neural networks models faster. From a high-level point of view, quantization works as mapping the float32 ranges of values as int8 with the less loss in the performances of the model.Hugging ... | import torch
# Quantize
model_pt_quantized = torch.quantization.quantize_dynamic(
model_pt.to("cpu"), {torch.nn.Linear}, dtype=torch.qint8
)
# Warm up
model_pt_quantized(**model_inputs)
# Benchmark PyTorch quantized model
time_buffer = []
for _ in trange(100):
with track_infer_time(time_buffer):
mo... | 100%|██████████| 100/100 [00:01<00:00, 90.15it/s]
| MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Benchmarking ONNX quantized model | from transformers.convert_graph_to_onnx import quantize
# Transformers allow you to easily convert float32 model to quantized int8 with ONNX Runtime
quantized_model_path = quantize(Path("bert.opt.onnx"))
# Then you just have to load through ONNX runtime as you would normally do
quantized_model = create_model_for_prov... | As of onnxruntime 1.4.0, models larger than 2GB will fail to quantize due to protobuf constraint.
This limitation will be removed in the next release of onnxruntime.
Quantized model has been written at bert.onnx: ✔
| MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Show the inference performance of each providers | %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
# Compute average inference time + std
time_results = {k: np.mean(v.model_inference_time) * 1e3 for k, v in results.items()}
time_results_std = np.std([v.model_inference_time for v in results.values()]) * 1000
plt.rcde... | _____no_output_____ | MIT | methods/transformers/notebooks/04-onnx-export.ipynb | INK-USC/RiddleSense |
Lecture 1. Introduction to CUDA Programming Model and Toolkit. Welcome to the GPU short course exercies!During this course we will introduce you with the syntax of CUDA programming in Python using `numba.cuda` package. During the first lecture we will try to focus on optimizing the following function, which adds two v... | import numpy as np
def add_vectors(a, b):
assert len(a) == len(b)
n = len(a)
result = [None]*n
for i in range(n):
result[i] = a[i] + b[i]
return result
add_vectors([1, 2, 3, 4],
[4, 5, 6, 7]) | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Lets measure the time needed to execute the `add_vectors` for big-scale arrays: | a = np.random.rand(2**24) # ~ 1e7 elements
b = np.random.rand(2**24)
%%timeit -n 2
add_vectors(a, b) | 2 loops, best of 5: 6.46 s per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
In the following sections we will show you how to optimize the above implementation by reimplementing vector addition on GPU. Exercise 1.1. CUDA kernels and CUDA threads. 1.1.1. One-dimensional grid. Lets do the all necessary Python imports first. | import math
from numba import cuda
import numpy as np | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The `numba.cuda` package provides a possibility to write CUDA kernels directly in Python language. We will describe Numba in more detail later. For now, it will be enough to understand that:- the code that is executed by each GPU core separately is called a *GPU kernel*,- in Numba, GPU kernel is a Python function with... | @cuda.jit
def my_first_gpu_kernel():
pass | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The following line launches the code to be executed by 64 thread blocks, each block has 256 threads: | my_first_gpu_kernel[64, 256]() | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Ok, now that we know what is the syntax for writing and lanuching CUDA kernel code, we can proceed with porting the `add_vectors` function to the GPU device. The key is to note that vector element additions are *independent tasks* - that is, for each `i` and `j`, the result of `a[i]+b[i]` does not depend on `a[j]+b[j]`... | @cuda.jit
def add_vectors_kernel(result, a, b):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
# Make sure not to go outside the grid area!
if i >= len(result):
return
result[i] = a[i] + b[i] | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The above code is executed by each CUDA thread separately. Fields `blockIdx`, `blockDim` and `threadIdx` allows to determine the position of the current thread in the whole grid of threads executed by CUDA device:- `blockIdx` is the identifier of the currently executed block of threads in the grid,- `blockDim` is the s... | def add_vectors_gpu(a, b):
assert len(a) == len(b)
# Create output array in the GPU memory.
result = cuda.device_array(shape=a.shape, dtype=a.dtype)
block_size = 256
grid_size = math.ceil(len(a)/block_size)
add_vectors_kernel[grid_size, block_size](result, a, b)
return result.copy_to_host()... | 1 loop, best of 5: 138 ms per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Congratulations! Your very first GPU kernel, i.e. `add_vectors_gpu` function, executes much faster than its CPU counterpart.Of course, writing CUDA kernels is not the only part of preparing GPU processing pipeline. One of the other important things to consider is the heterogenous nature of the CPU-GPU processing: is th... | import itertools
import numpy as np
def add_matrices(a, b):
a = np.array(a)
b = np.array(b)
assert a.shape == b.shape
height, width = a.shape
result = np.zeros(a.shape, dtype=a.dtype)
for i, j in itertools.product(range(height), range(width)):
result[i, j] = a[i, j] + b[i, j]... | 2 loops, best of 5: 8.95 s per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Similarly to the `add_vectors_kernel` implementation, the `add_matrices_kernel` will compute a single matrix element. This time, we will use `y` coordinate to address matrix elements in the second dimension: | @cuda.jit
def add_matrices_kernel(result, a, b):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
j = cuda.blockIdx.y*cuda.blockDim.y + cuda.threadIdx.y
height, width = result.shape
# Make sure we are not accessing data outside available space!
if i >= width or j >= height:
return
... | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Now, we must also pass the second dimension of the grid to the GPU kernel invocation parameters, as the implementation assumes a 2-D grid layout. The parameters `grid_size` and `block_size` now has to pairs of integer values: | def add_matrices_gpu(a, b):
assert a.shape == b.shape
# Create output array in the GPU memory.
result = cuda.device_array(shape=a.shape, dtype=a.dtype)
height, width = a.shape
block_size = (16, 16)
grid_size = (math.ceil(width/block_size[0]), math.ceil(height/block_size[1]))
add_matrices_ke... | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Let's test the implementation first: | C = add_matrices_gpu(A, B)
np.testing.assert_equal(C, A+B) | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Now lets compare CPU and GPU processing time: | %%timeit
add_matrices_gpu(A, B) | 10 loops, best of 5: 140 ms per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
We leave the implementation of adding two 3D arrays as homework for the students. 1.1.3. See also- CUDA kernels in Numba: introduction: https://numba.readthedocs.io/en/0.52.0/cuda/kernels.htmlintroduction- Matrix multiplication example https://numba.readthedocs.io/en/0.52.0/cuda/examples.htmlmatrix-multiplication Exe... | block_size = 256
grid_size = math.ceil(len(a)/block_size)
# Create an array for the result in the GPU global memory.
result_gpu = cuda.device_array(shape=a.shape, dtype=a.dtype)
# Here are the explicit data transfers from host PC memory to GPU global memory:
a_gpu = cuda.to_device(a)
b_gpu = cuda.to_device(b)
add_v... | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Data transfer to and from GPU memory is only possible with GPU global memory. The following functions are available in Numba:- create an array in the GPU global memory: `numba.cuda.device_array`, or `numba.cuda.device_array_like`,- host PC to GPU global memory transfer: `numba.cuda.to_device`- GPU global memory to host... | %%timeit -n 100
add_vectors_kernel[grid_size, block_size](result_gpu, a_gpu, b_gpu) | 100 loops, best of 5: 172 µs per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The difference is that we did not transfer data from the GPU to the CPU. Let's try now with the GPU -> CPU transfer: | %%timeit -n 100
add_vectors_kernel[grid_size, block_size](result_gpu, a_gpu, b_gpu)
result = result_gpu.copy_to_host() | 100 loops, best of 5: 34.6 ms per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The difference is due to the fact that the data transfer is a blocking operation - it waits for all queued operations to be performed, then performs the transfer. To wait for the kernels to execute explicitly, without transferring the result data to host PC, run `cuda.default_stream().synchronize()`. | %%timeit -n 100
add_vectors_kernel[grid_size, block_size](result_gpu, a_gpu, b_gpu)
cuda.default_stream().synchronize() | 100 loops, best of 5: 1.8 ms per loop
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
CUDA streams will be covered in more detail later in this short-course. 1.2.1 See also - CUDA Toolkit documentation: device memory management (CUDA C++): https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.htmldevice-memory- The complete list of Numba's functions for data transfer to and from GPU: https://numb... | ! nvidia-smi | Sun Jun 27 10:32:17 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 465.27 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id ... | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
`nvidia-smi` outputs information about:- the installed NVIDIA driver and CUDA Toolkit,- for each available GPU: - temperature, memory usage and GPU utilization, - processes that are currently running on that GPU. `nvidia-smi` is a command line tool, so use it in your shell to quickly check the state of your GPU. CUD... | import cupy as cp
cp.cuda.runtime.getDeviceCount() | _____no_output_____ | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Now, let's we check:- what is the name of the device and what is its compute capability,- what is the GPU clock frequency,- how much global, shared and constant memory our GPU card has. | device_props = cp.cuda.runtime.getDeviceProperties(0)
print(f"Device: {device_props['name']} (cc {device_props['major']}.{device_props['minor']})")
print(f"GPU clock frequency: {device_props['clockRate']/1e3} MHz")
print("Available memory: ")
print(f"- global memory: {device_props['totalGlobalMem']/2**20} MiB")
print(... | Device: b'Tesla T4' (cc 7.5)
GPU clock frequency: 1590.0 MHz
Available memory:
- global memory: 15109.75 MiB
- shared memory per thread block: 49152 B
- constant memory: 65536 B
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The complete list of device properties is available [here](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.htmlgroup__CUDART__DEVICE_1g1bf9d625a931d657e08db2b4391170f0). Exercise 1.3.2. Numba. - Numba is a just-in-time (JIT) compiler for Python.- It generates machine code from Python bytecode using... | @cuda.jit
def increment(x):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
x[i] += 2
%time increment[1, 5](np.arange(5)) | CPU times: user 125 ms, sys: 5.01 ms, total: 130 ms
Wall time: 132 ms
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The second kernel execution takes: | %time increment[1, 5](np.arange(5)) | CPU times: user 1.52 ms, sys: 10 µs, total: 1.53 ms
Wall time: 1.34 ms
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Exercise 1.3.3. CUDA-MEMCHECK and debugging Numba code. 1.3.3.1 CUDA-MEMCHECK CUDA-MEMCHECK is an tool available in CUDA SDK, which gives the possibility to check if CUDA application makes any of the following errors:- misaligned and out of bounds memory access errors,- shared memory data races,- unintialized accesse... | %%writefile 1_3_3_memcheck.py
import os
import numpy as np
from numba import cuda
import math
@cuda.jit(debug=True)
def add_vectors_invalid(result, a, b):
pass
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
# What are we missing here?
result[i] = a[i] + b[i]
a = np.arange(255)
b = np.arange... | Writing 1_3_3_memcheck.py
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The only thing the above cell does is saving the Python code to the `1_3_3_memcheck.py` script in the current directory (you can check it using `! pwd` command). Now, we can run `cuda-memcheck` along with the Python interpreter in order to see if there any issues with the script. | ! cuda-memcheck --show-backtrace no python 1_3_3_memcheck.py | ========= CUDA-MEMCHECK
========= Invalid __global__ read of size 8
========= at 0x00000490 in cudapy::__main__::add_vectors_invalid$241(Array<__int64, int=1, C, mutable, aligned>, Array<__int64, int=1, C, mutable, aligned>, Array<__int64, int=1, C, mutable, aligned>)
========= by thread (255,0,0) in block (0,0... | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
As we can see, CUDA-MEMCHECK detected, the `add_vectors_invalid` kernel was not properly executed by thread `255`. What is causing the issue? 1.3.3.2 Debugging Numba kernels CUDA SDK toolkit includes debuggers that can be run on the GPU kernel code, in case it's necessary to trace the cause of the issue. A list of CUD... | %%writefile 1_3_3_numba_debugger.py
# Turn on CUDA simulator.
import os
os.environ['NUMBA_ENABLE_CUDASIM'] = '1'
import numpy as np
from numba import cuda
import math
@cuda.jit
def add_vectors(result, a, b):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
# What are we missing here?
result[i] = a... | 20 = 10 + 10
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
Exercise 1.3.4. Profiling GPU code. Sometimes, to better understand and optimize performance of GPU appplication, it is necessary to perform a dynamic program analysis and to mesaure a specific metrics, for example the execution time and memory requirements of a particular CUDA kernel. The utility that performs such a... | %%writefile 1_3_4_nvprof_add_vectors.py
import math
from numba import cuda
import numpy as np
@cuda.jit
def add_vectors_kernel(result, a, b):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
# Make sure not to go outside the grid area!
if i >= len(result):
return
result[i] = a[i] + b[i]
... | Writing 1_3_4_nvprof_add_vectors.py
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
The usage is the following:```nvprof [options] [application] [application-arguments]``` For example, to run the above Python script: | ! nvprof python 1_3_4_nvprof_add_vectors.py | ==568== NVPROF is profiling process 568, command: python3 1_3_4_nvprof_add_vectors.py
==568== Profiling application: python3 1_3_4_nvprof_add_vectors.py
==568== Profiling result:
Type Time(%) Time Calls Avg Min Max Name
GPU activities: 46.64% 5.7600us 3 1.9200us 1.... | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
By default, `nvprof` outputs all GPU and API calls activity. Mainly we are interested in the CUDA GPU tracing -- we can turn off API calls by using `--trace gpu` option. | ! nvprof --trace gpu python 1_3_4_nvprof_add_vectors.py | ==590== NVPROF is profiling process 590, command: python3 1_3_4_nvprof_add_vectors.py
==590== Profiling application: python3 1_3_4_nvprof_add_vectors.py
==590== Profiling result:
Type Time(%) Time Calls Avg Min Max Name
GPU activities: 44.50% 5.3120us 3 1.7700us 1.... | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
CUDA GPU activities includes:- CUDA kernels activities,- GPU to Host memory transfers (`DtoH`), host to GPU memory transfers (`HtoD`). Let's we add one more kernel to the above code: | %%writefile 1_3_4_nvprof_increment_add_vectors.py
import math
from numba import cuda
import numpy as np
@cuda.jit
def increment(a):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
a[i] += 1
@cuda.jit
def add_vectors_kernel(result, a, b):
i = cuda.blockIdx.x*cuda.blockDim.x + cuda.threadIdx.x
#... | ==612== NVPROF is profiling process 612, command: python3 1_3_4_nvprof_increment_add_vectors.py
==612== Profiling application: python3 1_3_4_nvprof_increment_add_vectors.py
==612== Profiling result:
Type Time(%) Time Calls Avg Min Max Name
GPU activities: 54.69% 57.733ms ... | Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
In the above case, `nvprof` should display the execution times for both kernels. 1.3.4.2. NVIDIA Visual Profiler NVIDIA Visual Profiler (NVVP) allows to Let's export the profiling results to a file that can be loaded by NVVP. We can `nvprof` for this purpose, just use `--export-profile` parameter. | ! nvprof --trace gpu --export-profile nvvp_example.nvvp -f python 1_3_4_nvprof_increment_add_vectors.py | ==634== NVPROF is profiling process 634, command: python3 1_3_4_nvprof_increment_add_vectors.py
==634== Generated result file: /content/nvvp_example.nvvp
| Unlicense | exercises/1_CUDA_programming_model.ipynb | pjarosik/ius-2021-gpu-short-course |
**CS224W - Colab 2** In Colab 2, we will work to construct our own graph neural network using PyTorch Geometric (PyG) and then apply that model on two Open Graph Benchmark (OGB) datasets. These two datasets will be used to benchmark your model's performance on two different graph-based tasks: 1) node property predicti... | import torch
import os
print("PyTorch has version {}".format(torch.__version__)) | PyTorch has version 1.10.0
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Download the necessary packages for PyG. Make sure that your version of torch matches the output from the cell above. In case of any issues, more information can be found on the [PyG's installation page](https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html). | # Install torch geometric
if 'IS_GRADESCOPE_ENV' not in os.environ:
!pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html
!pip install torch-sparse -f https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html
!pip install torch-geometric
!pip install ogb | Looking in links: https://pytorch-geometric.com/whl/torch-1.9.0+cu111.html
Collecting torch-scatter
Downloading https://data.pyg.org/whl/torch-1.9.0%2Bcu111/torch_scatter-2.0.9-cp38-cp38-win_amd64.whl (4.0 MB)
Installing collected packages: torch-scatter
Successfully installed torch-scatter-2.0.9
Looking in links: ht... | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
1) PyTorch Geometric (Datasets and Data) PyTorch Geometric has two classes for storing and/or transforming graphs into tensor format. One is `torch_geometric.datasets`, which contains a variety of common graph datasets. Another is `torch_geometric.data`, which provides the data handling of graphs in PyTorch tensors.In... | from torch_geometric.datasets import TUDataset
if 'IS_GRADESCOPE_ENV' not in os.environ:
root = './enzymes'
name = 'ENZYMES'
# The ENZYMES dataset
pyg_dataset= TUDataset(root, name)
# You will find that there are 600 graphs in this dataset
print(pyg_dataset) | Downloading https://www.chrsmrrs.com/graphkerneldatasets/ENZYMES.zip
Extracting enzymes\ENZYMES\ENZYMES.zip
Processing...
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Question 1: What is the number of classes and number of features in the ENZYMES dataset? (5 points) | def get_num_classes(pyg_dataset):
# TODO: Implement a function that takes a PyG dataset object
# and returns the number of classes for that dataset.
num_classes = 0
############# Your code here ############
## (~1 line of code)
## Note
## 1. Colab autocomplete functionality might be useful.
num_classe... | ENZYMES dataset has 6 classes
ENZYMES dataset has 3 features
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
PyG DataEach PyG dataset stores a list of `torch_geometric.data.Data` objects, where each `torch_geometric.data.Data` object represents a graph. We can easily get the `Data` object by indexing into the dataset.For more information such as what is stored in the `Data` object, please refer to the [documentation](https:/... | def get_graph_class(pyg_dataset, idx):
# TODO: Implement a function that takes a PyG dataset object,
# an index of a graph within the dataset, and returns the class/label
# of the graph (as an integer).
label = -1
############# Your code here ############
## (~1 line of code)
graph = pyg_dataset[idx]
... | Data(edge_index=[2, 168], x=[37, 3], y=[1])
Graph with index 100 has label 4
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Question 3: How many edges does the graph with index 200 have? (5 points) | def get_graph_num_edges(pyg_dataset, idx):
# TODO: Implement a function that takes a PyG dataset object,
# the index of a graph in the dataset, and returns the number of
# edges in the graph (as an integer). You should not count an edge
# twice if the graph is undirected. For example, in an undirected
# gr... | _____no_output_____ | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
2) Open Graph Benchmark (OGB)The Open Graph Benchmark (OGB) is a collection of realistic, large-scale, and diverse benchmark datasets for machine learning on graphs. Its datasets are automatically downloaded, processed, and split using the OGB Data Loader. The model performance can then be evaluated by using the OGB E... | import torch_geometric.transforms as T
from ogb.nodeproppred import PygNodePropPredDataset
if 'IS_GRADESCOPE_ENV' not in os.environ:
dataset_name = 'ogbn-arxiv'
# Load the dataset and transform it to sparse tensor
dataset = PygNodePropPredDataset(name=dataset_name,
transform=T.T... | Downloading http://snap.stanford.edu/ogb/data/nodeproppred/arxiv.zip
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Question 4: How many features are in the ogbn-arxiv graph? (5 points) | def graph_num_features(data):
# TODO: Implement a function that takes a PyG data object,
# and returns the number of features in the graph (as an integer).
num_features = 0
############# Your code here ############
## (~1 line of code)
num_features = data.num_features
###################################... | The graph has 128 features
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
3) GNN: Node Property PredictionIn this section we will build our first graph neural network using PyTorch Geometric. Then we will apply it to the task of node property prediction (node classification).Specifically, we will use GCN as the foundation for your graph neural network ([Kipf et al. (2017)](https://arxiv.org... | import torch
import pandas as pd
import torch.nn.functional as F
print(torch.__version__)
# The PyG built-in GCNConv
from torch_geometric.nn import GCNConv
import torch_geometric.transforms as T
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator | 1.10.0
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Load and Preprocess the Dataset | if 'IS_GRADESCOPE_ENV' not in os.environ:
dataset_name = 'ogbn-arxiv'
dataset = PygNodePropPredDataset(name=dataset_name,
transform=T.ToSparseTensor())
data = dataset[0]
# Make the adjacency matrix to symmetric
data.adj_t = data.adj_t.to_symmetric()
device = 'cpu'
# If... | Device: cpu
128
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
GCN ModelNow we will implement our GCN model!Please follow the figure below to implement the `forward` function. | class GCN(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers,
dropout, return_embeds=False):
# TODO: Implement a function that initializes self.convs,
# self.bns, and self.softmax.
super(GCN, self).__init__()
# A list of GCNConv lay... | Epoch: 01, Loss: 4.0669, Train: 19.65%, Valid: 26.05% Test: 23.55%
Epoch: 02, Loss: 2.3643, Train: 21.23%, Valid: 20.62% Test: 26.14%
Epoch: 03, Loss: 1.9636, Train: 38.83%, Valid: 39.31% Test: 43.51%
Epoch: 04, Loss: 1.7614, Train: 45.58%, Valid: 46.42% Test: 43.25%
Epoch: 05, Loss: 1.6479, Train: 44.97%, Valid: 43.31... | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Question 5: What are your `best_model` validation and test accuracies?(20 points)Run the cell below to see the results of your best of model and save your model's predictions to a file named *ogbn-arxiv_node.csv*. You can view this file by clicking on the *Folder* icon on the left side pannel. As in Colab 1, when you ... | if 'IS_GRADESCOPE_ENV' not in os.environ:
best_result = test(best_model, data, split_idx, evaluator, save_model_results=True)
train_acc, valid_acc, test_acc = best_result
print(f'Best model: '
f'Train: {100 * train_acc:.2f}%, '
f'Valid: {100 * valid_acc:.2f}% '
f'Test: {100 * test_acc:.2f}... | Saving Model Predictions
Best model: Train: 73.88%, Valid: 71.90% Test: 71.29%
| Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
4) GNN: Graph Property PredictionIn this section we will create a graph neural network for graph property prediction (graph classification). Load and preprocess the dataset | from ogb.graphproppred import PygGraphPropPredDataset, Evaluator
from torch_geometric.data import DataLoader
from tqdm.notebook import tqdm
if 'IS_GRADESCOPE_ENV' not in os.environ:
# Load the dataset
dataset = PygGraphPropPredDataset(name='ogbg-molhiv')
device = 'cuda' if torch.cuda.is_available() else 'cpu'
... | _____no_output_____ | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Graph Prediction Model Graph Mini-BatchingBefore diving into the actual model, we introduce the concept of mini-batching with graphs. In order to parallelize the processing of a mini-batch of graphs, PyG combines the graphs into a single disconnected graph data object (*torch_geometric.data.Batch*). *torch_geometric.... | from ogb.graphproppred.mol_encoder import AtomEncoder
from torch_geometric.nn import global_add_pool, global_mean_pool
### GCN to predict graph property
class GCN_Graph(torch.nn.Module):
def __init__(self, hidden_dim, output_dim, num_layers, dropout):
super(GCN_Graph, self).__init__()
# Load encod... | _____no_output_____ | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Question 6: What are your `best_model` validation and test ROC-AUC scores? (20 points)Run the cell below to see the results of your best of model and save your model's predictions over the validation and test datasets. The resulting files are named *ogbn-arxiv_graph_valid.csv* and *ogbn-arxiv_graph_test.csv*. Again, y... | if 'IS_GRADESCOPE_ENV' not in os.environ:
train_acc = eval(best_model, device, train_loader, evaluator)[dataset.eval_metric]
valid_acc = eval(best_model, device, valid_loader, evaluator, save_model_results=True, save_file="valid")[dataset.eval_metric]
test_acc = eval(best_model, device, test_loader, evaluator, s... | _____no_output_____ | Unlicense | Colab 2/CS224W - Colab 2_tobias.ipynb | victorcroisfelt/aau-cs224w-ml-with-graphs |
Import Data | def boston_df(sklearn_dataset):
X = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
y = pd.DataFrame(sklearn_dataset.target, columns = ['MEDV'])
return X, y
X, y = boston_df(load_boston())
X.columns | _____no_output_____ | MIT | notebooks/00-data/04-boston.ipynb | mixerupper/mltools-fi_cate |
Save data | folder_name = 'boston'
try:
os.mkdir(processed_root(folder_name))
except FileExistsError:
print("Folder already exists")
X.to_csv(processed_root(f"{folder_name}/X.csv"), index = False)
y.to_csv(processed_root(f"{folder_name}/y.csv"), index = False) | _____no_output_____ | MIT | notebooks/00-data/04-boston.ipynb | mixerupper/mltools-fi_cate |
Example 1: Detecting an obvious outlier | import numpy as np
from isotree import IsolationForest
### Random data from a standard normal distribution
np.random.seed(1)
n = 100
m = 2
X = np.random.normal(size = (n, m))
### Will now add obvious outlier point (3, 3) to the data
X = np.r_[X, np.array([3, 3]).reshape((1, m))]
### Fit a small isolation forest mode... | Point with highest outlier score: [3. 3.]
| BSD-2-Clause | example/isotree_example.ipynb | ankane/isotree-1 |
Example 2: Plotting outlier and density regions | import numpy as np, pandas as pd
from isotree import IsolationForest
import matplotlib.pyplot as plt
from pylab import rcParams
%matplotlib inline
rcParams['figure.figsize'] = 10, 8
np.random.seed(1)
group1 = pd.DataFrame({
"x" : np.random.normal(loc=-1, scale=.4, size = 1000),
"y" : np.random.normal(loc=-1, s... | _____no_output_____ | BSD-2-Clause | example/isotree_example.ipynb | ankane/isotree-1 |
Example 3: calculating pairwise distances | import numpy as np, pandas as pd
from isotree import IsolationForest
from scipy.spatial.distance import cdist
### Generate random multivariate-normal data
np.random.seed(1)
n = 1000
m = 10
### This is a random PSD matrix to use as covariance
S = np.random.normal(size = (m, m))
S = S.T.dot(S)
mu = np.random.normal(si... | Correlations between different distance metrics
| BSD-2-Clause | example/isotree_example.ipynb | ankane/isotree-1 |
Example 4: imputing missing values | import numpy as np
from isotree import IsolationForest
### Generate random multivariate-normal data
np.random.seed(1)
n = 1000
m = 5
### This is a random PSD matrix to use as covariance
S = np.random.normal(size = (m, m))
S = S.T.dot(S)
mu = np.random.normal(size = m)
X = np.random.multivariate_normal(mu, S, n)
###... | MSE for imputed values w/model: 3.176113
MSE for imputed values w/means: 5.540559
| BSD-2-Clause | example/isotree_example.ipynb | ankane/isotree-1 |
决策树----- | # 准备工作
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labels... | _____no_output_____ | Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
训练与可视化 | from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2, random_state=42)
tree_clf.fit(X, y)
from sklearn.tree import export_graphviz
export_graphviz(tree_clf,... | _____no_output_____ | Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
根据上面得到的dot文件,可以使用`$ dot -Tpng iris_tree.dot -o iris_tree.png`命令转换为图片,如下: 上图可以看到树是的预测过程。假设想分类鸢尾花, 可以从根节点开始。 首先看花瓣宽度, 如果小于2.45cm, 分入左边节点(深度1,左)。这种情况下,叶子节点不同继续询问,可以直接预测为Setosa鸢尾花。 如果宽度大于2.45cm, 移到右边子节点继续判断。由于不是叶子节点,因此继续判断, 花萼宽度如果小于1.75cm,则很大可能是Versicolor花(深度2, 左)。否则,可能是Virginica... | from matplotlib.colors import ListedColormap
def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
x1s = np.linspace(axes[0], axes[1], 100)
x2s = np.linspace(axes[2], axes[3], 100)
x1, x2 = np.meshgrid(x1s, x2s)
X_new = np.c_[x1.ravel(), x2.ravel()]
... | /anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:967: UserWarning: The following kwargs were not used by contour: 'linewidth'
s)
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
上图显示了该决策树的决策边界。垂直线表示决策树的根节点(深度0), 花瓣长度等于2.45cm。 由于左边gini为0,只有一种分类,不再进一步分类判断。但是右边不是很纯,因此深度1的右边节点根据花萼宽度1.75cm进一步判断。 由于最大深度为2,决策树停止后面的判断。但是可以设置max_depth为3, 然后,两个深度2节点将各自添加另一个决策边界(由虚线表示)。 补充:可以看到决策树的过程容易理解,称之为白盒模型。与之不同的是,随机森林和神经网络一般称为黑盒模型。 它们预测效果很好,可以很容易地检查其计算结果, 来做出这些预测。但却难以解释为什么这样预测。 决策树提供了很好的和简单的分类规则,甚至可以在需要时手动分类。 ... | tree_clf.predict_proba([[5, 1.5]])
tree_clf.predict([[5, 1.5]]) | _____no_output_____ | Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
CART:分类回归树sklearn使用CART算法对训练决策树(增长树)。思想很简单:首先将训练集分为两个子集,根据特征k和阈值$t_k$(比如花瓣长度小于2.45cm)。重要的是怎么选出这个特征。 通过对每一组最纯的子集(k, $t_k$),根据大小的权重进行搜索。最小化如下损失函数: CART分类的损失函数$J(k, t_k) = \frac{m_{left}}{m}G_{left} + \frac{m_{right}}{m}G_{right} $最小化如上函数,一旦成功分为两个子集, 就可以使用相同逻辑递归进行切分。当到达给定的最大深度时(max_depth)... | not_widest_versicolor = (X[:, 1] != 1.8) | (y==2)
X_tweaked = X[not_widest_versicolor]
y_tweaked = y[not_widest_versicolor]
tree_clf_tweaked = DecisionTreeClassifier(max_depth=2, random_state=40)
tree_clf_tweaked.fit(X_tweaked, y_tweaked)
plt.figure(figsize=(8, 4))
plot_decision_boundary(tree_clf_tweaked, X_tweaked, y... | /anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:967: UserWarning: The following kwargs were not used by contour: 'linewidth'
s)
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
限制超参数如下情况所示,防止过拟合数据,需要限制决策树的自由度,这个过程也叫正则(限制)。 决策树的max_depth超参数来控制拟合程度,默认不限制。可以减少max_depth来限制模型,减少过拟合的风险。 | from sklearn.datasets import make_moons
Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
deep_tree_clf1.fit(Xm, ym)
deep_tree_clf2.fit(Xm, ym)
plt.figure(figsize=(11, 4... | /anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:967: UserWarning: The following kwargs were not used by contour: 'linewidth'
s)
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
DecisionTreeClassifier有如下超参数:min_samples_split表示切分数据时包含的最小实例, min_samples_leaf表示一个叶子节点必须拥有的最小样本数目, min_weight_fraction_leaf(与min_samples_leaf相同,但表示为加权实例总数的一小部分), max_leaf_nodes(最大叶节点数)和max_features(在每个节点上分配的最大特性数), 增加min_*超参数或减少max_*超参数将使模型规范化。其他算法开始时对决策树进行无约束训练,之后删除没必要的特征,称为减枝。 如果一个节点的所有子节点所提供的纯度改善没有统计学意义,则认为其和其子节点是不... | angle = np.pi / 180 * 20
rotation_maxtrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
Xr = X.dot(rotation_maxtrix)
tree_clf_r = DecisionTreeClassifier(random_state=42)
tree_clf_r.fit(Xr, y)
plt.figure(figsize=(8, 3))
plot_decision_boundary(tree_clf_r, Xr, y, axes=[0.5, 7.5, -1.0, 1]... | /anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:967: UserWarning: The following kwargs were not used by contour: 'linewidth'
s)
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
不稳定性目前为止,决策树有很多好处:它们易于理解和解释,易于使用,用途广泛,而且功能强大。 但是也有一些限制。首先, 决策树喜欢正交决策边界(所有的分割都垂直于一个轴),这使得它们对训练集的旋转很敏感。如下右图所示,旋转45度之后,尽管分类的很好,但是不会得到更大推广。其中的一种解决办法是PCA(后面介绍)。更普遍的,决策树对训练集中的微小变化很敏感。比如上图中移除一个实例的分类结果又很大的不同。 随机森林可以通过对许多树进行平均预测来限制这种不稳定, 对异常值,微小变化更加适用。 | np.random.seed(6)
Xs = np.random.rand(100, 2) - 0.5
ys = (Xs[:, 0] > 0).astype(np.float32) * 2
angle = np.pi / 4
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
Xsr = Xs.dot(rotation_matrix)
tree_clf_s = DecisionTreeClassifier(random_state=42)
tree_clf_s.fit(Xs, ys)
tree_... | /anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:967: UserWarning: The following kwargs were not used by contour: 'linewidth'
s)
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
回归树 | import numpy as np
# 带噪声的2阶训练集
np.random.seed(42)
m = 200
X = np.random.rand(m ,1)
y = 4 * (X - 0.5) ** 2
y = y + np.random.randn(m, 1) / 10
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
tree_reg.fit(X, y) | _____no_output_____ | Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
该回归决策树最大深度为2, dot后如下: 与分类树非常类似。 主要的不同在于,分类树根据每个节点预测每个分类。 比如当x1 = 0.6时进行预测。从根开始遍历树,最终到达叶节点,该节点预测值=0.1106。 这个预测仅仅是与此叶节点相关的110个训练实例的平均目标值。这个预测的结果是一个平均平方误差(MSE),在这110个实例中等于0.0151。 请注意,每个区域的预测值始终是该区域实例的平均目标值。该算法以一种使大多数训练实例尽可能接近预测值的方式来分割每个区域。 | from sklearn.tree import DecisionTreeRegressor
tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
tree_reg1.fit(X, y)
tree_reg2.fit(X, y)
def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
x1 = np.linsp... | Saving figure tree_regression_regularization_plot
| Apache-2.0 | 06_blog/06_blog_01.ipynb | yunshuipiao/hands-on-ml-with-sklearn-tf-python3 |
Use OSMnx to construct place boundaries and street networks, and save as various file formats for working with later - [Overview of OSMnx](http://geoffboeing.com/2016/11/osmnx-python-street-networks/) - [GitHub repo](https://github.com/gboeing/osmnx) - [Examples, demos, tutorials](https://github.com/gboeing/osmnx/t... | import osmnx as ox
%matplotlib inline
ox.config(log_file=True, log_console=True, use_cache=True)
place = 'Piedmont, California, USA' | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
Get place shape geometries from OSM and save as shapefile | gdf = ox.gdf_from_place(place)
gdf.loc[0, 'geometry']
# save place boundary geometry as ESRI shapefile
ox.save_gdf_shapefile(gdf, filename='place-shape') | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
Construct street network and save as shapefile to work with in GIS | G = ox.graph_from_place(place, network_type='drive')
G_projected = ox.project_graph(G)
# save street network as ESRI shapefile
ox.save_graph_shapefile(G_projected, filename='network-shape') | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
Save street network as GraphML to work with in Gephi or NetworkX | # save street network as GraphML file
ox.save_graphml(G_projected, filename='network.graphml') | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
Save street network as SVG to work with in Illustrator | # save street network as SVG
fig, ax = ox.plot_graph(G_projected, show=False, save=True,
filename='network', file_format='svg') | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
Load street network from saved GraphML file | G2 = ox.load_graphml('network.graphml')
fig, ax = ox.plot_graph(G2) | _____no_output_____ | MIT | examples/05-example-save-load-networks-shapes.ipynb | tanvim/test |
TAG MATRIX DATA SCRAPER- author: Richard Castro - sticky_rank: 1- toc: true- badges: true- comments: false- categories: [Matrix]- image: images/scraper.jpg | import pandas as pd
import requests
import datetime
date=datetime.datetime.now().strftime("%Y-%m-%d")
import dash
import dash_core_components as dcc
df=pd.read_csv("https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-province/dpc-covid19-ita-province.csv")
df.to_csv('../data/clients/CHEP/'+date+'-Italy.csv') | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
CANADA STUFF | #SOURCE - https://github.com/eebrown/data2019nCoV
df=pd.read_csv('https://raw.githubusercontent.com/eebrown/data2019nCoV/master/data-raw/covid19.csv')
df=df.rename(columns={'pruid':'uid', 'prname':'province'})
col=['uid', 'province','date', 'numconf', 'numprob',
'numdeaths', 'numtotal', 'numtested', 'numrecover'... | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
World-o-Meter | #WORLD O METER DATA
#NEW YORK COUNTY DATA
import datetime
date=datetime.datetime.now().strftime("%Y-%m-%d")
web=requests.get('https://www.worldometers.info/coronavirus/usa/new-york')
ny=pd.read_html(web.text)
ny=ny[1]
ny.columns=map(str.lower, ny.columns)
ny.to_csv('../data/sources/worldometer/'+date+'-NY-County-Data.... | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
rt live | rtlive=pd.read_csv('https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv')
rtlive.to_csv('../_data/data_sources/rtlive/rtlive'+date+'.csv') | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
Mobility Reports Google Mobility Reports Apple Mobility Reports | #GOOGLE AND APPLE MOBILITY DATA BY COUNTY
#apple=pd.read_csv('https://covid19-static.cdn-apple.com/covid19-mobility-data/2014HotfixDev8/v3/en-us/applemobilitytrends-2020-08-08.csv')
#apple.to_csv('../_data/Data_Sources/Mobility_Reports/apple.csv')
google=pd.read_csv('https://www.gstatic.com/covid19/mobility/Global_Mob... | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
WORLD-O-METER DATASETS NEW YORK CALIFORNIA NEW JERSEY PA SOUTH CAROLINA OHIO WASHINGTON STATE | healthDepartment=requests.get('https://data.ct.gov/Health-and-Human-Services/COVID-19-Tests-Cases-and-Deaths-By-Town-/28fr-iqnx/data')
hd=pd.read_html(healthDepartment.text) | _____no_output_____ | Apache-2.0 | _notebooks/Matrix Data Scrapper.ipynb | lalalaNomNomNom/Notebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.