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 |
|---|---|---|---|---|---|
Train and test on GT_split 2 | from google.colab import drive
import pickle
drive.mount('/content/drive')
DATA_PATH1 = "/content/drive/My Drive/Colab Notebooks/Data"
infile = open(DATA_PATH1+'/GT_train_2.pkl','rb')
Train = pickle.load(infile)
DATA_PATH2 = "/content/drive/My Drive/Colab Notebooks/Data"
testfile= open(DATA_PATH2+'/GT_test_2.pkl','rb')... | _____no_output_____ | MIT | DD-Net/jhmdb_1D_lite.ipynb | anhquannguyen21/Skeleton-Action-Recognition |
Train and test on GT_split 3 | from google.colab import drive
import pickle
drive.mount('/content/drive')
DATA_PATH1 = "/content/drive/My Drive/Colab Notebooks/Data"
infile = open(DATA_PATH1+'/GT_train_3.pkl','rb')
Train = pickle.load(infile)
DATA_PATH2 = "/content/drive/My Drive/Colab Notebooks/Data"
testfile= open(DATA_PATH2+'/GT_test_3.pkl','rb')... | _____no_output_____ | MIT | DD-Net/jhmdb_1D_lite.ipynb | anhquannguyen21/Skeleton-Action-Recognition |
Calculate average | (0.63+0.66+0.68)/3
| _____no_output_____ | MIT | DD-Net/jhmdb_1D_lite.ipynb | anhquannguyen21/Skeleton-Action-Recognition |
Face Recognition & Verification for Person IdentificationInspired by Coursera deeplearning.ai's assignment of programming a face recognition for happy house, I wanted to give it a try implementing a face recognition system by using face detection library(https://github.com/ageitgey/face_recognition) and face_recogniti... | #import the necessary packages
from keras.models import Sequential
from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling2D, AveragePooling2D
from keras.layers.mer... | _____no_output_____ | MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Image to Embedding`face_img_to_encoding(image_path, model)` : basically runs the forward propagation of the model on the specified image. | def face_img_to_encoding(image_path, model):
"""
returns the embedding vector of the specific image from the path
Arguments:
image_path -- Destination of the original image
model -- Inception model instance in Keras
Returns:
embeddings -- List containing embeddings of the people in... | _____no_output_____ | MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Create the Database | # Create a initial database for identifying people
database = {}
database["leonardo dicaprio"] = face_img_to_encoding("my_images/dicaprio.jpg", FRmodel)
database["brad pitt"] = face_img_to_encoding("my_images/bradPitt1.jpg", FRmodel)
database["matt damon"] = face_img_to_encoding("my_images/mattDamon.jpg", FRmodel)
data... | A face is located at pixel location Top: 142, Left: 82, Bottom: 409, Right: 349
[array([[ 1.78886820e-02, 5.65266944e-02, 2.81436834e-02,
-3.98353711e-02, -4.05346490e-02, 2.42677256e-02,
-1.41860060e-02, 1.34195894e-01, 1.05123438e-01,
8.81131622e-04, 1.01466812e-01, -8.59745964e-02,
... | MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Face VerificationFace Verification is a 1:1 matching problem given identity of a person program identifies if the picture of a person matches with identity- verify() function below implements simple face-verification functionality | def verify(image_path, identity, database, model):
"""
Function that verifies if the person on the "image_path" image is "identity".
Arguments:
image_path -- path to an image
identity -- string, name of the person.
database -- python dictionary mapping names of allowed people's names (strin... | _____no_output_____ | MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Let's see if we can verify Matt Damon | verify("my_images/dicaprio.jpg", "matt damon", database, FRmodel)
verify("my_images/mattDamon1.jpg", "matt damon", database, FRmodel) | A face is located at pixel location Top: 98, Left: 98, Bottom: 253, Right: 253
matt damon, you are verified
| MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Face RecognitionIdentifies the person withou needing to provide an identity. This is a 1:K matching problem. Steps:1. Compute the target encoding of the image from image_path2. Find the encoding from the database that has smallest distance with the target encoding. | def recognize(image_path, database, model):
"""
Implements face recognition by finding who is the person on the image_path image.
Arguments:
image_path -- path to an image
database -- database containing image encodings along with the name of the person on the image
model -- Inception model... | _____no_output_____ | MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Let's see if the database can recognize unseen picture of Matt Damon | recognize("my_images/mattDamon1.jpg", database, FRmodel) | A face is located at pixel location Top: 98, Left: 98, Bottom: 253, Right: 253
Not in the database.
Not in the database.
You're matt damon, the distance is 0.74256897
| MIT | Face_Rec_System.ipynb | zeynepCankara/Face-Recognition-Tensorflow |
Copyright 2018 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 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Text classification with movie reviews View on TensorFlow.org Run in Google Colab View source on GitHub This notebook classifies movie reviews as *positive* or *negative* using the text of the review. This is an example of *binary*—or two-class—classification, an important and widely applicable k... | # keras.datasets.imdb is broken in 1.13 and 1.14, by np 1.16.3
!pip install tf_nightly
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(tf.__version__) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Download the IMDB datasetThe IMDB dataset comes packaged with TensorFlow. It has already been preprocessed such that the reviews (sequences of words) have been converted to sequences of integers, where each integer represents a specific word in a dictionary.The following code downloads the IMDB dataset to your machine... | imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
The argument `num_words=10000` keeps the top 10,000 most frequently occurring words in the training data. The rare words are discarded to keep the size of the data manageable. Explore the dataLet's take a moment to understand the format of the data. The dataset comes preprocessed: each example is an array of integers ... | print("Training entries: {}, labels: {}".format(len(train_data), len(train_labels))) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
The text of reviews have been converted to integers, where each integer represents a specific word in a dictionary. Here's what the first review looks like: | print(train_data[0]) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Movie reviews may be different lengths. The below code shows the number of words in the first and second reviews. Since inputs to a neural network must be the same length, we'll need to resolve this later. | len(train_data[0]), len(train_data[1])
dir(imdb)
imdb.get_word_index? | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Convert the integers back to wordsIt may be useful to know how to convert integers back to text. Here, we'll create a helper function to query a dictionary object that contains the integer to string mapping: | # A dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# The first indices are reserved
word_index = {k:(v+3) for k,v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 # unknown
word_index["<UNUSED>"] = 3
reverse_word_index = dict([(value, k... | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Let's have a look at the propterties of the word_index dictionary | #imdb.load_data?
print(type(word_index))
print(len(word_index))
#print(word_index)
print(decode_review([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]))
print(decode_review([10003,1002,10001,10000])) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Now we can use the `decode_review` function to display the text for the first review: | decode_review(train_data[0]) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Prepare the dataThe reviews—the arrays of integers—must be converted to tensors before fed into the neural network. This conversion can be done a couple of ways:* Convert the arrays into vectors of 0s and 1s indicating word occurrence, similar to a one-hot encoding. For example, the sequence [3, 5] would become a 10,... | train_data = keras.preprocessing.sequence.pad_sequences(train_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
test_data = keras.preprocess... | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Let's look at the length of the examples now: | len(train_data[0]), len(train_data[1]) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
And inspect the (now padded) first review: | print(train_data[0]) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Build the modelThe neural network is created by stacking layers—this requires two main architectural decisions:* How many layers to use in the model?* How many *hidden units* to use for each layer?In this example, the input data consists of an array of word-indices. The labels to predict are either 0 or 1. Let's build... | # input shape is the vocabulary count used for the movie reviews (10,000 words)
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation=tf.nn.relu))
model.add(keras.layers.Dense(1, activ... | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
The layers are stacked sequentially to build the classifier:1. The first layer is an `Embedding` layer. This layer takes the integer-encoded vocabulary and looks up the embedding vector for each word-index. These vectors are learned as the model trains. The vectors add a dimension to the output array. The resulting dim... | model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['acc']) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Create a validation setWhen training, we want to check the accuracy of the model on data it hasn't seen before. Create a *validation set* by setting apart 10,000 examples from the original training data. (Why not use the testing set now? Our goal is to develop and tune our model using only the training data, then use ... | x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:] | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Train the modelTrain the model for 40 epochs in mini-batches of 512 samples. This is 40 iterations over all samples in the `x_train` and `y_train` tensors. While training, monitor the model's loss and accuracy on the 10,000 samples from the validation set: | history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Evaluate the modelAnd let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy. | results = model.evaluate(test_data, test_labels)
print(results) | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%. Create a graph of accuracy and loss over time`model.fit()` returns a `History` object that contains a dictionary with everything that happened during training: | history_dict = history.history
history_dict.keys() | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
There are four entries: one for each monitored metric during training and validation. We can use these to plot the training and validation loss for comparison, as well as the training and validation accuracy: | import matplotlib.pyplot as plt
acc = history_dict['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_lo... | _____no_output_____ | Apache-2.0 | bmcCompletedTutorials/tutorials/keras/basic_text_classification.ipynb | meisben/docs |
Fetching Hydrology DataWe have prepared shapefiles containing the USGS quarter quadrangles that have good coverage of forest stand delineations that we want to grab other data for. Mount Google Drive So we can access our files showing tile locations, and save the rasters we will generate from the elevation data. | from google.colab import drive
drive.mount('/content/drive', force_remount=True)
! sudo apt-get install -y libspatialindex-dev
! pip install geopandas rtree -q
import numpy as np
import geopandas as gpd
import os
import requests
from shapely.geometry import box, Polygon | _____no_output_____ | BSD-3-Clause | notebooks/01_Data_Fetching/06 - Hydro Features for Training Tiles.ipynb | valentina-s/stand_mapping |
The following function will retrieve the hydro data from The National Map's web service. | def nhd_from_tnm(nhd_layer,
bbox,
inSR=4326,
**kwargs):
"""Returns features from the National Hydrography Dataset Plus High
Resolution web service from The National Map.
Available layers are:
========= ======================
NHD Layer Descriptio... | _____no_output_____ | BSD-3-Clause | notebooks/01_Data_Fetching/06 - Hydro Features for Training Tiles.ipynb | valentina-s/stand_mapping |
Download Data for Training Tiles This function will loop through a GeoDataFrame, fetch the relevant data, and write data to disk in the appropriate format. | def fetch_hydro(gdf, state, overwrite=False):
epsg = gdf.crs.to_epsg()
print('Fetching hydro data for {:,d} tiles'.format(len(gdf)))
## loop through all the geometries in the geodataframe
for idx, row in gdf.iterrows():
xmin, ymin, xmax, ymax = row['geometry'].bounds
xmin, ymin = np.fl... | _____no_output_____ | BSD-3-Clause | notebooks/01_Data_Fetching/06 - Hydro Features for Training Tiles.ipynb | valentina-s/stand_mapping |
Fetch Hydro Layers for each tile | SHP_DIR = '/content/drive/Shared drives/stand_mapping/data/interim'
WA11_SHP = 'washington_utm11n_training_quads_epsg6340.shp'
WA10_SHP = 'washington_utm10n_training_quads_epsg6339.shp'
OR10_SHP = 'oregon_utm10n_training_quads_epsg6339.shp'
OR11_SHP = 'oregon_utm11n_training_quads_epsg6340.shp'
or10_gdf = gpd.read_fi... | Fetching hydro data for 524 tiles
0.........10.........20.........30.........40.........50.........60.........70.........80.........90.........
100.........110.........120.........130.........140.........150.........160.........170.........180.........190.........
200.........210.........220.........230.........240...... | BSD-3-Clause | notebooks/01_Data_Fetching/06 - Hydro Features for Training Tiles.ipynb | valentina-s/stand_mapping |
[Table of Contents](http://nbviewer.ipython.org/github/rlabbe/Kalman-and-Bayesian-Filters-in-Python/blob/master/table_of_contents.ipynb) | \appendix | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
Installation | #format the book
%matplotlib inline
from __future__ import division, print_function
from book_format import load_style
load_style() | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
This book is written in Jupyter Notebook, a browser based interactive Python environment that mixes Python, text, and math. I choose it because of the interactive features - I found Kalman filtering nearly impossible to learn until I started working in an interactive environment. It is difficult to form an intuition ab... | print(3+7.2) | 10.2
| CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
If you have this open in Jupyter Notebook now, go ahead and modify that code by changing the expression inside the print statement and pressing CTRL+ENTER. The output should be changed to reflect what you typed in the code cell. SymPy SymPy is a Python package for performing symbolic mathematics. The full scope of its... | import sympy
sympy.init_printing(use_latex='mathjax')
phi, x = sympy.symbols('\phi, x')
phi | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
Notice how it prints the symbol `phi` using LaTeX. Now let's do some math. What is the derivative of $\sqrt{\phi}$? | sympy.diff('sqrt(phi)') | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
We can factor equations | sympy.factor(phi**3 -phi**2 + phi - 1) | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
and we can expand them. | ((phi+1)*(phi-4)).expand() | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
You can evauate an equation for specific values of its variables: | w =x**2 -3*x +4
print(w.subs(x, 4))
print(w.subs(x, 12)) | 8
112
| CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
You can also use strings for equations that use symbols that you have not defined: | x = sympy.expand('(t+1)*2')
x | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
Now let's use SymPy to compute the Jacobian of a matrix. Given the function$$h=\sqrt{(x^2 + z^2)}$$find the Jacobian with respect to x, y, and z. | x, y, z = sympy.symbols('x y z')
H = sympy.Matrix([sympy.sqrt(x**2 + z**2)])
state = sympy.Matrix([x, y, z])
H.jacobian(state) | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
Now let's compute the discrete process noise matrix $\mathbf Q$ given the continuous process noise matrix $$\mathbf Q = \Phi_s \begin{bmatrix}0&0&0\\0&0&0\\0&0&1\end{bmatrix}$$The integral is $$\mathbf Q = \int_0^{\Delta t} \mathbf F(t)\mathbf Q\mathbf F^T(t)\, dt$$where $$\mathbf F(\Delta t) = \begin{bmatrix}1 & \Delt... | dt = sympy.symbols('\Delta{t}')
F_k = sympy.Matrix([[1, dt, dt**2/2],
[0, 1, dt],
[0, 0, 1]])
Q = sympy.Matrix([[0,0,0],
[0,0,0],
[0,0,1]])
sympy.integrate(F_k*Q*F_k.T,(dt, 0, dt)) | _____no_output_____ | CC-BY-4.0 | Appendix-A-Installation.ipynb | torjuskd/Kalman-and-Bayesian-Filters-in-Python |
first 30 points | kdata = np.load('KeplerSampleFullQ.npy',encoding='bytes')
print(kdata.shape)
print(len(kdata[250][0]))
kdata[0][0].shape
normalized_x_flux = []
normalized_y_flux = []
for i, _ in enumerate(kdata):
if len(kdata[i][1]) == 3534:
normalized_x_flux.append(kdata[i][0])
normalized_y_flux.append(kdata[i][1]... | _____no_output_____ | MIT | v1_exploration/dmdt_comparison.ipynb | kushaltirumala/outlier_kplr |
random 1/2 of the points | import random
def random_n_points(n, dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name)
normalized_x_flux = []
normalized_y_flux = []
for i, _ in enumerate(kdata):
if len(kdata[i][1]) == 3534:
normalized_x_flux.append(kdata[i][0])
normalized_y_... | _____no_output_____ | MIT | v1_exploration/dmdt_comparison.ipynb | kushaltirumala/outlier_kplr |
Content-Based Filtering Using Neural Networks This notebook relies on files created in the [content_based_preproc.ipynb](./content_based_preproc.ipynb) notebook. Be sure to run the code in there before completing this notebook. Also, we'll be using the **python3** kernel from here on out so don't forget to change the... | %bash
pip freeze | grep tensor | tensorboard==1.8.0
tensorflow==1.8.0
tensorflow-hub==0.1.1
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
If 'tensorflow-hub' isn't one of the outputs above, then you'll need to install it. Uncomment the cell below and execute the commands. After doing the pip install, click **"Reset Session"** on the notebook so that the Python environment picks up the new packages. | #%bash
#pip install tensorflow-hub
import os
import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
import shutil
PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION ... | Updated property [core/project].
Updated property [compute/region].
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Build the feature columns for the model. To start, we'll load the list of categories, authors and article ids we created in the previous **Create Datasets** notebook. | categories_list = open("categories.txt").read().splitlines()
authors_list = open("authors.txt").read().splitlines()
content_ids_list = open("content_ids.txt").read().splitlines()
mean_months_since_epoch = 523 | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
In the cell below we'll define the feature columns to use in our model. If necessary, remind yourself the [various feature columns](https://www.tensorflow.org/api_docs/python/tf/feature_column) to use. For the embedded_title_column feature column, use a Tensorflow Hub Module to create an embedding of the article title... | embedded_title_column = hub.text_embedding_column(
key="title",
module_spec="https://tfhub.dev/google/nnlm-de-dim50/1",
trainable=False)
content_id_column = tf.feature_column.categorical_column_with_hash_bucket(
key="content_id",
hash_bucket_size= len(content_ids_list) + 1)
embedded_content_column... | INFO:tensorflow:Using /tmp/tfhub_modules to cache modules.
INFO:tensorflow:Downloading TF-Hub Module 'https://tfhub.dev/google/nnlm-de-dim50/1'.
INFO:tensorflow:Downloaded TF-Hub Module 'https://tfhub.dev/google/nnlm-de-dim50/1'.
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Create the input function.Next we'll create the input function for our model. This input function reads the data from the csv files we created in the previous labs. | record_defaults = [["Unknown"], ["Unknown"],["Unknown"],["Unknown"],["Unknown"],[mean_months_since_epoch],["Unknown"]]
column_keys = ["visitor_id", "content_id", "category", "title", "author", "months_since_epoch", "next_content_id"]
label_key = "next_content_id"
def read_dataset(filename, mode, batch_size = 512):
de... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Create the model and train/evaluateNext, we'll build our model which recommends an article for a visitor to the Kurier.at website. Look through the code below. We use the input_layer feature column to create the dense input layer to our network. This is just a sigle layer network where we can adjust the number of hidd... | def model_fn(features, labels, mode, params):
net = tf.feature_column.input_layer(features, params['feature_columns'])
for units in params['hidden_units']:
net = tf.layers.dense(net, units=units, activation=tf.nn.relu)
# Compute logits (1 per class).
logits = tf.layers.dense(net, params['n_classes'], a... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Train and Evaluate | outdir = 'content_based_model_trained'
shutil.rmtree(outdir, ignore_errors = True) # start fresh each time
tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file
estimator = tf.estimator.Estimator(
model_fn=model_fn,
model_dir = outdir,
params={
'feature_colum... | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_master': '', '_task_type': 'worker', '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f902158b1d0>, '_task_id': 0, '_tf_random_seed': None, '_log_step_count_steps': 100, '_global_id_in_cluster': 0, '_keep_checkpoint_m... | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
This takes a while to complete but in the end, I get about **30% top 10 accuracy**. Make predictions with the trained model. With the model now trained, we can make predictions by calling the predict method on the estimator. Let's look at how our model predicts on the first five examples of the training set. To start... | %%bash
head -5 training_set.csv > first_5.csv
head first_5.csv
awk -F "\"*,\"*" '{print $2}' first_5.csv > first_5_content_ids | 1000148716229112932,299913368,News,U4-Störung legt Wiener Frühverkehr lahm ,Yvonne Widler,574,299931241
1000148716229112932,299931241,Stars & Kultur,Regisseur Michael Haneke kritisiert Flüchtlingspolitik,,574,299913879
1000360453832106474,299925700,Lifestyle,Nach Tod von Vater: Tochter bekommt jedes Jahr Blumen,Marlene... | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Recall, to make predictions on the trained model we pass a list of examples through the input function. Complete the code below to make predicitons on the examples contained in the "first_5.csv" file we created above. | output = list(estimator.predict(input_fn=read_dataset("first_5.csv", tf.estimator.ModeKeys.PREDICT)))
import numpy as np
recommended_content_ids = [np.asscalar(d["class_names"]).decode('UTF-8') for d in output]
content_ids = open("first_5_content_ids").read().splitlines() | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
Finally, we map the content id back to the article title. Let's compare our model's recommendation for the first example. This can be done in BigQuery. Look through the query below and make sure it is clear what is being returned. | import google.datalab.bigquery as bq
recommended_title_sql="""
#standardSQL
SELECT
(SELECT MAX(IF(index=6, value, NULL)) FROM UNNEST(hits.customDimensions)) AS title
FROM `cloud-training-demos.GA360_test.ga_sessions_sample`,
UNNEST(hits) AS hits
WHERE
# only include hits on pages
hits.type = "PAGE"
AND (SEL... | Current title: U4-Störung legt Wiener Frühverkehr lahm
Recommended title: Britische Urlauberin filmte in Australien eigenen Krokodil-Angriff
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
TensorboardAs usual, we can monitor the performance of our training job using Tensorboard. | from google.datalab.ml import TensorBoard
TensorBoard().start('content_based_model_trained')
for pid in TensorBoard.list()['pid']:
TensorBoard().stop(pid)
print("Stopped TensorBoard with pid {}".format(pid)) | Stopped TensorBoard with pid 12206
Stopped TensorBoard with pid 12311
| Apache-2.0 | courses/machine_learning/deepdive/10_recommend/content_based_using_neural_networks.ipynb | Keetaekpark/training-data-analyst |
PCA Implementation | pca = PCA()
pca_values = pca.fit_transform(wines_normal)
pca_values
var = pca.explained_variance_ratio_
var
var1 = np.cumsum(np.round(var,decimals = 4)*100)
var1
pca.components_
plt.plot(var1, color='red', marker = 'o',linestyle = '--')
# Final Dataframe
finalDf =pd.concat([wines['Type'],pd.DataFrame(pca_values[:,0:3],... | _____no_output_____ | Apache-2.0 | Assignment (8) PCA (2).ipynb | shraddhaghadage/PCA |
Checking with other Clustering Algorithms 1. Hierarchical Clustering | # Import Libraries
import scipy.cluster.hierarchy as sch
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import normalize
# As we already have normalized data, create Dendrograms
plt.figure(figsize=(10,8))
dendrogram=sch.dendrogram(sch.linkage(finalDf,method='average'))
hc=AgglomerativeCl... | _____no_output_____ | Apache-2.0 | Assignment (8) PCA (2).ipynb | shraddhaghadage/PCA |
2. K-Means Clustering | # Import Libraries
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_wines= scaler.fit_transform(wines.iloc[:,1:])
scaled_wines
# within-cluster sum-of-squares criterion
wcss=[]
for i in range (1,11):
kmeans=KMeans(n_clusters=i,random_state=0)
... | _____no_output_____ | Apache-2.0 | Assignment (8) PCA (2).ipynb | shraddhaghadage/PCA |
Build Cluster algorithm using K=4 | # Cluster algorithm using K=4
clusters3=KMeans(4,random_state=30).fit(finalDf)
clusters3
clusters3.labels_
# Assign clusters to the data set
wine4=wines.copy()
wine4['clustersid']=clusters3.labels_
wine4
wine4['clustersid'].value_counts()
scaled_wines | _____no_output_____ | Apache-2.0 | Assignment (8) PCA (2).ipynb | shraddhaghadage/PCA |
Final rescale for paper 1 Final figures for the scaling section of paper 1 and cleaner fits for:* Maximum and minimum squeezing of isopyncals (max $N^2/N^2_0$, min $N^2/N^2_0$ )* Effective stratification ($N_{eff}$)* Upwelling flux induced by the canyon ($\Phi$)* Maximum and minimum squeezing of isopyncals iso-concent... | %matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.gridspec as gspec
from matplotlib.ticker import FormatStrFormatter
from netCDF4 import Dataset
import numpy as np
import os
import pandas as pd
import seaborn as sns
import sys
import scipy.stats
import warnings
war... | _____no_output_____ | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Not all runs are used to fit all variables**records_dyn** has all runs where f, N or U vary. USe this list to fit upwelling flux $\Phi$ and modify *Howatt and Allen 2013*.**records_epsilon** has all runs in records_dyn plus the runs with a heaviside Kv profile. Use this list to fit $\Phi$ with scaled N.**records_real*... | # Indices of all runs that will be considered for paper 1
select_rec = [0,1,2,3,4,5,51,6,7,8,9,10,17,18,19,20,21,
22,23,24,25,26,27,29,30,31,32,33,
34,35,38,39,41,42,43,44,45,46,47,48,49]#,52, 53, 54, 55, 56, 57, 58, 59, 60]
for ii in select_rec:
print(ii,records[ii].label2, records[ii... | _____no_output_____ | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Stratification and upwelling fluxIn previous notebooks I found that the upwelling flux is porportional to an effective stratification $N_{eff}$ given by the weighted sum of the maximum stratification above the rim, near the head and the minimum stratification below the rim:$$N_{eff} = {0.75N_{max}+0.25N_{min}}$$So fir... | # Get kv form initial files
records_kv_files = [24,25,26,27,29,30,31,32,33,34,38,39,41,42,43,44,45,46,47,48,49]
kv_dir = '/ocean/kramosmu/Building_canyon/BuildCanyon/Stratification/616x360x90/'
ini_kv_files = [kv_dir + 'KrDiff_Mty_90zlev_616x360_Quad.bin',
kv_dir + 'KrDiff_Eel_90zlev_616x360_Quad.bin'... | _____no_output_____ | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Tracer gradient | X1_be = np.array([rec.S_min for rec in records_epsilon])
X2_be = np.array([rec.Sdif_min for rec in records_epsilon])
Y_be = np.array([(rec.dTr_be)/(rec.dTr0) for rec in records_epsilon])
X1_ab = np.array([rec.S_max for rec in records_epsilon])
X2_ab = np.array([rec.Sdif_max for rec in records_epsilon])
Y_ab = np.array... | _____no_output_____ | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Concentration | # Fit mean concentration just above the rim - I know using the max
# worked slightly better (smaller mse). Co is the initial concentration just above rim depth
X1_tr = np.array([rec.S_max for rec in records_epsilon])
X2_tr = np.array([rec.Sdif_max for rec in records_epsilon])
Y_tr = np.array([(rec.Tr/rec.Tr0) for rec... | $\bar{C}/Co$ = 0.33 $S^+$ + 0.06 $S^+_{diff}$ 1.00
5.77824258804
-0.0359832525253
| Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Tracer flux | Y_array = np.array([rec.PhiTr for rec in records_epsilon])
X_array = np.array([rec.RA2018*(rec.u_mod*rec.W*Dh(rec.f,rec.L,rec.N_eff_scaled))*
(rec.Tr_scaled) for rec in records_epsilon])
slope6, intercept6, r_value6, p_value6, std_err6 = scipy.stats.linregress(np.squeeze(X_array),
... | \Phi/UWD_{eff} = 5.00 Fw^{3/2} Ro^{1/2} (1-0.86 *Se)^3 +-0.01
\Phi_{Tr} = 1.01 $\Phi \ bar{C}$ + 551.08
| Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Figures | sns.set_context('paper')
plt.rcParams['font.size'] = 11.0
f = plt.figure(figsize = (5,5)) # 190mm = 7.48 in, 230cm = 9.05in
gs = gspec.GridSpec(2, 2,wspace=0.2)
ax1 = plt.subplot(gs[0,0])
ax0 = plt.subplot(gs[0,1])
ax3 = plt.subplot(gs[1,0])
ax2 = plt.subplot(gs[1,1])
# ---- plot 1:1 line ----
ax0.plot(np.linspace(-... | base
higher $N$
highest $N$
lower $N$
higher $N$
medium $N$
higher $f$
lower $f$
low $f$
lowest $f$
lower $U$
low $U$
lowest $U$
lowest $U$, lowest $N$
lowest $U$, highest $N$
lowest $U$, lowest $f$
$\K_{can}=10^{-2}$, $\epsilon=10$
$\K_{can}$, $\epsilon=25$
$\K_{can}$, $\epsilon=50$
$\K_{can}$, $\epsilon=100$
$\K_{can... | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
Tables | print ("\t".join(['Experiment &','$\kappa_{bg}$ &','$\kappa_{can}$&','$\epsilon$&'
]))
for rec in records_sel:
print ("\t".join(['%s\t&$%0.2e$\t&$%0.2e$\t&$%1.0f$\t '
% (rec.label2,
rec.kbg,
rec.kv,
... | Experiment & $N$ (s$^{-1}$)$& $f$ (s$^{-1}$)& U (ms$^{-1}$)& $Bu$& $R_L$ $R_W$
base case &$5.5e-03$ &$9.66e-05$ &$0.36$ &$0.40$ &$0.45$ &$0.31$
$\uparrow$ $K_{bg}$ &$5.5e-03$ &$9.66e-05$ &$0.36$ &$0.40$ &$0.45$ &$0.30$
$\uparrow \uparrow$ $K_{bg}$ &$5.5e-03$ &$9.66e-05$ &$0.32$ &$0.40$ &$0.40$ &$0.27$
$\uparro... | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks |
MISC. Conversion form $\mu Mm^3$ of $NO^-_3$ to kg of $NO^-_3$:molecular weight of $NO^-_3$ = 3x16 O + 1x14 N = 62 g/mol$\mu$Mm$^3$ = 1 x $10^{-6}$ x mol/0.001 m$^3$ x 1 m$^3$ = $10^{-3}$ mol$10^{-3}$ mol $NO_3$ = $10^{-3}$ mol x 62 g/mol = 0.062 g = $6.2 \times 10^{-5}$ kg | _____no_output_____ | Apache-2.0 | RealisticKvMaps/scaling_tracer_flux_paper1_clean.ipynb | UBC-MOAD/outputanalysisnotebooks | |
循环结构 在程序中我们需要执行重复重复再重复的东东,使用循环结构。一种是for-in循环一种是while循环 | """
for循环实现1~100 求和
"""
sum = 0
for x in range(101):
sum += x
print(sum)
sum = 0
for x in range(1,101):
sum += x
print(sum)
####偶数求和
sum = 0
for x in range(2,101,2):
sum += x
print(sum) | 2550
| Apache-2.0 | Untitled.ipynb | baicha12/snow-fox |
while循环 :常用于死循环进行取值 | """
for循环实现1~100 求和
"""
sum = 0
num = 1
while num <= 100:
sum += num
num += 1
print(sum)
"""
for循环实现1~100 偶数求和
"""
sum = 0
num = 2
while num <= 100:
sum += num
num += 2
print(sum) | 2550
| Apache-2.0 | Untitled.ipynb | baicha12/snow-fox |
函数和模块的使用 def关键字来定义函数,和变量一样每个函数也有一个响亮的名字,而且命名规则跟变量的命名规则是一致的。在函数名后面的圆括号中可以放置传递给函数的参数,这一点和数学上的函数非常相似,程序中函数的参数就相当于是数学上说的函数的自变量,而函数执行完成后我们可以通过return关键字来返回一个值,这相当于数学上说的函数的因变量。 | ###在参数名前面的*表示args是一个可变参数(不定长参数)
###记载调用add函数时可以传入0个或多个参数
def add (*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1,2,3,4))
##1一元二次方程
def gongshi():
a = float(input('请输入a:'))
b = float(input('请输入b:'))
c = float(input('请输入c:'))
r1 = (... | 请输入1
请输入1
请输入1
3
| Apache-2.0 | Untitled.ipynb | baicha12/snow-fox |
This notebook contains a bunch of experiments to determine the optimal learning rate value for different optimizers. The reference model is a CNN with 3 convolutional blocks; the dataset is an augmented version of the CBIS dataset. Environment setup | # Connect to Google Drive
from google.colab import drive
drive.mount('/content/gdrive')
# Copy the dataset from Google Drive to local
!cp "/content/gdrive/My Drive/CBIS_DDSM.zip" .
!unzip -qq CBIS_DDSM.zip
!rm CBIS_DDSM.zip
cbis_path = 'CBIS_DDSM'
# Import libraries
%tensorflow_version 1.x
import os
import numpy as ... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
Data pre-processing | def load_training():
"""
Load the training set (excluding baseline patches)
"""
images = np.load(os.path.join(cbis_path, 'numpy data', 'train_tensor.npy'))[1::2]
labels = np.load(os.path.join(cbis_path, 'numpy data', 'train_labels.npy'))[1::2]
return images, labels
def load_testing():
"""
... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
Learning rate estimation The following experiment involves four of the most popular optimizers for NNs: SGD, RMSprop, Adam and Nadam.In order to roughly approximate the range of reasonable values of learning rate for each optimizer, a simple strategy is adopted. Starting with a very low LR, its value is slightly incre... | loss_lower_threshold = 0.60
loss_upper_threshold = 0.69
class StopOnDivergingLoss(Callback):
def on_epoch_end(self, epoch, logs={}):
global low_reached
if logs.get('loss') < loss_lower_threshold:
low_reached = True
if logs.get('loss') > loss_upper_threshold and low_reached:
... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
The graph above clearly shows that learning rate plays a decisive role during the training. When it is too high, weight updates become too large and the network becomes unstable, failing to converge towards the loss minimum. On the other hand, if it set too low, the network learns slowly and we observe modest improveme... | # For each optimizer, execute a training run with the previously determined best learning rate
optimal_lr = {
SGD: 3e-2,
RMSprop: 1e-4,
Adam: 1e-4,
Nadam: 1e-4
}
histories = {}
for opt in opts:
print("Optimizer: " + opt.__name__)
cnn = create_cnn()
cnn.compile(
optimizer=... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
The graphs shows that SGD is relatively weak with respect to the other optimizers. Adam converges faster than RMSprop and Nadam, whose curves are quite similar. Learning rate verification Now that approximate values for the learning rate have been discovered, one may try to directly experiment with different nearby va... | # Try RMSprop with different learning rates
lr_to_test = (1e-5, 1e-4, 1e-3)
opt = RMSprop
histories = {}
for lr in lr_to_test:
print("RMS [lr = %.5f]: " % lr)
cnn = create_cnn()
cnn.compile(
optimizer=opt(learning_rate=lr),
loss='binary_crossentropy',
metri... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
**Result**: Values between 1e-4 and 1e-3 produce similar results. 1e-3 is more noisy, but converges a bit faster. On the other hand, 1e-5 represents an excessively low value. Adam | # Try Adam with different learning rates
lr_to_test = (1e-5, 1e-4, 1e-3)
opt = Adam
histories = {}
for lr in lr_to_test:
print("Adam [lr = %.5f]: " % lr)
cnn = create_cnn()
cnn.compile(
optimizer=opt(learning_rate=lr),
loss='binary_crossentropy',
metrics=['... | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN |
**Result**: 1e-5 is definitely a bad choice, as the network converges very slowly. Interestingly, 1e-4 produces better results than 1e-3. | _____no_output_____ | MIT | scripts/LearningRate.ipynb | leoll2/MedicalCNN | |
Converting between the 4-metric $g_{\mu\nu}$ and ADM variables $\left\{\gamma_{ij}, \alpha, \beta^i\right\}$ or BSSN variables $\left\{h_{ij}, {\rm cf}, \alpha, {\rm vet}^i\right\}$ Author: Zach Etienne[comment]: (Abstract: TODO) We will often find it useful to convert between the 4-metric $g_{\mu\nu}$ and the ADM or... | import sympy as sp
import NRPy_param_funcs as par
import indexedexp as ixp
import sys
def setup_ADM_quantities(inputvars):
if inputvars == "ADM":
gammaDD = ixp.declarerank2("gammaDD", "sym01")
betaU = ixp.declarerank1("betaU")
alpha = sp.symbols("alpha", real=True)
elif inputvars == "BS... | _____no_output_____ | BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 2: Write 4-metric $g_{\mu\nu}$ and its inverse $g^{\mu\nu}$ in terms of ADM or BSSN variables \[Back to [top](toc)\]$$\label{admbssn_to_fourmetric}$$ Step 2.a: 4-metric $g_{\mu\nu}$ in terms of ADM or BSSN variables \[Back to [top](toc)\]$$\label{admbssn_to_fourmetric_lower}$$Given ADM variables $\left\{\gamma_{i... | def g4DD_ito_BSSN_or_ADM(inputvars):
# Step 0: Declare g4DD as globals, to make interfacing with other modules/functions easier
global g4DD
# Step 1: Check that inputvars is set to a supported value
gammaDD,betaU,alpha = setup_ADM_quantities(inputvars)
# Step 2: Compute g4DD = g_{mu nu}:
# To ... | _____no_output_____ | BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 2.b: Inverse 4-metric $g^{\mu\nu}$ in terms of ADM or BSSN variables \[Back to [top](toc)\]$$\label{admbssn_to_fourmetric_inv}$$ B&S also provide a convenient form for the inverse 4-metric (Eq. 2.119; also Eq. 4.49 in [Gourgoulhon](https://arxiv.org/pdf/gr-qc/0703035.pdf)):$$g^{\mu\nu} = \gamma^{\mu\nu} - n^\mu n... | def g4UU_ito_BSSN_or_ADM(inputvars):
# Step 0: Declare g4UU as globals, to make interfacing with other modules/functions easier
global g4UU
# Step 1: Check that inputvars is set to a supported value
gammaDD,betaU,alpha = setup_ADM_quantities(inputvars)
# Step 2: Compute g4UU = g_{mu nu}:
# To ... | _____no_output_____ | BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 2.c: Validation check: Confirm $g_{\mu\nu}g^{\mu\nu}=4$ \[Back to [top](toc)\]$$\label{validationcontraction}$$ Next we compute $g^{\mu\nu} g_{\mu\nu}$ as a validation check. It should equal 4: | g4DD_ito_BSSN_or_ADM("BSSN")
g4UU_ito_BSSN_or_ADM("BSSN")
sum = 0
for mu in range(4):
for nu in range(4):
sum += g4DD[mu][nu]*g4UU[mu][nu]
if sp.simplify(sum) == sp.sympify(4):
print("TEST PASSED!")
else:
print("TEST FAILED: "+str(sum)+" does not apparently equal 4.")
sys.exit(1) | TEST PASSED!
| BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 3: Write ADM/BSSN metric quantities in terms of 4-metric $g_{\mu\nu}$ (Excludes extrinsic curvature $K_{ij}$, the BSSN $a_{ij}$, $K$, and $\lambda^i$) \[Back to [top](toc)\]$$\label{fourmetric_to_admbssn}$$ Given $g_{\mu\nu}$, we now compute ADM/BSSN metric quantities, excluding extrinsic curvature. Let's start b... | def BSSN_or_ADM_ito_g4DD(inputvars):
# Step 0: Declare output variables as globals, to make interfacing with other modules/functions easier
if inputvars == "ADM":
global gammaDD,betaU,alpha
elif inputvars == "BSSN":
global hDD,cf,vetU,alpha
else:
print("inputvars = " + str(inputv... | _____no_output_____ | BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 3.a: ADM in terms of 4-metric validation: Confirm $\gamma_{ij}\gamma^{ij}=3$ \[Back to [top](toc)\]$$\label{adm_ito_fourmetric_validate}$$Next we compute $\gamma^{ij} \gamma_{ij}$ as a validation check. It should equal 3: | BSSN_or_ADM_ito_g4DD("ADM")
gammaUU, gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)
sum = sp.sympify(0)
for i in range(3):
for j in range(3):
sum += gammaDD[i][j]*gammaUU[i][j]
if sp.simplify(sum) == sp.sympify(3):
print("TEST PASSED!")
else:
print("TEST FAILED: "+str(sum)+" does not apparently eq... | TEST PASSED!
| BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 3.b: BSSN in terms of 4-metric validation: Confirm $\bar{\gamma}_{ij}\bar{\gamma}^{ij}=3$ \[Back to [top](toc)\]$$\label{bssn_ito_fourmetric_validate}$$Next we compute $\bar{\gamma}_{ij}\bar{\gamma}^{ij}$ as a validation check. It should equal 3: | import reference_metric as rfm
par.set_parval_from_str("reference_metric::CoordSystem","SinhCylindrical")
rfm.reference_metric()
BSSN_or_ADM_ito_g4DD("BSSN")
gammabarDD = ixp.zerorank2()
for i in range(3):
for j in range(3):
# gammabar_{ij} = h_{ij}*ReDD[i][j] + gammahat_{ij}
gammabarDD[i][j] = hD... | TEST PASSED!
| BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 4: Code Validation against `BSSN.ADMBSSN_tofrom_4metric` NRPy+ module \[Back to [top](toc)\]$$\label{code_validation}$$Here, as a code validation check, we verify agreement in the SymPy expressions for BrillLindquist initial data between1. this tutorial and 2. the NRPy+ [BSSN.ADMBSSN_tofrom_4metric](../edit/BSSN/... | par.set_parval_from_str("reference_metric::CoordSystem","SinhCylindrical")
rfm.reference_metric()
import BSSN.ADMBSSN_tofrom_4metric as AB4m
for inputvars in ["BSSN","ADM"]:
g4DD_ito_BSSN_or_ADM(inputvars)
AB4m.g4DD_ito_BSSN_or_ADM(inputvars)
for i in range(4):
for j in range(4):
print(... | BSSN input: g4DD[0][0] - g4DD_mod[0][0] = 0
BSSN input: g4DD[0][1] - g4DD_mod[0][1] = 0
BSSN input: g4DD[0][2] - g4DD_mod[0][2] = 0
BSSN input: g4DD[0][3] - g4DD_mod[0][3] = 0
BSSN input: g4DD[1][0] - g4DD_mod[1][0] = 0
BSSN input: g4DD[1][1] - g4DD_mod[1][1] = 0
BSSN input: g4DD[1][2] - g4DD_mod[1][2] = 0
BSSN input: ... | BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct... | import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-ADMBSSN_tofrom_4metric") | Created Tutorial-ADMBSSN_tofrom_4metric.tex, and compiled LaTeX file to PDF
file Tutorial-ADMBSSN_tofrom_4metric.pdf
| BSD-2-Clause | Tutorial-ADMBSSN_tofrom_4metric.ipynb | rhaas80/nrpytutorial |
Load Test deployed web applicationThis notebook pulls some images and tests them against the deployed web application. We submit requests asychronously which should reduce the contribution of latency. | import asyncio
import json
import random
import urllib.request
from timeit import default_timer
import aiohttp
import matplotlib.pyplot as plt
import testing_utilities
from tqdm import tqdm
%matplotlib inline | _____no_output_____ | MIT | Tensorflow/06_SpeedTestWebApp.ipynb | marabout2015/AKSDeploymentTutorial |
We will test our deployed service with 100 calls. We will only have 4 requests concurrently at any time. We have only deployed one pod on one node and increasing the number of concurrent calls does not really increase throughput. Feel free to try different values and see how the service responds. | NUMBER_OF_REQUESTS = 100 # Total number of requests
CONCURRENT_REQUESTS = 4 # Number of requests at a time | _____no_output_____ | MIT | Tensorflow/06_SpeedTestWebApp.ipynb | marabout2015/AKSDeploymentTutorial |
Get the IP address of our service | service_json = !kubectl get service azure-dl -o json
service_dict = json.loads(''.join(service_json))
app_url = service_dict['status']['loadBalancer']['ingress'][0]['ip']
scoring_url = 'http://{}/score'.format(app_url)
version_url = 'http://{}/version'.format(app_url)
!curl $version_url # Reports the Tensorflow Version... | _____no_output_____ | MIT | Tensorflow/06_SpeedTestWebApp.ipynb | marabout2015/AKSDeploymentTutorial |
Below we run the 100 requests against our deployed service | loop = asyncio.get_event_loop()
start_time = default_timer()
complete_responses = loop.run_until_complete(asyncio.ensure_future(run(url_list, num_concurrent=CONCURRENT_REQUESTS)))
elapsed = default_timer() - start_time
print('Total Elapsed {}'.format(elapsed))
print('Avg time taken {0:4.2f} ms'.format(1000*elapsed/len(... | 100%|██████████| 100/100 [00:05<00:00, 19.73it/s] | MIT | Tensorflow/06_SpeedTestWebApp.ipynb | marabout2015/AKSDeploymentTutorial |
Below we can see the output of some of our calls | complete_responses[:3]
num_succesful=[i[0]['result'][0]['image'][0][0] for i in complete_responses].count('n02127052 lynx, catamount')
print('Succesful {} out of {}'.format(num_succesful, len(url_list)))
# Example response
plt.imshow(testing_utilities.to_img(IMAGEURL))
complete_responses[0] | _____no_output_____ | MIT | Tensorflow/06_SpeedTestWebApp.ipynb | marabout2015/AKSDeploymentTutorial |
Uncertainty Sampling on the Radio Galaxy Zoo | import sys
import h5py, numpy, sklearn.neighbors
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
sys.path.insert(1, '..')
import crowdastro.train, crowdastro.test
TRAINING_H5_PATH = '../training.h5'
CROWDASTRO_H5_PATH = '../crowdastro.h5'
NORRIS_DAT_PATH = '../data/norris_2006_atlas_classifi... | _____no_output_____ | MIT | notebooks/37_uncertainty_sampling_rgz.ipynb | chengsoonong/crowdastro |
Please complete the missing parts in the code below. Moreover, please correct the mistakes in the code if the performance is not satisfactory. Implementation of Neural Style Transfer with PyTorch | # importing libraries to implement style-transfer
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models... | _____no_output_____ | Apache-2.0 | Copy_of_Style_Transfer_PyTorch.ipynb | lasyaistla/Ai.fellowshiplasya |
Show your output image | output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
content_img, style_img, input_img)
plt.figure()
imshow(output, title='Output Image')
# sphinx_gallery_thumbnail_number = 4
plt.ioff()
plt.show() | Building the style transfer model..
Optimizing..
| Apache-2.0 | Copy_of_Style_Transfer_PyTorch.ipynb | lasyaistla/Ai.fellowshiplasya |
Assignment 1: Numpy RNNImplement a RNN and run BPTT | from typing import Dict, Tuple
import numpy as np
class RNN(object):
"""Numpy implementation of sequence-to-one recurrent neural network for regression tasks."""
def __init__(self, input_size: int, hidden_size: int, output_size: int):
"""Initialization
Parameters
----------
... | _____no_output_____ | CC0-1.0 | Assignment1.ipynb | rnbdsh/lstm_rnn |
Numerical gradient checkTo validate your implementation, especially the backward pass, use the two-sided gradient approximation given by the equation below. | def get_numerical_gradient(model: RNN, x: np.ndarray, eps: float=1e-7) -> Dict:
"""Implementation of the two-sided numerical gradient approximation
Parameters
----------
model : RNN
The RNN model object
x : np.ndarray
Input sequence(s) of shape [sequence length, number of featur... | _____no_output_____ | CC0-1.0 | Assignment1.ipynb | rnbdsh/lstm_rnn |
Compare the time for gradient computationFinally, use the code below to investigate the benefit of being able to calculate the exact analytical gradient. | print("Gradient check with a single output neuron:")
model = RNN(input_size=5, hidden_size=10, output_size=1)
x = np.random.rand(5, 5)
gradient_check(model, x)
print("\nGradient check with multiple output neurons:")
model = RNN(input_size=5, hidden_size=10, output_size=5)
x = np.random.rand(5, 5)
gradient_check(model,... | The analytical gradient computation was 96 times faster
| CC0-1.0 | Assignment1.ipynb | rnbdsh/lstm_rnn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.