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 |
|---|---|---|---|---|---|
Simulation | n_loop = 10
rnd = np.random.RandomState(7)
labels = np.arange(C).repeat(100)
results = {}
for N in ns:
num_iters = int(len(labels) / N)
total_samples_for_bounds = float(num_iters * N * (n_loop))
for _ in range(n_loop):
rnd.shuffle(labels)
for batch_id in range(len(labels) // N):
... | _____no_output_____ | MIT | code/notebooks/coupon.ipynb | nzw0301/Understanding-Negative-Samples-in-Instance-Discriminative-Self-supervised-Representation-Learning |
3K Rice Genome GWAS Dataset Export Usage Data for this was exported as single Hail MatrixTable (`.mt`) as well as individual variants (`csv.gz`), samples (`csv`), and call datasets (`zarr`). | from pathlib import Path
import pandas as pd
import numpy as np
import hail as hl
import zarr
hl.init()
path = Path('~/data/gwas/rice-snpseek/1M_GWAS_SNP_Dataset/rg-3k-gwas-export').expanduser()
path
!du -sh {str(path)}/* | 582M /home/eczech/data/gwas/rice-snpseek/1M_GWAS_SNP_Dataset/rg-3k-gwas-export/rg-3k-gwas-export.calls.zarr
336K /home/eczech/data/gwas/rice-snpseek/1M_GWAS_SNP_Dataset/rg-3k-gwas-export/rg-3k-gwas-export.cols.csv
471M /home/eczech/data/gwas/rice-snpseek/1M_GWAS_SNP_Dataset/rg-3k-gwas-export/rg-3k-gwas-export.mt
7.5M /... | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
Hail | # The entire table with row, col, and call data:
hl.read_matrix_table(str(path / 'rg-3k-gwas-export.mt')).describe() | ----------------------------------------
Global fields:
None
----------------------------------------
Column fields:
's': str
'acc_seq_no': int64
'acc_stock_id': int64
'acc_gs_acc': float64
'acc_gs_variety_name': str
'acc_igrc_acc_src': int64
'pt_APANTH_REPRO': float64
'pt_APSH': flo... | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
Pandas Sample data contains phenotypes prefixed by `pt_` and `s` (sample_id) in the MatrixTable matches to the `s` in this table, as does the order: | pd.read_csv(path / 'rg-3k-gwas-export.cols.csv').head() | _____no_output_____ | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
Variant data shouldn't be needed for much, but it's here: | pd.read_csv(path / 'rg-3k-gwas-export.rows.csv.gz').head() | _____no_output_____ | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
Zarr Call data (dense and mean imputed in this case) can be sliced from a zarr array: | gt = zarr.open(str(path / 'rg-3k-gwas-export.calls.zarr'), mode='r')
# Get calls for 10 variants and 5 samples
gt[5:15, 5:10] | _____no_output_____ | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
Selecting Phenotypes Pick a phenotype: - Definitions are in https://s3-ap-southeast-1.amazonaws.com/oryzasnp-atcg-irri-org/3kRG-phenotypes/3kRG_PhenotypeData_v20170411.xlsx - The ">2007 Dictionary" sheet- Choose one with low sparsity | df = pd.read_csv(path / 'rg-3k-gwas-export.cols.csv')
df.info()
# First 1k variants with samples having data for this phenotype
mask = df['pt_FLA_REPRO'].notnull()
gtp = gt[:1000][:,mask]
gtp.shape, gtp.dtype | _____no_output_____ | Apache-2.0 | notebooks/organism/rice/rg-export-usage.ipynb | tomwhite/gwas-analysis |
PageRank Performance Benchmarking Skip notebook testThis notebook benchmarks performance of running PageRank within cuGraph against NetworkX. NetworkX contains several implementations of PageRank. This benchmark will compare cuGraph versus the defaukt Nx implementation as well as the SciPy versionNotebook Credits ... | # Import needed libraries
import gc
import time
import rmm
import cugraph
import cudf
# NetworkX libraries
import networkx as nx
from scipy.io import mmread
try:
import matplotlib
except ModuleNotFoundError:
os.system('pip install matplotlib')
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as n... | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
Define the test data | # Test File
data = {
'preferentialAttachment' : './data/preferentialAttachment.mtx',
'caidaRouterLevel' : './data/caidaRouterLevel.mtx',
'coAuthorsDBLP' : './data/coAuthorsDBLP.mtx',
'dblp' : './data/dblp-2010.mtx',
'citationCiteseer' : './data/citationCiteseer... | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
Define the testing functions | # Data reader - the file format is MTX, so we will use the reader from SciPy
def read_mtx_file(mm_file):
print('Reading ' + str(mm_file) + '...')
M = mmread(mm_file).asfptype()
return M
# CuGraph PageRank
def cugraph_call(M, max_iter, tol, alpha):
gdf = cudf.DataFrame()
gdf['src'] = M.row
... | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
Run the benchmarks | # arrays to capture performance gains
time_cu = []
time_nx = []
time_sp = []
perf_nx = []
perf_sp = []
names = []
# init libraries by doing a simple task
v = './data/preferentialAttachment.mtx'
M = read_mtx_file(v)
trapids = cugraph_call(M, 100, 0.00001, 0.85)
del M
for k,v in data.items():
gc.collect()
# ... | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
plot the output | %matplotlib inline
plt.figure(figsize=(10,8))
bar_width = 0.35
index = np.arange(len(names))
_ = plt.bar(index, perf_nx, bar_width, color='g', label='vs Nx')
_ = plt.bar(index + bar_width, perf_sp, bar_width, color='b', label='vs SciPy')
plt.xlabel('Datasets')
plt.ylabel('Speedup')
plt.title('PageRank Performance S... | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
Dump the raw stats | perf_nx
perf_sp
time_cu
time_nx
time_sp | _____no_output_____ | Apache-2.0 | notebooks/cugraph_benchmarks/pagerank_benchmark.ipynb | hlinsen/cugraph |
My Notebook 2 | import os
print("I am notebook 2") | _____no_output_____ | BSD-3-Clause | nbcollection/tests/data/my_notebooks/sub_path1/notebook2.ipynb | jonathansick/nbcollection |
We'll continue to make use of the fuel economy dataset in this workspace. | fuel_econ = pd.read_csv('./data/fuel_econ.csv')
fuel_econ.head() | _____no_output_____ | MIT | Matplotlib/Violin_and_Box_Plot_Practice.ipynb | iamleeg/AIPND |
**Task**: What is the relationship between the size of a car and the size of its engine? The cars in this dataset are categorized into one of five different vehicle classes based on size. Starting from the smallest, they are: {Minicompact Cars, Subcompact Cars, Compact Cars, Midsize Cars, and Large Cars}. The vehicle c... | # YOUR CODE HERE
car_classes = ['Minicompact Cars', 'Subcompact Cars', 'Compact Cars', 'Midsize Cars', 'Large Cars']
vclasses = pd.api.types.CategoricalDtype(ordered = True, categories = car_classes)
fuel_econ['VClass'] = fuel_econ['VClass'].astype(vclasses)
sb.violinplot(data = fuel_econ, x = 'VClass', y = 'displ')
pl... | I used a violin plot to depict the data in this case; you might have chosen a box plot instead. One of the interesting things about the relationship between variables is that it isn't consistent. Compact cars tend to have smaller engine sizes than the minicompact and subcompact cars, even though those two vehicle sizes... | MIT | Matplotlib/Violin_and_Box_Plot_Practice.ipynb | iamleeg/AIPND |
Langmuir-enhanced entrainmentThis notebook reproduces Fig. 15 of [Li et al., 2019](https://doi.org/10.1029/2019MS001810). | import sys
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
sys.path.append("../../../gotmtool")
from gotmtool import *... | _____no_output_____ | MIT | examples/Entrainment-LF17/plot_Entrainment-LF17.ipynb | jithuraju1290/gotmtool |
Load LF17 data | # load LF17 data
lf17_data = np.load('LF17_dPEdt.npz')
us0 = lf17_data['us0']
b0 = lf17_data['b0']
ustar = lf17_data['ustar']
hb = lf17_data['hb']
dpedt = lf17_data['dpedt']
casenames = lf17_data['casenames']
ncase = len(casenames)
# get parameter h/L_L= w*^3/u*^2/u^s(0)
inds = us0==0
us0[inds] = np.nan
h... | _____no_output_____ | MIT | examples/Entrainment-LF17/plot_Entrainment-LF17.ipynb | jithuraju1290/gotmtool |
Compute the rate of change in potential energy in GOTM runs | turbmethods = [
'GLS-C01A',
'KPP-CVMix',
'KPPLT-VR12',
'KPPLT-LF17',
]
ntm = len(turbmethods)
cmap = cm.get_cmap('rainbow')
if ntm == 1:
colors = ['gray']
else:
colors = cmap(np.linspace(0,1,ntm))
m = Model(name='Entrainment-LF17', environ='../../.gotm_env.yaml')
gotmdir = m.environ['gotmdi... | _____no_output_____ | MIT | examples/Entrainment-LF17/plot_Entrainment-LF17.ipynb | jithuraju1290/gotmtool |
Statistics **Quick intro to the following packages**- `hepstats`.I will not discuss here the `pyhf` package, which is very niche.Please refer to the [GitHub repository](https://github.com/scikit-hep/pyhf) or related material at https://scikit-hep.org/resources. **`hepstats` - statistics tools and utilities**The packag... | import numpy as np
import matplotlib.pyplot as plt
from hepstats.modeling import bayesian_blocks
data = np.append(np.random.laplace(size=10000), np.random.normal(5., 1., size=15000))
bblocks = bayesian_blocks(data)
plt.hist(data, bins=1000, label='Fine Binning', density=True)
plt.hist(data, bins=bblocks, label='Bay... | _____no_output_____ | BSD-3-Clause | 05-statistics.ipynb | eduardo-rodrigues/2020-03-03_DESY_Scikit-HEP_HandsOn |
Tirmzi Analysisn=1000 m+=1000 nm-=120 istep= 4 min=150 max=700 | import sys
sys.path
import matplotlib.pyplot as plt
import numpy as np
import os
from scipy import signal
ls
import capsol.newanalyzecapsol as ac
ac.get_gridparameters
import glob
folders = glob.glob("FortranOutputTest/*/")
folders
all_data= dict()
for folder in folders:
params = ac.get_gridparameters(folder + 'c... | No handles with labels found to put in legend.
| MIT | data/Output-Python/Tirmzi_istep4-Copy2.ipynb | maroniea/xsede-spm |
cut off last experiment because capacitance was off the scale | for params in all_params.values():
print(params['Thickness_sample'])
print(params['m-'])
all_params
for key in {key: params for key, params in all_params.items() if params['Thickness_sample'] == 1.0}:
data=all_data[key]
thickness=all_params[key]['Thickness_sample']
rtip= all_params[key]['Rtip']
... | _____no_output_____ | MIT | data/Output-Python/Tirmzi_istep4-Copy2.ipynb | maroniea/xsede-spm |
Q-learning - Initialize $V(s)$ arbitrarily- Repeat for each episode- Initialize s- Repeat (for each step of episode)- - $\alpha \leftarrow$ action given by $\pi$ for $s$- - Take action a, observe reward r, and next state s'- - $V(s) \leftarrow V(s) + \alpha [r = \gamma V(s') - V(s)]$ - - $s \leftarrow s'$- until $s... | import td
import scipy as sp
α = 0.05
γ = 0.1
td_learning = td.TD(α, γ) | _____no_output_____ | MIT | notebooks/TD Learning Black Scholes.ipynb | FinTechies/HedgingRL |
Black Scholes $${\displaystyle d_{1}={\frac {1}{\sigma {\sqrt {T-t}}}}\left[\ln \left({\frac {S_{t}}{K}}\right)+(r-q+{\frac {1}{2}}\sigma ^{2})(T-t)\right]}$$ $${\displaystyle C(S_{t},t)=e^{-r(T-t)}[FN(d_{1})-KN(d_{2})]\,}$$ $${\displaystyle d_{2}=d_{1}-\sigma {\sqrt {T-t}}={\frac {1}{\sigma {\sqrt {T-t}}}}\left[\ln \... | d_1 = lambda σ, T, t, S, K: 1. / σ / np.sqrt(T - t) * (np.log(S / K) + 0.5 * (σ ** 2) * (T-t))
d_2 = lambda σ, T, t, S, K: 1. / σ / np.sqrt(T - t) * (np.log(S / K) - 0.5 * (σ ** 2) * (T-t))
call = lambda σ, T, t, S, K: S * sp.stats.norm.cdf( d_1(σ, T, t, S, K) ) - K * sp.stats.norm.cdf( d_2(σ, T, t, S, K) )
plt.plot(n... | _____no_output_____ | MIT | notebooks/TD Learning Black Scholes.ipynb | FinTechies/HedgingRL |
Plotting with Matplotlib IPython works with the [Matplotlib](http://matplotlib.org/) plotting library, which integrates Matplotlib with IPython's display system and event loop handling. matplotlib mode To make plots using Matplotlib, you must first enable IPython's matplotlib mode.To do this, run the `%matplotlib` ma... | %matplotlib inline | _____no_output_____ | BSD-3-Clause | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/Plotting in the Notebook.ipynb | willirath/jupyter-jsc-notebooks |
You can also use Matplotlib GUI backends in the Notebook, such as the Qt backend (`%matplotlib qt`). This will use Matplotlib's interactive Qt UI in a floating window to the side of your browser. Of course, this only works if your browser is running on the same system as the Notebook Server. You can always call the `d... | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp'); | _____no_output_____ | BSD-3-Clause | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/Plotting in the Notebook.ipynb | willirath/jupyter-jsc-notebooks |
These images can be resized by dragging the handle in the lower right corner. Double clicking will return them to their original size. One thing to be aware of is that by default, the `Figure` object is cleared at the end of each cell, so you will need to issue all plotting commands for a single figure in a single cel... | # %load http://matplotlib.org/mpl_examples/showcase/integral_demo.py
"""
Plot demonstrating the integral as the area under a curve.
Although this is a simple example, it demonstrates some important tweaks:
* A simple line plot with custom color and line width.
* A shaded region created using a Polygon patch.
... | _____no_output_____ | BSD-3-Clause | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/Plotting in the Notebook.ipynb | willirath/jupyter-jsc-notebooks |
Matplotlib 1.4 introduces an interactive backend for use in the notebook,called 'nbagg'. You can enable this with `%matplotlib notebook`.With this backend, you will get interactive panning and zooming of matplotlib figures in your browser. | %matplotlib widget
plt.figure()
x = np.linspace(0, 5 * np.pi, 1000)
for n in range(1, 4):
plt.plot(np.sin(n * x))
plt.show() | _____no_output_____ | BSD-3-Clause | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/Plotting in the Notebook.ipynb | willirath/jupyter-jsc-notebooks |
Let's start by importing the libraries that we need for this exercise. | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib
from sklearn.model_selection import train_test_split
#matplotlib settings
matplotlib.rcParams['xtick.major.size'] = 7
matplotlib.rcParams['xtick.labelsize'] = 'x-large'
matplotlib.rcParams['ytick.major.size'] = 7
matplotlib.rcP... | _____no_output_____ | MIT | day2/nn_qso_finder.ipynb | mjvakili/MLcourse |
df1.query('age == 10')
You can also achieve this result via the traditional filtering method.
filter_1 = df['Mon'] > df['Tues']
df[filter_1]
If needed you can also use an environment variable to filter your data.
Make sure to put an "@" sign in front of your variable within the string.
dinner_limit=120
df.que... | _____no_output_____ | MIT | PandasQureys.ipynb | nealonleo9/SQL | |
Udacity PyTorch Scholarship Final Lab Challenge Guide **A hands-on guide to get 90% + accuracy and complete the challenge** **By [Soumya Ranjan Behera](https://www.linkedin.com/in/soumya044)** This Tutorial will be divided into Two Parts, [1. Model Building and Training](https://www.kaggle.com/soumya044/udacity-py... | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
print(os.listdir("../input/"))
# Any results you write to the current directory are saved as output. | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Import some visualization Libraries** | import matplotlib.pyplot as plt
%matplotlib inline
import cv2
# Set Train and Test Directory Variables
TRAIN_DATA_DIR = "../input/flower_data/flower_data/train/"
VALID_DATA_DIR = "../input/flower_data/flower_data/valid/"
#Visualiza Some Images of any Random Directory-cum-Class
FILE_DIR = str(np.random.randint(1,103))
p... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
2. Data Preprocessing (Image Augmentation) **Import PyTorch libraries** | import torch
import torchvision
from torchvision import datasets, models, transforms
import torch.nn as nn
torch.__version__ | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Note:** **Look carefully! Kaggle uses v1.0.0 while Udcaity workspace has v0.4.0 (Some issues may arise but we'll solve them)** | # check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...') | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Make a Class Variable i.e a list of Target Categories (List of 102 species) ** | # I used os.listdir() to maintain the ordering
classes = os.listdir(VALID_DATA_DIR) | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Load and Transform (Image Augmentation)** Soucre: https://github.com/udacity/deep-learning-v2-pytorch/blob/master/convolutional-neural-networks/cifar-cnn/cifar10_cnn_augmentation.ipynb | # Load and transform data using ImageFolder
# VGG-16 Takes 224x224 images as input, so we resize all of them
data_transform = transforms.Compose([transforms.RandomResizedCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, ... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
Find more on Image Transforms using PyTorch Here (https://pytorch.org/docs/stable/torchvision/transforms.html) 3. Make a DataLoader | # define dataloader parameters
batch_size = 32
num_workers=0
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
num_workers=num_workers, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Visualize Sample Images** | # Visualize some sample data
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20)... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Here plt.imshow() clips our data into [0,....,255] range to show the images. The Warning message is due to our Transform Function. We can Ignore it.** 4. Use a Pre-Trained Model (VGG16) Here we used a VGG16. You can experiment with other models. References: https://github.com/udacity/deep-learning-v2-pytorch/blob... | # Load the pretrained model from pytorch
model = models.<ModelNameHere>(pretrained=True)
print(model) | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
We can see from above output that the last ,i.e, 6th Layer is a Fully-connected Layer with in_features=4096, out_features=1000 | print(model.classifier[6].in_features)
print(model.classifier[6].out_features)
# The above lines work for vgg only. For other models refer to print(model) and look for last FC layer | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**Freeze Training for all 'Features Layers', Only Train Classifier Layers** | # Freeze training for all "features" layers
for param in model.features.parameters():
param.requires_grad = False
#For models like ResNet or Inception use the following,
# Freeze training for all "features" layers
# for _, param in model.named_parameters():
# param.requires_grad = False | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
Let's Add our own Last Layer which will have 102 out_features for 102 species | # VGG16
n_inputs = model.classifier[6].in_features
#Others
# n_inputs = model.fc.in_features
# add last linear layer (n_inputs -> 102 flower classes)
# new layers automatically have requires_grad = True
last_layer = nn.Linear(n_inputs, len(classes))
# VGG16
model.classifier[6] = last_layer
# Others
#model.fc = la... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
5. Specify our Loss Function and Optimzer | import torch.optim as optim
# specify loss function (categorical cross-entropy)
criterion = #TODO
# specify optimizer (stochastic gradient descent) and learning rate = 0.01 or 0.001
optimizer = #TODO | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
6. Train our Model and Save necessary checkpoints | # Define epochs (between 50-200)
epochs = 20
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf # set initial "min" to infinity
# Some lists to keep track of loss and accuracy during each epoch
epoch_list = []
train_loss_list = []
val_loss_list = []
train_acc_list = []
val_acc_list = []
# Start e... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
Load Model State from Checkpoint | model.load_state_dict(torch.load('model.pt')) | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
Save the whole Model (Pickling) | #Save/Pickle the Model
torch.save(model, 'classifier.pth') | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
7. Visualize Model Training and Validation | # Training / Validation Loss
plt.plot(epoch_list,train_loss_list)
plt.plot(val_loss_list)
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Training/Validation Loss vs Number of Epochs")
plt.legend(['Train', 'Valid'], loc='upper right')
plt.show()
# Train/Valid Accuracy
plt.plot(epoch_list,train_acc_list)
plt.plot(val... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
From the above graphs we get some really impressive results **Overall Accuracy** | val_acc = sum(val_acc_list[:]).item()/len(val_acc_list)
print("Validation Accuracy of model = {} %".format(val_acc)) | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
8. Test our Model Performance | # obtain one batch of test images
dataiter = iter(test_loader)
images, labels = dataiter.next()
img = images.numpy()
# move model inputs to cuda, if GPU available
if train_on_gpu:
images = images.cuda()
model.eval() # Required for Evaluation/Test
# get sample outputs
output = model(images)
if type(output) == tupl... | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
**We can see that the Correctly Classifies Results are Marked in "Green" and the misclassifies ones are "Red"** 8.1 Test our Model Performance with Gabriele Picco's Program **Credits: ** **Gabriele Picco** (https://github.com/GabrielePicco/deep-learning-flower-identifier) **Special Instruction:** 1. **Uncomment the f... | # !git clone https://github.com/GabrielePicco/deep-learning-flower-identifier
# !pip install airtable
# import sys
# sys.path.insert(0, 'deep-learning-flower-identifier')
# from test_model_pytorch_facebook_challenge import calc_accuracy
# calc_accuracy(model, input_image_size=224, use_google_testset=False) | _____no_output_____ | MIT | udacity-pytorch-final-lab-guide-part-1.ipynb | styluna7/notebooks |
Exercise: Find correspondences between old and modern english The purpose of this execise is to use two vecsigrafos, one built on UMBC and Wordnet and another one produced by directly running Swivel against a corpus of Shakespeare's complete works, to try to find corelations between old and modern English, e.g. "thou... | import os
%ls
#!rm -r tutorial
!git clone https://github.com/HybridNLP2018/tutorial | fatal: destination path 'tutorial' already exists and is not an empty directory.
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Let us see if the corpus is where we think it is: | %cd tutorial/lit
%ls | /content/tutorial/lit
[0m[01;34mcoocs[0m/ shakespeare_complete_works.txt [01;34mswivel[0m/ wget-log
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Downloading Swivel | !wget http://expertsystemlab.com/hybridNLP18/swivel.zip
!unzip swivel.zip
!rm swivel/*
!rm swivel.zip |
Redirecting output to ‘wget-log.1’.
Archive: swivel.zip
inflating: swivel/analogy.cc
inflating: swivel/distributed.sh
inflating: swivel/eval.mk
inflating: swivel/fastprep.cc
inflating: swivel/fastprep.mk
inflating: swivel/glove_to_shards.py
inflating: swivel/nearest.py ... | MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Learn the Swivel embeddings over the Old Shakespeare corpus Calculating the co-occurrence matrix | corpus_path = '/content/tutorial/lit/shakespeare_complete_works.txt'
coocs_path = '/content/tutorial/lit/coocs'
shard_size = 512
freq=3
!python /content/tutorial/scripts/swivel/prep.py --input={corpus_path} --output_dir={coocs_path} --shard_size={shard_size} --min_count={freq}
%ls {coocs_path} | head -n 10 | col_sums.txt
col_vocab.txt
row_sums.txt
row_vocab.txt
shard-000-000.pb
shard-000-001.pb
shard-000-002.pb
shard-000-003.pb
shard-000-004.pb
shard-000-005.pb
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Learning the embeddings from the matrix | vec_path = '/content/tutorial/lit/vec/'
!python /content/tutorial/scripts/swivel/swivel.py --input_base_path={coocs_path} \
--output_base_path={vec_path} \
--num_epochs=20 --dim=300 \
--submatrix_rows={shard_size} --submatrix_cols={shard_size} | WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/input.py:187: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.
Instructions for updating:
To construct input pipelines, use the `tf.data` module.
WARNI... | MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Checking the context of the 'vec' directory. Should contain checkpoints of the model plus tsv files for column and row embeddings. | os.listdir(vec_path)
| _____no_output_____ | MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Converting tsv to bin: | !python /content/tutorial/scripts/swivel/text2bin.py --vocab={vec_path}vocab.txt --output={vec_path}vecs.bin \
{vec_path}row_embedding.tsv \
{vec_path}col_embedding.tsv
%ls {vec_path} | checkpoint
col_embedding.tsv
events.out.tfevents.1539004459.46972dad0a54
graph.pbtxt
model.ckpt-0.data-00000-of-00001
model.ckpt-0.index
model.ckpt-0.meta
model.ckpt-42320.data-00000-of-00001
model.ckpt-42320.index
model.ckpt-42320.meta
row_embedding.tsv
vecs.bin
vocab.txt
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Read stored binary embeddings and inspect them | import importlib.util
spec = importlib.util.spec_from_file_location("vecs", "/content/tutorial/scripts/swivel/vecs.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
shakespeare_vecs = m.Vecs(vec_path + 'vocab.txt', vec_path + 'vecs.bin') | Opening vector with expected size 23552 from file /content/tutorial/lit/vec/vocab.txt
vocab size 23552 (unique 23552)
read rows
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Basic method to print the k nearest neighbors for a given word | def k_neighbors(vec, word, k=10):
res = vec.neighbors(word)
if not res:
print('%s is not in the vocabulary, try e.g. %s' % (word, vecs.random_word_in_vocab()))
else:
for word, sim in res[:10]:
print('%0.4f: %s' % (sim, word))
k_neighbors(shakespeare_vecs, 'strife')
k_neighbors(sh... | 1.0000: youth
0.3436: tall,
0.3350: vanity,
0.2945: idleness.
0.2929: womb;
0.2847: tall
0.2823: suffering
0.2742: stillness
0.2671: flow'ring
0.2671: observation
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Load vecsigrafo from UMBC over WordNet | %ls
!wget https://zenodo.org/record/1446214/files/vecsigrafo_umbc_tlgs_ls_f_6e_160d_row_embedding.tar.gz
%ls
!tar -xvzf vecsigrafo_umbc_tlgs_ls_f_6e_160d_row_embedding.tar.gz
!rm vecsigrafo_umbc_tlgs_ls_f_6e_160d_row_embedding.tar.gz
umbc_wn_vec_path = '/content/tutorial/lit/vecsi_tlgs_wnscd_ls_f_6e_160d/' | _____no_output_____ | MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Extracting the vocabulary from the .tsv file: | with open(umbc_wn_vec_path + 'vocab.txt', 'w', encoding='utf_8') as f:
with open(umbc_wn_vec_path + 'row_embedding.tsv', 'r', encoding='utf_8') as vec_lines:
vocab = [line.split('\t')[0].strip() for line in vec_lines]
for word in vocab:
print(word, file=f) | _____no_output_____ | MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
Converting tsv to bin: | !python /content/tutorial/scripts/swivel/text2bin.py --vocab={umbc_wn_vec_path}vocab.txt --output={umbc_wn_vec_path}vecs.bin \
{umbc_wn_vec_path}row_embedding.tsv
%ls
umbc_wn_vecs = m.Vecs(umbc_wn_vec_path + 'vocab.txt', umbc_wn_vec_path + 'vecs.bin')
k_neighbors(umbc_wn_vecs, 'lem_California') | 1.0000: lem_California
0.6301: lem_Central Valley
0.5959: lem_University of California
0.5542: lem_Southern California
0.5254: lem_Santa Cruz
0.5241: lem_Astro Aerospace
0.5168: lem_San Francisco Bay
0.5092: lem_San Diego County
0.5074: lem_Santa Barbara
0.5069: lem_Santa Rosa
| MIT | 06_shakespeare_exercise.ipynb | flaviomerenda/tutorial |
T81-558: Applications of Deep Neural Networks**Module 4: Training for Tabular Data*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class w... | try:
%tensorflow_version 2.x
COLAB = True
print("Note: using Google CoLab")
except:
print("Note: not using Google CoLab")
COLAB = False | Note: not using Google CoLab
| Apache-2.0 | t81_558_class_04_3_regression.ipynb | akramsystems/t81_558_deep_learning |
Part 4.3: Keras Regression for Deep Neural Networks with RMSERegression results are evaluated differently than classification. Consider the following code that trains a neural network for regression on the data set **jh-simple-dataset.csv**. | import pandas as pd
from scipy.stats import zscore
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Read the data set
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
na_values=['NA','?'])
# Generate dummies for job
df = pd.concat([d... | Train on 1500 samples, validate on 500 samples
Epoch 1/1000
1500/1500 - 1s - loss: 1905.4454 - val_loss: 1628.1341
Epoch 2/1000
1500/1500 - 0s - loss: 1331.4213 - val_loss: 889.0575
Epoch 3/1000
1500/1500 - 0s - loss: 554.8426 - val_loss: 303.7261
Epoch 4/1000
1500/1500 - 0s - loss: 276.2087 - val_loss: 241.2495
Epoch ... | Apache-2.0 | t81_558_class_04_3_regression.ipynb | akramsystems/t81_558_deep_learning |
Mean Square ErrorThe mean square error is the sum of the squared differences between the prediction ($\hat{y}$) and the expected ($y$). MSE values are not of a particular unit. If an MSE value has decreased for a model, that is good. However, beyond this, there is not much more you can determine. Low MSE values ar... | from sklearn import metrics
# Predict
pred = model.predict(x_test)
# Measure MSE error.
score = metrics.mean_squared_error(pred,y_test)
print("Final score (MSE): {}".format(score)) | Final score (MSE): 0.5463447829677607
| Apache-2.0 | t81_558_class_04_3_regression.ipynb | akramsystems/t81_558_deep_learning |
Root Mean Square ErrorThe root mean square (RMSE) is essentially the square root of the MSE. Because of this, the RMSE error is in the same units as the training data outcome. Low RMSE values are desired.$ \mbox{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^n \left(\hat{y}_i - y_i\right)^2} $ | import numpy as np
# Measure RMSE error. RMSE is common for regression.
score = np.sqrt(metrics.mean_squared_error(pred,y_test))
print("Final score (RMSE): {}".format(score)) | Final score (RMSE): 0.7391513938076291
| Apache-2.0 | t81_558_class_04_3_regression.ipynb | akramsystems/t81_558_deep_learning |
Lift ChartTo generate a lift chart, perform the following activities:* Sort the data by expected output. Plot the blue line above.* For every point on the x-axis plot the predicted value for that same data point. This is the green line above.* The x-axis is just 0 to 100% of the dataset. The expected always starts low... | # Regression chart.
def chart_regression(pred, y, sort=True):
t = pd.DataFrame({'pred': pred, 'y': y.flatten()})
if sort:
t.sort_values(by=['y'], inplace=True)
plt.plot(t['y'].tolist(), label='expected')
plt.plot(t['pred'].tolist(), label='prediction')
plt.ylabel('output')
plt.legend()
... | _____no_output_____ | Apache-2.0 | t81_558_class_04_3_regression.ipynb | akramsystems/t81_558_deep_learning |
Test zplot | zplot()
zplot(area=0.80, two_tailed=False)
zplot(area=0.80, two_tailed=False, align_right=True) | _____no_output_____ | MIT | notebooks/test_plot.ipynb | rajvpatil5/ab-framework |
Test abplot | abplot(n=4000, bcr=0.11, d_hat=0.03, show_alpha=True) | _____no_output_____ | MIT | notebooks/test_plot.ipynb | rajvpatil5/ab-framework |
About this NotebookIn this notebook, we provide the tensor factorization implementation using an iterative Alternating Least Square (ALS), which is a good starting point for understanding tensor factorization. | import numpy as np
from numpy.linalg import inv as inv | _____no_output_____ | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
Part 1: Matrix Computation Concepts 1) Kronecker product- **Definition**:Given two matrices $A\in\mathbb{R}^{m_1\times n_1}$ and $B\in\mathbb{R}^{m_2\times n_2}$, then, the **Kronecker product** between these two matrices is defined as$$A\otimes B=\left[ \begin{array}{cccc} a_{11}B & a_{12}B & \cdots & a_{1m_2}B \\ a_... | def kr_prod(a, b):
return np.einsum('ir, jr -> ijr', a, b).reshape(a.shape[0] * b.shape[0], -1)
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8], [9, 10]])
print(kr_prod(A, B)) | [[ 5 12]
[ 7 16]
[ 9 20]
[15 24]
[21 32]
[27 40]]
| MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
3) CP decomposition CP Combination (`cp_combination`)- **Definition**:The CP decomposition factorizes a tensor into a sum of outer products of vectors. For example, for a third-order tensor $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$, the CP decomposition can be written as$$\hat{\mathcal{Y}}=\sum_{s=1}^{r}\boldsymb... | def cp_combine(U, V, X):
return np.einsum('is, js, ts -> ijt', U, V, X)
U = np.array([[1, 2], [3, 4]])
V = np.array([[1, 3], [2, 4], [5, 6]])
X = np.array([[1, 5], [2, 6], [3, 7], [4, 8]])
print(cp_combine(U, V, X))
print()
print('tensor size:')
print(cp_combine(U, V, X).shape) | [[[ 31 38 45 52]
[ 42 52 62 72]
[ 65 82 99 116]]
[[ 63 78 93 108]
[ 86 108 130 152]
[135 174 213 252]]]
tensor size:
(2, 3, 4)
| MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
4) Tensor Unfolding (`ten2mat`)Using numpy reshape to perform 3rd rank tensor unfold operation. [[**link**](https://stackoverflow.com/questions/49970141/using-numpy-reshape-to-perform-3rd-rank-tensor-unfold-operation)] | def ten2mat(tensor, mode):
return np.reshape(np.moveaxis(tensor, mode, 0), (tensor.shape[mode], -1), order = 'F')
X = np.array([[[1, 2, 3, 4], [3, 4, 5, 6]],
[[5, 6, 7, 8], [7, 8, 9, 10]],
[[9, 10, 11, 12], [11, 12, 13, 14]]])
print('tensor size:')
print(X.shape)
print('original tensor... | tensor size:
(3, 2, 4)
original tensor:
[[[ 1 2 3 4]
[ 3 4 5 6]]
[[ 5 6 7 8]
[ 7 8 9 10]]
[[ 9 10 11 12]
[11 12 13 14]]]
(1) mode-1 tensor unfolding:
[[ 1 3 2 4 3 5 4 6]
[ 5 7 6 8 7 9 8 10]
[ 9 11 10 12 11 13 12 14]]
(2) mode-2 tensor unfolding:
[[ 1 5 9 2 6 10 3 7 11 4 8 1... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
Part 2: Tensor CP Factorization using ALS (TF-ALS)Regarding CP factorization as a machine learning problem, we could perform a learning task by minimizing the loss function over factor matrices, that is,$$\min _{U, V, X} \sum_{(i, j, t) \in \Omega}\left(y_{i j t}-\sum_{r=1}^{R}u_{ir}v_{jr}x_{tr}\right)^{2}.$$Within th... | def CP_ALS(sparse_tensor, rank, maxiter):
dim1, dim2, dim3 = sparse_tensor.shape
dim = np.array([dim1, dim2, dim3])
U = 0.1 * np.random.rand(dim1, rank)
V = 0.1 * np.random.rand(dim2, rank)
X = 0.1 * np.random.rand(dim3, rank)
pos = np.where(sparse_tensor != 0)
binary_tensor = np.z... | _____no_output_____ | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
Part 3: Data Organization 1) Matrix StructureWe consider a dataset of $m$ discrete time series $\boldsymbol{y}_{i}\in\mathbb{R}^{f},i\in\left\{1,2,...,m\right\}$. The time series may have missing elements. We express spatio-temporal dataset as a matrix $Y\in\mathbb{R}^{m\times f}$ with $m$ rows (e.g., locations) and $... | import scipy.io
tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/tensor.mat')
dense_tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/ran... | _____no_output_____ | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
**Question**: Given only the partially observed data $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$, how can we impute the unknown missing values?The main influential factors for such imputation model are:- `rank`.- `maxiter`. | import time
start = time.time()
rank = 80
maxiter = 1000
tensor_hat, U, V, X = CP_ALS(sparse_tensor, rank, maxiter)
pos = np.where((dense_tensor != 0) & (sparse_tensor == 0))
final_mape = np.sum(np.abs(dense_tensor[pos] - tensor_hat[pos])/dense_tensor[pos])/dense_tensor[pos].shape[0]
final_rmse = np.sqrt(np.sum((dense_... | Iter: 100
Training MAPE: 0.0809251
Training RMSE: 3.47736
Iter: 200
Training MAPE: 0.0805399
Training RMSE: 3.46261
Iter: 300
Training MAPE: 0.0803688
Training RMSE: 3.45631
Iter: 400
Training MAPE: 0.0802661
Training RMSE: 3.45266
Iter: 500
Training MAPE: 0.0801768
Training RMSE: 3.44986
Iter: 600
Training MAPE: ... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
**Experiment results** of missing data imputation using TF-ALS:| scenario |`rank`| `maxiter`| mape | rmse ||:----------|-----:|---------:|-----------:|----------:||**20%, RM**| 80 | 1000 | **0.0833** | **3.5928**||**40%, RM**| 80 | 1000 | **0.0837** | **3.6190**||**20%, NM**| 10 | 1000 | *... | import scipy.io
tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat')
dense_tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/... | Iter: 100
Training MAPE: 0.0509401
Training RMSE: 15.3163
Iter: 200
Training MAPE: 0.0498774
Training RMSE: 14.9599
Iter: 300
Training MAPE: 0.0490062
Training RMSE: 14.768
Iter: 400
Training MAPE: 0.0481006
Training RMSE: 14.6343
Iter: 500
Training MAPE: 0.0474233
Training RMSE: 14.5365
Iter: 600
Training MAPE: 0... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
**Experiment results** of missing data imputation using TF-ALS:| scenario |`rank`| `maxiter`| mape | rmse ||:----------|-----:|---------:|-----------:|-----------:||**10%, RM**| 30 | 1000 | **0.0615** | **18.5005**||**30%, RM**| 30 | 1000 | **0.0583** | **18.9148**||**10%, NM**| 10 | 1000... | import scipy.io
tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat')
dense_tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random... | Iter: 100
Training MAPE: 0.176548
Training RMSE: 17.0263
Iter: 200
Training MAPE: 0.174888
Training RMSE: 16.8609
Iter: 300
Training MAPE: 0.175056
Training RMSE: 16.7835
Iter: 400
Training MAPE: 0.174988
Training RMSE: 16.7323
Iter: 500
Training MAPE: 0.175013
Training RMSE: 16.6942
Iter: 600
Training MAPE: 0.174... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
**Experiment results** of missing data imputation using TF-ALS:| scenario |`rank`| `maxiter`| mape | rmse ||:----------|-----:|---------:|-----------:|----------:||**20%, RM**| 50 | 1000 | **0.1991** |**111.303**||**40%, RM**| 50 | 1000 | **0.2098** |**100.315**||**20%, NM**| 5 | 1000 | *... | import scipy.io
tensor = scipy.io.loadmat('../datasets/NYC-data-set/tensor.mat')
dense_tensor = tensor['tensor']
rm_tensor = scipy.io.loadmat('../datasets/NYC-data-set/rm_tensor.mat')
rm_tensor = rm_tensor['rm_tensor']
nm_tensor = scipy.io.loadmat('../datasets/NYC-data-set/nm_tensor.mat')
nm_tensor = nm_tensor['nm_ten... | Iter: 100
Training MAPE: 0.511739
Training RMSE: 4.07981
Iter: 200
Training MAPE: 0.501094
Training RMSE: 4.0612
Iter: 300
Training MAPE: 0.504264
Training RMSE: 4.05578
Iter: 400
Training MAPE: 0.507211
Training RMSE: 4.05119
Iter: 500
Training MAPE: 0.509956
Training RMSE: 4.04623
Iter: 600
Training MAPE: 0.5104... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
**Experiment results** of missing data imputation using TF-ALS:| scenario |`rank`| `maxiter`| mape | rmse ||:----------|-----:|---------:|-----------:|----------:||**10%, RM**| 30 | 1000 | **0.5262** | **6.2444**||**30%, RM**| 30 | 1000 | **0.5488** | **6.8968**||**10%, NM**| 30 | 1000 | *... | import pandas as pd
dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0)
RM_mat = pd.read_csv('../datasets/Seattle-data-set/RM_mat.csv', index_col = 0)
dense_mat = dense_mat.values
RM_mat = RM_mat.values
dense_tensor = dense_mat.reshape([dense_mat.shape[0], 28, 288])
RM_tensor = RM_mat.reshap... | Iter: 100
Training MAPE: 0.0996282
Training RMSE: 5.55963
Iter: 200
Training MAPE: 0.0992568
Training RMSE: 5.53825
Iter: 300
Training MAPE: 0.0986723
Training RMSE: 5.51806
Iter: 400
Training MAPE: 0.0967838
Training RMSE: 5.46447
Iter: 500
Training MAPE: 0.0962312
Training RMSE: 5.44762
Iter: 600
Training MAPE: ... | MIT | experiments/Imputation-TF-ALS.ipynb | shawnwang-tech/transdim |
Let's look at:Number of labels per image (histogram)Quality score per image for images with multiple labels (sigmoid?) | import csv
from itertools import islice
from collections import defaultdict
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torchvision
import numpy as np
CSV_PATH = 'wgangp_data.csv'
realness = {}
# real_votes = defaultdict(int)
# fake_votes = defaultdict(int)
total_votes = defaultdict(int)
cor... | _____no_output_____ | MIT | wgan_experiment/WGAN_experiment.ipynb | kolchinski/humanception-score |
Naive Bayes ClassifierPredicting positivty/negativity of movie reviews using Naive Bayes algorithm 1. Import DatasetLabels:* 0 : Negative review* 1 : Positive review | import pandas as pd
import warnings
warnings.filterwarnings('ignore')
reviews = pd.read_csv('ratings_train.txt', delimiter='\t')
reviews.head(10)
#divide between negative and positive reviews with more than 30 words in length
neg = reviews[(reviews.document.str.len() >= 30) & (reviews.label == 0)].sample(3000, random_... | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
2. Create Corpus | neg_corpus = set(neg_train.parsed_doc.sum())
pos_corpus = set(pos_train.parsed_doc.sum())
corpus = list((neg_corpus).union(pos_corpus))
print('corpus length : ', len(corpus))
corpus[:10] | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
3. Create Bag of Words | from collections import OrderedDict
neg_bow_vecs = []
for _, doc in neg.parsed_doc.items():
bow_vecs = OrderedDict()
for w in corpus:
if w in doc:
bow_vecs[w] = 1
else:
bow_vecs[w] = 0
neg_bow_vecs.append(bow_vecs)
pos_bow_vecs = []
for _, doc in pos.parsed_doc.items(... | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
4. Model Training $n$ is the dimension of each document, in other words, the length of corpus $$\large p(pos|doc) = \Large \frac{p(doc|pos) \cdot p(pos)}{p(doc)}$$$$\large p(neg|doc) = \Large \frac{p(doc|neg) \cdot p(neg)}{p(doc)}$$**Likelihood functions:** $p(word_{i}|pos) = \large \frac{\text{the number of positive ... | import numpy as np
corpus[:5]
list(neg_train.parsed_doc.items())[0]
#this counts how many times a word in corpus appeares in neg_train data
neg_words_likelihood_cnts = {}
for w in corpus:
cnt = 0
for _, doc in neg_train.parsed_doc.items():
if w in doc:
cnt += 1
neg_words_likelihood_cnts[... | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
5. Classifier* We represent each documents in terms of bag of words. If the size of Corpus is $n$, this means that each bag of word of document is $n-dimensional$* When there isn't a word, we use **Laclacian Smoothing** | test_data = pd.concat([neg_test, pos_test], axis=0)
test_data.head()
def predict(doc):
pos_prior, neg_prior = 1/2, 1/2 #because we have equal number of pos and neg training documents
# Posterior of pos
pos_prob = np.log(1)
for word in corpus:
if word in doc:
# the word is in the cur... | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
There are a total of 200 test documents, and of these 200 tests only 46 were different | 1 - sum(test_data.label ^ test_data.pred) / len(test_data) | _____no_output_____ | MIT | algorithm_exercise/semantic_analysis/semantic_analysis_naive_bayes_algorithm.ipynb | jbaeckn/learning_projects |
Auditing a dataframeIn this notebook, we shall demonstrate how to use `privacypanda` to _audit_ the privacy of your data. `privacypanda` provides a simple function which prints the names of any columns which break privacy. Currently, these are:- Addresses - E.g. "10 Downing Street"; "221b Baker St"; "EC2R 8AH"- Pho... | %load_ext watermark
%watermark -n -p pandas,privacypanda -g
import pandas as pd
import privacypanda as pp | _____no_output_____ | Apache-2.0 | examples/01_auditing_a_dataframe.ipynb | TTitcombe/PrivacyPanda |
--- Firstly, we need data | data = pd.DataFrame(
{
"user ID": [
1665,
1,
5287,
42,
],
"User email": [
"xxxxxxxxxxxxx",
"xxxxxxxx",
"I'm not giving you that",
"an_email@email.com",
],
"User address": [
... | _____no_output_____ | Apache-2.0 | examples/01_auditing_a_dataframe.ipynb | TTitcombe/PrivacyPanda |
You will notice two things about this dataframe:1. _Some_ of the data has already been anonymized, for example by replacing characters with "x"s. However, the person who collected this data has not been fastidious with its cleaning as there is still some raw, potentially problematic private information. As the dataset ... | report = pp.report_privacy(data)
print(report) | User address: ['address']
User email: ['email']
| Apache-2.0 | examples/01_auditing_a_dataframe.ipynb | TTitcombe/PrivacyPanda |
read datafiles- C-18 for language population- C-13 for particular age-range population from a state | c18=pd.read_excel('datasets/C-18.xlsx',skiprows=6,header=None,engine='openpyxl')
c13=pd.read_excel('datasets/C-13.xls',skiprows=7,header=None) | _____no_output_____ | MIT | Q8_asgn2.ipynb | sunil-dhaka/census-language-analysis |
particular age groups are- 5-9- 10-14- 15-19- 20-24- 25-29- 30-49- 50-69- 70+- Age not stated obtain useful data from C-13 and C-18 for age-groups- first get particular state names for identifying specific states- get particular age-groups from C-18 file- make list of particular age group row/col for a particular sta... | # STATE_NAMES=[list(np.unique(c18.iloc[:,2].values))]
STATE_NAMES=[]
for state in c18.iloc[:,2].values:
if not (state in STATE_NAMES):
STATE_NAMES.append(state)
AGE_GROUPS=list(c18.iloc[1:10,4].values)
# although it is a bit of manual work but it is worth the efforts
AGE_GROUP_RANGES=[list(range(5,10)),list... | _____no_output_____ | MIT | Q8_asgn2.ipynb | sunil-dhaka/census-language-analysis |
age-analysis - get highest ratio age-group for a state and store it into csv file- above process can be repeated for all parts of the question | tri_list=[]
bi_list=[]
uni_list=[]
for i in range(36):
male_values=df[df['state-code']==i].sort_values(by='tri-male-ratio',ascending=False).iloc[0,[2,5]].values
female_values=df[df['state-code']==i].sort_values(by='tri-male-ratio',ascending=False).iloc[0,[2,6]].values
tri_item={
'state/ut':i,
... | _____no_output_____ | MIT | Q8_asgn2.ipynb | sunil-dhaka/census-language-analysis |
- convert into pandas dataframes and store into CSVs | tri_df=pd.DataFrame(tri_list)
bi_df=pd.DataFrame(bi_list)
uni_df=pd.DataFrame(uni_list)
tri_df.to_csv('outputs/age-gender-a.csv',index=False)
bi_df.to_csv('outputs/age-gender-b.csv',index=False)
uni_df.to_csv('outputs/age-gender-c.csv',index=False) | _____no_output_____ | MIT | Q8_asgn2.ipynb | sunil-dhaka/census-language-analysis |
observations- in almost all states(and all cases) both highest ratio female and male age-groups are same.- interestingly in only one language case for all states '5-9' age group dominates, and it is also quite intutive; since at that early stage in life children only speak their mother toung only | uni_df | _____no_output_____ | MIT | Q8_asgn2.ipynb | sunil-dhaka/census-language-analysis |
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"); | #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | _____no_output_____ | Apache-2.0 | site/en/guide/data.ipynb | zyberg2091/docs |
tf.data: Build TensorFlow input pipelines View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The `tf.data` API enables you to build complex input pipelines from simple,reusable pieces. For example, the pipeline for an image model might aggregatedata from fil... | import tensorflow as tf
import pathlib
import os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
np.set_printoptions(precision=4) | _____no_output_____ | Apache-2.0 | site/en/guide/data.ipynb | zyberg2091/docs |
Basic mechanicsTo create an input pipeline, you must start with a data *source*. For example,to construct a `Dataset` from data in memory, you can use`tf.data.Dataset.from_tensors()` or `tf.data.Dataset.from_tensor_slices()`.Alternatively, if your input data is stored in a file in the recommendedTFRecord format, you c... | dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1])
dataset
for elem in dataset:
print(elem.numpy()) | _____no_output_____ | Apache-2.0 | site/en/guide/data.ipynb | zyberg2091/docs |
Or by explicitly creating a Python iterator using `iter` and consuming itselements using `next`: | it = iter(dataset)
print(next(it).numpy()) | _____no_output_____ | Apache-2.0 | site/en/guide/data.ipynb | zyberg2091/docs |
Alternatively, dataset elements can be consumed using the `reduce`transformation, which reduces all elements to produce a single result. Thefollowing example illustrates how to use the `reduce` transformation to computethe sum of a dataset of integers. | print(dataset.reduce(0, lambda state, value: state + value).numpy()) | _____no_output_____ | Apache-2.0 | site/en/guide/data.ipynb | zyberg2091/docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.