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 |
|---|---|---|---|---|---|
pun wunnayook | pun_wunayook('กา')
pun_wunayook('กาไปไหน')
pun_wunayook('ขาวจังเลย')
for k in case_1:
print(k)
print(pun_wunayook(k))
print('===========') | WARNING:root:มะ with tone 0 not availabe (Dead word type), return normalize
WARNING:root:ดุ๊ด with tone 0 not availabe (Dead word type), return normalize
WARNING:root:removing taikoo from เป็น
WARNING:root:removing taikoo from เป็น
WARNING:root:removing taikoo from เป็น
WARNING:root:removing taikoo from เป็น
| MIT | notebooks/Example.ipynb | Theerit/kampuan_api |
load a model | # load json and create model
# load json and create model
def load_model(filename, weights):
with open(filename, 'r') as json: # cnn_transfer_augm
loaded_model_json = json.read()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights(weights)
... | _____no_output_____ | MIT | src/nn/transfer learning-plots.ipynb | voschezang/trash-image-classification |
running tests | # import sklearn.metrics.confusion_matrix
def evaluate(model):
cvscores = []
scores = model.evaluate(x_test, y_test, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores)))
# eval... | Confusion matrix, without normalization
[[ 3 2 5 85 5]
[ 0 76 19 2 3]
[ 0 13 72 9 6]
[ 0 0 2 95 3]
[ 0 36 22 5 37]]
| MIT | src/nn/transfer learning-plots.ipynb | voschezang/trash-image-classification |
T-teststtest for the TP per class, between the 2 networks | tp_c1 = c1.diagonal()
tp_c2 = c2.diagonal()
print(tp_c1)
print(tp_c2)
from utils import utils
utils.ttest(0.05, tp_c1, tp_c2)
utils.ttest(0.05, tp_c1.flatten(), tp_c2.flatten())
def select_not_diagonal(arr=[]):
a = arr.copy()
np.fill_diagonal(a, -1)
return [x for x in list(a.flatten()) if x > -1]
# everythi... | c1 - no aug
label, recall, precision
Paper : 1.0 0.483
Glass : 0.707 0.683
Plastic : 0.919 0.567
Metal : 0.647 0.917
Cardboard : 0.56 0.85
c2 - aug
label, recall, precision
Paper : 1.0 0.03
Glass : 0.598 0.76
Plastic : 0.6 0.72
Metal : 0.485 0.95
Cardboard : 0.685 0.37
| MIT | src/nn/transfer learning-plots.ipynb | voschezang/trash-image-classification |
Module 2: Playing with pytorch: linear regression | import matplotlib.pyplot as plt
%matplotlib inline
import torch
import numpy as np
torch.__version__ | _____no_output_____ | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Warm-up: Linear regression with numpy Our model is:$$y_t = 2x^1_t-3x^2_t+1, \quad t\in\{1,\dots,30\}$$Our task is given the 'observations' $(x_t,y_t)_{t\in\{1,\dots,30\}}$ to recover the weights $w^1=2, w^2=-3$ and the bias $b = 1$.In order to do so, we will solve the following optimization problem:$$\underset{w^1,w^2... | import numpy as np
from numpy.random import random
# generate random input data
x = random((30,2))
# generate labels corresponding to input data x
y = np.dot(x, [2., -3.]) + 1.
w_source = np.array([2., -3.])
b_source = np.array([1.])
print(x.shape)
print(y.shape)
print(np.array([2., -3.]).shape)
print(x[-5:])
print(... | _____no_output_____ | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
In vector form, we define:$$\hat{y}_t = {\bf w}^T{\bf x}_t+b$$and we want to minimize the loss given by:$$loss = \sum_t\underbrace{\left(\hat{y}_t-y_t \right)^2}_{loss_t}.$$To minimize the loss we first compute the gradient of each $loss_t$:\begin{eqnarray*}\frac{\partial{loss_t}}{\partial w^1} &=& 2x^1_t\left({\bf w}^... | # randomly initialize learnable weights and bias
w_init = random(2)
b_init = random(1)
w = w_init
b = b_init
print("initial values of the parameters:", w, b )
# our model forward pass
def forward(x):
return x.dot(w)+b
# Loss function
def loss(x, y):
y_pred = forward(x)
return (y_pred - y)**2
print("init... | _____no_output_____ | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Linear regression with tensors | dtype = torch.FloatTensor
print(dtype)
# dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU
x_t = torch.from_numpy(x).type(dtype)
y_t = torch.from_numpy(y).type(dtype).unsqueeze(1)
print(y.shape)
print(torch.from_numpy(y).type(dtype).shape)
print(y_t.shape) | (30,)
torch.Size([30])
torch.Size([30, 1])
| Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
This is an implementation of **(Batch) Gradient Descent** with tensors.Note that in the main loop, the functions loss_t and gradient_t are always called with the same inputs: they can easily be incorporated into the loop (we'll do that below). | w_init_t = torch.from_numpy(w_init).type(dtype)
b_init_t = torch.from_numpy(b_init).type(dtype)
w_t = w_init_t.clone()
w_t.unsqueeze_(1)
b_t = b_init_t.clone()
b_t.unsqueeze_(1)
print("initial values of the parameters:\n", w_t, b_t )
# our model forward pass
def forward_t(x):
return x.mm(w_t)+b_t
# Loss function
... | progress: epoch: 0 loss tensor(26.0386)
progress: epoch: 1 loss tensor(16.9264)
progress: epoch: 2 loss tensor(15.5589)
progress: epoch: 3 loss tensor(14.4637)
progress: epoch: 4 loss tensor(13.4501)
progress: epoch: 5 loss tensor(12.5081)
progress: epoch: 6 loss tensor(11.6326)
progress: epoch: 7 loss tensor(10.8187)
... | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Linear regression with Autograd | # Setting requires_grad=True indicates that we want to compute gradients with
# respect to these Tensors during the backward pass.
w_v = w_init_t.clone().unsqueeze(1)
w_v.requires_grad_(True)
b_v = b_init_t.clone().unsqueeze(1)
b_v.requires_grad_(True)
print("initial values of the parameters:", w_v.data, b_v.data ) | initial values of the parameters: tensor([[0.9705],
[0.0264]]) tensor([[0.6573]])
| Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
An implementation of **(Batch) Gradient Descent** without computing explicitly the gradient and using autograd instead. | for epoch in range(10):
y_pred = x_t.mm(w_v)+b_v
loss = (y_pred - y_t).pow(2).sum()
# Use autograd to compute the backward pass. This call will compute the
# gradient of loss with respect to all Variables with requires_grad=True.
# After this call w.grad and b.grad will be tensors holding the g... | progress: epoch: 0 loss 26.03858184814453
progress: epoch: 1 loss 16.926387786865234
progress: epoch: 2 loss 15.558940887451172
progress: epoch: 3 loss 14.46370792388916
progress: epoch: 4 loss 13.450118064880371
progress: epoch: 5 loss 12.508138656616211
progress: epoch: 6 loss 11.63258171081543
progress: epoch: 7 los... | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Linear regression with neural network An implementation of **(Batch) Gradient Descent** using the nn package. Here we have a super simple model with only one layer and no activation function! | # Use the nn package to define our model as a sequence of layers. nn.Sequential
# is a Module which contains other Modules, and applies them in sequence to
# produce its output. Each Linear Module computes output from input using a
# linear function, and holds internal Variables for its weight and bias.
model = torch.n... | progress: epoch: 0 loss 26.03858184814453
progress: epoch: 1 loss 16.926387786865234
progress: epoch: 2 loss 15.558940887451172
progress: epoch: 3 loss 14.46370792388916
progress: epoch: 4 loss 13.450118064880371
progress: epoch: 5 loss 12.508138656616211
progress: epoch: 6 loss 11.63258171081543
progress: epoch: 7 los... | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Last step, we use directly the optim package to update the weights and bias. | model = torch.nn.Sequential(
torch.nn.Linear(2, 1),
)
for m in model.children():
m.weight.data = w_init_t.clone().unsqueeze(0)
m.bias.data = b_init_t.clone()
loss_fn = torch.nn.MSELoss(reduction='sum')
model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
for epoch in range(1... | progress: epoch: 0 loss 385.95172119140625
progress: epoch: 0 loss tensor(385.9517, grad_fn=<MseLossBackward>)
progress: epoch: 1 loss 9597.4716796875
progress: epoch: 1 loss tensor(9597.4717, grad_fn=<MseLossBackward>)
progress: epoch: 2 loss 595541.875
progress: epoch: 2 loss tensor(595541.8750, grad_fn=<MseLossBackw... | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
RemarkThis problem can be solved in 3 lines of code! | xb_t = torch.cat((x_t,torch.ones(30).unsqueeze(1)),1)
# print(xb_t)
sol, _ =torch.lstsq(y_t,xb_t)
print(sol[:3]) | tensor([[ 2.0000],
[-3.0000],
[ 1.0000]])
| Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
Exercise: Play with the code Change the number of samples from 30 to 300. What happens? How to correct it? | x = random((300,2))
y = np.dot(x, [2., -3.]) + 1.
x_t = torch.from_numpy(x).type(dtype)
y_t = torch.from_numpy(y).type(dtype).unsqueeze(1)
model = torch.nn.Sequential(
torch.nn.Linear(2, 1),
)
for m in model.children():
m.weight.data = w_init_t.clone().unsqueeze(0)
m.bias.data = b_init_t.clone()
loss_fn =... | progress: epoch: 499 loss 0.1583678424358368
progress: epoch: 999 loss 0.03177538886666298
progress: epoch: 1499 loss 0.006897071376442909
progress: epoch: 1999 loss 0.0016702644061297178
progress: epoch: 2499 loss 0.00045764277456328273
progress: epoch: 2999 loss 0.0001400149194523692
progress: epoch: 3499 loss 4.6387... | Apache-2.0 | Module2/02b_linear_reg.ipynb | GenBill/notebooks |
GHCN V2 Temperatures ANOM (C) CR 1200KM 1880-presentGLOBAL Temperature Anomalies in .01 C base period: 1951-1980http://climatecode.org/ | import os
import git
if not os.path.exists('ccc-gistemp'):
git.Git().clone('https://github.com/ClimateCodeFoundation/ccc-gistemp.git')
if not os.path.exists('madqc'):
git.Git().clone('https://github.com/ClimateCodeFoundation/madqc.git') | _____no_output_____ | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
It seems thathttp://data.giss.nasa.gov/gistemp/sources_v3/GISTEMPv3_sources.tar.gzand http://data.giss.nasa.gov/pub/gistemp/SBBX.ERSST.gzare down, so let's use a local copy instead. | !mkdir -p ccc-gistemp/input
!cp data/GISTEMPv3_sources.tar.gz data/SBBX.ERSST.gz ccc-gistemp/input
%cd ccc-gistemp/ | /home/filipe/Dropbox/Meetings/2018-CicloPalestrasComputacaoCientifica/notebooks/ccc-gistemp
| CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
We don't really need `pypy` for the fetch phase, but the code is Python 2 and the notebook is Python 3, so this is just a lazy way to call py2k code from a py3k notebook ;-pPS: we are also using the International Surface Temperature Initiative data (ISTI). | !pypy tool/fetch.py isti | input/isti.v1.tar.gz already exists.
... input/isti.merged.inv already exists.
... input/isti.merged.dat already exists.
| CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
QC the ISTI data. | !../madqc/mad.py --progress input/isti.merged.dat | 100% ZIXLT831324 TAVG 1960 180
| CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
We need to copy the ISTI data into the `input` directory. | !cp isti.merged.qc.dat input/isti.merged.qc.dat
!cp input/isti.merged.inv input/isti.merged.qc.inv | _____no_output_____ | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
Here is where `pypy` is really needed, this step takes ~35 minutes on valina `python` but only ~100 seconds on `pypy`. | !pypy tool/run.py -p 'data_sources=isti.merged.qc.dat;element=TAVG' -s 0-1,3-5 | input/ghcnm.tavg.latest.qca.tar.gz already exists.
... input/ghcnm.tavg.qca.dat already exists.
input/GISTEMPv3_sources.tar.gz already exists.
... input/oisstv2_mod4.clim.gz already exists.
... input/sumofday.tbl already exists.
... input/v3.inv already exists.
... input/ushcn3.tbl already exists.
... input... | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
Python `gistemp` saves the results in the same format as the Fortran program but it ships with `gistemp2csv.py` to make it easier to read the data with `pandas`. | !pypy tool/gistemp2csv.py result/*.txt
import pandas as pd
df = pd.read_csv(
'result/landGLB.Ts.GHCN.CL.PA.csv',
skiprows=3,
index_col=0,
na_values=('*****', '****'),
) | _____no_output_____ | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
Let's use `sklearn` to compute the full trend... | from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
reg0 = linear_model.LinearRegression()
series0 = df['J-D'].dropna()
y = series0.values
X = series0.index.values[:, None]
reg0.fit(X, y)
y_pred0 = reg0.predict(X)
R2_0 = mean_squared_error(y, y_pred0)
var0 = r2_score(y, y_pred0... | _____no_output_____ | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
and the past 30 years trend. | reg1 = linear_model.LinearRegression()
series1 = df['J-D'].dropna().iloc[-30:]
y = series1.values
X = series1.index.values[:, None]
reg1.fit(X, y)
y_pred1 = reg1.predict(X)
R2_1 = mean_squared_error(y[-30:], y_pred1)
var1 = r2_score(y[-30:], y_pred1)
%matplotlib inline
ax = df.plot.line(y='J-D', figsize=(9, 9), legen... | _____no_output_____ | CC0-1.0 | notebooks/gistemp.ipynb | ocefpaf/bioinfo |
Inheriting from Unit Abstract attributes and methods  **A Unit subclass has class attributes that dictate how an instance is initialized:** * `_BM` : dict[str, float] Bare module factors for each purchase cost item.* `_units` : [dict] Units of measure for the `design_results` ... | import biosteam as bst
from math import ceil
class Boiler(bst.Unit):
"""
Create a Boiler object that partially boils the feed.
Parameters
----------
ins : stream
Inlet fluid.
outs : stream sequence
* [0] vapor product
* [1] liquid product
V : float
Molar... | _____no_output_____ | MIT | docs/tutorial/Inheriting_from_Unit.ipynb | sarangbhagwat/biosteam |
Simulation test | import biosteam as bst
bst.settings.set_thermo(['Water'])
water = bst.Stream('water', Water=300)
B1 = Boiler('B1', ins=water, outs=('gas', 'liq'),
V=0.5, P=101325)
B1.diagram()
B1.show()
B1.simulate()
B1.show()
B1.results() | _____no_output_____ | MIT | docs/tutorial/Inheriting_from_Unit.ipynb | sarangbhagwat/biosteam |
Graphviz attributes All [graphviz](https://graphviz.readthedocs.io/en/stable/manual.html) attributes for generating a diagram are stored in `_graphics` as a Graphics object. One Graphics object is generated for each Unit subclass: | graphics = Boiler._graphics
edge_in = graphics.edge_in
edge_out = graphics.edge_out
node = graphics.node
# Attributes correspond to each inlet stream respectively
# For example: Attributes for B1.ins[0] would correspond to edge_in[0]
edge_in
# Attributes correspond to each outlet stream respectively
# For example: Att... | _____no_output_____ | MIT | docs/tutorial/Inheriting_from_Unit.ipynb | sarangbhagwat/biosteam |
These attributes can be changed to the user's liking: | edge_out[0]['tailport'] = 'n'
edge_out[1]['tailport'] = 's'
node['width'] = '1'
node['height'] = '1.2'
B1.diagram() | _____no_output_____ | MIT | docs/tutorial/Inheriting_from_Unit.ipynb | sarangbhagwat/biosteam |
It is also possible to dynamically adjust node and edge attributes by setting the `tailor_node_to_unit` attribute: | def tailor_node_to_unit(node, unit):
feed = unit.ins[0]
if not feed.F_mol:
node['name'] += '\n-empty-'
graphics.tailor_node_to_unit = tailor_node_to_unit
B1.diagram()
B1.ins[0].empty()
B1.diagram() | _____no_output_____ | MIT | docs/tutorial/Inheriting_from_Unit.ipynb | sarangbhagwat/biosteam |
Altitude | q = 0.001
A = np.array([[1.0, 0.1, 0.005], [0, 1.0, 0.1], [0, 0, 1]])
H = np.array([[1.0, 0.0, 0.0],[ 0.0, 0.0, 1.0]])
P = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
# R = np.array([[0.5, 0.0], [0.0, 0.0012]])
# Q = np.array([[q, 0.0, 0.0], [0.0, q, 0.0], [0.0, 0.0, q]])
I = np.identity(3)
x_hat = np... | _____no_output_____ | MIT | Src/Notebooks/oprimizeValues.ipynb | nakujaproject/MPUdata |
import os
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
!pip install tensorflow-addons
import tensorflow_addons as tfa
from sklearn.model_selection import KFold, train_test_split
!git clone https://github.com/naufalhisyam/TurbidityPrediction-thesis.git
os... | _____no_output_____ | MIT | ResNet50_CV.ipynb | naufalhisyam/TurbidityPrediction-thesis | |
Copyright 2019 The TensorFlow Authors. | #@title Licensed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Lab 04a: Dogs vs Cats Image Classification Without Image Augmentation Run in Google Colab View source on GitHub In this tutorial, we will discuss how to classify images into pictures of cats or pictures of dogs. We'll build an image classifier using `tf.keras.Sequential` model and load data using `tf.ke... | import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
import matplotlib.pyplot as plt
import numpy as np
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR) | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Data Loading To build our image classifier, we begin by downloading the dataset. The dataset we are using is a filtered version of Dogs vs. Cats dataset from Kaggle (ultimately, this dataset is provided by Microsoft Research).In previous Colabs, we've used TensorFlow Datasets, which is a very easy and convenient way t... | _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
zip_dir = tf.keras.utils.get_file('cats_and_dogs_filterted.zip', origin=_URL, extract=True) | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
The dataset we have downloaded has the following directory structure.cats_and_dogs_filtered|__ train |______ cats: [cat.0.jpg, cat.1.jpg, cat.2.jpg ...] |______ dogs: [dog.0.jpg, dog.1.jpg, dog.2.jpg ...]|__ validation |______ cats: [cat.2000.jpg, cat.2001.jpg, cat.2002.jpg ...] |______ dogs: [dog.2000.jpg,... | zip_dir_base = os.path.dirname(zip_dir)
!find $zip_dir_base -type d -print | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
We'll now assign variables with the proper file path for the training and validation sets. | base_dir = os.path.join(os.path.dirname(zip_dir), 'cats_and_dogs_filtered')
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
train_cats_dir = os.path.join(train_dir, 'cats') # directory with our training cat pictures
train_dogs_dir = os.path.join(train_dir, 'dogs') # ... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Understanding our data Let's look at how many cats and dogs images we have in our training and validation directory | num_cats_tr = len(os.listdir(train_cats_dir))
num_dogs_tr = len(os.listdir(train_dogs_dir))
num_cats_val = len(os.listdir(validation_cats_dir))
num_dogs_val = len(os.listdir(validation_dogs_dir))
total_train = num_cats_tr + num_dogs_tr
total_val = num_cats_val + num_dogs_val
print('total training cat images:', num_ca... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Setting Model Parameters For convenience, we'll set up variables that will be used later while pre-processing our dataset and training our network. | BATCH_SIZE = 100 # Number of training examples to process before updating our models variables
IMG_SHAPE = 150 # Our training data consists of images with width of 150 pixels and height of 150 pixels | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Data Preparation Images must be formatted into appropriately pre-processed floating point tensors before being fed into the network. The steps involved in preparing these images are:1. Read images from the disk2. Decode contents of these images and convert it into proper grid format as per their RGB content3. Convert... | train_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our training data
validation_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our validation data | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
After defining our generators for training and validation images, **flow_from_directory** method will load images from the disk, apply rescaling, and resize them using single line of code. | train_data_gen = train_image_generator.flow_from_directory(batch_size=BATCH_SIZE,
directory=train_dir,
shuffle=True,
target_size=(IMG_SHAPE,IMG... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Visualizing Training images We can visualize our training images by getting a batch of images from the training generator, and then plotting a few of them using `matplotlib`. | sample_training_images, _ = next(train_data_gen) | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
The `next` function returns a batch from the dataset. One batch is a tuple of (*many images*, *many labels*). For right now, we're discarding the labels because we just want to look at the images. | # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column.
def plotImages(images_arr):
fig, axes = plt.subplots(1, 5, figsize=(20,20))
axes = axes.flatten()
for img, ax in zip(images_arr, axes):
ax.imshow(img)
plt.tight_layout()
pl... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Model Creation Exercise 4.1 Define the modelThe model consists of four convolution blocks with a max pool layer in each of them. Then we have a fully connected layer with 512 units, with a `relu` activation function. The model will output class probabilities for two classes — dogs and cats — using `softmax`. The lis... | model = tf.keras.models.Sequential([
# TODO - Create the CNN model as specified above
]) | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Exercise 4.1 SolutionThe solution for the exercise can be found [here](https://colab.research.google.com/github/rses-dl-course/rses-dl-course.github.io/blob/master/notebooks/python/solutions/E4.1.ipynb) Exercise 4.2 Compile the modelAs usual, we will use the `adam` optimizer. Since we output a softmax categorization,... | # TODO - Compile the model | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Exercise 4.2 SolutionThe solution for the exercise can be found [here](https://colab.research.google.com/github/rses-dl-course/rses-dl-course.github.io/blob/master/notebooks/python/solutions/E4.2.ipynb) Model SummaryLet's look at all the layers of our network using **summary** method. | model.summary() | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Exercise 4.3 Train the model It's time we train our network.* Since we have a validation dataset, we can use this to evaluate our model as it trains by adding the `validation_data` parameter. * `validation_steps` can also be added if you'd like to use less than full validation set. | # TODO - Fit the model | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
Exercise 4.3 SolutionThe solution for the exercise can be found [here](https://colab.research.google.com/github/rses-dl-course/rses-dl-course.github.io/blob/master/notebooks/python/solutions/E4.3.ipynb) Visualizing results of the training We'll now visualize the results we get after training our network. | acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(EPOCHS)
plt.figure(figsize=(20, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label=... | _____no_output_____ | CC-BY-4.0 | notebooks/python/L04_C01_dogs_vs_cats_without_augmentation.ipynb | rses-dl-course/rses-dl-course.github.io |
CHANDAN KUMAR (BATCH 3)- GOOGLE COLAB / logistic regression & Rigid & Lasso Regression(Rahul Agnihotri(T.L)) DATASET [HEART ](https://drive.google.com/file/d/10dopwCjH4VE557tSynCcY3fV9OBowq9h/view?usp=sharing) Packages to load | import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import GridSearchCV
# for hiding warning
import warnings
warnings.filterwarnings('ignore') | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Input directory | heart_df = pd.read_csv(r'/content/heart.csv')
heart_df | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
About data set The "target" field refers to the presence of heart disease in the patient. It is integer valued 0 = no/less chance of heart attack and 1 = more chance of heart attackAttribute Information- 1) age- 2) sex- 3) chest pain type (4 values)- 4) resting blood pressure- 5) serum cholestoral in mg/dl- 6)fasting b... | heart_df.head()
heart_df.dtypes
heart_df.isnull().sum()
print('Shape : ',heart_df.shape)
print('Describe : ',heart_df.describe()) | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
EDA(Exploratory Data Analysis) | #import pandas_profiling as pp
#pp.ProfileReport(heart_df)
%matplotlib inline
from matplotlib import pyplot as plt
fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(10,5))
sns.countplot(heart_df.target)
fig,axes=plt.subplots(nrows=1,ncols=1,figsize=(15,10))
sns.distplot(heart_df['age'],hist=True,kde=True,rug=False,label='... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Creating and Predicting Learning Models | X= heart_df.drop(columns= ['target'])
y= heart_df['target'] | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Data normalization | from sklearn.preprocessing import MinMaxScaler
# Data normalization [0, 1]
transformer = MinMaxScaler()
transformer.fit(X)
X = transformer.transform(X)
X
from sklearn.model_selection import train_test_split
x_test,x_train,y_test,y_train = train_test_split(X,y,test_size = 0.2,random_state = 123)
from sklearn.linear_mod... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Confusion_matrix - conf_mat=multiclass,- colorbar=True,- show_absolute=False,- show_normed=True,- class_names=class_names | from sklearn.metrics import confusion_matrix, classification_report
from mlxtend.plotting import plot_confusion_matrix
cm=confusion_matrix(y_test, y_pred)
fig, ax = plot_confusion_matrix(conf_mat=cm)
plt.rcParams['font.size'] = 40
#(conf_mat=multiclass,colorbar=True, show_absolute=False, show_normed=True, class_names=... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
L1 and L2 are regularization parameters.They're used to avoid overfiting.Both L1 and L2 regularization prevents overfitting by shrinking (imposing a penalty) on the coefficients.L1 is the first moment norm |x1-x2| (|w| for regularization case) that is simply the absolute dıstance between two points where L2 is second m... | heart_df.corr()
from sklearn.model_selection import GridSearchCV
LR= GridSearchCV(LR_model, tuned_parameters,cv=10)
LR.fit(x_train,y_train)
print(LR.best_params_)
y_prob = LR.predict_proba(x_test)[:,1] # This will give positive class prediction probabilities
y_pred = np.where(y_prob > 0.5, 1, 0) # This will thresho... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
**EXPERIMENTAL ZONE** LASSO AND RIDGE``` This is formatted as code``` | Training_Accuracy_Before = []
Testing_Accuracy_Before = []
Training_Accuracy_After = []
Testing_Accuracy_After = []
Models = ['Linear Regression', 'Lasso Regression', 'Ridge Regression']
alpha_space = np.logspace(-4, 0, 30) # Checking for alpha from .0001 to 1 and finding the best value for alpha
alpha_space
ridge_sc... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
**DANGER** **ZONE** | #list of alpha for tuning
params = {'alpha' : [0.001 , 0.001,0.01,0.05,
0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,.9,
1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,
10.0,20,30,40,50,100,500,1000]}
ridge = Ridge()
# cross validation
folds = 5
model_cv = GridSearchCV(estimator... | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Insights: | alpha = 4
ridge = Ridge(alpha=alpha)
ridge.fit(x_train,y_train)
ridge.coef_ | _____no_output_____ | Apache-2.0 | GAN Model/Logistic_regression_Chandan_kumar.ipynb | MrTONYCHAN/xyz |
Selected Economic Characteristics: Employment Status from the American Community Survey**[Work in progress]**This notebook downloads [selected economic characteristics (DP03)](https://data.census.gov/cedsci/table?tid=ACSDP5Y2018.DP03) from the American Community Survey 2018 5-Year Data.Data source: [American Community... | import os
import pandas as pd
from pathlib import Path
import time
pd.options.display.max_rows = None # display all rows
pd.options.display.max_columns = None # display all columsns
NEO4J_IMPORT = Path(os.getenv('NEO4J_IMPORT'))
print(NEO4J_IMPORT) | /Users/peter/Library/Application Support/com.Neo4j.Relate/data/dbmss/dbms-8bf637fc-0d20-4d9f-9c6f-f7e72e92a4da/import
| MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Download selected variables* [Selected economic characteristics for US](https://data.census.gov/cedsci/table?tid=ACSDP5Y2018.DP03)* [List of variables as HTML](https://api.census.gov/data/2018/acs/acs5/profile/groups/DP03.html) or [JSON](https://api.census.gov/data/2018/acs/acs5/profile/groups/DP03/)* [Description of ... | variables = {# EMPLOYMENT STATUS
'DP03_0001E': 'population16YearsAndOver',
'DP03_0002E': 'population16YearsAndOverInLaborForce',
'DP03_0002PE': 'population16YearsAndOverInLaborForcePct',
'DP03_0003E': 'population16YearsAndOverInCivilianLaborForce',
'DP03_... | 9
| MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Download county-level data using US Census API | url_county = f'https://api.census.gov/data/2018/acs/acs5/profile?get={fields}&for=county:*'
df = pd.read_json(url_county, dtype='str')
df.fillna('', inplace=True)
df.head() | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Add column names | df = df[1:].copy() # skip first row of labels
columns = list(variables.values())
columns.append('stateFips')
columns.append('countyFips')
df.columns = columns | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Remove Puerto Rico (stateFips = 72) to limit data to US StatesTODO handle data for Puerto Rico (GeoNames represents Puerto Rico as a country) | df.query("stateFips != '72'", inplace=True) | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Save list of state fips (required later to get tract data by state) | stateFips = list(df['stateFips'].unique())
stateFips.sort()
print(stateFips)
df.head()
# Example data
df[(df['stateFips'] == '06') & (df['countyFips'] == '073')]
df['source'] = 'American Community Survey 5 year'
df['aggregationLevel'] = 'Admin2' | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Save data | df.to_csv(NEO4J_IMPORT / "03a-USCensusDP03EmploymentAdmin2.csv", index=False) | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Download zip-level data using US Census API | url_zip = f'https://api.census.gov/data/2018/acs/acs5/profile?get={fields}&for=zip%20code%20tabulation%20area:*'
df = pd.read_json(url_zip, dtype='str')
df.fillna('', inplace=True)
df.head() | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Add column names | df = df[1:].copy() # skip first row
columns = list(variables.values())
columns.append('stateFips')
columns.append('postalCode')
df.columns = columns
df.head()
# Example data
df.query("postalCode == '90210'")
df['source'] = 'American Community Survey 5 year'
df['aggregationLevel'] = 'PostalCode' | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Save data | df.to_csv(NEO4J_IMPORT / "03a-USCensusDP03EmploymentZip.csv", index=False) | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Download tract-level data using US Census APITract-level data are only available by state, so we need to loop over all states. | def get_tract_data(state):
url_tract = f'https://api.census.gov/data/2018/acs/acs5/profile?get={fields}&for=tract:*&in=state:{state}'
df = pd.read_json(url_tract, dtype='str')
time.sleep(1)
# skip first row of labels
df = df[1:].copy()
# Add column names
columns = list(variables.values())
... | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Save data | df.to_csv(NEO4J_IMPORT / "03a-USCensusDP03EmploymentTract.csv", index=False)
df.shape | _____no_output_____ | MIT | notebooks/dataprep/03a-USCensusDP03Employment.ipynb | yogeshchaudhari/covid-19-community |
Settings | %env TF_KERAS = 1
import os
sep_local = os.path.sep
import sys
# sys.path.append('..' + sep_local + '..' + sep_local +'..' + sep_local + '..' + sep_local + '..'+ sep_local + '..') # For Windows import
# os.chdir('..' + sep_local + '..' + sep_local +'..' + sep_local + '..' + sep_local + '..'+ sep_local + '..') # For Lin... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Dataset loading | dataset_name='atari_pacman'
images_dir = IMG_DIR
# images_dir = '/home/azeghost/datasets/.mspacman/atari_v1/screens/mspacman' #Linux
#images_dir = 'C:\\projects\\pokemon\DS06\\'
validation_percentage = 25
valid_format = 'png'
from training.generators.file_image_generator import create_image_lists, get_generators
imgs_l... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Model's Layers definition | # tdDense = lambda **kwds: tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(**kwds))
# enc_lays = [tdDense(units=intermediate_dim//2, activation='relu'),
# tdDense(units=intermediate_dim//2, activation='relu'),
# tf.keras.layers.Flatten(),
# tf.keras.layers.Dense(units=latents_d... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Model definition | model_name = dataset_name+'AE_Dense_reconst_ell'
#windows
#experiments_dir='..' + sep_local + '..' + sep_local +'..' + sep_local + '..' + sep_local + '..'+sep_local+'experiments'+sep_local + model_name
#linux
experiments_dir=os.getcwd()+ sep_local +'experiments'+sep_local + model_name
from training.autoencoding_basi... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Callbacks | from training.callbacks.sample_generation import SampleGeneration
from training.callbacks.save_model import ModelSaver
es = tf.keras.callbacks.EarlyStopping(
monitor='loss',
min_delta=1e-12,
patience=12,
verbose=1,
restore_best_weights=False
)
ms = ModelSaver(filepath=_restore)
csv_dir = os.path... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Model Training | ae.fit(
x=train_ds,
input_kw=None,
steps_per_epoch=10,
epochs=10,
verbose=2,
callbacks=[ es, ms, csv_log, sg],
workers=-1,
use_multiprocessing=True,
validation_data=test_ds,
validation_steps=10
) | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Model Evaluation inception_score | from evaluation.generativity_metrics.inception_metrics import inception_score
is_mean, is_sigma = inception_score(ae, tolerance_threshold=1e-6, max_iteration=200)
print(f'inception_score mean: {is_mean}, sigma: {is_sigma}') | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Frechet_inception_distance | from evaluation.generativity_metrics.inception_metrics import frechet_inception_distance
fis_score = frechet_inception_distance(ae, training_generator, tolerance_threshold=1e-6, max_iteration=10, batch_size=32)
print(f'frechet inception distance: {fis_score}') | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
perceptual_path_length_score | from evaluation.generativity_metrics.perceptual_path_length import perceptual_path_length_score
ppl_mean_score = perceptual_path_length_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200, batch_size=32)
print(f'perceptual path length score: {ppl_mean_score}') | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
precision score | from evaluation.generativity_metrics.precision_recall import precision_score
_precision_score = precision_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'precision score: {_precision_score}') | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
recall score | from evaluation.generativity_metrics.precision_recall import recall_score
_recall_score = recall_score(ae, training_generator, tolerance_threshold=1e-6, max_iteration=200)
print(f'recall score: {_recall_score}') | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Image Generation image reconstruction Training dataset | %load_ext autoreload
%autoreload 2
from training.generators.image_generation_testing import reconstruct_from_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'reconstruct_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
reconstruct_from_a_... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
with Randomness | from training.generators.image_generation_testing import generate_images_like_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'generate_training_images_like_a_batch_dir')
create_if_not_exist(save_dir)
generate_images_like_a_batch(ae, training_generator, ... | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Complete Randomness | from training.generators.image_generation_testing import generate_images_randomly
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'random_synthetic_dir')
create_if_not_exist(save_dir)
generate_images_randomly(ae, testing_generator, save_dir) | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
Stacked inputs outputs and predictions | from training.generators.image_generation_testing import predict_from_a_batch
from utils.data_and_files.file_utils import create_if_not_exist
save_dir = os.path.join(experiments_dir, 'predictions')
create_if_not_exist(save_dir)
predict_from_a_batch(ae, testing_generator, save_dir) | _____no_output_____ | MIT | notebooks/Atari/Pacman_Colab/Transformative/Dense/AE/pacman_AE_Dense_reconst_ellwlb_episode_flat_working.ipynb | azeghost/Generative_Models |
DS106 Machine Learning : Lesson Nine Companion Notebook Table of Contents * [Table of Contents](DS106L9_toc) * [Page 1 - Introduction](DS106L9_page_1) * [Page 2 - What are Bayesian Statistics?](DS106L9_page_2) * [Page 3 - Bayes Theorem](DS106L9_page_3) * [Page 4 - Parts of Bayes Theorem](DS106L9_page_4) ... | from IPython.display import VimeoVideo
# Tutorial Video Name: Bayesian Networks
VimeoVideo('388131444', width=720, height=480) | _____no_output_____ | MIT | Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/05_MACHINE_LEARNING/ML/ML04.ipynb | okara83/Becoming-a-Data-Scientist |
Dimensionality Reduction | from sklearn.decomposition import PCA | _____no_output_____ | MIT | Practical-06-2. Exploration.ipynb | kingsgeocomp/applied_gsa |
Principal Components Analysis | o_dir = os.path.join('outputs','pca')
if os.path.isdir(o_dir) is not True:
print("Creating '{0}' directory.".format(o_dir))
os.mkdir(o_dir)
pca = PCA() # Use all Principal Components
pca.fit(scdf) # Train model on all data
pcdf = pd.DataFrame(pca.transfo... | _____no_output_____ | MIT | Practical-06-2. Exploration.ipynb | kingsgeocomp/applied_gsa |
What Have We Done? | sns.set_style('white')
sns.jointplot(data=scores, x=0, y=1, kind='hex', height=8, ratio=8) | _____no_output_____ | MIT | Practical-06-2. Exploration.ipynb | kingsgeocomp/applied_gsa |
Create an Output Directory and Load the Data | o_dir = os.path.join('outputs','clusters-pca')
if os.path.isdir(o_dir) is not True:
print("Creating '{0}' directory.".format(o_dir))
os.mkdir(o_dir)
score_df = pd.read_csv(os.path.join('outputs','pca','Scores.csv.gz'))
score_df.rename(columns={'Unnamed: 0':'lsoacd'}, inplace=True)
score_df.set_index('lsoacd', i... | _____no_output_____ | MIT | Practical-06-2. Exploration.ipynb | kingsgeocomp/applied_gsa |
Rescale the Loaded DataWe need this so that differences in the component scores don't cause the clustering algorithms to focus only on the 1st component. | scaler = preprocessing.MinMaxScaler()
df[df.columns] = scaler.fit_transform(df[df.columns])
df.describe()
df.sample(3, random_state=42) | _____no_output_____ | MIT | Practical-06-2. Exploration.ipynb | kingsgeocomp/applied_gsa |
The model$u(c) = log(c)$ utility function $y = 1$ Deterministic income $p(r = 0.02) = 0.5$ $p(r = -0.02) = 0.5$ value iteration | # infinite horizon MDP problem
%pylab inline
import numpy as np
from scipy.optimize import minimize
def u(c):
return np.log(c)
# discounting factor
beta = 0.95
# wealth level
w_low = 0
w_high = 10
# interest rate
r = 0.02
# deterministic income
y = 1
# good state and bad state economy with equal probability 0.5
#... | _____no_output_____ | MIT | 20210115/.ipynb_checkpoints/policyGradient -checkpoint.ipynb | dongxulee/lifeCycle |
policy gradientAssume the policy form $\theta = (a,b,c, \sigma)$, then $\pi_\theta$ ~ $N(log(ax+b)+c, \sigma)$Assume the initial value $a = 1$, $b = 1$, $c = 1$, $\sigma = 1$ $$\theta_{k+1} = \theta_{k} + \alpha \nabla_\theta V(\pi_\theta)|\theta_k$$ | # simulation step T = 100
T = 10
def mu(theta, w):
return np.log(theta[0] * w + theta[1]) + theta[2]
def simSinglePath(theta):
wPath = np.zeros(T)
aPath = np.zeros(T)
rPath = np.zeros(T)
w = np.random.choice(ws)
for t in range(T):
c = np.random.normal(mu(theta, w), theta[3])
wh... | _____no_output_____ | MIT | 20210115/.ipynb_checkpoints/policyGradient -checkpoint.ipynb | dongxulee/lifeCycle |
Copyright 2019 The TensorFlow Authors. | #@title Licensed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
TFRecord and tf.Example View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook To read data efficiently it can be helpful to serialize your data and store it in a set of files (100-200MB each) that can each be read linearly. This is especially true if the data is... | !pip install tf-nightly
import tensorflow as tf
import numpy as np
import IPython.display as display | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
`tf.Example` Data types for `tf.Example` Fundamentally, a `tf.Example` is a `{"string": tf.train.Feature}` mapping.The `tf.train.Feature` message type can accept one of the following three types (See the [`.proto` file](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/example/feature.proto) for re... | # The following functions can be used to convert a value to a type compatible
# with tf.Example.
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
return tf.train... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Note: To stay simple, this example only uses scalar inputs. The simplest way to handle non-scalar features is to use `tf.serialize_tensor` to convert tensors to binary-strings. Strings are scalars in tensorflow. Use `tf.parse_tensor` to convert the binary-string back to a tensor. Below are some examples of how these fu... | print(_bytes_feature(b'test_string'))
print(_bytes_feature(u'test_bytes'.encode('utf-8')))
print(_float_feature(np.exp(1)))
print(_int64_feature(True))
print(_int64_feature(1)) | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
All proto messages can be serialized to a binary-string using the `.SerializeToString` method: | feature = _float_feature(np.exp(1))
feature.SerializeToString() | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Creating a `tf.Example` message Suppose you want to create a `tf.Example` message from existing data. In practice, the dataset may come from anywhere, but the procedure of creating the `tf.Example` message from a single observation will be the same:1. Within each observation, each value needs to be converted to a `tf.... | # The number of observations in the dataset.
n_observations = int(1e4)
# Boolean feature, encoded as False or True.
feature0 = np.random.choice([False, True], n_observations)
# Integer feature, random from 0 to 4.
feature1 = np.random.randint(0, 5, n_observations)
# String feature
strings = np.array([b'cat', b'dog',... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Each of these features can be coerced into a `tf.Example`-compatible type using one of `_bytes_feature`, `_float_feature`, `_int64_feature`. You can then create a `tf.Example` message from these encoded features: | def serialize_example(feature0, feature1, feature2, feature3):
"""
Creates a tf.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.Example-compatible
# data type.
feature = {
'feature0': _int64_feature(feature0),
'feature1': _int64_feature... | _____no_output_____ | Apache-2.0 | site/en/tutorials/load_data/tfrecord.ipynb | blueyi/docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.