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 |
|---|---|---|---|---|---|
Implement Generate Functions Get TensorsGet tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graphget_tensor_by_name). Get the tensors using the following names:- "input:0"- "initial_state:0"- "final_state:0"- "probs:0"Return the tensors in the foll... | def get_tensors(loaded_graph):
"""
Get input, initial state, final state, and probabilities tensor from <loaded_graph>
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
"""
# TODO: Implement Function
inputs ... | Tests Passed
| MIT | tv-script-generation/dlnd_tv_script_generation.ipynb | dxl0632/deeplearning_nd_udacity |
Choose WordImplement the `pick_word()` function to select the next word using `probabilities`. | # import numpy as np
def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: ... | Tests Passed
| MIT | tv-script-generation/dlnd_tv_script_generation.ipynb | dxl0632/deeplearning_nd_udacity |
Generate TV ScriptThis will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate. | gen_length = 200
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'moe_szyslak'
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_dir + '.meta')
loa... | INFO:tensorflow:Restoring parameters from ./save
moe_szyslak:(victorious chuckle) no more-- that's them for lenny and i can run ziffcorp, the time you ever heard you could save mckinley.
homer_simpson: i can't close a man named much lost with him, on the little woman. you can do about the bathroom who whatever those le... | MIT | tv-script-generation/dlnd_tv_script_generation.ipynb | dxl0632/deeplearning_nd_udacity |
Purpose of this Notebook Purpose of this NotebookIn this Notebook we perform an initial eyeball exploration of the datasets to find cleaning steps that might be particular to the individual datsets only (does not include generall cleaning steps like mentions, hashtags, punctuation removal, etc).This helps to reduce co... | import pandas as pd
import numpy as np
import re
pd.set_option('display.max_colwidth', 700)
#('MAX_COL_WIDTH', 500) | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Face Book Hate Speech | fb = pd.read_csv("transformed_data/facebook_hate_speech_translated.csv", encoding='utf-8')
# drop the duplicates
fb = fb.drop_duplicates(subset=['translated_message'])
fb.label.value_counts() | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
ObserveTo find the nuances of this dataset we will observe the dataset by sampling it multiple times.Remove:- "- &39;(unicode in dataset) with '. In fact remove all decimal encoded puctuation marks with the actual punctuation marks.Note:- remove accented characters- URL- @ 137c9c6970afb7fc- repeating !!![^a-zA-Z... | x = fb.loc[643,'translated_message']
re.sub("[^a-zA-Z_\.\s,]",'', x) # remove all special characters and numbers
re.sub(r"\b(([a-z]+\d+)|(\d+[a-z]+))(\w)+\b", '', x) # 02ab63aad79877f5, ab63aad79877f5, 3f3g6hj7j5v and fg54jkk098ui
# re.sub("'", "'", x)
re.findall("\d+", ''.join(re.findall("&#\d+;", "Hello !")... | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Also remove sentences that are abusive only in specific context. We want a generalised system.Remove :0, 9, 10, 13, 18, 31, 34, 35, 39, 41, 52, 55, 59, 69, 70, 72, 73, 78, 101, 103, 107, 116, 117 | delete_rows = [0, 9, 10, 13, 18, 31, 34, 35, 39, 41, 52, 55, 59, 69, 70, 72, 73, 78, 101, 103, 107, 116, 117]
fb.drop(index=delete_rows).shape | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Wikipedia Personal Attacks | wiki = pd.read_csv("transformed_data/wikipedia_personal_attacks.csv", encoding='utf-8')
wiki.shape
wiki = wiki.drop_duplicates(subset=['comment'])
wiki.label.value_counts()
msg = "NEWLINE_TOKENNEWLINE_TOKEN== Statement ==NEWLINE_TOKENI would like to be unblocked please, my actions four years ago were unwarranted and I ... | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
ObservationsRemove:- NEWLINE_TOKEN- ``.*`` indicates quotes- (UTC)Notes:- remove accented characters- u with you White Supremist | w_s = pd.read_csv("transformed_data/white_supremist_data.csv", encoding="utf-8")
print('Original Shape: {0}'.format(w_s.shape))
print('After Duplicate removal:', w_s.drop_duplicates(subset=['text']).shape)
w_s.label.value_counts() | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Observations- "[....]" | '[....]' : every document is a list element.Notes:n't --> not | # x = ''.join(w_s.text.loc[[6310, 2334]].values)
x = ''.join(w_s.text.loc[6310])
# re.sub('([(\"|\')).*((\"|\')])', "", x)
# ''.join(re.sub('''("|')\]''', "", re.sub('''\[("|')''', "", x)))
# x
x.replace('["', '').replace('"]', '') | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Tweeter | tweetr = pd.read_csv("transformed_data/tweeter_data.csv")
tweetr.columns
print('Original Shape: {0}'.format(tweetr.shape))
print('After Duplicate removal:', tweetr.drop_duplicates(subset=['tweet']).shape)
tweetr = tweetr.drop_duplicates(subset=['tweet'])
tweetr.label.unique()
tweetr = tweetr.drop(index=0) | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
ObservationRemove:- RTNOte:- emoji &9825; &128166; &128540; --> &\d+;- &8220; &128526;&8221;- Emojis have similar regex compared to apostrophe. Hence they must be removed only after apostrophe substitution.Column name change in combined data. Data in DB already has same column names. | x = tweetr.tweet.loc[14721]
re.sub("&#\d+;", "", x)
del tweetr | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Toxic Comments | toxic = pd.read_csv("transformed_data/toxic_comments.csv", encoding='utf-8')
toxic.columns
print("Shape of original data:", toxic.shape)
toxic = toxic.drop_duplicates(subset=['comment_text'])
print("Shape after duplicate removal:", toxic.shape)
toxic.label.unique() | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
ObservationRemove:- \n \r- dawgggNote:- 50% -> fifty percent : Eg: Rihanna is 50% black. Her mother is also mixed race, not black. | x = toxic.comment_text.loc[377713]# 1839087
# x.replace("\n", '')
x | _____no_output_____ | MIT | NoteBooks/pecularities_data_source.ipynb | gunnerVivek/Abusive-language-detection-in-Online-content |
Direct Inversion of the Iterative SubspaceWhen solving systems of linear (or nonlinear) equations, iterative methods are often employed. Unfortunately, such methods often suffer from convergence issues such as numerical instability, slow convergence, and significant computational expense when applied to difficult pro... | # ==> Basic Setup <==
# Import statements
import psi4
import numpy as np
# Memory specification
psi4.set_memory(int(5e8))
numpy_memory = 2
# Set output file
psi4.core.set_output_file('output.dat', False)
# Define Physicist's water -- don't forget C1 symmetry!
mol = psi4.geometry("""
O
H 1 1.1
H 1 1.1 2 104
symmetry ... | _____no_output_____ | BSD-3-Clause | Tutorials/03_Hartree-Fock/3b_rhf-diis.ipynb | konpat/psi4numpy |
Now let's put DIIS into action. Before our iterations begin, we'll need to create empty lists to hold our previous residual vectors (AO orbital gradients) and trial vectors (previous Fock matrices), along with setting starting values for our SCF energy and previous energy: | # ==> Pre-Iteration Setup <==
# SCF & Previous Energy
SCF_E = 0.0
E_old = 0.0 | _____no_output_____ | BSD-3-Clause | Tutorials/03_Hartree-Fock/3b_rhf-diis.ipynb | konpat/psi4numpy |
Now we're ready to write our SCF iterations according to Algorithm 2. Here are some hints which may help you along the way: Starting DIISSince DIIS builds the approximate solution vector $\mid{\bf p}\,\rangle$ as a linear combination of the previous trial vectors $\{\mid{\bf p}_i\,\rangle\}$, there's no need to perfor... | # Start from fresh orbitals
F_p = A.dot(H).dot(A)
e, C_p = np.linalg.eigh(F_p)
C = A.dot(C_p)
C_occ = C[:, :ndocc]
D = np.einsum('pi,qi->pq', C_occ, C_occ)
# Trial & Residual Vector Lists
F_list = []
DIIS_RESID = []
# ==> SCF Iterations w/ DIIS <==
print('==> Starting SCF Iterations <==\n')
# Begin Iterations
for s... | _____no_output_____ | BSD-3-Clause | Tutorials/03_Hartree-Fock/3b_rhf-diis.ipynb | konpat/psi4numpy |
Congratulations! You've written your very own Restricted Hartree-Fock program with DIIS convergence accelleration! Finally, let's check your final RHF energy against Psi4: | # Compare to Psi4
SCF_E_psi = psi4.energy('SCF')
psi4.compare_values(SCF_E_psi, SCF_E, 6, 'SCF Energy') | _____no_output_____ | BSD-3-Clause | Tutorials/03_Hartree-Fock/3b_rhf-diis.ipynb | konpat/psi4numpy |
Phase:IMove exact matching | import os
import pandas as pd
path='../data/sanskrit_treebank/'
GT = []
for folder in os.listdir(path):
for file in os.listdir(path+folder):
temp = []
data = pd.read_csv(path+folder+'/'+file, sep=',')
for i in range(len(data)):
temp.append(data.iloc[i,3])
temp = sorted(te... | _____no_output_____ | MIT | notebooks/Filter_20k.ipynb | krishnamrith12/DCST |
Phase IICheck sentence length atleast 6 | count = 0
for file in os.listdir('../data/train_20k/'):
data = pd.read_csv('../data/train_20k/'+file, sep=',')
temp = []
for i in range(len(data)):
temp.append(data.iloc[i,3])
temp = sorted(temp)
if len(temp)>=6:
count+=1
shutil.move('../data/train_20k/'+file,'../data/train_1... | _____no_output_____ | MIT | notebooks/Filter_20k.ipynb | krishnamrith12/DCST |
Welcome in the introductory template of the python graph gallery. Here is how to proceed to add a new `.ipynb` file that will be converted to a blogpost in the gallery! Notebook Metadata It is very important to add the following fields to your notebook. It helps building the page later on:- **slug**: the URL of the bl... | import seaborn as sns, numpy as np
np.random.seed(0)
x = np.random.randn(100)
ax = sns.distplot(x) | _____no_output_____ | 0BSD | src/notebooks/171-basic-venn-diagram-with-3-groups.ipynb | nrslt/The-Python-Graph-Gallery |
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN... | %load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p torch | Sebastian Raschka
CPython 3.6.8
IPython 7.2.0
torch 1.0.0
| MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Model Zoo -- CNN Gender Classifier (ResNet-18 Architecture, CelebA) with Data Parallelism Network Architecture The network in this notebook is an implementation of the ResNet-18 [1] architecture on the CelebA face dataset [2] to train a gender classifier. References - [1] He, K., Zhang, X., Ren, S., & Sun, J. (20... | import os
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
import matplotlib.pyplot as plt
from PIL i... | _____no_output_____ | MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Settings | ##########################
### SETTINGS
##########################
# Hyperparameters
RANDOM_SEED = 1
LEARNING_RATE = 0.001
NUM_EPOCHS = 10
# Architecture
NUM_FEATURES = 128*128
NUM_CLASSES = 2
BATCH_SIZE = 256*torch.cuda.device_count()
DEVICE = 'cuda:0' # default GPU device
GRAYSCALE = False | _____no_output_____ | MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Dataset Downloading the Dataset Note that the ~200,000 CelebA face image dataset is relatively large (~1.3 Gb). The download link provided below was provided by the author on the official CelebA website at http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html. 1) Download and unzip the file `img_align_celeba.zip`, which ... | df1 = pd.read_csv('list_attr_celeba.txt', sep="\s+", skiprows=1, usecols=['Male'])
# Make 0 (female) & 1 (male) labels instead of -1 & 1
df1.loc[df1['Male'] == -1, 'Male'] = 0
df1.head()
df2 = pd.read_csv('list_eval_partition.txt', sep="\s+", skiprows=0, header=None)
df2.columns = ['Filename', 'Partition']
df2 = df2.... | (218, 178, 3)
| MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Implementing a Custom DataLoader Class | class CelebaDataset(Dataset):
"""Custom Dataset for loading CelebA face images"""
def __init__(self, csv_path, img_dir, transform=None):
df = pd.read_csv(csv_path, index_col=0)
self.img_dir = img_dir
self.csv_path = csv_path
self.img_names = df.index.values
self.y =... | Epoch: 1 | Batch index: 0 | Batch size: 1024
Epoch: 2 | Batch index: 0 | Batch size: 1024
| MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Model The following code cell that implements the ResNet-34 architecture is a derivative of the code provided at https://pytorch.org/docs/0.4.0/_modules/torchvision/models/resnet.html. | ##########################
### MODEL
##########################
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
... | Using 4 GPUs
| MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Training | def compute_accuracy(model, data_loader, device):
correct_pred, num_examples = 0, 0
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets.to(device)
logits, probas = model(features)
_, predicted_labels = torch.max(pro... | Epoch: 001/010 | Batch 0000/0159 | Cost: 0.6782
Epoch: 001/010 | Batch 0050/0159 | Cost: 0.1445
Epoch: 001/010 | Batch 0100/0159 | Cost: 0.1169
Epoch: 001/010 | Batch 0150/0159 | Cost: 0.0913
Epoch: 001/010 | Train: 93.687% | Valid: 94.101%
Time elapsed: 3.83 min
Epoch: 002/010 | Batch 0000/0159 | Cost: 0.0851
Epoch: 0... | MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Evaluation | with torch.set_grad_enabled(False): # save memory during inference
print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader, device=DEVICE)))
for batch_idx, (features, targets) in enumerate(test_loader):
features = features
targets = targets
break
plt.imshow(np.transpose(features[0], (... | numpy 1.15.4
pandas 0.23.4
torch 1.0.0
PIL.Image 5.3.0
| MIT | pytorch_ipynb/cnn/cnn-resnet18-celeba-dataparallel.ipynb | chloe-wang/deeplearning-models |
Create data Create data generator | simple_data_genertator = False
percent_sequence_before_anomaly = 70.0
percent_sequence_after_anomaly = 0.0
def create_time_series_normal_parameters():
normal_freq_noise_scale = 1.0
normal_frequence_noise_shift = 1.0
normal_ampl_noise_scale = 1.0
normal_ampl_noise_shift = 1.0
normal_noise_noise_scale = 1.0... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Create training and evaluation data | number_of_training_normal_sequences = 64000
number_of_validation_normal_1_sequences = 6400
number_of_validation_normal_2_sequences = 6400
number_of_validation_anomalous_sequences = 6400
number_of_test_normal_sequences = 6400
number_of_test_anomalous_sequences = 6400
seq_len = 30
number_of_tags = 5
tag_columns = ["ta... | 0.21651224,2.04016484,-0.47583765,-0.23555634,2.45546603,0.3235766,-1.2904606,1.67762694,1.68130188,-0.78770077,0.47435638,1.63288897,-0.1088109,-0.80535951,1.5247533,0.6913622,-1.02549557,1.50642533,1.64192016,-1.29912246,0.42280094,2.57050962,-0.07996142,-0.77842833,1.84379046,1.13805856,-0.82112047,1.65391633,1.9578... | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Local Development | # Set logging to be level of INFO
tf.logging.set_verbosity(tf.logging.INFO)
# Determine CSV and label columns
UNLABELED_CSV_COLUMNS = tag_columns
LABEL_COLUMN = "anomalous_sequence_flag"
LABELED_CSV_COLUMNS = UNLABELED_CSV_COLUMNS + [LABEL_COLUMN]
# Set default values for each CSV column
UNLABELED_DEFAULTS = [[""] fo... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Train reconstruction variables | # Train the model
shutil.rmtree(path = arguments["output_dir"], ignore_errors = True) # start fresh each time
estimator = train_and_evaluate(arguments) | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_device_fn': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7efb36cceda0>, '_save_checkpoints_steps': None, '_num_worker_replicas': 1, '_global_id_in_cluster': 0, '_model_dir': 'tr... | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Look at PCA variable values | estimator.get_variable_names()
arr_training_normal_sequences = np.genfromtxt(fname = "data/training_normal_sequences.csv", delimiter = ';', dtype = str)
print("arr_training_normal_sequences.shape = {}".format(arr_training_normal_sequences.shape))
if number_of_tags == 1:
arr_training_normal_sequences = np.expand_dims(... | arr_training_normal_sequences.shape = (64000, 5)
arr_training_normal_sequences_features.shape = (64000, 30, 5)
| Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Time based | X_time = arr_training_normal_sequences_features.reshape(arr_training_normal_sequences_features.shape[0] * arr_training_normal_sequences_features.shape[1], number_of_tags)
X_time.shape | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Count | estimator.get_variable_value(name = "pca_variables/pca_time_count_variable")
time_count = X_time.shape[0]
time_count | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Mean | estimator.get_variable_value(name = "pca_variables/pca_time_mean_variable")
time_mean = np.mean(X_time, axis = 0)
time_mean
estimator.get_variable_value(name = "pca_variables/pca_time_mean_variable") / time_mean | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Covariance | if estimator.get_variable_value(name = "pca_variables/pca_time_cov_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_time_cov_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_time_cov_variable").shape)
if arguments["seq_len"] == 1:
time_cov = np.... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Eigenvalues | if estimator.get_variable_value(name = "pca_variables/pca_time_eigenvalues_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_time_eigenvalues_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_time_eigenvalues_variable").shape)
time_eigenvalues, time... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Eigenvectors | if estimator.get_variable_value(name = "pca_variables/pca_time_eigenvectors_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_time_eigenvectors_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_time_eigenvectors_variable").shape)
if time_eigenvector... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Features based | X_features = np.transpose(arr_training_normal_sequences_features, [0, 2, 1]).reshape(arr_training_normal_sequences_features.shape[0] * number_of_tags, arr_training_normal_sequences_features.shape[1])
X_features.shape | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Count | estimator.get_variable_value(name = "pca_variables/pca_features_count_variable")
feat_count = X_features.shape[0]
feat_count | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Mean | estimator.get_variable_value(name = "pca_variables/pca_features_mean_variable")
feat_mean = np.mean(X_features, axis = 0)
feat_mean
estimator.get_variable_value(name = "pca_variables/pca_features_mean_variable") / feat_mean | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Covariance | if estimator.get_variable_value(name = "pca_variables/pca_features_cov_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_features_cov_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_features_cov_variable").shape)
if number_of_tags == 1:
feat_cov... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Eigenvalues | if estimator.get_variable_value(name = "pca_variables/pca_features_eigenvalues_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_features_eigenvalues_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_features_eigenvalues_variable").shape)
feat_eigen... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Eigenvectors | if estimator.get_variable_value(name = "pca_variables/pca_features_eigenvectors_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "pca_variables/pca_features_eigenvectors_variable"))
else:
print(estimator.get_variable_value(name = "pca_variables/pca_features_eigenvectors_variable").shape)
if feat... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Train error distribution statistics variables | arguments["training_mode"] = "calculate_error_distribution_statistics"
arguments["train_file_pattern"] = "data/validation_normal_1_sequences.csv"
arguments["eval_file_pattern"] = "data/validation_normal_1_sequences.csv"
arguments["train_batch_size"] = 32
arguments["eval_batch_size"] = 32
estimator = train_and_evaluate(... | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_device_fn': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7efaac0ae9b0>, '_save_checkpoints_steps': None, '_num_worker_replicas': 1, '_global_id_in_cluster': 0, '_model_dir': 'tr... | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Look at variable values | estimator.get_variable_names()
arr_validation_normal_1_sequences = np.genfromtxt(fname = "data/validation_normal_1_sequences.csv", delimiter = ';', dtype = str)
print("arr_validation_normal_1_sequences.shape = {}".format(arr_validation_normal_1_sequences.shape))
if number_of_tags == 1:
arr_validation_normal_1_sequenc... | arr_validation_normal_1_sequences.shape = (6400, 5)
WARNING:tensorflow:From /usr/local/lib/python3.5/dist-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py:62: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future versio... | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Time based | validation_normal_1_time_absolute_error = np.stack(arrays = [prediction["X_time_abs_reconstruction_error"] for prediction in validation_normal_1_predictions_list], axis = 0)
time_abs_err = validation_normal_1_time_absolute_error.reshape(validation_normal_1_time_absolute_error.shape[0] * validation_normal_1_time_absolut... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Count | estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_count_time_variable")
time_count = time_abs_err.shape[0]
time_count | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Mean | estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_mean_time_variable")
time_mean = np.mean(time_abs_err, axis = 0)
time_mean
estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_mean_time_variable") / time_mean | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Covariance | if estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_cov_time_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_cov_time_variable"))
else:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_cov_time_v... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Inverse Covariance | if estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_inv_cov_time_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_inv_cov_time_variable"))
else:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_in... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Features based | validation_normal_1_features_absolute_error = np.stack(arrays = [prediction["X_features_abs_reconstruction_error"] for prediction in validation_normal_1_predictions_list], axis = 0)
feat_abs_err = np.transpose(validation_normal_1_features_absolute_error, [0, 2, 1]).reshape(validation_normal_1_features_absolute_error.sh... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Count | estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_count_features_variable")
feat_count = feat_abs_err.shape[0]
feat_count | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Mean | estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_mean_features_variable")
feat_mean = np.mean(feat_abs_err, axis = 0)
feat_mean
estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_mean_features_variable") / feat_mean | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Covariance | if estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_cov_features_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_cov_features_variable"))
else:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_co... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Inverse Covariance | if estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_inv_cov_features_variable").shape[0] <= 10:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/abs_err_inv_cov_features_variable"))
else:
print(estimator.get_variable_value(name = "mahalanobis_distance_variables/ab... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Tune anomaly thresholds | arguments["training_mode"] = "tune_anomaly_thresholds"
arguments["train_file_pattern"] = "data/labeled_validation_mixed_sequences.csv"
arguments["eval_file_pattern"] = "data/labeled_validation_mixed_sequences.csv"
arguments["train_batch_size"] = 64
arguments["eval_batch_size"] = 64
estimator = train_and_evaluate(argume... | INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_device_fn': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7ef771a4f6a0>, '_save_checkpoints_steps': None, '_num_worker_replicas': 1, '_global_id_in_cluster': 0, '_model_dir': 'tr... | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Time based | estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/tp_at_thresholds_time_variable")
estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/fn_at_thresholds_time_variable")
estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/fp_at_thresholds_tim... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Features based | estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/tp_at_thresholds_features_variable")
estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/fn_at_thresholds_features_variable")
estimator.get_variable_value(name = "mahalanobis_distance_threshold_variables/fp_at_thresh... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Numpy | arr_validation_mixed_sequences = np.genfromtxt(
fname = "data/labeled_validation_mixed_sequences.csv", delimiter = ';', dtype = str)
print("arr_validation_mixed_sequences.shape = {}".format(arr_validation_mixed_sequences.shape))
arr_validation_mixed_sequences_features = np.stack(
arrays = [np.stack(
arrays = [... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Time based | arr_validation_mixed_predictions_mahalanobis_distance_batch_time = np.stack(
arrays = [prediction["mahalanobis_distance_time"]
for prediction in validation_mixed_predictions_list], axis = 0)
print("arr_validation_mixed_predictions_mahalanobis_distance_batch_time.shape = {}".format(arr_validation_mixed_pr... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Features based | arr_validation_mixed_predictions_mahalanobis_distance_batch_features = np.stack(
arrays = [prediction["mahalanobis_distance_features"]
for prediction in validation_mixed_predictions_list], axis = 0)
print("arr_validation_mixed_predictions_mahalanobis_distance_batch_features.shape = {}".format(arr_validat... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Local Prediction | arr_labeled_test_mixed_sequences = np.genfromtxt(fname = "data/labeled_test_mixed_sequences.csv", delimiter = ';', dtype = str)
arr_labeled_test_mixed_sequences_features = np.stack(
arrays = [np.stack(
arrays = [np.array(arr_labeled_test_mixed_sequences[example_index, tag_index].split(',')).astype(np.float)
... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Normal example | normal_test_example_index = np.argmax(arr_test_labels == '0')
predictions_list[normal_test_example_index]
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
for i, arr in enumerate(np.split(ary = predictions_list[normal_test_example_index]["X_time_abs_reconstruction_error"].flatten(), indices_o... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Anomalous Example | anomalous_test_example_index = np.argmax(arr_test_labels == '1')
predictions_list[anomalous_test_example_index]
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
for i, arr in enumerate(np.split(ary = predictions_list[anomalous_test_example_index]["X_time_abs_reconstruction_error"].flatten(), ... | _____no_output_____ | Apache-2.0 | machine_learning/anomaly_detection/tf_pca/pca_anomaly_detection_local.ipynb | ryangillard/artificial_intelligence |
Estimating COVID-19's $R_t$ in Real-Time for all US countiesModified version of the work by [Kevin Systrom](https://github.com/k-sys/covid-19) to estimate $R_t$ for all US states based on the [NYT](https://github.com/nytimes/covid-19-data) county level data | !pip install pymc3==3.8
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import os
import requests
import pymc3 as pm
import pandas as pd
import numpy as np
import theano
import theano.tensor as tt
from matplotlib import pyplot as plt
from matplotlib import dates as mdates
from matplotli... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Load COUNTY Information | # Import NYT data
url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'
counties = pd.read_csv(url,parse_dates=['date']).sort_index()
counties
#counties[counties.county != 'Unknown']
counties=counties[counties.county != 'Unknown']
counties.insert(0, 'key', counties['state'] + '_' + cou... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Load Patient Information Download~100mb download (be ... patient!) | def download_file(url, local_filename):
"""From https://stackoverflow.com/questions/16694907/"""
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk: # filter out ... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Parse & Clean Patient Info | # Load the patient CSV
patients = pd.read_csv(
'data/linelist.csv',
parse_dates=False,
usecols=[
'date_confirmation',
'date_onset_symptoms'],
low_memory=False)
patients.columns = ['Onset', 'Confirmed']
# colnames renamed ~05-07. rename back for code below to work
#patients.columns = ['... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Show Relationship between Onset of Symptoms and Confirmation | ax = patients.plot.scatter(
title='Onset vs. Confirmed Dates - COVID19',
x='Onset',
y='Confirmed',
alpha=.1,
lw=0,
s=10,
figsize=(6,6))
formatter = mdates.DateFormatter('%m/%d')
locator = mdates.WeekdayLocator(interval=2)
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_formatter(forma... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Calculate the Probability Distribution of Delay | # Calculate the delta in days between onset and confirmation
delay = (patients.Confirmed - patients.Onset).dt.days
# Convert samples to an empirical distribution
p_delay = delay.value_counts().sort_index()
new_range = np.arange(0, p_delay.index.max()+1)
p_delay = p_delay.reindex(new_range, fill_value=0)
p_delay /= p_d... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
A single County | #key = 'Nebraska_Douglas'
key = 'NYC_NYC'
key = 'NYC_New York City'
#key = 'New York_New York City'
#key = 'New Jersey_Hudson'
confirmed = counties.xs(key).cases.diff().dropna().clip(0) # new cases (not cumulative)
confirmed | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Translate Confirmation Dates to Onset DatesOur goal is to translate positive test counts to the dates where they likely occured. Since we have the distribution, we can distribute case counts back in time according to that distribution. To accomplish this, we reverse the case time series, and convolve it using the dist... | def confirmed_to_onset(confirmed, p_delay):
assert not confirmed.isna().any()
# Reverse cases so that we convolve into the past
convolved = np.convolve(confirmed[::-1].values, p_delay)
# Calculate the new date range
dr = pd.date_range(end=confirmed.index[-1],
periods=le... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Adjust for Right-CensoringSince we distributed observed cases into the past to recreate the onset curve, we now have a right-censored time series. We can correct for that by asking what % of people have a delay less than or equal to the time between the day in question and the current day.For example, 5 days ago, ther... | def adjust_onset_for_right_censorship(onset, p_delay):
cumulative_p_delay = p_delay.cumsum()
# Calculate the additional ones needed so shapes match
ones_needed = len(onset) - len(cumulative_p_delay)
padding_shape = (0, ones_needed)
# Add ones and flip back
cumulative_p_delay = np.pad(
... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Take a look at all three series: confirmed, onset and onset adjusted for right censoring. | fig, ax = plt.subplots(figsize=(5,3))
confirmed.plot(
ax=ax,
label='Confirmed',
title=key,
c='k',
alpha=.25,
lw=1)
onset.plot(
ax=ax,
label='Onset',
c='k',
lw=1)
adjusted.plot(
ax=ax,
label='Adjusted Onset',
c='k',
linestyle='--',
lw=1)
ax.legend(); | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Let's have the model run on days where we have enough data ~last 50 or so Sample the Posterior with PyMC3 We assume a poisson likelihood function and feed it what we believe is the onset curve based on reported data. We model this onset curve based on the same math in the previous notebook:$$ I^\prime = Ie^{\gamma(R_t... | class MCMCModel(object):
def __init__(self, region, onset, cumulative_p_delay, window=50):
# Just for identification purposes
self.region = region
# For the model, we'll only look at the last N
self.onset = onset.iloc[-window:]
self.cumulative_p_delay =... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Run Pymc3 Model | def df_from_model(model):
r_t = model.trace['r_t']
mean = np.mean(r_t, axis=0)
median = np.median(r_t, axis=0)
hpd_90 = pm.stats.hpd(r_t, credible_interval=.9)
hpd_50 = pm.stats.hpd(r_t, credible_interval=.5)
idx = pd.MultiIndex.from_product([
[model.region],
mo... | NYC_Bronx County
| MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Handle Divergences | # Check to see if there were divergences
n_diverging = lambda x: x.trace['diverging'].nonzero()[0].size
divergences = pd.Series([n_diverging(m) for m in models.values()], index=models.keys())
has_divergences = divergences.gt(0)
print('Diverging states:')
display(divergences[has_divergences])
# Rerun states with diver... | Diverging states:
| MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Compile Results | results = None
for state_county, model in models.items():
df = df_from_model(model)
if results is None:
results = df
else:
results = pd.concat([results, df], axis=0)
results | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Render to CSV | !pip install ckanapi
# New York City
resultscsv=results.reset_index()
resultscsv.drop(resultscsv[resultscsv['region'] == 'NYC_NYC'].index, inplace=True)
resultscsv['region']= resultscsv['region'].str.replace("NYC_", "", case = False)
resultscsv.rename(columns={"region": "county"}, inplace=True)
resultscsv
maxdate = ... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Render Charts | def plot_rt(name, result, ax, c=(.3,.3,.3,1), ci=(0,0,0,.05)):
ax.set_ylim(-1, 2) # change y-axis limits
ax.set_title(name)
ax.plot(result['median'],
marker='o',
markersize=4,
markerfacecolor='w',
lw=1,
c=c,
markevery=2)
ax.fill_bet... | _____no_output_____ | MIT | Realtime_Rt_mcmc_NYC.ipynb | dathere/notebooks |
Dataproc - Submit PySpark Job Intended UseA Kubeflow Pipeline component to submit a PySpark job to Google Cloud Dataproc service. Run-Time Parameters:Name | Description:--- | :----------project_id | Required. The ID of the Google Cloud Platform project that the cluster belongs to.region | Required. The Cloud Dataproc... | !gsutil cat gs://dataproc-examples-2f10d78d114f6aaec76462e3c310f31f/src/pyspark/hello-world/hello-world.py | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Set sample parameters | PROJECT_ID = '<Please put your project ID here>'
CLUSTER_NAME = '<Please put your existing cluster name here>'
REGION = 'us-central1'
PYSPARK_FILE_URI = 'gs://dataproc-examples-2f10d78d114f6aaec76462e3c310f31f/src/pyspark/hello-world/hello-world.py'
ARGS = ''
EXPERIMENT_NAME = 'Dataproc - Submit PySpark Job'
SUBMIT_PYS... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Install KFP SDKInstall the SDK (Uncomment the code if the SDK is not installed before) | # KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.12/kfp.tar.gz'
# !pip3 install $KFP_PACKAGE --upgrade | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Load component definitions | import kfp.components as comp
dataproc_submit_pyspark_job_op = comp.load_component_from_url(SUBMIT_PYSPARK_JOB_SPEC_URI)
display(dataproc_submit_pyspark_job_op) | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Here is an illustrative pipeline that uses the component | import kfp.dsl as dsl
import kfp.gcp as gcp
import json
@dsl.pipeline(
name='Dataproc submit PySpark job pipeline',
description='Dataproc submit PySpark job pipeline'
)
def dataproc_submit_pyspark_job_pipeline(
project_id = PROJECT_ID,
region = REGION,
cluster_name = CLUSTER_NAME,
main_python_f... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Compile the pipeline | pipeline_func = dataproc_submit_pyspark_job_pipeline
pipeline_filename = pipeline_func.__name__ + '.pipeline.tar.gz'
import kfp.compiler as compiler
compiler.Compiler().compile(pipeline_func, pipeline_filename) | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Submit the pipeline for execution | #Specify pipeline argument values
arguments = {}
#Get or create an experiment and submit a pipeline run
import kfp
client = kfp.Client()
experiment = client.create_experiment(EXPERIMENT_NAME)
#Submit a pipeline run
run_name = pipeline_func.__name__ + ' run'
run_result = client.run_pipeline(experiment.id, run_name, pi... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_pyspark_job/sample.ipynb | ryan-williams/pipelines |
Module 2 - Python Fundamentals Sequence: Lists - **List Creation**- **List Access**- List Append- List Insert- List Delete----- > Student will be able to - **Create Lists**- **Access items in a list**- Add Items to the end of a list- Insert items into a list- Delete items from a list Concepts Creating Lists[!... | # [ ] review and run example
# define list of strings
ft_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform", "intermediate cuneiform", "medial cuneiform"]
# display type information
print("ft_bones: ", type(ft_bones))
# print the list
print(ft_bones)
# [ ] review and run example
# define list o... | _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 1 Create Lists | # [ ] create team_names list and populate with 3-5 team name strings
# [ ] print the list
# [ ] Create a list mix_list with numbers and strings with 4-6 items
# [ ] print the list
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Concepts List Access []( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfabd20e.html?details=[{"src":"http://jupyternootbookwams.streaming.mediaservices.windows.net/efc23682-3b15-4c73-afe0-77067fac2769/Un... | # [ ] review and run example
print(ft_bones[0], "is the 1st bone on the list")
print(ft_bones[2], "is the 3rd bone on the list")
print(ft_bones[-1], "is the last bone on the list")
# [ ] review and run example
print(ft_bones[1], "is connected to the",ft_bones[3])
# [ ] review and run example
three_ages_sum = age_survey... | _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 2 | # [ ] Create a list, streets, that lists the name of 5 street name strings
# [ ] print a message that there is "No Parking" on index 0 or index 4 streets
# [ ] Create a list, num_2_add, made of 5 different numbers between 0 - 25
# [ ] print the sum of the numbers
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 3 Fix the Errors | # [ ] Review & Run, but ***Do Not Edit*** this code cell
# [ ] Fix the error by only editing and running the block below
print(" Total of checks 3 & 4 = $", pay_checks[2] + pay_checks[3])
# [ ] Fix the error above by creating and running code in this cell
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Module 2 Part 2 Lists - List Creation- List Access- **List Append**- List Insert- List Delete----- > Student will be able to - Create Lists- Access items in a list- **Add Items to the end of a list**- Insert items into a list- Delete items from a list Concepts Appending to Lists[
sample_list.append(3)
# the list after append
print("sample_list after: ", sample_list)
# [ ] review and run example
# append number to sample_list
print("sample_list start: ", sample_list)
sample... | _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 4 `.append()` | # Currency Values
# [ ] create a list of 3 or more currency denomination values, cur_values
# cur_values, contains values of coins and paper bills (.01, .05, etc.)
# [ ] print the list
# [ ] append an item to the list and print the list
# Currency Names
# [ ] create a list of 3 or more currency denomination NAMES... | _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 5 Append items to a list with `input()` | # [ ] append additional values to the Currency Names list using input()
# [ ] print the appended list
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 6 `while` loop `.append()`- define an empty list: **`bday_survey`** - get user input, **`bday`**, asking for the day of the month they were born (1-31) or "q" to finish - using a **`while`** loop (while user not entering "quit") - append the **`bday`** input to the **`bday_survey`** list - get user ... | # [ ] complete the Birthday Survey task above
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Task 7 Fix The Error | # [ ] Fix the Error
three_numbers = [1, 1, 2]
print("an item in the list is: ", three_numbers[3])
| _____no_output_____ | MIT | Python Fundamentals/Module_2.0_Tutorials_Sequence_Lists_Python_Fundamentals.ipynb | Mt9555/pythonteachingcode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.