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 |
|---|---|---|---|---|---|
Result/Stat of 1 trees random forest of CMC with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.496 | 0.488 | 0.485 | 0.476 |Result/Stat of 5 trees random forest of CMC with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score,... | ploter(cmcaccuracy, '# of n in ntree V.S. accuracy of CMC Data with information gain', '# of n in ntree', 'Accuracy')
ploter(cmcprecision, '# of n in ntree V.S. precision of CMC Data with information gain', '# of n in ntree', 'Precision', cmcprecisionstd)
ploter(cmcrecall, '# of n in ntree V.S. recall of CMC Data with ... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
The result is kind of weird. with max accuracy around 52-53%, I tried to modified all the parameters, like maxdepth to 5 and so, but that only helps me to improve from 50% to 52%.. IV. Appendix: Code 1. evaluationmatrix.py | import math
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Markdown
def accuracy(truePosi, trueNega, falsePosi, falseNega): # Count of all four
return (truePosi+trueNega)/(truePosi+trueNega+falseNega+falsePosi)
def precision(truePosi, trueNega, falsePosi, falseNega):
if (tru... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
2. utils.py | from sqlite3 import Row
from evaluationmatrix import *
from sklearn import datasets
import random
import numpy as np
import csv
import math
import matplotlib.pyplot as plt
from collections import Counter
def importfile(name:str,delimit:str):
# importfile('hw3_wine.csv', '\t')
file = open("datasets/"+name, enco... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
3. decisiontree.py | import sklearn.model_selection
import numpy as np
import csv
import math
import matplotlib.pyplot as plt
import random
from collections import Counter
from utils import *
class Treenode:
type = ""
datatype = ""
label = None
testattribute = ""
edge = {}
majority = -1
threshold = -1 # for num... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
4. randomforest.py | from utils import *
from decisiontree import *
# Stratified K-Fold method
def stratifiedkfold(data, categorydict, k = 10):
classindex = list(categorydict.values()).index("class")
datacopy = np.copy(data).T
classes = list(Counter(datacopy[classindex]).keys())
nclass = len(classes) # number of classes
... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
5. run.py | from utils import *
from decisiontree import *
from randomforest import *
def importhousedata():
house = importfile('hw3_house_votes_84.csv', ',')
housecategory = {}
for i in house[0]:
housecategory[i] = 'categorical'
housecategory["class"] = 'class'
housedata = np.array(house[1:]).astype(f... | 0.9599562592948999
[array([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[1., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[1.,... | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
- Canonical Correlation Analysis btw Cell painting & L1000- This notebook focus on calculating the canonical coefficients between the canonical variables of Cell painting and L1000 level-4 profiles after applying PCA on them.---------------------------------------------- The aim of CCA is finding the relationship betw... | from google.colab import drive
drive.mount('/content/drive')
import os, sys
from matplotlib import pyplot as plt
%matplotlib inline
import numpy as np
import pickle
import pandas as pd
import seaborn as sns
import gzip
sns.set_context("talk")
sns.set_style("darkgrid")
from sklearn.decomposition import PCA
from sklearn.... | _____no_output_____ | BSD-3-Clause | 4.CCA/CP_L1000_SVCCA.ipynb | broadinstitute/lincs-profiling-comparison |
- CCA on CP & L1000 train data | cca_results = cca_core.get_cca_similarity(df_cp_pc_x.values.T, df_L1_pc_x.values.T, epsilon=1e-10, verbose=False)
plt.figure(figsize=(12,8))
sns.set_context('talk', font_scale = 0.85)
sns.lineplot(x=range(len(cca_results["cca_coef1"])), y=cca_results["cca_coef1"])
plt.title("CCA correlation coefficients between CP and ... | Mean Canonical Correlation co-efficient between CP and L1000 canonical variables (300): 0.14511046236358863
| BSD-3-Clause | 4.CCA/CP_L1000_SVCCA.ipynb | broadinstitute/lincs-profiling-comparison |
- (Singular Vectors)CCA as a method to analyze the correlation between Cell painting & L1000 | print("Results using SVCCA keeping 300 dims")
# Mean subtract activations
cacts1 = df_cp_pc_x.values.T - np.mean(df_cp_pc_x.values.T, axis=1, keepdims=True)
cacts2 = df_L1_pc_x.values.T - np.mean(df_L1_pc_x.values.T, axis=1, keepdims=True)
# Perform SVD
U1, s1, V1 = np.linalg.svd(cacts1, full_matrices=False)
U2, s2, ... | Results using SVCCA keeping 300 dims
mean svcca correlation coefficient: 0.14511046236358852
| BSD-3-Clause | 4.CCA/CP_L1000_SVCCA.ipynb | broadinstitute/lincs-profiling-comparison |
- Using Sklearn CCA package for CCA | cca = CCA(n_components=df_cp_pc_x.shape[1])
cp_cca_vars, L1000_cca_vars = cca.fit_transform(df_cp_pc_x, df_L1_pc_x)
canonical_coeffs = np.corrcoef(cp_cca_vars.T, L1000_cca_vars.T).diagonal(offset=df_cp_pc_x.shape[1])
print('mean svcca correlation coefficient:', np.mean(svcca_results["cca_coef1"]))
plt.figure(figsize=(1... | mean svcca correlation coefficient: 0.14511046236358852
| BSD-3-Clause | 4.CCA/CP_L1000_SVCCA.ipynb | broadinstitute/lincs-profiling-comparison |
Preprocessing train datasetDivide the *train* folder into two folders *mytrain* and *myvalid*- mytrain ---- including two folders - cat ---- including about 11250 cat images - dog ---- including about 11250 dog images - myvalid ---- including two folders - cat ---- including about 1250 cat images - dog... | from sklearn.model_selection import train_test_split
import seaborn as sns
import os
import shutil
%matplotlib inline | _____no_output_____ | Apache-2.0 | Preprocessing train dataset.ipynb | biexingle/ResNet-50-for-Cats.Vs.Dogs |
Visualize the size of the original *train* dataset. | train_filenames = os.listdir('train')
train_cat = filter(lambda x:x[:3] == 'cat', train_filenames)
train_dog = filter(lambda x:x[:3] == 'dog', train_filenames)
x = ['train_cat', 'train_dog', 'test']
y = [len(train_cat), len(train_dog), len(os.listdir('test'))]
ax = sns.barplot(x=x, y=y) | _____no_output_____ | Apache-2.0 | Preprocessing train dataset.ipynb | biexingle/ResNet-50-for-Cats.Vs.Dogs |
Shuffle and split the train filenames | mytrain, myvalid = train_test_split(train_filenames, test_size=0.1)
print len(mytrain), len(myvalid) | 22500 2500
| Apache-2.0 | Preprocessing train dataset.ipynb | biexingle/ResNet-50-for-Cats.Vs.Dogs |
Visualize the size of the processed train dataset | mytrain_cat = filter(lambda x:x[:3] == 'cat', mytrain)
mytrain_dog = filter(lambda x:x[:3] == 'dog', mytrain)
myvalid_cat = filter(lambda x:x[:3] == 'cat', myvalid)
myvalid_dog = filter(lambda x:x[:3] == 'dog', myvalid)
x = ['mytrain_cat', 'mytrain_dog', 'myvalid_cat', 'myvalid_dog']
y = [len(mytrain_cat), len(mytrain_... | _____no_output_____ | Apache-2.0 | Preprocessing train dataset.ipynb | biexingle/ResNet-50-for-Cats.Vs.Dogs |
Create symbolic link of images | def remove_and_create_class(dirname):
if os.path.exists(dirname):
shutil.rmtree(dirname)
os.mkdir(dirname)
os.mkdir(dirname+'/cat')
os.mkdir(dirname+'/dog')
remove_and_create_class('mytrain')
remove_and_create_class('myvalid')
for filename in mytrain_cat:
os.symlink('../../train/'+filename... | _____no_output_____ | Apache-2.0 | Preprocessing train dataset.ipynb | biexingle/ResNet-50-for-Cats.Vs.Dogs |
import pandas as pd
import numpy as np
import plotly.express as px
import six
import plotly.express as px
from google.colab import files
# Import csvs as dataframes
df_fuel = pd.read_csv('https://raw.githubusercontent.com/mehurlock94/identifying-factors-contributing-to-armed-conflict/main/Fuel_exports_percent_mercha... | _____no_output_____ | MIT | Identifying_factors_contributing_to_armed_conflict_scatterplot_analyses.ipynb | dmathe18/global_armed_conflict_final_repo | |
What was the Annualized Return of the Lo 20 portfolio over the entire period? | rt.annualized_return(returns['Lo 20']) * 100
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Volatility of the Lo 20 portfolio over the entire period? | rt.annualized_volatility(returns['Lo 20']) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Return of the Hi 20 portfolio over the entire period? | rt.annualized_return(returns['Hi 20']) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Volatility of the Hi 20 portfolio over the entire period? | rt.annualized_volatility(returns['Hi 20']) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Return of the Lo 20 portfolio over the period 1999 - 2015 (both inclusive)? | lo20_range_1999_2015 = returns['Lo 20']['1999':'2015']
rt.annualized_return(lo20_range_1999_2015) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Volatility of the Lo 20 portfolio over the period 1999 - 2015 (both inclusive)? | rt.annualized_volatility(lo20_range_1999_2015) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Return of the Hi 20 portfolio over the period 1999 - 2015 (both inclusive)? | hi20_range_1999_2015 = returns['Hi 20']['1999':'2015']
rt.annualized_return(hi20_range_1999_2015) * 100
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Annualized Volatility of the Hi 20 portfolio over the period 1999 - 2015 (both inclusive)? | rt.annualized_volatility(hi20_range_1999_2015) * 100 | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Max Drawdown (expressed as a positive number) experienced over the 1999-2015 period in the SmallCap (Lo 20) portfolio? | (rt.drawdown(lo20_range_1999_2015, 1000)['Drawdowns']).max() | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
At the end of which month over the period 1999-2015 did that maximum drawdown on the SmallCap (Lo 20) portfolio occur? | (rt.drawdown(lo20_range_1999_2015, 1000)['Drawdowns']).idxmax()
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
What was the Max Drawdown (expressed as a positive number) experienced over the 1999-2015 period in the LargeCap (Hi 20) portfolio? | (rt.drawdown(hi20_range_1999_2015, 1000)['Drawdowns']).max()
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
Over the period 1999-2015, at the end of which month did that maximum drawdown of the LargeCap (Hi 20) portfolio occur? | (rt.drawdown(hi20_range_1999_2015, 1000)['Drawdowns']).idxmax()
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
For the remaining questions, use the EDHEC Hedge Fund Indices data set that we used in the lab assignment and load them into Python. Looking at the data since 2009 (including all of 2009) through 2018 which Hedge Fund Index has exhibited the highest semideviation? | hfi = pd.read_csv('data/edhec-hedgefundindices.csv',
header=0, index_col=0, parse_dates=True)
hfi_after_2009 = hfi['2009':]
hfi_after_2009.head()
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
Looking at the data since 2009 (including all of 2009) which Hedge Fund Index has exhibited the lowest semideviation? | rt.semideviation(hfi_after_2009)
| _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
Looking at the data since 2009 (including all of 2009) which Hedge Fund Index has been most negatively skewed? | rt.skewness(hfi_after_2009) | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
Looking at the data since 2000 (including all of 2000) through 2018 which Hedge Fund Index has exhibited the highest kurtosis? | hfi_after_2000 = hfi['2000':]
rt.kurtosis(hfi_after_2000) | _____no_output_____ | Apache-2.0 | risk/q1.ipynb | deyantodorov/python |
YOLO on PYNQ-Z1 and Movidius NCS: Webcam exampleTo run this notebook, you need to connect a USB webcam to the PYNQ-Z1 and a monitor to the HDMI output. You'll already need a powered USB hub for the Movidius NCS, so you should have a spare port for the webcam. Load required packages | from mvnc import mvncapi as mvnc
import cv2
import numpy as np
import time
from pynq.overlays.base import BaseOverlay
from pynq.lib.video import *
import yolo_ncs,ncs
import PIL.Image
%matplotlib inline
# Load the base overlay
base = BaseOverlay("base.bit") | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Configure the webcamTo get a decent frame rate, we use a webcam resolution of 640x480 so that resizing to 448x448 for the YOLO network is reasonably fast. Note that OpenCV uses BGR, but the YOLO network needs RGB, so we'll have to swap the colors around before sending images to YOLO. | # Webcam resolution
frame_in_w = 640
frame_in_h = 480
# Configure webcam - note that output images will be BGR
videoIn = cv2.VideoCapture(0)
videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, frame_in_w);
videoIn.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_in_h);
print("Capture device is open: " + str(videoIn.isOpened())) | Capture device is open: True
| MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Configure the HDMI output | hdmi_out = base.video.hdmi_out
# Configure the HDMI output to the same resolution as the webcam input
mode = VideoMode(frame_in_w,frame_in_h,24)
hdmi_out.configure(mode, PIXEL_BGR)
# Start the HDMI output
hdmi_out.start() | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Take a photo with the webcam | ret, frame = videoIn.read()
if (not ret):
raise RuntimeError("Failed to read from camera.")
# Convert BGR image to RGB (required by YOLO and PIL)
frame = frame[:,:,(2,1,0)]
# Resize the image to the size required by YOLO network (448x448)
small_frame = cv2.resize(frame, dsize=(448, 448), interpolation=cv2.I... | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Open the Movidius NCS | # Open the Movidius NCS device
ncsdev = ncs.MovidiusNCS()
# Load the graph file
if ncsdev.load_graph('../graph'):
print('Graph file loaded to Movidius NCS') | Graph file loaded to Movidius NCS
| MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Send image to NCS | ncsdev.graph.LoadTensor(ncs_frame.astype(np.float16), 'user object')
out, userobj = ncsdev.graph.GetResult()
# Interpret results and draw boxes on the image
results = yolo_ncs.interpret_output(out.astype(np.float32), frame.shape[1], frame.shape[0]) # fc27 instead of fc12 for yolo_small
img_res = yolo_ncs.draw_boxes(fr... | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Webcam to HDMI pass-through (without YOLO) | n_frames = 2000
start_time = time.time()
for _ in range(n_frames):
# Get a frame from the webcam
ret, frame = videoIn.read()
# Copy the input frame to the output frame
frame_out = hdmi_out.newframe()
frame_out[:,:,:] = frame[:,:,:]
hdmi_out.writeframe(frame_out)
end_time = time.time()
p... | Runtime: 72.0343644618988 FPS: 27.764526208291343
| MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Webcam to HDMI with YOLO | n_frames = 200
start_time = time.time()
for _ in range(n_frames):
# Get a frame from the webcam
ret, frame = videoIn.read()
# Resize to the frame size required by YOLO network (448x448) and convert to RGB
small_frame = cv2.resize(frame[:,:,(2,1,0)], dsize=(448, 448), interpolation=cv2.INTER_CUBIC... | Runtime: 86.11693739891052 FPS: 2.3224235097163386
| MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Close the NCS device | ncsdev.close() | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Release the webcam and HDMI output | videoIn.release()
hdmi_out.stop()
del hdmi_out | _____no_output_____ | MIT | notebooks/yolo-webcam.ipynb | fpgadeveloper/pynq-ncs-yolo |
Copyright 2019 Carsten BlankLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed u... | import sys
import os
import numpy as np
import matplotlib.pyplot as plt
sys.path.append("{}/../lib_paper".format(os.getcwd()))
from lib_experimental_utils import FinishedExperiment, RunningExperiment, qasm_simulator | _____no_output_____ | Apache-2.0 | notebooks/experiment_archive_theory.ipynb | carstenblank/Quantum-classifier-with-tailored-quantum-kernels---Supplemental |
InterestingGood results:* 5c962f6581cbf700560b9504* 5c9755f199c2c6005f6bc532Withou any barriers (except measurement)* 5c975badf4e1bf0057a03d2b* 5c976069adfd43005f0fef6b (+ 0.2pi theta correction) | experiment = FinishedExperiment.from_data(job_id='5c976069adfd43005f0fef6b', backend='ibmqx4')
theta_start = 0.0
theta_end = 2*np.pi
theta_step = 0.1
w_1 = 0.5
w_2 = 1 - w_1
theta = np.arange(theta_start, theta_end, theta_step)
def classification(copies=1):
return w_1 * np.sin(theta/2 + np.pi/4)**(2*copies) - w_... | _____no_output_____ | Apache-2.0 | notebooks/experiment_archive_theory.ipynb | carstenblank/Quantum-classifier-with-tailored-quantum-kernels---Supplemental |
SUTD 2021 50.007 Homework 2> James Raphael Tiovalen / 1004555 | # Setup and install dependencies
!pip3 install numpy scipy numba libsvm-official | Requirement already satisfied: numpy in c:\python38\lib\site-packages (1.19.5)
Requirement already satisfied: scipy in c:\python38\lib\site-packages (1.5.2)
Requirement already satisfied: numba in c:\python38\lib\site-packages (0.52.0)
Requirement already satisfied: libsvm-official in c:\python38\lib\site-packages (3.2... | MIT | hw/hw2/hw2.ipynb | jamestiotio/ml |
Question 2.3 | # Import libraries
from libsvm.svmutil import svm_read_problem, svm_train, svm_predict
import os
# Set OS-independent paths, relative to current directory
train_path = os.path.join("fishorrock", "training.txt")
test_path = os.path.join("fishorrock", "test.txt")
# Load data from files
train_y, train_x = svm_read_probl... | Executing SVM prediction with LINEAR kernel type...
Accuracy = 79.3651% (50/63) (classification)
Executing SVM prediction with POLYNOMIAL kernel type...
Accuracy = 55.5556% (35/63) (classification)
Executing SVM prediction with RADIAL BASIS FUNCTION kernel type...
Accuracy = 87.3016% (55/63) (classification)
Executi... | MIT | hw/hw2/hw2.ipynb | jamestiotio/ml |
Data Fetch | import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import math
#extracting lines for simplied verion
open('2-fft-malicious-n-0-4-m-12.txt','w').writelines([ line for line in open("2-fft-malicious-n-0-4-m-12.log") if "Enqueue" in line])
print ("done")
#extract... | _____no_output_____ | MIT | [03 - Results]/dos results ver 4/router-fetch/malicious/2-fft-malicious-n-0-4-m-12.ipynb | chamikasudusinghe/nocml |
Router Fetch | def roundup(x):
return int(math.ceil(x / 1000.0)) * 1000
def fetch(i):
df = pd.read_csv('2-fft-malicious-n-0-4-m-12.csv')
df = df.loc[df['router'] == i]
df = df.drop(columns=['router'])
df.to_csv('2-fft-malicious-n-0-4-m-12-r'+str(i)+'.csv',index=False)
df = pd.read_csv('2-fft-malicious-n-0-4... | (99481, 26)
(58807, 26)
(39303, 26)
(26430, 26)
(158087, 26)
(67123, 26)
(63254, 26)
(59990, 26)
(95898, 26)
(53293, 26)
(49289, 26)
(64634, 26)
(73474, 26)
(39427, 26)
(37649, 26)
(35144, 26)
| MIT | [03 - Results]/dos results ver 4/router-fetch/malicious/2-fft-malicious-n-0-4-m-12.ipynb | chamikasudusinghe/nocml |
Skip-gram word2vecIn this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like machine translation. Re... | import time
import numpy as np
import tensorflow as tf
import utils | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Load the [text8 dataset](http://mattmahoney.net/dc/textdata.html), a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the `data` folder. Then you can extract it and delete the archive file to save storage space. | from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import zipfile
dataset_folder_path = 'data'
dataset_filename = 'text8.zip'
dataset_name = 'Text8 Dataset'
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
s... | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
PreprocessingHere I'm fixing up the text to make training easier. This comes from the `utils` module I wrote. The `preprocess` function coverts any punctuation into tokens, so a period is changed to ` `. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words th... | words = utils.preprocess(text)
print(words[:30])
print("Total words: {}".format(len(words)))
print("Unique words: {}".format(len(set(words)))) | Total words: 16680599
Unique words: 63641
| MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list `int_wo... | vocab_to_int, int_to_vocab = utils.create_lookup_tables(words)
int_words = [vocab_to_int[word] for word in words] | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
SubsamplingWords that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ i... | from collections import Counter
import random
threshold = 1e-5
threshold = 0.0006849873916398326
word_counts = Counter(int_words)
total_count = len(int_words)
print(total_count)
freqs = {word: count/total_count for word, count in word_counts.items()}
p_drop = {word: 1 - np.sqrt(threshold/freqs[word]) for word in word_... | 16680599
11171980
[5234, 3082, 194, 3136, 45, 58, 155, 127, 741, 476]
| MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From [Mikolov et al.](https://arxiv.org/pdf/1301.3781.pdf): "Sinc... | def get_target(words, idx, window_size=5):
''' Get a list of words in a window around an index. '''
R = np.random.randint(1, window_size+1)
start = idx - R if (idx - R) > 0 else 0
stop = idx + R
target_words = set(words[start:idx] + words[idx+1:stop+1])
return list(target_words) | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Here's a function that returns batches for our network. The idea is that it grabs `batch_size` words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per i... | def get_batches(words, batch_size, window_size=5):
''' Create a generator of word batches as a tuple (inputs, targets) '''
n_batches = len(words)//batch_size
# only full batches
words = words[:n_batches*batch_size]
for idx in range(0, len(words), batch_size):
x, y = [], []
... | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Building the graphFrom [Chris McCormick's blog](http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/), we can see the general structure of our network.The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of l... | train_graph = tf.Graph()
with train_graph.as_default():
inputs = tf.placeholder(tf.int32, [None], name='inputs')
labels = tf.placeholder(tf.int32, [None, None], name='labels') | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Embedding The embedding matrix has a size of the number of words by the number of units in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using tokenized data for our inputs, usually as integers, where the number of tokens is the ... | n_vocab = len(int_to_vocab)
n_embedding = 200 # Number of embedding features
with train_graph.as_default():
embedding = tf.Variable(tf.random_uniform((n_vocab, n_embedding), -1, 1))
embed = tf.nn.embedding_lookup(embedding, inputs) | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from t... | # Number of negative labels to sample
n_sampled = 100
with train_graph.as_default():
softmax_w = tf.Variable(tf.truncated_normal((n_vocab, n_embedding), stddev=0.1))
softmax_b = tf.Variable(tf.zeros(n_vocab))
# Calculate the loss using negative sampling
loss = tf.nn.sampled_softmax_loss(softmax_w, ... | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
ValidationThis code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. | with train_graph.as_default():
## From Thushan Ganegedara's implementation
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100
# pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent
valid_examples = np.array(random.sample(range(vali... | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Restore the trained network if you need to: | with train_graph.as_default():
saver = tf.train.Saver()
with tf.Session(graph=train_graph) as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
embed_mat = sess.run(embedding) | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
Visualizing the word vectorsBelow we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out [this post from Christopher Olah](http://colah.github.io/posts/2014-10-Visualizing-MNIST/) to lear... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
viz_words = 500
tsne = TSNE()
embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :])
fig, ax = plt.subplots(figsize=(14, 14))
for idx in range(viz_words):
plt.scatter(*embed_tsne[i... | _____no_output_____ | MIT | embeddings/Skip-Grams-Solution.ipynb | arghasarkar/DeepLearningFoundations-Udacity |
BOOLEAN INDEXING and &or |Equal to ==Not equal to !=Not in ~Equals: ==Not equals: !=Greater than, less than: > or <Greater than or equal to >=Less than or equal to <= | condition = (df.item == 'call')
condition.head()
condition = (df.item == 'call')
df[~condition].head()
condition = (df.item == 'call') & (df.network == 'Vodafone')
df[condition].head() | _____no_output_____ | Apache-2.0 | Pandas New.ipynb | ankit98040/DataScience-Seminar |
NOW IF YOU WANT TO SEE THE ITEMS WHICH ARE NOT INCLUDED (EXCLUDED ONES) | condition = (df.item == 'call')
df[~condition].head()
condition = (df.item == 'call') | (df.network == 'Vodafone')
df[condition].head() | _____no_output_____ | Apache-2.0 | Pandas New.ipynb | ankit98040/DataScience-Seminar |
NOW IF YOU WANT TO ADD A COLUMN WHICH WILL BE A MULTIPLE OF A PARTICULAR COLUMN | df['new_column'] = df['duration']*3
df.head()
df['new_column'] = df['network']*3
df.head()
df.head()
df.drop(['new_column'], axis = 1, inplace=True)
df.head()
df.head()
df.sort_values('duration') #ascending
df.sort_values('duration', ascending = False ).head() #descending
df.sort_values(['duration', 'network'], ascendi... | _____no_output_____ | Apache-2.0 | Pandas New.ipynb | ankit98040/DataScience-Seminar |
WORKING WITH DATESDirective%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US) So, Mo, …, Sa (de_DE)%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US) Sonntag, Montag, …, Samstag (de_DE)%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, 2, 3, 4, 5, 6%d Day of the... | pd.to_datetime(df['date']) >= '2015-01-01'
sum(pd.to_datetime(df['date']) >= '2015-01-01')
from datetime import datetime
from datetime import date
df['new_date']=[datetime.strptime(x,'%d/%m/%y %H:%M') for x in df['date']]
type(df['new_date'][0])
type(df['date'][0])
print(date.today())
print(datetime.now())
df[df.month=... | _____no_output_____ | Apache-2.0 | Pandas New.ipynb | ankit98040/DataScience-Seminar |
DAPA Tutorial 2: Area - Sentinel-2 Load environment variablesPlease make sure that the environment variable "DAPA_URL" is set in the `custom.env` file. You can check this by executing the following block. If DAPA_URL is not set, please create a text file named `custom.env` in your home directory with the following in... | from edc import setup_environment_variables
setup_environment_variables() | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Check notebook compabtibility**Please note:** If you conduct this notebook again at a later time, the base image of this Jupyter Hub service can include newer versions of the libraries installed. Thus, the notebook execution can fail. This compatibility check is only necessary when something is broken. | from edc import check_compatibility
check_compatibility("user-0.19.6") | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Load librariesPython libraries used in this tutorial will be loaded. | import os
import xarray as xr
import pandas as pd
import requests
import matplotlib
from ipyleaflet import Map, Rectangle, DrawControl, basemaps, basemap_to_tiles
%matplotlib inline | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Set DAPA endpointExecute the following code to check if the DAPA_URL is available in the environment variable and to set the `/dapa` endpoint. | service_url = None
dapa_url = None
if 'DAPA_URL' not in os.environ:
print('!! DAPA_URL does not exist as environment variable. Please make sure this is the case - see first block of this notebook! !!')
else:
service_url = os.environ['DAPA_URL']
dapa_url = '{}/{}'.format(service_url, 'oapi')
print('... | DAPA path: /oapi
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Get collections supported by this endpointThis request provides a list of collections. The path of each collection is used as starting path of this service. | collections_url = '{}/{}'.format(dapa_url, 'collections')
collections = requests.get(collections_url, headers={'Accept': 'application/json'})
print('DAPA path: {}'.format(collections.url.replace(service_url, '')))
collections.json() | DAPA path: /oapi/collections
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Get fields of collection Sentinel-2 L2AThe fields (or variables in other DAPA endpoints - these are the bands of the raster data) can be retrieved in all requests to the DAPA endpoint. In addition to the fixed set of fields, "virtual" fields can be used to conduct math operations (e.g., the calculation of indices). | collection = 'S2L2A'
fields_url = '{}/{}/{}/{}'.format(dapa_url, 'collections', collection, 'dapa/fields')
fields = requests.get(fields_url, headers={'Accept': 'application/json'})
print('DAPA path: {}'.format(fields.url.replace(service_url, '')))
fields.json() | DAPA path: /oapi/collections/S2L2A/dapa/fields
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Retrieve data as raster aggregated by time Set DAPA URL and parametersThe output of this request is a single raster (`area` endpoint). As the input collection (S2L2A) is a multi-temporal raster and the output format is an area, temporal aggregation is conducted for each pixel in the area.To retrieve a single raster, ... | # DAPA URL
url = '{}/{}/{}/{}'.format(dapa_url, 'collections', collection, 'dapa/area')
# Parameters for this request
params = {
'bbox': '11.49,48.05,11.66,48.22',
'time': '2018-05-07T10:00:00Z/2018-05-07T12:00:00Z',
'fields': 'NDVI=(B08-B04)/(B08%2BB04),NDBI=(B11-B08)/(B11%2BB08)', # Please note: + signs ... | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Build request URL and conduct request | params_str = "&".join("%s=%s" % (k, v) for k,v in params.items())
r = requests.get(url, params=params_str)
print('DAPA path: {}'.format(r.url.replace(service_url, '')))
print('Status code: {}'.format(r.status_code)) | DAPA path: /oapi/collections/S2L2A/dapa/area?bbox=11.49,48.05,11.66,48.22&time=2018-05-07T10:00:00Z/2018-05-07T12:00:00Z&fields=NDVI=(B08-B04)/(B08%2BB04),NDBI=(B11-B08)/(B11%2BB08)&aggregate=avg
Status code: 200
| MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Write raster dataset to GeoTIFF fileThe response of the `area` endpoint is currently a GeoTIFF file, which can either be saved to disk or used directly in further processing. | with open('area_avg.tif', 'wb') as filew:
filew.write(r.content) | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Open raster dataset with xarrayThe GeoTIFF file can be opened with xarray. The file consists of bands related to each `field` and each aggregation function (see descriptions attribute in the xarray output). | ds = xr.open_rasterio('area_avg.tif')
ds | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Plot NDVI image (first band) | ds[0].plot(cmap="RdYlGn") | _____no_output_____ | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Output gdalinfo | !gdalinfo -stats area_avg.tif | Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples.
Driver: GTiff/GeoTIFF
Files: area_avg.tif
Size is 512, 512
Coordinate System is:
GEOGCRS["WGS 84",
DATUM["World Geodetic System 1984",
ELLI... | MIT | notebooks/contributions/DAPA/DAPA_Tutorial_2_-_Area_-_Sentinel-2.ipynb | jonas-eberle/notebooks |
Core> Basic healper functions | #hide
from nbdev.showdoc import *
#hide
%load_ext autoreload
%autoreload 2
#export
import torch
from torch import nn, einsum
import torch.nn.functional as F
import torch.autograd.profiler as profiler
from fastai.basics import *
from fastai.text.all import *
from fastai.test_utils import *
from functools import partia... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Helper functions General purpose utils | #export
def exists(val):
return val is not None
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) else d
def expand_dim1(x):
if len(x.shape) == 1:
return x[None, :]
else: return x
def max_neg_value(tensor):
return -torch.finfo(tensor.dtype).max
#expor... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Generative utils | #export
# generative helpers
# credit https://github.com/huggingface/transformers/blob/a0c62d249303a68f5336e3f9a96ecf9241d7abbe/src/transformers/generation_logits_process.py
def top_p_filter(logits, top_p=0.9):
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cum_probs = torch.cumsum(F.softma... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
LSH specific helpers From [lucidrains/reformer-pytorch](https://github.com/lucidrains/reformer-pytorch/). | #exports
def cache_method_decorator(cache_attr, cache_namespace, reexecute = False):
def inner_fn(fn):
@wraps(fn)
def wrapper(self, *args, key_namespace=None, fetch=False, set_cache=True, **kwargs):
namespace_str = str(default(key_namespace, ''))
_cache = getattr(self, cache_... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Profiling functions Utility functions to assess model performance. Test functions with `mod` and input `x`. | mod = get_text_classifier(AWD_LSTM, vocab_sz=10_000, n_class=10)
x = torch.randint(0, 100, (3, 72))
#export
def do_cuda_timing(f, inp, context=None, n_loops=100):
'''
Get timings of cuda modules. Note `self_cpu_time_total` is returned, but
from experiments this appears to be similar/same to the tota... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Number of params for our test model: | total_params(mod) | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Translation CallbacksCallbacks used to ensuring training a translation model works. All 3 are neededSee [notebook here](https://github.com/bentrevett/pytorch-seq2seq/blob/master/6%20-%20Attention%20is%20All%20You%20Need.ipynb) for explanation of EOS shifting | # exports
class CombineInputOutputCallback(Callback):
"""
Callback to combine the source (self.xb) and target (self.yb) into self.xb
"""
def __init__(self): pass
def before_batch(self):
self.learn.xb = (self.xb[0], self.yb[0])
class AssertAndCancelFit(Callback):
"Cancels batch after bac... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Loss functions | #export
class LabelSmoothingCrossEntropy(Module):
"""Label smotthing cross entropy similar to fastai implementation
https://github.com/fastai/fastai/blob/89b1afb59e37e5abf7008888f6e4dd1bf1211e3e/fastai/losses.py#L79
with added option to provide ignore_index"""
y_int = True
def __init__(self, eps:flo... | _____no_output_____ | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Distributed | #export
from fastai.distributed import *
@patch
@contextmanager
def distrib_ctx(self: Learner, cuda_id=None,sync_bn=True):
"A context manager to adapt a learner to train in distributed data parallel mode."
# Figure out the GPU to use from rank. Create a dpg if none exists yet.
if cuda_id is None: cuda_id =... | Converted 00_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_attention.ipynb.
Converted 03_transformer.ipynb.
Converted 04_reformer.ipynb.
Converted 05_tokenizers.ipynb.
Converted 06_data.ipynb.
Converted 07_metrics.ipynb.
Converted 08_optimizers.ipynb.
Converted 09_tracking.ipynb.
Converted 10_experiment.synthetic... | MIT | nbs/00_core.ipynb | tyoc213-contrib/reformer_fastai |
Lambda School Data Science*Unit 2, Sprint 1, Module 3*--- Ridge Regression AssignmentWe're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.But not just for condos in Tribeca...- [ ] Use a subset of the data where `BUILDING_CLAS... | %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
# Ignore this Numpy warning w... | _____no_output_____ | MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Use a subset of the data where BUILDING_CLASS_CATEGORY == '01 ONE FAMILY DWELLINGS' and the sale price was more than 100 thousand and less than 2 million. | df_new = df[df.BUILDING_CLASS_CATEGORY == '01 ONE FAMILY DWELLINGS']
df_new.head()
df_new = df_new[(df_new.SALE_PRICE >= 100000 ) & (df_new.SALE_PRICE <= 2000000)] | _____no_output_____ | MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Do train/test split. Use data from January — March 2019 to train. Use data from April 2019 to test. | df_new.head()
#Remove unecessary columns
df_new = df_new.drop('APARTMENT_NUMBER', axis = 'columns')
df_new = df_new.drop('TAX_CLASS_AT_TIME_OF_SALE', axis = 'columns')
cutoff = pd.to_datetime('2019-04-01')
train = df_new[df_new.SALE_DATE < cutoff]
test = df_new[df_new.SALE_DATE >= cutoff]
print(train.shape)
print(tes... | (2517, 18)
(647, 18)
| MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Do one-hot encoding of categorical features. | test.describe(include='object')
target = 'SALE_PRICE'
high_cardinality = ['ADDRESS', 'LAND_SQUARE_FEET', 'SALE_DATE']
features = train.columns.drop([target] + high_cardinality)
X_train = train[features]
y_train = train[target]
X_test = test[features]
y_test = test[target]
import category_encoders as ce
encoder = ce.One... | _____no_output_____ | MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Do feature selection with SelectKBest. | X_train.dtypes
from sklearn.feature_selection import SelectKBest, f_regression
selector = SelectKBest(score_func=f_regression, k=29)
# .fit_transform on the train set
# .transform on test set
X_train_selected = selector.fit_transform(X_train, y_train)
X_train_selected.shape
selected_mask = selector.get_support()
all... | _____no_output_____ | MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Looks like 29 features minimizes the error Fit a ridge regression model with multiple features. Use the normalize=True parameter (or do feature scaling beforehand — use the scaler's fit_transform method with the train set, and the scaler's transform method with the test set) | import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from IPython.display import display, HTML
for alpha in [0.001, 0.01, 0.1, 1.0, 10, 100.0, 1000.0]:
# Fit Ridge Regression model
display(HTML(f'Ridge Regression, with alpha={alpha}'))
model = Ridge(alpha=alpha)
model.fit(X_train,... | _____no_output_____ | MIT | module3-ridge-regression/Jaimie_Onigkeit_LS_DS_213_assignment.ipynb | JaimieOnigkeit/DS-Unit-2-Linear-Models |
Exercise 1 | pd.read_csv("precip_monthly.csv").set_index('month').loc['Jul'] | _____no_output_____ | CC-BY-4.0 | scientific_python/Pandas Solutions.ipynb | elliewix/2016-01-28-uiuc-swc |
Exercise 2 | region_yearly_precip = monthly.groupby(['region', 'year'])['precip'].mean().unstack()
region_yearly_precip | _____no_output_____ | CC-BY-4.0 | scientific_python/Pandas Solutions.ipynb | elliewix/2016-01-28-uiuc-swc |
Exercise 3 | monthly.loc[monthly.region == 'COLORADO RIVER']
monthly.query('region == "COLORADO RIVER"')
monthly.loc[(monthly.region == 'COLORADO RIVER') & (monthly.year >= 1999) & (monthly.year <= 2003)]
monthly.query('region == "COLORADO RIVER" and year >= 1999 and year <= 2003') | _____no_output_____ | CC-BY-4.0 | scientific_python/Pandas Solutions.ipynb | elliewix/2016-01-28-uiuc-swc |
Example Class | import datetime # we will use this for date objects
class Person:
def __init__(self, name, surname, birthdate, address, telephone, email):
self.name = name
self.surname = surname
self.birthdate = birthdate
self.address = address
self.telephone = telephone
self.emai... | Jane
jane.doe@example.com
26
| MIT | jupyter_notebooks/oop/OOP_Tutorial.ipynb | manual123/Nacho-Jupyter-Notebooks |
__init__() method is used to initialize an instance or object of a classself.name, self.surname, self.birthdate, self.address, self.telephone, and self.email are **instance** attributes You may have noticed that both of these method definitions have ```self``` as the first parameter, and we use this variable inside the... | class Person:
TITLES = ('Dr', 'Mr', 'Mrs', 'Ms') # This is a Class attribute
def __init__(self, title, name, surname):
if title not in self.TITLES:
raise ValueError("%s is not a valid title." % title)
self.title = title
self.name = name
self.surname = surname
... | Mr
John
Doe
('Dr', 'Mr', 'Mrs', 'Ms')
| MIT | jupyter_notebooks/oop/OOP_Tutorial.ipynb | manual123/Nacho-Jupyter-Notebooks |
Prediction Build images The images for the prediction process are generated in the same way but in this case, the masks are not going to be created.In the prediction process, the size and the step-size must be the same to do not generate an overlap in the predicted results. However, there is no need that the images h... | !ls
!satproc_extract_chips \
./data_cordoba/img/NBR_img/NBR_2021-10-07_2021-10-21_0.tif \
-o ./data_predict_cba/onedate_FW/160_160/ \
--size 160 \
--step-size 160 \
--rescale \
--rescale-mode percentiles \
--upper-cut 98 --lower-cut 2 | _____no_output_____ | Apache-2.0 | 3_Prediction.ipynb | dymaxionlabs/burned-area-detection |
The **--aoi** option is useful to reduce the predicction area to some shapefile. Predict | from unetseg.predict import PredictConfig, predict
from unetseg.evaluate import plot_data_results
import os | _____no_output_____ | Apache-2.0 | 3_Prediction.ipynb | dymaxionlabs/burned-area-detection |
The paths to the files and for the outputresults, as well as the path to the model weights is defined in the predictConfig | predict_config = PredictConfig(
images_path=os.path.join('./data_predict_cba/','onedate_FW','160_160'),
results_path=os.path.join('./data_result_cba/','onedate_FW','160_160'),
batch_size=16,
... | _____no_output_____ | Apache-2.0 | 3_Prediction.ipynb | dymaxionlabs/burned-area-detection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.