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 |
|---|---|---|---|---|---|
Bootstrap Estimate the standard error of $\hat{p}$ using bootstrap. | def bootstrap_se_est(y, stat_function, B=1000):
# 1. Generate bootstrap samples from the observed/simulated data (i.e. y)
# 2. Compute the statistic (using stat_function passed) on the bootstrap
# samples
# 3. Compute the standard error -> std dev
t_boot_list = [stat_function(np.random.choice(y, len(y), r... | Standard error of p_hat computed by bootstrap:
0.04889048066853097
| MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Validate the estimated standard error by computing it analytically. | def estimator_analytical_se(p, n):
return np.sqrt(p * (1-p) / n)
print("Analytical standard error for the estimator: ", estimator_analytical_se(p, n)) | Analytical standard error for the estimator: 0.04898979485566356
| MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Estimate the 95% confidence interval for $p$. | def confidence_interval_95_for_p(y):
ci_lower = estimator(y) - 1.96*bootstrap_se_est(y, estimator)
ci_higher = estimator(y) + 1.96*bootstrap_se_est(y, estimator)
return (ci_lower, ci_higher)
lower, higher = confidence_interval_95_for_p(y)
print("95% confidence interval for p: ({},{})".format(lower, higher)) | 95% confidence interval for p: (0.5254445619916019,0.717033857596202)
| MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Validate the 95% confidence interval for $p$. | ci_contains_p_flags = []
for sim in range(1000):
y = np.random.binomial(n=1, p=p, size=n)
ci_lower, ci_higher = confidence_interval_95_for_p(y)
if ci_lower < p and p < ci_higher:
ci_contains_p_flags.append(1)
else:
ci_contains_p_flags.append(0)
coverage = np.mean(ci_contains_p_flags)
print("Coverage o... | Coverage of 95% confidence interval for p: 0.93
| MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Bayesian Inference **[Optional]**Estimate $p$ using Bayesian inference. As the prior for $p$ use Normal(0.5, 0.1). | !pip install pystan
import pystan
model_code = """
data {
int<lower=0> n;
int<lower=0,upper=1> y[n];
}
parameters {
real<lower=0,upper=1> p;
}
model {
p ~ normal(0.5, 0.1);
for (i in 1:n)
y[i] ~ bernoulli(p);
}
"""
model = pystan.StanModel(model_code=model_code)
fit = model.sampling(data={"n": n, "y": y}... | _____no_output_____ | MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
Compute the Bayesian inference results if our data contains 20 coin tosses instead. | n = 20
p = 0.6
y = np.random.binomial(1, p, n)
model = pystan.StanModel(model_code=model_code)
fit = model.sampling(data={"n": n, "y": y}, iter=2000, chains=4, n_jobs=4)
print(fit.stansummary()) | _____no_output_____ | MIT | colab/lab_1_statistical_inference_cmunoz.ipynb | cmunozcortes/ds-fundamentals |
XResNet baseline | #https://github.com/fastai/fastai_docs/blob/master/dev_course/dl2/11_train_imagenette.ipynb
def noop(x): return x
class Flatten(nn.Module):
def forward(self, x): return x.view(x.size(0), -1)
def conv(ni, nf, ks=3, stride=1, bias=False):
return nn.Conv2d(ni, nf, kernel_size=ks, stride=stride, padding=ks//2, bi... | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
XResNet with Self Attention | #Unmodified from https://github.com/fastai/fastai/blob/5c51f9eabf76853a89a9bc5741804d2ed4407e49/fastai/layers.py
def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride... | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Data loading | #https://github.com/fastai/fastai/blob/master/examples/train_imagenette.py
def get_data(size, woof, bs, workers=None):
if size<=128: path = URLs.IMAGEWOOF_160 if woof else URLs.IMAGENETTE_160
elif size<=224: path = URLs.IMAGEWOOF_320 if woof else URLs.IMAGENETTE_320
else : path = URLs.IMAGEWOOF ... | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Train | opt_func = partial(optim.Adam, betas=(0.9,0.99), eps=1e-6) | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Imagewoof Image size = 256 | image_size = 256
data = get_data(image_size,woof =True,bs=64) | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Epochs = 5 | # we use the same parameters for baseline and new model
epochs = 5
lr = 3e-3
bs = 64
mixup = 0 | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Baseline | m = xresnet50(c_out=10)
learn = (Learner(data, m, wd=1e-2, opt_func=opt_func,
metrics=[accuracy,top_k_accuracy],
bn_wd=False, true_wd=True,
loss_func = LabelSmoothingCrossEntropy())
)
if mixup: learn = learn.mixup(alpha=mixup)
learn = learn.to_fp16(dynamic=True)
learn.... | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
New model | m = xresnet50_sa(c_out=10)
learn = None
gc.collect()
learn = (Learner(data, m, wd=1e-2, opt_func=opt_func,
metrics=[accuracy,top_k_accuracy],
bn_wd=False, true_wd=True,
loss_func = LabelSmoothingCrossEntropy())
)
if mixup: learn = learn.mixup(alpha=mixup)
learn = lear... | _____no_output_____ | Apache-2.0 | Imagenette Simple Self Attention.ipynb | RubensZimbres/SimpleSelfAttention |
Software License Agreement (MIT License) Copyright (c) 2020, Amirhossein Pakdaman. Simple DFS, BFS **Problem**: Implement a search tree with the following characteristics:1. The initial state contains value 10.2. At each step two successors are created, the value one of them is one unit smaller than its parent and the... | import IPython
IPython.core.display.Image("tree.png", embed=True) | _____no_output_____ | MIT | BFS_DFS_simple_example/BFS_DFS_simple_example.ipynb | amirhpd/Python_Basics |
BFS | import queue
class Node:
def __init__(self,value,parent,depth):
self.value = value
self.parent = parent
self.depth = depth
parent = Node(10,None,0)
frontier = queue.Queue()
frontier.put(parent)
while frontier:
current_node = frontier.get()
if current_node.depth > ... | 10
9
11
8
10
10
12
7
9
9
11
9
11
11
13
| MIT | BFS_DFS_simple_example/BFS_DFS_simple_example.ipynb | amirhpd/Python_Basics |
DFS | class Node:
def __init__(self,value,parent,depth):
self.value = value
self.parent = parent
self.depth = depth
parent = Node(10,None,0)
frontier = []
frontier.append(parent)
while frontier:
current_node = frontier.pop()
if current_node.depth > 3:
current_node =... | 10
9
8
7
9
10
9
11
11
10
9
11
12
11
13
| MIT | BFS_DFS_simple_example/BFS_DFS_simple_example.ipynb | amirhpd/Python_Basics |
FunctionsLet's say that we have some code that does some task, but the code is 25 lines long, we need to run it over 1000 items and it doesn't work in a loop. How in the world will we handle this situation? That is where functions come in really handy. Functions are a generalized block of code that allow you to run cod... | def add1(x):
return x+1
print(add1(1))
def xsq(x):
return x**2
print(xsq(5))
for i in range(0,10):
print(xsq(i)) | 2
25
0
1
4
9
16
25
36
49
64
81
| MIT | Python Workshop/Functions.ipynb | CalPolyPat/Python-Workshop |
The true power of functions is being able to call it as many times as we would like. In the previous example, we called the square function, xsq in a loop 10 times. Let's check out some more complicated examples. | def removefs(data):
newdata=''
for d in data:
if(d=="f" or d=="F"):
pass
else:
newdata+=(d)
return newdata
print(removefs('ffffffFFFFFg'))
intro='''##Functions
Let's say that we have some code that does some task, but the code is 25 lines long, we need to run it over ... | ##Fnctns
Lt's s tht w hv sm cd tht ds sm tsk, bt th cd s 25 lns lng, w nd t rn t vr 1000 tms nd t dsn't wrk n lp. Hw n th wrld wll w hndl ths sttn? Tht s whr fnctns cm n rll hnd. Fnctns r gnrlzd blck f cd tht llw t rn cd vr nd vr whl chngng ts prmtrs f s chs. Fnctns m tk **(rgmnts)** tht r llwd t chng whn cll th ... | MIT | Python Workshop/Functions.ipynb | CalPolyPat/Python-Workshop |
So clearly we can do some powerful things. Now let's see why these functions have significant power over loops. | def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
def printfib(n):
for i in range(0,n):
print(fib(i))
printfib(15) | 1
1
1
2
3
5
8
13
21
34
55
89
144
233
377
| MIT | Python Workshop/Functions.ipynb | CalPolyPat/Python-Workshop |
Here, using loops within functions allows to generate the fibonacci sequence. We then write a function to print out the first n numbers. Exercises1. Write a function that takes two arguments and returns a value that uses the arguments.2. Write a power function. It should take two arguments and returns the first argumen... | thoudigits = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890... | _____no_output_____ | MIT | Python Workshop/Functions.ipynb | CalPolyPat/Python-Workshop |
LambdaNext we will look at a special type of function called a lambda. A lambda is a single line, single expression function. It is perfect for evaluating mathematical expressions like x^2 and e^sin(x^cos(x)). To write a lambda function, we use the following syntax: func = lambda : for example: xsq = lambda x:... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#^^^Some junk we will learn later^^^
func = lambda x:np.exp(np.sin(x**np.cos(x)))
#^^^The important part^^^
plt.plot(np.linspace(0,10,1000), func(np.linspace(0,10,1000)))
#^^^We will learn this next^^^ | _____no_output_____ | MIT | Python Workshop/Functions.ipynb | CalPolyPat/Python-Workshop |
Exploring colour channels In this session, we'll be looking at how to explore the different colour channels that compris an image. | # We need to include the home directory in our path, so we can read in our own module.
import os
# image processing tools
import cv2
import numpy as np
# utility functions for this course
import sys
sys.path.append(os.path.join("..", "..", "CDS-VIS"))
from utils.imutils import jimshow
from utils.imutils import jimsho... | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
Rotation | filename = os.path.join("..", "..", "CDS-VIS", "img", "terasse.jpeg")
image = cv2.imread(filename)
image.shape
jimshow(image) | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
Splitting channels | (B, G, R) = cv2.split(image)
jimshow_channel(R, "Red") | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
__Empty numpy array__ | zeros = np.zeros(image.shape[:2], dtype = "uint8")
jimshow(cv2.merge([zeros, zeros, R]))
jimshow(cv2.merge([zeros, G, zeros]))
jimshow(cv2.merge([B, zeros, zeros])) | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
Histograms | jimshow_channel(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), "Greyscale") | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
__A note on ```COLOR_BRG2GRAY```__ | greyed_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
```greyed_image.flatten() != image.flatten()``` A quick greyscale histogram using matplotlib | # Create figure
plt.figure()
# Add histogram
plt.hist(image.flatten(), 256, [0,256])
# Plot title
plt.title("Greyscale histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.show() | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
Plotting color histograms ```cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])```- images : it is the source image of type uint8 or float32 represented as โ[img]โ.- channels : it is the index of channel for which we calculate histogram. - For grayscale image, its value is [0] and - co... | # split channels
channels = cv2.split(image)
# names of colours
colors = ("b", "g", "r")
# create plot
plt.figure()
# add title
plt.title("Histogram")
# Add xlabel
plt.xlabel("Bins")
# Add ylabel
plt.ylabel("# of Pixels")
# for every tuple of channel, colour
for (channel, color) in zip(channels, colors):
# Create ... | _____no_output_____ | MIT | notebooks/session2_inclass_rdkm.ipynb | Rysias/cds-visual |
[๋ชจ๋ 2.1] SageMaker ํด๋ฌ์คํฐ์์ ํ๋ จ (No VPC์์ ์คํ)์ด ๋
ธํธ๋ถ์ ์๋์ ์์
์ ์คํ ํฉ๋๋ค.- SageMaker Hosting Cluster ์์ ํ๋ จ์ ์คํ- ํ๋ จํ Job ์ด๋ฆ์ ์ ์ฅ - ๋ค์ ๋
ธํธ๋ถ์์ ๋ชจ๋ธ ๋ฐฐํฌ ๋ฐ ์ถ๋ก ์์ ์ฌ์ฉ ํฉ๋๋ค.--- SageMaker์ ์ธ์
์ ์ป๊ณ , role ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ต๋๋ค.- ์์ ๋ ์ ๋ณด๋ฅผ ํตํด์ SageMaker Hosting Cluster์ ์ฐ๊ฒฐํฉ๋๋ค. | import os
import sagemaker
from sagemaker import get_execution_role
sagemaker_session = sagemaker.Session()
role = get_execution_role() | _____no_output_____ | MIT | scratch/working/2.2.NoVPC-EFS-Train-Model.ipynb | gonsoomoon-ml/SageMaker-With-Secure-VPC |
๋ก์ปฌ์ ๋ฐ์ดํฐ S3 ์
๋ก๋ฉ๋ก์ปฌ์ ๋ฐ์ดํฐ๋ฅผ S3์ ์
๋ก๋ฉํ์ฌ ํ๋ จ์์ Input์ผ๋ก ์ฌ์ฉ ํฉ๋๋ค. | # dataset_location = sagemaker_session.upload_data(path='data', key_prefix='data/DEMO-cifar10')
# display(dataset_location)
dataset_location = 's3://sagemaker-ap-northeast-2-057716757052/data/DEMO-cifar10'
dataset_location
# efs_dir = '/home/ec2-user/efs/data'
# ! ls {efs_dir} -al
# ! aws s3 cp {dataset_location} {efs... | train_instance_type has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_count has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_type has been renamed in sagemaker>=2.
See: https://sagema... | MIT | scratch/working/2.2.NoVPC-EFS-Train-Model.ipynb | gonsoomoon-ml/SageMaker-With-Secure-VPC |
VPC_Mode๋ฅผ True, False ์ ํ **[์ค์] VPC_Mode์์ ์คํ์์ True๋ก ๋ณ๊ฒฝํด์ฃผ์ธ์** | VPC_Mode = False
from sagemaker.tensorflow import TensorFlow
def retrieve_estimator(VPC_Mode):
if VPC_Mode:
# VPC ๋ชจ๋ ๊ฒฝ์ฐ์ subnets, security_group์ ๊ธฐ์ ํฉ๋๋ค.
estimator = TensorFlow(base_job_name='cifar10',
entry_point='cifar10_keras_sm_tf2.py',
... | train_instance_type has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_count has been renamed in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
train_instance_type has been renamed in sagemaker>=2.
See: https://sagema... | MIT | scratch/working/2.2.NoVPC-EFS-Train-Model.ipynb | gonsoomoon-ml/SageMaker-With-Secure-VPC |
ํ์ต์ ์ํํฉ๋๋ค. ์ด๋ฒ์๋ ๊ฐ๊ฐ์ ์ฑ๋(`train, validation, eval`)์ S3์ ๋ฐ์ดํฐ ์ ์ฅ ์์น๋ฅผ ์ง์ ํฉ๋๋ค.ํ์ต ์๋ฃ ํ Billable seconds๋ ํ์ธํด ๋ณด์ธ์. Billable seconds๋ ์ค์ ๋ก ํ์ต ์ํ ์ ๊ณผ๊ธ๋๋ ์๊ฐ์
๋๋ค.```Billable seconds: ```์ฐธ๊ณ ๋ก, `ml.p2.xlarge` ์ธ์คํด์ค๋ก 5 epoch ํ์ต ์ ์ ์ฒด 6๋ถ-7๋ถ์ด ์์๋๊ณ , ์ค์ ํ์ต์ ์์๋๋ ์๊ฐ์ 3๋ถ-4๋ถ์ด ์์๋ฉ๋๋ค. | %%time
estimator.fit({'train':'{}/train'.format(dataset_location),
'validation':'{}/validation'.format(dataset_location),
'eval':'{}/eval'.format(dataset_location)}) | 2021-01-27 04:02:44 Starting - Starting the training job...
2021-01-27 04:03:08 Starting - Launching requested ML instancesProfilerReport-1611720164: InProgress
.........
2021-01-27 04:04:29 Starting - Preparing the instances for training......
2021-01-27 04:05:44 Downloading - Downloading input data
2021-01-27 04:05:4... | MIT | scratch/working/2.2.NoVPC-EFS-Train-Model.ipynb | gonsoomoon-ml/SageMaker-With-Secure-VPC |
training_job_name ์ ์ฅํ์ฌ์ training_job_name์ ์ ์ฅ ํฉ๋๋ค.- training_job_name์ ์๋ ํ๋ จ์ ๊ด๋ จ ๋ด์ฉ ๋ฐ ํ๋ จ ๊ฒฐ๊ณผ์ธ **Model Artifact** ํ์ผ์ S3 ๊ฒฝ๋ก๋ฅผ ์ ๊ณต ํฉ๋๋ค. | train_job_name = estimator._current_job_name
%store train_job_name | Stored 'train_job_name' (str)
| MIT | scratch/working/2.2.NoVPC-EFS-Train-Model.ipynb | gonsoomoon-ml/SageMaker-With-Secure-VPC |
Running scripts with python shell | #!pip install tensorflow==1.14.0
#!pip install tensorflow-base==1.14.0
#!pip install tensorflow-gpu==1.14.0
%tensorflow_version 1.x
! python main_train.py --config config_default.json | _____no_output_____ | MIT | notebooks/test_0_lstm_shell_colab.ipynb | SPRACE/track-ml |
Plot Predicted Data | import os
import json
import numpy as np
import pandas as pd
configs = json.load(open('config_default.json', 'r'))
cylindrical = configs['data']['cylindrical'] # set to polar or cartesian coordenates
normalise = configs['data']['normalise']
name = configs['model']['name']
if cylindrical:
coord = 'cylin'
else:
... | _____no_output_____ | MIT | notebooks/test_0_lstm_shell_colab.ipynb | SPRACE/track-ml |
Matrix Profile IntroductionThe matrix profile (MP) is a data structure and associated algorithms that helps solve the dual problem of anomaly detection and motif discovery. It is robust, scalable and largely parameter-free.MP can be combined with other algorithms to accomplish:* Motif discovery* Time series chains* ... | !pip install matrixprofile-ts
import pandas as pd
## example data importing
data = pd.read_csv('https://raw.githubusercontent.com/iotanalytics/IoTTutorial/main/data/SCG_data.csv').drop('Unnamed: 0',1).to_numpy()[0:20,:1000]
import operator
import numpy as np
import matplotlib.pyplot as plt
from matrixprofile import *
... | _____no_output_____ | MIT | code/preprocessing_and_decomposition/Matrix_Profile.ipynb | iotanalytics/IoTTutorial |
Steps to build a Neural Network1. Empty Model (sequential/Model)2 | import tensorflow.keras.datasets as kd
data = kd.fashion_mnist.load_data()
(xtrain,ytrain),(xtest,ytest) = data
xtrain.shape
import matplotlib.pyplot as plt
plt.imshow(xtrain[0,:,:],cmap='gray_r')
ytrain[0]
xtrain1 = xtrain.reshape(-1,28*28)
xtest1 = xtest.reshape(-1,28*28)
xtrain1.shape
from tensorflow.keras.models im... | 313/313 [==============================] - 1s 2ms/step - loss: 0.4793 - accuracy: 0.8335
| MIT | day37_ML_ANN_RNN.ipynb | DynamicEngine2001/Programming-Codes |
Churn Modelling | import pandas as pd
df = pd.read_csv('Churn_Modelling.csv')
df
df.info()
df1 = pd.get_dummies(df)
df1.head() | _____no_output_____ | MIT | day37_ML_ANN_RNN.ipynb | DynamicEngine2001/Programming-Codes |
Recurrent Neural Network | import numpy as np
stock_data = pd.read_csv('stock_data.csv')
fb = stock_data[['Open']] [stock_data['Stock']=='FB'].copy()
fb.head()
fb = fb.values
fb.shape
x = []
y = []
for i in range(20, len(fb)):
x.append(fb['Open'].valuesfb[i-20:1].tolist())
y.append(fb[i].tolist())
| _____no_output_____ | MIT | day37_ML_ANN_RNN.ipynb | DynamicEngine2001/Programming-Codes |
Python Modules | %%writefile weather.py
def prognosis():
print("It will rain today")
import weather
weather.prognosis() | It will rain today
| MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
How does Python know from where to import packages/modules from? | # Python imports work by searching the directories listed in sys.path.
import sys
sys.path
## "__main__" usage
# A module can discover whether or not it is running in the main scope by checking its own __name__,
# which allows a common idiom for conditionally executing code in a module when it is run as a script or ... | _____no_output_____ | MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
Make main.py self running on Linux (also should work on MacOS): Add !/usr/bin/env python to first line of scriptmark it executable using need to change permissions too!$ chmod +x main.py Making Standalone .EXEs for Python in Windows * http://www.py2exe.org/ used to be for Python 2 , now supposedly Python 3 as wel... | # Exercise Write a function which returns a list of fibonacci numbers up to starting with 1, 1, 2, 3, 5 up to the nth.
So Fib(4) would return [1,1,2,3] | _____no_output_____ | MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
  | %%writefile fibo.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 1 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 1, 1
while b < n:
result.append(b)
... | _____no_output_____ | MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
If you intend to use a function often you can assign it to a local name: | fib(300) | 1 1 2 3 5 8 13 21 34 55 89 144 233
| MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
There is a variant of the import statement that imports names from a module directly into the importing moduleโs symbol table. | from fibo import fib, fib2 # we overwrote fib=fibo.fib
fib(100)
fib2(200) | _____no_output_____ | MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined). There is even a variant to import all names that a module defines: **NOT RECOMMENDED** | ## DO not do this Namespace collission possible!!
from fibo import *
fib(400) | 1 1 2 3 5 8 13 21 34 55 89 144 233 377
| MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
If the module name is followed by as, then the name following as is bound directly to the imported module. | import fibo as fib
dir(fib)
fib.fib(50)
### It can also be used when utilising from with similar effects:
from fibo import fib as fibonacci
fibonacci(200) | 1 1 2 3 5 8 13 21 34 55 89 144
| MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
Executing modules as scriptsยถ When you run a Python module withpython fibo.py the code in the module will be executed, just as if you imported it, but with the \_\_name\_\_ set to "\_\_main\_\_". That means that by adding this code at the end of your module: | %%writefile fibbo.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
... | 1 1 2 3 5 8 13 21 34 55 89 144
| MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite). The Module Search PathWhen a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches ... | sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
... | _____no_output_____ | MIT | Python_Core/Python Modules and Imports.ipynb | ValRCS/RCS_Python_11 |
Quick analysis | from phimal_utilities.analysis import Results
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='notebook', style='white')
%config InlineBackend.figure_format = 'svg'
data_mt = Results('runs/testing_multitask_unnormalized//')
data_bl = Results('runs/testing_normal_unnormalized//')
keys = data_mt.k... | _____no_output_____ | MIT | notebooks/testing_multitask.ipynb | GJBoth/MultiTaskPINN |
What is `torch.nn` *really*?============================by Jeremy Howard, `fast.ai `_. Thanks to Rachel Thomas and Francisco Ingham. We recommend running this tutorial as a notebook, not a script. To download the notebook (.ipynb) file,click `here `_ .PyTorch provides the elegantly designed modules and classes `torch.n... | from pathlib import Path
import requests
DATA_PATH = Path("data")
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)
URL = "http://deeplearning.net/data/mnist/"
FILENAME = "mnist.pkl.gz"
if not (PATH / FILENAME).exists():
content = requests.get(URL + FILENAME).content
(PATH / FILENAM... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
This dataset is in numpy array format, and has been stored using pickle,a python-specific format for serializing data. | import pickle
import gzip
with gzip.open((PATH / FILENAME).as_posix(), "rb") as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding="latin-1") | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Each image is 28 x 28, and is being stored as a flattened row of length784 (=28x28). Let's take a look at one; we need to reshape it to 2dfirst. | from matplotlib import pyplot
import numpy as np
pyplot.imshow(x_train[0].reshape((28, 28)), cmap="gray")
print(x_train.shape) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
PyTorch uses ``torch.tensor``, rather than numpy arrays, so we need toconvert our data. | import torch
x_train, y_train, x_valid, y_valid = map(
torch.tensor, (x_train, y_train, x_valid, y_valid)
)
n, c = x_train.shape
x_train, x_train.shape, y_train.min(), y_train.max()
print(x_train, y_train)
print(x_train.shape)
print(y_train.min(), y_train.max()) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Neural net from scratch (no torch.nn)---------------------------------------------Let's first create a model using nothing but PyTorch tensor operations. We're assumingyou're already familiar with the basics of neural networks. (If you're not, you canlearn them at `course.fast.ai `_).PyTorch provides methods to create ... | import math
weights = torch.randn(784, 10) / math.sqrt(784)
weights.requires_grad_()
bias = torch.zeros(10, requires_grad=True) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Thanks to PyTorch's ability to calculate gradients automatically, we canuse any standard Python function (or callable object) as a model! Solet's just write a plain matrix multiplication and broadcasted additionto create a simple linear model. We also need an activation function, sowe'll write `log_softmax` and use it.... | def log_softmax(x):
return x - x.exp().sum(-1).log().unsqueeze(-1)
def model(xb):
return log_softmax(xb @ weights + bias) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
In the above, the ``@`` stands for the dot product operation. We will callour function on one batch of data (in this case, 64 images). This isone *forward pass*. Note that our predictions won't be any better thanrandom at this stage, since we start with random weights. | bs = 64 # batch size
xb = x_train[0:bs] # a mini-batch from x
preds = model(xb) # predictions
preds[0], preds.shape
print(preds[0], preds.shape) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
As you see, the ``preds`` tensor contains not only the tensor values, but also agradient function. We'll use this later to do backprop.Let's implement negative log-likelihood to use as the loss function(again, we can just use standard Python): | def nll(input, target):
return -input[range(target.shape[0]), target].mean()
loss_func = nll | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's check our loss with our random model, so we can see if we improveafter a backprop pass later. | yb = y_train[0:bs]
print(loss_func(preds, yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's also implement a function to calculate the accuracy of our model.For each prediction, if the index with the largest value matches thetarget value, then the prediction was correct. | def accuracy(out, yb):
preds = torch.argmax(out, dim=1)
return (preds == yb).float().mean() | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's check the accuracy of our random model, so we can see if ouraccuracy improves as our loss improves. | print(accuracy(preds, yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
We can now run a training loop. For each iteration, we will:- select a mini-batch of data (of size ``bs``)- use the model to make predictions- calculate the loss- ``loss.backward()`` updates the gradients of the model, in this case, ``weights`` and ``bias``.We now use these gradients to update the weights and bias. ... | from IPython.core.debugger import set_trace
lr = 0.5 # learning rate
epochs = 2 # how many epochs to train for
for epoch in range(epochs):
for i in range((n - 1) // bs + 1):
# set_trace()
start_i = i * bs
end_i = start_i + bs
xb = x_train[start_i:end_i]
yb = y_tra... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
That's it: we've created and trained a minimal neural network (in this case, alogistic regression, since we have no hidden layers) entirely from scratch!Let's check the loss and accuracy and compare those to what we gotearlier. We expect that the loss will have decreased and accuracy tohave increased, and they have. | print(loss_func(model(xb), yb), accuracy(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Using torch.nn.functional------------------------------We will now refactor our code, so that it does the same thing as before, onlywe'll start taking advantage of PyTorch's ``nn`` classes to make it more conciseand flexible. At each step from here, we should be making our code one or moreof: shorter, more understandab... | import torch.nn.functional as F
loss_func = F.cross_entropy
def model(xb):
return xb @ weights + bias | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Note that we no longer call ``log_softmax`` in the ``model`` function. Let'sconfirm that our loss and accuracy are the same as before: | print(loss_func(model(xb), yb), accuracy(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Refactor using nn.Module-----------------------------Next up, we'll use ``nn.Module`` and ``nn.Parameter``, for a clearer and moreconcise training loop. We subclass ``nn.Module`` (which itself is a class andable to keep track of state). In this case, we want to create a class thatholds our weights, bias, and method fo... | from torch import nn
class Mnist_Logistic(nn.Module):
def __init__(self):
super().__init__()
self.weights = nn.Parameter(torch.randn(784, 10) / math.sqrt(784))
self.bias = nn.Parameter(torch.zeros(10))
def forward(self, xb):
return xb @ self.weights + self.bias | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Since we're now using an object instead of just using a function, wefirst have to instantiate our model: | model = Mnist_Logistic() | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Now we can calculate the loss in the same way as before. Note that``nn.Module`` objects are used as if they are functions (i.e they are*callable*), but behind the scenes Pytorch will call our ``forward``method automatically. | print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Previously for our training loop we had to update the values for each parameterby name, and manually zero out the grads for each parameter separately, like this::: with torch.no_grad(): weights -= weights.grad * lr bias -= bias.grad * lr weights.grad.zero_() bias.grad.zero_()Now we can take advanta... | def fit():
for epoch in range(epochs):
for i in range((n - 1) // bs + 1):
start_i = i * bs
end_i = start_i + bs
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backwa... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's double-check that our loss has gone down: | print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Refactor using nn.Linear-------------------------We continue to refactor our code. Instead of manually defining andinitializing ``self.weights`` and ``self.bias``, and calculating ``xb @self.weights + self.bias``, we will instead use the Pytorch class`nn.Linear `_ for alinear layer, which does all that for us. Pytorc... | class Mnist_Logistic(nn.Module):
def __init__(self):
super().__init__()
self.lin = nn.Linear(784, 10)
def forward(self, xb):
return self.lin(xb) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
We instantiate our model and calculate the loss in the same way as before: | model = Mnist_Logistic()
print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
We are still able to use our same ``fit`` method as before. | fit()
print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Refactor using optim------------------------------Pytorch also has a package with various optimization algorithms, ``torch.optim``.We can use the ``step`` method from our optimizer to take a forward step, insteadof manually updating each parameter.This will let us replace our previous manually coded optimization step::... | from torch import optim | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
We'll define a little function to create our model and optimizer so wecan reuse it in the future. | def get_model():
model = Mnist_Logistic()
return model, optim.SGD(model.parameters(), lr=lr)
model, opt = get_model()
print(loss_func(model(xb), yb))
for epoch in range(epochs):
for i in range((n - 1) // bs + 1):
start_i = i * bs
end_i = start_i + bs
xb = x_train[start_i:end_i]
... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Refactor using Dataset------------------------------PyTorch has an abstract Dataset class. A Dataset can be anything that hasa ``__len__`` function (called by Python's standard ``len`` function) anda ``__getitem__`` function as a way of indexing into it.`This tutorial `_walks through a nice example of creating a custo... | from torch.utils.data import TensorDataset | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Both ``x_train`` and ``y_train`` can be combined in a single ``TensorDataset``,which will be easier to iterate over and slice. | train_ds = TensorDataset(x_train, y_train) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Previously, we had to iterate through minibatches of x and y values separately::: xb = x_train[start_i:end_i] yb = y_train[start_i:end_i]Now, we can do these two steps together::: xb,yb = train_ds[i*bs : i*bs+bs] | model, opt = get_model()
for epoch in range(epochs):
for i in range((n - 1) // bs + 1):
xb, yb = train_ds[i * bs: i * bs + bs]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Refactor using DataLoader------------------------------Pytorch's ``DataLoader`` is responsible for managing batches. You cancreate a ``DataLoader`` from any ``Dataset``. ``DataLoader`` makes it easierto iterate over batches. Rather than having to use ``train_ds[i*bs : i*bs+bs]``,the DataLoader gives us each minibatch a... | from torch.utils.data import DataLoader
train_ds = TensorDataset(x_train, y_train)
train_dl = DataLoader(train_ds, batch_size=bs) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Previously, our loop iterated over batches (xb, yb) like this::: for i in range((n-1)//bs + 1): xb,yb = train_ds[i*bs : i*bs+bs] pred = model(xb)Now, our loop is much cleaner, as (xb, yb) are loaded automatically from the data loader::: for xb,yb in train_dl: pred = model(xb) | model, opt = get_model()
for epoch in range(epochs):
for xb, yb in train_dl:
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
print(loss_func(model(xb), yb)) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Thanks to Pytorch's ``nn.Module``, ``nn.Parameter``, ``Dataset``, and ``DataLoader``,our training loop is now dramatically smaller and easier to understand. Let'snow try to add the basic features necessary to create effecive models in practice.Add validation-----------------------In section 1, we were just trying to ge... | train_ds = TensorDataset(x_train, y_train)
train_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)
valid_ds = TensorDataset(x_valid, y_valid)
valid_dl = DataLoader(valid_ds, batch_size=bs * 2) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
We will calculate and print the validation loss at the end of each epoch.(Note that we always call ``model.train()`` before training, and ``model.eval()``before inference, because these are used by layers such as ``nn.BatchNorm2d``and ``nn.Dropout`` to ensure appropriate behaviour for these different phases.) | model, opt = get_model()
for epoch in range(epochs):
model.train()
for xb, yb in train_dl:
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
model.eval()
with torch.no_grad():
valid_loss = sum(loss_func(model(xb), yb... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Create fit() and get_data()----------------------------------We'll now do a little refactoring of our own. Since we go through a similarprocess twice of calculating the loss for both the training set and thevalidation set, let's make that into its own function, ``loss_batch``, whichcomputes the loss for one batch.We pa... | def loss_batch(model, loss_func, xb, yb, opt=None):
loss = loss_func(model(xb), yb)
if opt is not None:
loss.backward()
opt.step()
opt.zero_grad()
return loss.item(), len(xb) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
``fit`` runs the necessary operations to train our model and compute thetraining and validation losses for each epoch. | import numpy as np
def fit(epochs, model, loss_func, opt, train_dl, valid_dl):
for epoch in range(epochs):
model.train()
for xb, yb in train_dl:
loss_batch(model, loss_func, xb, yb, opt)
model.eval()
with torch.no_grad():
losses, nums = zip(
... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
``get_data`` returns dataloaders for the training and validation sets. | def get_data(train_ds, valid_ds, bs):
return (
DataLoader(train_ds, batch_size=bs, shuffle=True),
DataLoader(valid_ds, batch_size=bs * 2),
) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Now, our whole process of obtaining the data loaders and fitting themodel can be run in 3 lines of code: | train_dl, valid_dl = get_data(train_ds, valid_ds, bs)
model, opt = get_model()
fit(epochs, model, loss_func, opt, train_dl, valid_dl) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
You can use these basic 3 lines of code to train a wide variety of models.Let's see if we can use them to train a convolutional neural network (CNN)!Switch to CNN-------------We are now going to build our neural network with three convolutional layers.Because none of the functions in the previous section assume anythin... | class Mnist_CNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1)
self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1)
self.conv3 = nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1)
def forward(... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
`Momentum `_ is a variation onstochastic gradient descent that takes previous updates into account as welland generally leads to faster training. | model = Mnist_CNN()
opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)
fit(epochs, model, loss_func, opt, train_dl, valid_dl) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
nn.Sequential------------------------``torch.nn`` has another handy class we can use to simply our code:`Sequential `_ .A ``Sequential`` object runs each of the modules contained within it, in asequential manner. This is a simpler way of writing our neural network.To take advantage of this, we need to be able to easily... | class Lambda(nn.Module):
def __init__(self, func):
super().__init__()
self.func = func
def forward(self, x):
return self.func(x)
def preprocess(x):
return x.view(-1, 1, 28, 28) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
The model created with ``Sequential`` is simply: | model = nn.Sequential(
Lambda(preprocess),
nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.AvgPool2d(4),
Lambda(lambda x: x.view(x.s... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Wrapping DataLoader-----------------------------Our CNN is fairly concise, but it only works with MNIST, because: - It assumes the input is a 28\*28 long vector - It assumes that the final CNN grid size is 4\*4 (since that's the averagepooling kernel size we used)Let's get rid of these two assumptions, so our model wor... | def preprocess(x, y):
return x.view(-1, 1, 28, 28), y
class WrappedDataLoader:
def __init__(self, dl, func):
self.dl = dl
self.func = func
def __len__(self):
return len(self.dl)
def __iter__(self):
batches = iter(self.dl)
for b in batches:
yield (s... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Next, we can replace ``nn.AvgPool2d`` with ``nn.AdaptiveAvgPool2d``, whichallows us to define the size of the *output* tensor we want, rather thanthe *input* tensor we have. As a result, our model will work with anysize input. | model = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d(1),
Lambda(lambda x: x.view(x.size(0), -1)),
)
... | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's try it out: | fit(epochs, model, loss_func, opt, train_dl, valid_dl) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Using your GPU---------------If you're lucky enough to have access to a CUDA-capable GPU (you canrent one for about $0.50/hour from most cloud providers) you canuse it to speed up your code. First check that your GPU is working inPytorch: | print(torch.cuda.is_available()) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
And then create a device object for it: | dev = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu") | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Let's update ``preprocess`` to move batches to the GPU: | def preprocess(x, y):
return x.view(-1, 1, 28, 28).to(dev), y.to(dev)
train_dl, valid_dl = get_data(train_ds, valid_ds, bs)
train_dl = WrappedDataLoader(train_dl, preprocess)
valid_dl = WrappedDataLoader(valid_dl, preprocess) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Finally, we can move our model to the GPU. | model.to(dev)
opt = optim.SGD(model.parameters(), lr=lr, momentum=0.9) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
You should find it runs faster now: | fit(epochs, model, loss_func, opt, train_dl, valid_dl) | _____no_output_____ | MIT | notebook/pytorch/nn_tutorial.ipynb | mengwangk/myinvestor-toolkit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.