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 |
|---|---|---|---|---|---|
You have now managed to search for a list of strings in several lines of text data. These skills come in handy when you want to flag certain words based on what you discovered in your topic model, or when you know beforehand what you want to search for. In the next exercises you're going to learn how to clean text data... | # Import nltk packages and string
from nltk.corpus import stopwords
import string
# Define stopwords to exclude
stop = set(stopwords.words('english'))
# stop.update(("to","cc","subject","http","from","sent", "ect", "u", "fwd", "www", "com"))
# Define punctuations to exclude and lemmatizer
exclude = set(string.punct... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
The following is the stop contents. However, stop = set(stopwords('english')) has problems to run. {'a', 'about', 'above', 'after', 'again', 'against', 'ain', 'all', 'am', . . . 'y', 'you', "you'd", "you'll", "you're", "you've", 'your', 'yours', 'yourself', 'yourselves' } Cleaning text dataNow that you've defined the... | # Import the lemmatizer from nltk
from nltk.stem.wordnet import WordNetLemmatizer
lemma = WordNetLemmatizer()
# Define word cleaning function
def clean(text, stop):
text = text.rstrip()
# Remove stopwords
stop_free = " ".join([word for word in text.lower().split() if ((word not in stop) and (not word.isdig... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Now that you have cleaned your data entirely with the necessary steps, including splitting the text into words, removing stopwords and punctuations, and lemmatizing your words. You are now ready to run a topic model on this data. In the following exercises you're going to explore how to do that. Create dictionary and ... | # Import the packages
import gensim
from gensim import corpora
# Define the dictionary
dictionary = corpora.Dictionary(text_clean)
# Define the corpus
corpus = [dictionary.doc2bow(text) for text in text_clean]
# Print corpus and dictionary
print(dictionary)
print(corpus) | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Dictionary(8948 unique tokens: ['conducted', 'read', 'wil', 'daniel', 'piazze']...) [[(0, 1), (1, 2), (2, 1), (3, 1), (4, 2), (5, 1), (6, 2), (7, 1), (8, 1), (9, 1), (10, 5), (11, 2), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), (20, 1), (21, 1), (22, 1), (23, 1), (24, 1),....] total length.... | ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=5, id2word=dictionary, passes=5)
# Save the topics and top 5 words
topics = ldamodel.print_topics(num_words=5)
# Print the results
for topic in topics:
print(topic) | (0, '0.043*"enron" + 0.023*"company" + 0.022*"employee" + 0.019*"million" + 0.016*"energy"')
(1, '0.019*"enron" + 0.013*"company" + 0.010*"energy" + 0.008*"com" + 0.007*"power"')
(2, '0.040*"enron" + 0.017*"stock" + 0.011*"option" + 0.010*"com" + 0.010*"dynegy"')
(3, '0.015*"enron" + 0.009*"company" + 0.009*"com" + 0.0... | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
`(0, '0.024*"enron" + 0.015*"ect" + 0.011*"com" + 0.007*"hou" + 0.005*"company"') (1, '0.032*"enron" + 0.011*"com" + 0.009*"diabetes" + 0.008*"message" + 0.006*"please"') (2, '0.031*"enron" + 0.011*"company" + 0.010*"said" + 0.007*"mr" + 0.005*"partnership"') (3, '0.021*"enron" + 0.012*"employee" + 0.010*"comp... | # Run get_topic_details function and check the results
print(get_topic_details(ldamodel, corpus))
# Add original text to topic details in a dataframe
contents = pd.DataFrame({'Original text': text_clean})
topic_details = pd.concat([get_topic_details(ldamodel, corpus), contents], axis=1)
topic_details.head()
# Add origi... | _____no_output_____ | MIT | machineLearning/applications/anomaly_detection/2 - fraud_detection_with_classical_machine_learning/fraud detection.ipynb | ljyang100/dataScience |
Copyright 2018 The TensorFlow Hub Authors. Copyright 2019-2020 Google LLCLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law... | import os
IS_COLAB_BACKEND = 'COLAB_GPU' in os.environ # this is always set on Colab, the value is 0 or 1 depending on GPU presence
if IS_COLAB_BACKEND:
from google.colab import auth
# Authenticates the Colab machine and also the TPU using your
# credentials so that they can access your private GCS buckets.
au... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Updating tensorboard_plugin_profile | !pip install -U pip install -U tensorboard_plugin_profile==2.3.0 | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Enabling and testing the TPUFirst, you'll need to enable TPUs for the notebook:- Navigate to Edit→Notebook Settings- select TPU from the Hardware Accelerator drop-downNext, we'll check that we can connect to the TPU: | %tensorflow_version 2.x
import tensorflow as tf
print("Tensorflow version " + tf.__version__)
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection
print('Running on TPU ', tpu.cluster_spec().as_dict()['worker'])
except ValueError:
raise BaseException('ERROR: Not connected to a TPU runt... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Input dataOur input data is stored on Google Cloud Storage. To more fully use the parallelism TPUs offer us, and to avoid bottlenecking on data transfer, we've stored our input data in TFRecord files, 230 images per file.Below, we make heavy use of `tf.data.experimental.AUTOTUNE` to optimize different parts of input l... | AUTO = tf.data.experimental.AUTOTUNE
IMAGE_SIZE = [331, 331]
batch_size = 16 * tpu_strategy.num_replicas_in_sync
gcs_pattern = 'gs://flowers-public/tfrecords-jpeg-331x331/*.tfrec'
validation_split = 0.19
filenames = tf.io.gfile.glob(gcs_pattern)
split = len(filenames) - int(len(filenames) * validation_split)
train_f... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Let's take a peek at the training dataset we've created: | CLASSES = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
def display_one_flower(image, title, subplot, color):
plt.subplot(subplot)
plt.axis('off')
plt.imshow(image)
plt.title(title, fontsize=16, color=color)
# If model is provided, use it to generate predictions.
def display_nine_flowers(images, t... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
ModelTo get maxmimum accuracy, we leverage a pretrained image recognition model (here, [Xception](http://openaccess.thecvf.com/content_cvpr_2017/papers/Chollet_Xception_Deep_Learning_CVPR_2017_paper.pdf)). We drop the ImageNet-specific top layers (`include_top=false`), and add a max pooling and a softmax layer to pred... | def create_model():
pretrained_model = tf.keras.applications.Xception(input_shape=[*IMAGE_SIZE, 3], include_top=False)
pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(5, activation='softmax')
])
model... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Training Calculate the number of images in each dataset. Rather than actually load the data to do so (expensive), we rely on hints in the filename. This is used to calculate the number of batches per epoch. | def count_data_items(filenames):
# The number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items
n = [int(re.compile(r"-([0-9]*)\.").search(filename).group(1)) for filename in filenames]
return np.sum(n)
n_train = count_data_items(train_fns)
n_valid = count_data_i... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Calculate and show a learning rate schedule. We start with a fairly low rate, as we're using a pre-trained model and don't want to undo all the fine work put into training it. | EPOCHS = 12
start_lr = 0.00001
min_lr = 0.00001
max_lr = 0.00005 * tpu_strategy.num_replicas_in_sync
rampup_epochs = 5
sustain_epochs = 0
exp_decay = .8
def lrfn(epoch):
if epoch < rampup_epochs:
return (max_lr - start_lr)/rampup_epochs * epoch + start_lr
elif epoch < rampup_epochs + sustain_epochs:
retur... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Train the model. While the first epoch will be quite a bit slower as we must XLA-compile the execution graph and load the data, later epochs should complete in ~5s. | # Load the TensorBoard notebook extension.
%load_ext tensorboard
# Get TPU profiling service address. This address will be needed for capturing
# profile information with TensorBoard in the following steps.
service_addr = tpu.get_master().replace(':8470', ':8466')
print(service_addr)
# Launch TensorBoard.
%tensorboard ... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
The TensorBoard UI is displayed in a browser window. In this colab, perform the following steps to prepare to capture profile information.1. Click on the dropdown menu box on the top right side and scroll down and click PROFILE. A new window appears that shows: **No profile data was found** at the top.1. Click on the... | history = model.fit(training_dataset, validation_data=validation_dataset,
steps_per_epoch=train_steps, epochs=EPOCHS, callbacks=[lr_callback])
final_accuracy = history.history["val_accuracy"][-5:]
print("FINAL ACCURACY MEAN-5: ", np.mean(final_accuracy))
def display_training_curves(training, valida... | _____no_output_____ | Apache-2.0 | tools/colab/profiling_tpus_in_colab.ipynb | zhtmike/tpu |
Deep learning hands-on  What frameworks do- Tensor math- Common network operations/layers- Gradient of common operations- Backpropagation- Optimizer- GPU implementation of the above- usally: data loading, serialization (saving/loading) of models- sometime: dist... | %pylab inline
import tensorflow as tf
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3)) | tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor([4 6], shape=(2,), dtype=int32)
tf.Tensor(25, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(13, shape=(), dtype=int32)
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Each Tensor has a shape and a datatype | x = tf.matmul([[1]], [[2, 3]])
print(x.shape)
print(x.dtype) | (1, 2)
<dtype: 'int32'>
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
The most obvious differences between NumPy arrays and TensorFlow Tensors are: - Tensors can be backed by accelerator memory (like GPU, TPU). - Tensors are immutable. GPU accelerationMany TensorFlow operations can be accelerated by using the GPU for computation. Without any annotations, TensorFlow automatically decid... | x = tf.random.uniform([3, 3])
print("Is there any GPUs available?"),
print(tf.config.list_physical_devices('GPU'))
print("Is the Tensor on GPU #0: "),
print(x.device.endswith('GPU:0')) | Is there any GPUs available?
[]
Is the Tensor on GPU #0:
False
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Explicit Device PlacementThe term "placement" in TensorFlow refers to how individual operations are assigned (placed on) a device for execution. As mentioned above, when there is no explicit guidance provided, TensorFlow automatically decides which device to execute an operation, and copies Tensors to that device if n... | def time_matmul(x):
%timeit tf.matmul(x, x)
# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("CPU:0")
time_matmul(x)
# Force execution on GPU #0 if available
if tf.test.is_gpu_available():
with tf.device("GPU:0"): # Or GPU:1 fo... | On CPU:
7.62 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
WARNING:tensorflow:From <ipython-input-6-750e9424349b>:12: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices(... | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Derivatives of a function - Computing gradientsTensorFlow provides APIs for automatic differentiation - computing the derivative of a function. To differentiate automatically, TensorFlow needs to remember what operations happen in what order during the forward pass. Then, during the backward pass, TensorFlow traverse... | # With scalars:
x = tf.constant(3.0)
# y = x ^ 2
with tf.GradientTape() as t:
t.watch(x)
y = x * x
# dy = 2x
dy_dx = t.gradient(y, x)
dy_dx.numpy()
# Using matrices:
x = tf.constant([3.0, 3.0])
with tf.GradientTape() as t:
t.watch(x)
z = tf.multiply(x, x)
print(z)
# Find derivative of z with respect to the ... | tf.Tensor([18. 18.], shape=(2,), dtype=float32)
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Recording control flowBecause tapes record operations as they are executed, Python control flow (using ifs and whiles for example) is naturally handled: | def f(x, y):
output = 1.0
for i in range(y):
if i > 1 and i < 5:
output *= x
return output
def grad(x, y):
with tf.GradientTape() as t:
t.watch(x)
out = f(x, y)
return t.gradient(out, x)
x = tf.constant(2.0)
print(grad(x, 6).numpy()) # 12.0
print(grad(x, 5).numpy()) # 12.0
print(grad(... | 12.0
12.0
4.0
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Higher-order gradientsOperations inside of the `GradientTape` context manager are recorded for automatic differentiation. If gradients are computed in that context, then the gradient computation is recorded as well. As a result, the exact same API works for higher-order gradients as well. For example: | x = tf.Variable(1.0) # Create a Tensorflow variable initialized to 1.0
with tf.GradientTape() as t:
with tf.GradientTape() as t2:
y = x * x * x
# Compute the gradient inside the 't' context manager
# which means the gradient computation is differentiable as well.
dy_dx = t2.gradient(y, x)
d2y_dx2 = t.gra... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Canny edgeCanny, John. "A computational approach to edge detection." IEEE Transactions on pattern analysis and machine intelligence 6 (1986): 679-698. (27000+ citations)Canny:- assume noisy step edges- construct an edge detector using an optimal linear filterThis is actually a simple neural network... | # package loading, helper functions
import os
import pickle
import numpy as np
import scipy.ndimage as ndi
import sklearn
import tensorflow.keras
import tensorflow.keras.backend as K
import tensorflow as tf
import matplotlib.pyplot as plt
#Source("digraph {X->Y; Y->Z;}")
from graphviz import Source
from scipy.stats ... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
The Process of Canny edge detection algorithm can be broken down to 5 different steps:- Apply Gaussian filter to smooth the image in order to remove the noise- Find the intensity gradients of the image- Apply non-maximum suppression to get rid of spurious response to edge detection- Apply double threshold t... | length = 50
pos = np.random.randint(length, size=10000)
signal = np.random.rand(10000,length) / 5
gt = np.zeros((10000,length))
for j,i in enumerate(pos):
signal[j, i:] = signal[j, i:] + 0.5
gt[j, i] = 1
figure(figsize=(14,4))
plt.plot(signal[15])
plt.plot(gt[15])
from tensorflow.keras.models import Sequentia... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Kanny kernel | plt.plot(model.get_layer(index=0).get_weights( )[0].flatten()) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
There is a large and rich theory of linear filters in signal processing and image processing: - mathematical properties: superposition, decomposition, impulse response - frequency domain analysis - optimal design for given tasksNB: "optimal linear" is not the same as "optimal" No free lunch theorem! A model, a... | from tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding1D
# DL model
model = Sequential()
model.add(ZeroPadding1D(input_shape=(length, 1), padding=(8,1)))
model.add(Conv1D(4, 7))
model.add(BatchNormalization(momentum=0.1))
model.add(Activation('relu'))
model.add(ZeroPadding1D(padding=(2,1)))
mo... | 0 zero_padding1d
1 conv1d_1
2 batch_normalization
3 activation
4 zero_padding1d_1
5 conv1d_2
6 flatten_1
7 activation_1
| MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
How does it works? | figure(figsize=(14,4))
x = signal[a,:].reshape((1,length,1))
layer = model.layers[1]
f = K.function([model.get_input_at(0)], [layer.get_output_at(0)])
plt.plot(f([x])[0][0,:,:]) # your activation tensor
plt.plot(gt[a,:], '-.')
figure(figsize=(14,6))
layer = model.layers[2]
f = K.function([model.get_input_at(0)], [la... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
- Zero padding on the boundary creates spurious edge responses.- DL can automatically suppress these for you (beware when benchmarking)- How would you pick weights to get rid of such spurious responses? | # DL model
model = Sequential()
model.add(ZeroPadding1D(input_shape=(length, 1), padding=(8,1)))
model.add(Conv1D(16, 7))
model.add(BatchNormalization(momentum=0.1))
model.add(Activation('relu'))
model.add(ZeroPadding1D(padding=(2,1)))
model.add(Conv1D(1, 7))
model.add(Flatten())
model.add(Activation('sigmoid'))
model... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
- DL discovered another neat trick: Instead of a single edge localizer, train two localization filters in the first layer (plus multiple suppression filters again).- Each localization filter is offset from the desired peak by one pixel.- The padding on the second convolutional layer means that the spuriousedges on the ... | from sklearn import svm
from tensorflow.keras.layers import Input, Dense, Activation
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import L1L2
import tensorflow.keras.backend as K
def make_meshgrid(x, y, h=.02):
"""Create a mesh of points to plot in
Parameters
----------
... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
IIR Filters and their DL Equivalents | # simple IIR filter
def simple_iir(xs):
value = xs[0]
output = zeros(len(xs))
for i in range(len(xs)):
output[i] = value
value = 0.7 * value + 0.3 * xs[i]
return output
xs = rand(100) * (rand(100) < 0.1)
figure(figsize=(14,5))
plot(xs)
plot(simple_iir(xs)) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
IIR FiltersIIR filters are simple linear filters.Unlike FIR filters, the output is a linear function of both inputs and past output values.IIR filters can approximate FIR filters well.IIR filters are the linear equivalent of *recurrent neural networks*. | inputs = array([(rand(200) < 0.1).astype('f') for i in range(10000)]).reshape(-1, 1, 200)
outputs = array([4.0*ndi.gaussian_filter(s, 3.0) for s in inputs]).reshape(-1, 1, 200)
figure(figsize=(14,5))
plot(inputs[0,0]); plot(outputs[0,0]) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Simple NN | length = 200
model = Sequential()
model.add(Conv1D(1, 33, input_shape=(length, 1), activation="sigmoid", padding='same'))
model.add(Flatten())
model.compile(SGD(lr=.1, momentum=0.9, decay=1e-5), loss='mse')
model.summary()
#K.set_value(model.optimizer.lr, 1e-2)
model.fit(x=inputs.reshape((-1, 200,1)), y=outputs.resha... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Recurrent neural network - LSTM | from tensorflow.keras.layers import LSTM, Bidirectional
length = 200
model = Sequential()
model.add(Bidirectional(LSTM(4, input_shape=(length, 1), activation="sigmoid", return_sequences=True)))
model.add(Conv1D(1, 8, padding='same'))
model.compile(SGD(lr=.1, momentum=0.9, decay=1e-5), loss='mse')
model.build(input_sh... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Handsome input pipelines with the `tf.data` API The `tf.data` API offers functions for data pipelining and related operations. We can build pipelines, map preprocessing functions, shuffle or batch a dataset and much more. From tensors | dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1])
iter(dataset).next().numpy() | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Batch and Shuffle | # Shuffle
dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).shuffle(6)
iter(dataset).next().numpy()
# Batch
dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).batch(2)
iter(dataset).next().numpy()
# Shuffle and Batch
dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).shuffle(6... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Zipping Two Datsets | dataset0 = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1])
dataset1 = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
dataset = tf.data.Dataset.zip((dataset0, dataset1))
iter(dataset).next() | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Mapping External Functions | def into_2(num):
return num * 2
dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).map(into_2) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
ImageDataGeneratorThis is one of the best features of the `tensorflow.keras` API (in my opinion). The `ImageDataGenerator` is capable of generating dataset slices while batching and preprocessing along with data augmentation in real-time.The Generator allows data flow directly from directories or from dataframes.A mis... | from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Here, the rescaling is done on all the samples (for normalizing), while the other parameters are for augmentation. | train_generator = train_datagen.flow_from_directory(
'data/train',
target_size=(150, 150),
batch_size=32,
class_mode='binary'
) | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Custom LayersNeural Nets are known for many layer deep networks wherein the layers can be of different types. TensorFlow contains many predefined layers (like Dense, LSTM, etc.). But for more complex architectures, the logic of a layer is much more complex than a primary layer. For such instances, TensorFlow allows bu... | class CustomDense(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(CustomDense, self).__init__()
self.num_outputs = num_outputs
def build(self, input_shape):
self.kernel = self.add_weight(
"kernel",
shape=[int(input_shape[-1]),
self.num_... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
As stated in the documentation, The best way to implement your own layer is extending the `tf.keras.Layer` class and implementing:- `__init__` , where you can do all input-independent initialization.- `build`, where you know the shapes of the input tensors and can do the rest of the initialization.- `call`, wh... | def train(model, inputs, outputs, learning_rate):
with tf.GradientTape() as t:
# Computing Losses from Model Prediction
current_loss = loss(outputs, model(inputs)) # Gradients for Trainable Variables with Obtained Losses
dW, db = t.gradient(current_loss, [model.W, model.b]) # Applyin... | _____no_output_____ | MIT | tf2-handson.ipynb | msavardi/tf2.0-handson |
Lasso just adds L1 regularization | class LinRegLasso:
def _init(self, n_feat: int) -> None:
self.weights = np.ones((n_feat + 1)) # (n_feat + 1,) weights + bias
def predict(self, feature_vector: Union[np.ndarray, List[int]]) -> float:
'''
feature_vector may be a list or have shape (n_feat,)
or it may be a ... | epoch: 0, MSE: 17.28968604018978
epoch: 1, MSE: 14.626147202039622
epoch: 2, MSE: 12.378658694531488
epoch: 3, MSE: 10.479716191022815
epoch: 4, MSE: 8.877331485218843
epoch: 5, MSE: 7.523061332680313
epoch: 6, MSE: 6.380218738551775
epoch: 7, MSE: 5.413992777056065
epoch: 8, MSE: 4.598539218214396
ep... | MIT | ml_algos/linear_reg_lasso.ipynb | igor-davidyuk/ds_interview |
Just to check the result we can use scikit-learnThe difference may be explained by lr scheduler in scikit probably | from sklearn.linear_model import Lasso
lassoreg = Lasso(alpha=alpha, max_iter=epochs)
lassoreg.fit(x[:,np.newaxis],y)
y_pred = lassoreg.predict(x[:,np.newaxis])
y_hat = lrs.predict(x[:,np.newaxis])
plt.plot(x,y,'.')
plt.plot(x,y_hat,'.')
plt.plot(x,y_pred,'.') | _____no_output_____ | MIT | ml_algos/linear_reg_lasso.ipynb | igor-davidyuk/ds_interview |
Paillier Encrypted Linear Classification ExampleDISCLAIMER: This is a proof-of-concept implementation. It does not represent a remotely product ready implementation or follow proper conventions for security, convenience, or scalability. It is part of a broader proof-of-concept demonstrating the vision of the OpenMined... | from syft.he.paillier import KeyPair
from syft.nn.linear import LinearClassifier
from syft.he.keys import Paillier
import numpy as np
pk, sk = Paillier()
model = LinearClassifier(n_inputs=4, n_labels=2)
epochs = 3
model = model.encrypt(pk)
input = np.array([[0,0,1,1],[0,0,1,0]])
target = np.array([[0,1],[0,0]])
for i i... | _____no_output_____ | Apache-2.0 | notebooks/Syft - Paillier Encrypted Linear Classification.ipynb | ivuckovic/PySyft |
Newton's Method for Logistic Regression - The Math of Intelligence (Week 2) Our TaskWe're going to compute the probability that someone has Diabetes given their height, weight, and blood pressure. We'll generate this data o... | %matplotlib inline
#matrix math
import numpy as np
#data manipulation
import pandas as pd
#matrix data structure
from patsy import dmatrices
#for error logging
import warnings | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Setup Parameter / Data SetupIn the below cells, there are various parameters and options to play with involving data creation, algorithm settings, and what model you want to try and fit. | #outputs probability between 0 and 1, used to help define our logistic regression curve
def sigmoid(x):
'''Sigmoid function of x.'''
return 1/(1+np.exp(-x)) | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
 | #makes the random numbers predictable
#(pseudo-)random numbers work by starting with a number (the seed),
#multiplying it by a large number, then taking modulo of that product.
#The resulting number is then used as the seed to generate the next "random" number.
#When you set the seed (every time), it does the same t... | /home/dks/.local/lib/python3.5/site-packages/ipykernel/__main__.py:4: RuntimeWarning: overflow encountered in exp
| Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Algorithm SetupWe begin with a quick function for catching singular matrix errors that we will use to decorate our Newton steps. | #like dividing by zero (Wtff omgggggg universe collapses)
def catch_singularity(f):
'''Silences LinAlg Errors and throws a warning instead.'''
def silencer(*args, **kwargs):
try:
return f(*args, **kwargs)
except np.linalg.LinAlgError:
warnings.warn('Algorithm termina... | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Explanation of a Single Newton StepRecall that Newton's method for maximizing / minimizing a given function $f(\beta)$ iteratively computes the following estimate:$$\beta^+ = \beta - Hf(\beta)^{-1}\nabla f(\beta)$$The Hessian of the log-likelihood for logistic regression is given by:hessian of our function = negative ... | @catch_singularity
def newton_step(curr, X, lam=None):
'''One naive step of Newton's Method'''
#how to compute inverse? http://www.mathwarehouse.com/algebra/matrix/images/square-matrix/inverse-matrix.gif
## compute necessary objects
#create probability matrix, miniminum 2 dimensions, tranpose ... | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Next, we implement Newton's method in a *slightly* different way; this time, at each iteration, we actually compute the full inverse of the Hessian using `np.linalg.inv()`. | @catch_singularity
def alt_newton_step(curr, X, lam=None):
'''One naive step of Newton's Method'''
## compute necessary objects
p = np.array(sigmoid(X.dot(curr[:,0])), ndmin=2).T
W = np.diag((p*(1-p))[:,0])
hessian = X.T.dot(W).dot(X)
grad = X.T.dot(y-p)
## regularization
if la... | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Convergence SetupFirst we implement coefficient convergence; this stopping criterion results in convergence whenever$$\|\beta^+ - \beta\|_\infty < \epsilon$$where $\epsilon$ is a given tolerance. | def check_coefs_convergence(beta_old, beta_new, tol, iters):
'''Checks whether the coefficients have converged in the l-infinity norm.
Returns True if they have converged, False otherwise.'''
#calculate the change in the coefficients
coef_change = np.abs(beta_old - beta_new)
#if change hasn't r... | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
Numerical Examples Standard Newton with Coefficient Convergence | ## initial conditions
#initial coefficients (weight values), 2 copies, we'll update one
beta_old, beta = np.ones((len(X.columns),1)), np.zeros((len(X.columns),1))
#num iterations we've done so far
iter_count = 0
#have we reached convergence?
coefs_converged = False
#if we haven't reached convergence... (training step... | _____no_output_____ | Apache-2.0 | Logistic_Regression/logistic_regression_newtons_method-master/NewtonCode.ipynb | DillipKS/The-Math-of-Intelligence-course |
A=int(input ("Digite um número "))
B=int(input ("Digite um número "))
C=A+B
print (C)
A=int(input ("Digite um número "))
B=int(input ("Digite um número "))
C=A+B
D=A-B
E=A/B
F=A*B
print (C)
print (D)
print (E)
print (F)
Dist=float(input ("Digite a distância percorrida "))
Comb= float(input ("Digite o combustível gasto ... | _____no_output_____ | Unlicense | Trabalho.ipynb | Clayton100/Phyton | |
Variables and data typesVariables are used to temporarily store a value in the computer's memory. We can then use it later, when we need it in the program. We can compare that to a small box in which we could store information. Since Python is a dynamically typed language, Python values, not variables, carry type. Thi... | # BAD
2name = "James"
# BAD
-name = "Bond"
# BAD
My name = "bond" | _____no_output_____ | MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
The print() function allows us to display the result. | # GOOD
name = "Bond"
print("Your name is", name) | _____no_output_____ | MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
To format the text, you can use the format() method in the class string | last_name = "Bond"
first_name = "James"
text = "My name is {}, {} {}.".format(last_name, first_name, last_name)
print(text) | My name is Bond, James Bond.
| MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
Another example. Replace the value of the variable ``age`` with your age and the variable ``firstname`` with your First name. | age = "34"
first_name ="Ludovic"
text = "Hello, my name is {} and i am {}".format(first_name, age)
print(text) | Hello, my name is Ludovic and i am 34
| MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
Data typesSince Python is a high-level language, it has a dynamic variable typing. By dynamics, understand that it is the computer that deals with defining what type of variable should be used. To be perfectly accurate, **it is not the variable that is typed (unlike Java) but its content**In java we declare a varia... | first_name = "James" # String
last_name = "Bond" # String
age = 39 # Integer
weigth = 81.56 # Float
double_agent = True # Boolean
login = "007" # String
agent = [first_name, last_name, age, weigth, double_agent, login] # List
print(agent) | ['James', 'Bond', 39, 81.56, True, '007']
| MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
1. Note that ``True`` and ``False`` are written with the first letter uppercase.2. ``login`` is a string.3. ``List`` is like an array, but you can store values of different types. Here is a not limited list of the types we use most often. These are the most frequently used. For tuples, dictionaries and sets we'll see ... | print(first_name, type(first_name))
print(last_name, type(last_name))
print(age, type(age))
print(weigth, type(weigth))
print(agent, type(agent)) | James <class 'str'>
Bond <class 'str'>
39 <class 'int'>
81.56 <class 'float'>
['James', 'Bond', 39, 81.56, True, '007'] <class 'list'>
| MIT | Content/1.python/1.python_fundamentals/01.Python-Basics/2.variables-and-data-types/variables_and_data_types.ipynb | becodeorg/ai_fundamentals_1.0 |
TF-IDF | import mwdsbe
import mwdsbe.datasets.licenses as licenses
import schuylkill as skool
import pandas as pd
import numpy as np
# import registry
registry = mwdsbe.load_registry() # geopandas df
registry.head()
# import license data
license = licenses.CommercialActivityLicenses.download()
license.head()
mini_registry = reg... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/tf-idf-alg-test-nick-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Generating percentiles for TensorFlow model input featuresThe current TensorFlow model uses histogram-like percentile features, which are kind of a continuous version of one-hot features.For example, if key cutoff points are `[-3, 1, 0, 2, 10]`, we might encode a value `x` as `sigma((x - cutoff) / scale)`. If `sigma` ... | # Different options for soft-onehot function.
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-10, 10, 100)
cutoff = 1.0
sigmoid = lambda x: 1/(1+np.exp(-x))
scale = 2.0
logit = (x - cutoff) / scale
plt.plot(x, sigmoid(logit))
plt.plot(x, np.exp(- logit * logit))
NUM_LCS = 10_... | _____no_output_____ | MIT | tf_align_model_input_feature_percentiles.ipynb | aimalz/justice |
Really messy code to get a histogram with mostly-unique bins.Because we want fixed-size arrays for TensorFlow code, we want a set of e.g. 32 unique cutoff points that reflect a good distribution of cutoffs. However its is really messy, because there tend to be strong peaks in the histogram which are repeated frequentl... | import collections
import scipy.optimize
def _some_duplicates(non_unique, unique, num_desired):
to_duplicate_candidates = non_unique.tolist()
for x in unique:
to_duplicate_candidates.remove(x)
unique = unique.tolist()
while len(unique) < num_desired:
assert len(unique) <= num_desired
... | _____no_output_____ | MIT | tf_align_model_input_feature_percentiles.ipynb | aimalz/justice |
Save to nicely-formatted JSONWrites numpy arrays as strings, then rewrites those strings. | import datetime
import json
from justice import path_util
class ArrayPreEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return "<<<<{}>>>>".format(", ".join(f"{x:.8f}" for x in obj.tolist()))
else:
print(obj)
return json.JSONEncode... | _____no_output_____ | MIT | tf_align_model_input_feature_percentiles.ipynb | aimalz/justice |
`BcForms` is a toolkit for concretely describing the primary structure of macromolecular complexes, including non-canonical monomeric forms and intra and inter-subunit crosslinks. `BcForms` includes a textual grammar for describing complexes and a Python library, a command line program, and a REST API for validating an... | import bcforms
import bpforms | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Create complexes from their string representations | form_1 = bcforms.BcForm().from_str('2 * subunit_a + 3 * subunit_b')
form_1.set_subunit_attribute('subunit_a', 'structure',
bpforms.ProteinForm().from_str('CAAAAAAAA'))
form_1.set_subunit_attribute('subunit_b', 'structure',
bpforms.ProteinForm().from_str('AAAAAAAAC'))
form_2 = bcforms.BcForm().from_str(
'2 *... | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Create complexes programmatically | form_1_b = bcforms.BcForm()
form_1_b.subunits.append(bcforms.core.Subunit('subunit_a', 2,
bpforms.ProteinForm().from_str('CAAAAAAAA')))
form_1_b.subunits.append(bcforms.core.Subunit('subunit_b', 3,
bpforms.ProteinForm().from_str('AAAAAAAAC')))
form_2_b = bcforms.BcForm()
subunit = bcforms.core.Subunit('subunit_... | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Get properties of polymers Subunits | form_1.subunits | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Crosslinks | form_2.crosslinks | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Get the string representation of a complex | str(form_1_b) | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Check equality of complexes | form_1_b.is_equal(form_1) | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Calculate properties of a complex Molecular structure | form_1.get_structure()[0] | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
SMILES representation | form_1.export('smiles') | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Formula | form_1.get_formula() | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Charge | form_1.get_charge() | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Molecular weight | form_1.get_mol_wt() | _____no_output_____ | MIT | examples/1. Introductory tutorial.ipynb | KarrLab/bcforms |
Copyright 2018 The AdaNet 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 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
AdaNet on TPU Run in Google Colab View source on GitHub AdaNet supports training on Google's custom machine learning accelerators knownas Tensor Processing Units (TPU). Conveniently, we provide `adanet.TPUEstimator`which handles TPU support behind the scenes. There are only a few minor changesneeded to ... | #@test {"skip": true}
# If you're running this in Colab, first install the adanet package:
!pip install adanet
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import json
import os
import six
import time
import adanet
from google.colab impo... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
Fashion MNISTWe focus again on the Fashion MNIST dataset and download the data via Keras. | (x_train, y_train), (x_test, y_test) = (
tf.keras.datasets.fashion_mnist.load_data()) | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
32768/29515 [=================================] - 0s 0us/step
40960/29515 [=========================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datase... | Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
`input_fn` ChangesThere are two minor changes we must make to `input_fn` to support running onTPU:1. TPUs dynamically shard the input data depending on the number of cores used. Because of this, we augment `input_fn` to take a dictionary `params` argument. When running on TPU, `params` contains a `batch_size` f... | FEATURES_KEY = "images"
def generator(images, labels):
"""Returns a generator that returns image-label pairs."""
def _gen():
for image, label in zip(images, labels):
yield image, label
return _gen
def preprocess_image(image, label):
"""Preprocesses an image for an `Estimator`."""
image = image... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
`model_fn` ChangesWe use a similar CNN architecture as used in the[Customizing AdaNet](https://colab.sandbox.google.com/github/tensorflow/adanet/blob/master/adanet/examples/tutorials/customizing_adanet.ipynb)tutorial. The only TPU specific change we need to make is wrap the `optimizer`in a[`tf.contrib.tpu.CrossShardOp... | #@title Define the Builder and Generator
class SimpleCNNBuilder(adanet.subnetwork.Builder):
"""Builds a CNN subnetwork for AdaNet."""
def __init__(self, learning_rate, max_iteration_steps, seed):
"""Initializes a `SimpleCNNBuilder`.
Args:
learning_rate: The float learning rate to use.
max_iter... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
Launch TensorBoardLet's run [TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard) to visualize model training over time. We'll use [ngrok](https://ngrok.com/) to tunnel traffic to localhost.*The instructions for setting up Tensorboard were obtained from https://www.dlology.com/blog/quick-guide-to-r... | #@test {"skip": true}
get_ipython().system_raw(
'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
.format(MODEL_DIR)
)
# Install ngrok binary.
! wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
! unzip ngrok-stable-linux-amd64.zip
print("Follow this link to open TensorBoard in a ne... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
Using `adanet.TPUEstimator` to Train and EvaluateFinally, we switch from `adanet.Estimator` to `adanet.TPUEstimator`. There aretwo last changes needed:1. Update the `RunConfig` to be a [`tf.contrib.tpu.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/contrib/tpu/RunConfig). We supply the TPU `master` a... | #@title AdaNet Parameters
LEARNING_RATE = 0.25 #@param {type:"number"}
TRAIN_STEPS = 1000 #@param {type:"integer"}
BATCH_SIZE = 512 #@param {type:"integer"}
ADANET_ITERATIONS = 2 #@param {type:"integer"}
# TPU: switch `tf.estimator.RunConfig` to `tf.contrib.tpu.RunConfig`.
# The main required changes are specifyin... | Accuracy: 0.8913
Loss: 0.298405
| Apache-2.0 | adanet/examples/tutorials/adanet_tpu.ipynb | gitter-badger/adanet |
Time windows Setup | import tensorflow as tf | _____no_output_____ | MIT | 4. Time Series/Udacity/03_time_windows.ipynb | AmirRazaMBA/TensorFlow-Certification |
Time WindowsFirst, we will train a model to forecast the next step given the previous 20 steps, therefore, we need to create a dataset of 20-step windows for training. | dataset = tf.data.Dataset.range(10)
for val in dataset:
print(val.numpy())
dataset = tf.data.Dataset.range(10)
dataset = dataset.window(5, shift=1)
for window_dataset in dataset:
for val in window_dataset:
print(val.numpy(), end=" ")
print()
dataset = tf.data.Dataset.range(10)
dataset = dataset.wind... | _____no_output_____ | MIT | 4. Time Series/Udacity/03_time_windows.ipynb | AmirRazaMBA/TensorFlow-Certification |
Data Procesing | import pandas as pd
import h2o
from h2o.estimators.random_forest import H2ORandomForestEstimator
h2o.init()
%%time
train_new = pd.read_csv("D:\\DC Universe\\Ucsc\\Third Year\\ENH 3201 Industrial Placements\\H20 Applications\\H20 ML Notebooks\\H20Csv\\Titanic\\titanic_train.csv")
test = pd.read_csv("D:\\DC Universe\\Ucs... | _____no_output_____ | Apache-2.0 | H20 ML Notebooks/H20 Finalized Chunking Procedure.ipynb | Pandula1234/Data-Analysis-Intern |
MNIST Classification with CNN -- Customized training loops --In this notebook, I describe how to implement CNN using tf.keras.Training loop is defined by customized step-by-step training loops. | import tensorflow as tf
import time
import numpy as np
import sklearn
from sklearn.model_selection import train_test_split
import matplotlib
import matplotlib.pyplot as plt
import os
%matplotlib inline
print("tensorflow version: ", tf.__version__)
print("numpy version: ", np.__version__)
print("scikit learn version: "... | tensorflow version: 2.3.0
numpy version: 1.19.1
scikit learn version: 0.23.2
matplotlib version: 3.3.0
| MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
1. Load data & preprocessingIn this notebook, I use pre-defined mnist dataset. | (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# Split original training dataset into train/validation dataset
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, shuffle=True)
# Normalize Intensity
X_train = X_train / 255.
X_val = X_val / 255.
X_test = X_test ... | _____no_output_____ | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
2. Create tf.data.Dataset | train_batch_size = 64
test_batch_size = 1
# Build source dataset for training
X_train_dataset = tf.data.Dataset.from_tensor_slices(X_train)
y_train_dataset = tf.data.Dataset.from_tensor_slices(y_train)
train_dataset = tf.data.Dataset.zip((X_train_dataset, y_train_dataset)).batch(train_batch_size)
# Build source datas... | _____no_output_____ | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
Debug dataset | def visualize_batch(X_batch, y_batch, y_pred=None):
assert len(X_batch) == len(y_batch)
n_col = 10
if len(X_batch) % n_col ==0:
n_row=len(X_batch)//n_col
else:
n_row=len(X_batch)//n_col + 1
fig = plt.figure(figsize=(20,15))
for idx in range(len(y_batch)):
i... | _____no_output_____ | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
3. Create CNN modelNetwork structure:[CONV(32) - BN - RELU] - MAXPOOL - [CONV(64) - BN - RELU] - MAXPOOL - [FC(1024) - BN - RELU] - DROPOUT - FC(10) - SOFTMAXThe weight initialization rule are following: - Layer with relu activation: He initialization - Others: Xavier initialization Define networkBy creating mode... | class ConvNet(tf.keras.Model):
def __init__(self, conv_filters=[32, 64], units=1024, num_class=10, dropout_rate=0.2):
super(ConvNet, self).__init__(name="ConvNet")
self.conv1 = tf.keras.layers.Conv2D(conv_filters[0], 3, 1, 'same',
kernel_initializer=tf.ke... | _____no_output_____ | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
4. Training | lr = 0.0001
epochs = 10
# -------------------------------------------------------------
loss = tf.keras.losses.BinaryCrossentropy(from_logits=True)
accuracy = tf.keras.metrics.CategoricalAccuracy()
optimizer = tf.keras.optimizers.Adam(lr)
# Define model
model = ConvNet()
@tf.function
def train_on_batch(model, X, y,... | WARNING:tensorflow:Layer ConvNet is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this w... | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
5. Test | accuracy.reset_states()
test_losses = []
for X, y in test_dataset:
test_loss = eval_on_batch(model, X, y, accuracy)
test_losses.append(test_loss)
test_accuracy = accuracy.result()
test_loss = np.average(test_losses)
print('loss: {:.5f}, accuracy: {:.5f}'.format(test_loss, test_accuracy))
index = np.random.ch... | _____no_output_____ | MIT | notebooks_tf2/3_ConvolutionalNetwork/2_CustomizedTrainingLoops.ipynb | kattoyoshi/Tensorflow-Examples |
"Thresholding" RecapThis is the Lab on Thresholding for Classical Image Segmention in CE6003. You should complete the tasks in this lab as part of the Thresholding section of the lesson.Please remember this lab must be completed before taking the quiz at the end of this lesson. First, if we haven't already done so, ... | #!git clone https://github.com/EmdaloTechnologies/CE6003.git | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
IntroductionIn this lab we introduce our first image segmentation project where we will use thresholding operations to segment a relatively simple image. We will work through this project using the types of image processing techniques such projects typically need and then segment an image. At the end of the lab we'll... | # First import OpenCV, NumPY and MatPlotLib as we will use these libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Load a color image
#img = cv2.imread("/content/CE6003/images/lab2/starfish.png")
img = cv2.imread("./images/lab2/starfish.png")
#plt.imshow(img, cmap='gray')
#... | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
After applying the fastN1MeansDenoisingColored routine above, you should end up with an image similar to the one on the right here. You may need to vary the h and hColor parameters to observe the effect of changing them on the blurred image.Your blurred image should look like this one. Now, lets run a morphological op... | # Apply a morphological gradient (dilate the image, erode the image, and take the difference
elKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13,13))
# YOUR CODE HERE
# Exercise: Use openCV's morphologyEx to generate a gradient using the kernel above
gradient = cv2.morphologyEx(blur, cv2.MORPH_GRADIENT, elKer... | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
After applying the gradient morphology routine above, you should end up with an image similar to the one shown here. The outline of the starfish should be starting to emerge at this point. We now have completed the pre-processing of our image. From this point onwards, we are concerning ourselves with:a) filling th... | # Apply Otsu's method - or you can adjust the level at which thresholding occurs
# and see what the effect of this is
# Convert gradient to grayscale
gray_gradient = cv2.cvtColor(gradient, cv2.COLOR_BGR2GRAY)
# YOUR CODE HERE
# Exercise: Generate a matrix called otsu using OpenCV's threshold() function. Use
# Otsu'... | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
After switching to black and white and applying our closing and erosion operations, our simplified starfish is starting to emerge Original Image | B&W Image | After Closing | After Erosion:------------------------:|:------------------------------:|:------------------... | p = int(img.shape[1] * 0.05)
eroded[:, 0:p] = 0
eroded[:, img.shape[1] - p:] = 0
plt.imshow(eroded, cmap='gray')
# from https://www.programcreek.com/python/example/70440/cv2.findContours
major = cv2.__version__.split('.')[0]
print(major)
# YOUR CODE HERE
# Exercise: Find the contours - just external contours to keep ... | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
You should have generated a reasonable mask representing our image as having two parts - a 'starfish' and 'not a starfish'. It should look like the final mask in the image below. Starfish Mask | Not Starfish Mask | Final Mask:-------------------------------:|:----------------------... | # Now, lets just blend our original image with our mask
# YOUR CODE HERE
# Exercise: Blend the original image 'img' and our mask 'mask'
# in any way you see fit, and store it in a variable called output
# Hint: You'll find answers at the bottom of the lab.
output = cv2.bitwise_or(mask, img)
# END YOUR CODE HERE
plt.i... | _____no_output_____ | MIT | Lab_2_1_Thresholding.ipynb | power9939/CE6003 |
Week 1 Assignment: Housing PricesIn this exercise you'll try to build a neural network that predicts the price of a house according to a simple formula.Imagine that house pricing is as easy as:A house has a base cost of 50k, and every additional bedroom adds a cost of 50k. This will make a 1 bedroom house cost 100k, a... | import keras
import numpy as np
# GRADED FUNCTION: house_model
def normalize(xs,ys):
return xs,ys*0.01
def un_normalize(xs,ys):
return xs,ys*100.
def house_model():
### START CODE HERE
# Define input and output tensors with the values for houses with 1 up to 6 bedrooms
# Hint: Remember to expli... | _____no_output_____ | MIT | Tensorflow/Courses/0_Intro_to_tf/2_Week1_Assignmen_normalized.ipynb | maxtcurie/Artificial_Intelligence |
Now that you have a function that returns a compiled and trained model when invoked, use it to get the model to predict the price of houses: | # Get your trained model
model = house_model() | [0. 1. 2. 3. 4. 5.]
[ 50. 100. 150. 200. 250. 300.]
[0. 1. 2. 3. 4. 5.]
[0.5 1. 1.5 2. 2.5 3. ]
Epoch 1/1000
1/1 [==============================] - 0s 236ms/step - loss: 0.6199
Epoch 2/1000
1/1 [==============================] - 0s 997us/step - loss: 0.4340
Epoch 3/1000
1/1 [==============================] - 0s 2ms/s... | MIT | Tensorflow/Courses/0_Intro_to_tf/2_Week1_Assignmen_normalized.ipynb | maxtcurie/Artificial_Intelligence |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.