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 |
|---|---|---|---|---|---|
Comparison with detectron | def load_images(image_path):
files = os.listdir(frame_path)
files_name = [file_name for file_name in files if file_name.endswith('.jpg')]
files_name.sort()
frames = []
#read the first 100 images
for i, file_name in enumerate(files_name):
frame = cv2.imread(image_path + file_name)
frames.a... | _____no_output_____ | MIT | Part2.ipynb | ismailfaruk/ECSE415-Final-Project |
Understanding Cross-Entropy Loss**Recall:** a loss function compares the predictions of a model with the correct labels to tell us how well the model is doing, and to help find out how we can update the model's parameters to improve its performance (using gradient descent).**Cross-entropy** is a loss function we can u... | import torch
t = torch.tensor([[-9, 5, 10]], dtype=torch.double)
torch.softmax(t, dim=1) | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
Mathematically, each of the values above is calculated as follows:We can create a function to calculate the softmax on our own as follows: | def softmax(x):
return torch.exp(x) / torch.exp(x).sum()
softmax(t) | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
Each value can be interpreted as the confidence with which the model predicts the corresponding output as the correct class.Since the exponential function is used in the softmax layer, any raw output from the model that is slightly higher than another will be amplified by the softmax layer.*The exponential... | model_output = torch.randn((3, 5))
model_output | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
Let us also assume that the correct classes for these data points are as follows: | targets = torch.tensor([3, 0, 1])
targets | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
We first pass these outputs through a softmax layer: | sm = torch.softmax(model_output, dim = 1)
sm | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
As expected, all values have been squished between 0 and 1.We can also confirm that for each data point, the values sum up to 1: | sm.sum(dim=1) | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
Next, we take the log of these values: | lg = torch.log(sm)
lg | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
We can then use `nll_loss` (i.e. Negative Log Likelihood) that will find the mean of the values corresponding to the correct class. This function will also multiply the values by -1 for us before doing so. | import torch.nn.functional as F
loss = F.nll_loss(lg, targets)
loss | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
We can manually verify this for the 3 data points: | -1 * (lg[0][targets[0]] + lg[1][targets[1]] + lg[2][targets[2]]) / 3 | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
Note that the `nll_loss` function assumes that the log has been taken before the values are passed to the function.PyTorch has a `log_softmax` function that combines softmax with log in one step. We can use that function to achieve the same result as follows: | lsm = F.log_softmax(model_output, dim = 1)
loss = F.nll_loss(lsm, targets)
loss | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
PyTorch also has a cross-entropy loss that can be used directly on raw model outputs: | F.cross_entropy(model_output, targets) | _____no_output_____ | MIT | content/notebooks/2021-07-18-understanding-cross-entropy-loss.ipynb | mashruravi/homepage |
--- Some websites to open up for class: - [Overleaf](https://v2.overleaf.com/)- [Overleaf Docs and Help](https://v2.overleaf.com/learn)- [Latex Symbols](https://en.wikipedia.org/wiki/Wikipedia:LaTeX_symbols)- [Latex draw symbols](http://detexify.kirelabs.org/classify.html)- [The SAO/NASA Astrophysics Data System](... | -----------------------------------------------------------------------------
LaTeX homework - Create a LaTeX document with references.
-----------------------------------------------------------------------------
Start with the file: FirstLast.tex
Minimum required elements:
* Between 2 and 4 pages in length (pages ... | _____no_output_____ | MIT | LaTeX_Assignment.ipynb | UWashington-Astro300/Astro300-Wtr19 |
`pandas` can output $\LaTeX$ tables | import pandas as pd
my_table = pd.read_csv('./Data/Zodiac.csv')
my_table[0:3]
print(my_table.to_latex(index=False)) | _____no_output_____ | MIT | LaTeX_Assignment.ipynb | UWashington-Astro300/Astro300-Wtr19 |
Read the CSV and Perform Basic Data Cleaning | df = pd.read_csv("exoplanet_data.csv")
# Drop the null columns where all values are null
df = df.dropna(axis='columns', how='all')
# Drop the null rows
df = df.dropna()
df.head()
df = df[df["koi_disposition"] != 'CANDIDATE']
df["koi_disposition"].value_counts() | _____no_output_____ | ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Select your features (columns) | # Set features. This will also be used as your x values.
selected_features = df[['koi_period', 'koi_impact', 'koi_duration', 'koi_depth', 'koi_prad', 'koi_teq', 'koi_insol', 'koi_steff', 'koi_slogg', 'koi_srad']]
selected_features.koi_period.astype(float) | _____no_output_____ | ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Create a Train Test SplitUse `koi_disposition` for the y values | selected_features['koi_disposition_dummy'] = selected_features.koi_disposition.map({'FALSE POSITIVE':0, 'CONFIRMED':1})
y = selected_features['koi_disposition_dummy']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(selected_features, y, random_state=0)
y_train.h... | _____no_output_____ | ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Pre-processingScale the data using the MinMaxScaler and perform some feature selection | # Scale your data
from sklearn.preprocessing import MinMaxScaler
minmax = MinMaxScaler()
minmax_fitted = minmax.fit(X_train)
X_trains = minmax_fitted.transform(X_train)
X_tests = minmax_fitted.transform(X_test)
# y_trains = minmax.fit_transform(y_train)
# y_tests = minmax.fit_transform(y_test) | _____no_output_____ | ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Train the Model Not using scaled | from sklearn.cluster import KMeans
from sklearn import metrics
model1 = KMeans(n_clusters=3)
model1.fit(X_train)
# Predict the clusters
pred = model1.predict(X_test)
pred_train = model1.predict(X_train)
# testing score
score = metrics.f1_score(y_test, pred, pos_label=list(set(y_test)), average=None)
# training score
sc... | Training Data Score: 0.7941800545619885
-----------------------------------------------------
Testing Data Score: 0.7972789115646258
| ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Using scaled | kmeansS = KMeans(n_clusters=3)
kmeansS.fit(X_trains)
# Predict the clusters
preds = kmeansS.predict(X_tests)
pred_trains = kmeansS.predict(X_trains)
# testing score
scores = metrics.f1_score(y_test, preds, pos_label=list(set(y_test)), average=None)
# training score
score_trains = metrics.f1_score(y_train, pred_trains... | Testing score: -29.14663974446135
Training score: -87.19826994353079
[0.21327968 0.5829904 0. ]
[0.23431242 0.59401416 0. ]
| ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Save the Model | # save your model by updating "your_name" with your name
# and "your_model" with your model variable
# be sure to turn this in to BCS
# if joblib fails to import, try running the command to install in terminal/git-bash
import joblib
filename = 'megan_okerlund_model1.sav'
joblib.dump(model1, filename) | _____no_output_____ | ADSL | Mokerlund's_solution/Ipynb_and_code/model_1.ipynb | mokerlund/machine_learning_classification_challenge |
Transfer LearningIn this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html). ImageNet is a massiv... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`. | ! curl -O "https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip"
! unzip Cat_Dog_data.zip
data_dir = 'Cat_Dog_data'
# TODO: Define transforms for the training data and testing data
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transform... | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.htmlid5). Let's print out the model architecture so we can see what's going on. | model = models.densenet121(pretrained=True)
model | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. T... | # Freeze parameters so we don't backprop through them
for param in model.parameters():
param.requires_grad = False
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(1024, 500)),
('relu', nn.ReLU()),
... | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU lea... | import time
for device in ['cpu', 'cuda']:
criterion = nn.NLLLoss()
# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
model.to(device)
for ii, (inputs, labels) in enumerate(trainloader):
# Move input and ... | Device = cpu; Time per batch: 4.035 seconds
Device = cuda; Time per batch: 0.008 seconds
| MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
You can write device agnostic code which will automatically use CUDA if it's enabled like so:```python at beginning of the scriptdevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")... then whenever you get a new Tensor or Module this won't copy if they are already on the desired deviceinput = data.t... | ## TODO: Use a pretrained model to classify the cat and dog images
sum([p.numel() for p in model.parameters()])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = models.densenet121(pretrained=True)
# Freeze parameters so we don't backprop through them
for param in model.parameters():
... | _____no_output_____ | MIT | intro-to-pytorch/Part 8 - Transfer Learning (Exercises).ipynb | AdelNamani/deep-learning-v2-pytorch |
Declare data | edges = pd.read_csv('../../../assets/energy.csv')
edges.head(5) | _____no_output_____ | BSD-3-Clause | examples/gallery/demos/bokeh/energy_sankey.ipynb | jsignell/holoviews |
Plot | hv.Sankey(edges).options(label_position='left') | _____no_output_____ | BSD-3-Clause | examples/gallery/demos/bokeh/energy_sankey.ipynb | jsignell/holoviews |
**Chapter 12 – Custom Models and Training with TensorFlow** _This notebook contains all the sample code in chapter 12._ Setup First, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed... | # Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
# TensorFlow ≥2.4 is required in this notebook
# Earl... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Tensors and operations Tensors | tf.constant([[1., 2., 3.], [4., 5., 6.]]) # matrix
tf.constant(42) # scalar
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])
t
t.shape
t.dtype | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Indexing | t[:, 1:]
t[..., 1, tf.newaxis] | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Ops | t + 10
tf.square(t)
t @ tf.transpose(t) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Using `keras.backend` | from tensorflow import keras
K = keras.backend
K.square(K.transpose(t)) + 10 | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
From/To NumPy | a = np.array([2., 4., 5.])
tf.constant(a)
t.numpy()
np.array(t)
tf.square(a)
np.square(t) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Conflicting Types | try:
tf.constant(2.0) + tf.constant(40)
except tf.errors.InvalidArgumentError as ex:
print(ex)
try:
tf.constant(2.0) + tf.constant(40., dtype=tf.float64)
except tf.errors.InvalidArgumentError as ex:
print(ex)
t2 = tf.constant(40., dtype=tf.float64)
tf.constant(2.0) + tf.cast(t2, tf.float32) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Strings | tf.constant(b"hello world")
tf.constant("café")
u = tf.constant([ord(c) for c in "café"])
u
b = tf.strings.unicode_encode(u, "UTF-8")
tf.strings.length(b, unit="UTF8_CHAR")
tf.strings.unicode_decode(b, "UTF-8") | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
String arrays | p = tf.constant(["Café", "Coffee", "caffè", "咖啡"])
tf.strings.length(p, unit="UTF8_CHAR")
r = tf.strings.unicode_decode(p, "UTF8")
r
print(r) | <tf.RaggedTensor [[67, 97, 102, 233], [67, 111, 102, 102, 101, 101], [99, 97, 102, 102, 232], [21654, 21857]]>
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Ragged tensors | print(r[1])
print(r[1:3])
r2 = tf.ragged.constant([[65, 66], [], [67]])
print(tf.concat([r, r2], axis=0))
r3 = tf.ragged.constant([[68, 69, 70], [71], [], [72, 73]])
print(tf.concat([r, r3], axis=1))
tf.strings.unicode_encode(r3, "UTF-8")
r.to_tensor() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Sparse tensors | s = tf.SparseTensor(indices=[[0, 1], [1, 0], [2, 3]],
values=[1., 2., 3.],
dense_shape=[3, 4])
print(s)
tf.sparse.to_dense(s)
s2 = s * 2.0
try:
s3 = s + 1.
except TypeError as ex:
print(ex)
s4 = tf.constant([[10., 20.], [30., 40.], [50., 60.], [70., 80.]])
tf.sparse.spars... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Sets | set1 = tf.constant([[2, 3, 5, 7], [7, 9, 0, 0]])
set2 = tf.constant([[4, 5, 6], [9, 10, 0]])
tf.sparse.to_dense(tf.sets.union(set1, set2))
tf.sparse.to_dense(tf.sets.difference(set1, set2))
tf.sparse.to_dense(tf.sets.intersection(set1, set2)) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Variables | v = tf.Variable([[1., 2., 3.], [4., 5., 6.]])
v.assign(2 * v)
v[0, 1].assign(42)
v[:, 2].assign([0., 1.])
try:
v[1] = [7., 8., 9.]
except TypeError as ex:
print(ex)
v.scatter_nd_update(indices=[[0, 0], [1, 2]],
updates=[100., 200.])
sparse_delta = tf.IndexedSlices(values=[[1., 2., 3.], [4., ... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Tensor Arrays | array = tf.TensorArray(dtype=tf.float32, size=3)
array = array.write(0, tf.constant([1., 2.]))
array = array.write(1, tf.constant([3., 10.]))
array = array.write(2, tf.constant([5., 7.]))
array.read(1)
array.stack()
mean, variance = tf.nn.moments(array.stack(), axes=0)
mean
variance | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Custom loss function Let's start by loading and preparing the California housing dataset. We first load it, then split it into a training set, a validation set and a test set, and finally we scale it: | from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing()
X_train_full, X_test, y_train_full, y_test = train_test_split(
housing.data, housing.target.reshape(-1, 1), random_state=4... | Epoch 1/2
363/363 [==============================] - 1s 2ms/step - loss: 1.0443 - mae: 1.4660 - val_loss: 0.2862 - val_mae: 0.5866
Epoch 2/2
363/363 [==============================] - 0s 737us/step - loss: 0.2379 - mae: 0.5407 - val_loss: 0.2382 - val_mae: 0.5281
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Saving/Loading Models with Custom Objects | model.save("my_model_with_a_custom_loss.h5")
model = keras.models.load_model("my_model_with_a_custom_loss.h5",
custom_objects={"huber_fn": huber_fn})
model.fit(X_train_scaled, y_train, epochs=2,
validation_data=(X_valid_scaled, y_valid))
def create_huber(threshold=1.0):
def... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Other Custom Functions | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
def my_softplus(z): # return value is just tf.nn.softplus(z)
return tf.math.log(tf.exp(z) + 1.0)
def my_glorot_initializer(shape, dtype=tf.float32):
stddev = tf.sqrt(2. / (shape[0] + shape[1]))
return tf.random.normal(shape, stddev=std... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Custom Metrics | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="selu", kernel_initializer="lecun_normal",
input_shape=input_shape),
keras.layers.Dense(1),
])
model.compile(loss="mse", optimizer="nadam", metrics=[... | Epoch 1/2
363/363 [==============================] - 1s 572us/step - loss: 3.5903 - huber_fn: 1.5558
Epoch 2/2
363/363 [==============================] - 0s 552us/step - loss: 0.8054 - huber_fn: 0.3095
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
**Note**: if you use the same function as the loss and a metric, you may be surprised to see different results. This is generally just due to floating point precision errors: even though the mathematical equations are equivalent, the operations are not run in the same order, which can lead to small differences. Moreove... | model.compile(loss=create_huber(2.0), optimizer="nadam", metrics=[create_huber(2.0)])
sample_weight = np.random.rand(len(y_train))
history = model.fit(X_train_scaled, y_train, epochs=2, sample_weight=sample_weight)
history.history["loss"][0], history.history["huber_fn"][0] * sample_weight.mean() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Streaming metrics | precision = keras.metrics.Precision()
precision([0, 1, 1, 1, 0, 1, 0, 1], [1, 1, 0, 1, 0, 1, 0, 1])
precision([0, 1, 0, 0, 1, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0])
precision.result()
precision.variables
precision.reset_states() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Creating a streaming metric: | class HuberMetric(keras.metrics.Metric):
def __init__(self, threshold=1.0, **kwargs):
super().__init__(**kwargs) # handles base args (e.g., dtype)
self.threshold = threshold
self.huber_fn = create_huber(threshold)
self.total = self.add_weight("total", initializer="zeros")
sel... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Let's check that the `HuberMetric` class works well: | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="selu", kernel_initializer="lecun_normal",
input_shape=input_shape),
keras.layers.Dense(1),
])
model.compile(loss=create_huber(2.0), optimizer="nadam... | Epoch 1/2
363/363 [==============================] - 0s 545us/step - loss: 0.2350 - huber_metric: 0.2350
Epoch 2/2
363/363 [==============================] - 0s 524us/step - loss: 0.2278 - huber_metric: 0.2278
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
**Warning**: In TF 2.2, tf.keras adds an extra first metric in `model.metrics` at position 0 (see [TF issue 38150](https://github.com/tensorflow/tensorflow/issues/38150)). This forces us to use `model.metrics[-1]` rather than `model.metrics[0]` to access the `HuberMetric`. | model.metrics[-1].threshold | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Looks like it works fine! More simply, we could have created the class like this: | class HuberMetric(keras.metrics.Mean):
def __init__(self, threshold=1.0, name='HuberMetric', dtype=None):
self.threshold = threshold
self.huber_fn = create_huber(threshold)
super().__init__(name=name, dtype=dtype)
def update_state(self, y_true, y_pred, sample_weight=None):
metric... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
This class handles shapes better, and it also supports sample weights. | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="selu", kernel_initializer="lecun_normal",
input_shape=input_shape),
keras.layers.Dense(1),
])
model.compile(loss=keras.losses.Huber(2.0), optimizer=... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Custom Layers | exponential_layer = keras.layers.Lambda(lambda x: tf.exp(x))
exponential_layer([-1., 0., 1.]) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Adding an exponential layer at the output of a regression model can be useful if the values to predict are positive and with very different scales (e.g., 0.001, 10., 10000): | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="relu", input_shape=input_shape),
keras.layers.Dense(1),
exponential_layer
])
model.compile(loss="mse", optimizer="sgd")
model.fit(X_train_scaled, y_train, epochs=5,
... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Our custom layer can be called using the functional API like this: | inputs1 = keras.layers.Input(shape=[2])
inputs2 = keras.layers.Input(shape=[2])
outputs1, outputs2 = MyMultiLayer()((inputs1, inputs2)) | X1.shape: (None, 2) X2.shape: (None, 2)
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Note that the `call()` method receives symbolic inputs, whose shape is only partially specified (at this stage, we don't know the batch size, which is why the first dimension is `None`):We can also pass actual data to the custom layer. To test this, let's split each dataset's inputs into two parts, with four features e... | def split_data(data):
columns_count = data.shape[-1]
half = columns_count // 2
return data[:, :half], data[:, half:]
X_train_scaled_A, X_train_scaled_B = split_data(X_train_scaled)
X_valid_scaled_A, X_valid_scaled_B = split_data(X_valid_scaled)
X_test_scaled_A, X_test_scaled_B = split_data(X_test_scaled)
... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Now notice that the shapes are fully specified: | outputs1, outputs2 = MyMultiLayer()((X_train_scaled_A, X_train_scaled_B)) | X1.shape: (11610, 4) X2.shape: (11610, 4)
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Let's build a more complete model using the functional API (this is just a toy example, don't expect awesome performance): | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
input_A = keras.layers.Input(shape=X_train_scaled_A.shape[-1])
input_B = keras.layers.Input(shape=X_train_scaled_B.shape[-1])
hidden_A, hidden_B = MyMultiLayer()((input_A, input_B))
hidden_A = keras.layers.Dense(30, activation='selu')(hidden_A)
hi... | Epoch 1/2
X1.shape: (None, 4) X2.shape: (None, 4)
X1.shape: (None, 4) X2.shape: (None, 4)
356/363 [============================>.] - ETA: 0s - loss: 3.6305X1.shape: (None, 4) X2.shape: (None, 4)
363/363 [==============================] - 1s 1ms/step - loss: 3.5973 - val_loss: 1.3630
Epoch 2/2
363/363 [========... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Now let's create a layer with a different behavior during training and testing: | class AddGaussianNoise(keras.layers.Layer):
def __init__(self, stddev, **kwargs):
super().__init__(**kwargs)
self.stddev = stddev
def call(self, X, training=None):
if training:
noise = tf.random.normal(tf.shape(X), stddev=self.stddev)
return X + noise
els... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Here's a simple model that uses this custom layer: | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
AddGaussianNoise(stddev=1.0),
keras.layers.Dense(30, activation="selu"),
keras.layers.Dense(1)
])
model.compile(loss="mse", optimizer="nadam")
model.fit(X_train_scaled, y_train, epochs=2,
val... | Epoch 1/2
363/363 [==============================] - 1s 892us/step - loss: 3.7869 - val_loss: 7.6082
Epoch 2/2
363/363 [==============================] - 0s 685us/step - loss: 1.2375 - val_loss: 4.4597
162/162 [==============================] - 0s 416us/step - loss: 0.7560
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Custom Models | X_new_scaled = X_test_scaled
class ResidualBlock(keras.layers.Layer):
def __init__(self, n_layers, n_neurons, **kwargs):
super().__init__(**kwargs)
self.hidden = [keras.layers.Dense(n_neurons, activation="elu",
kernel_initializer="he_normal")
... | Epoch 1/5
363/363 [==============================] - 1s 851us/step - loss: 0.9476
Epoch 2/5
363/363 [==============================] - 0s 736us/step - loss: 0.6998
Epoch 3/5
363/363 [==============================] - 0s 737us/step - loss: 0.4668
Epoch 4/5
363/363 [==============================] - 0s 758us/step - loss:... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
We could have defined the model using the sequential API instead: | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
block1 = ResidualBlock(2, 30)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="elu", kernel_initializer="he_normal"),
block1, block1, block1, block1,
ResidualBlock(2, 30),
keras.layers.Dense(1)
])
model.compile(l... | Epoch 1/5
363/363 [==============================] - 1s 709us/step - loss: 1.5508
Epoch 2/5
363/363 [==============================] - 0s 645us/step - loss: 0.5562
Epoch 3/5
363/363 [==============================] - 0s 625us/step - loss: 0.6406
Epoch 4/5
363/363 [==============================] - 0s 636us/step - loss:... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Losses and Metrics Based on Model Internals **Note**: the following code has two differences with the code in the book:1. It creates a `keras.metrics.Mean()` metric in the constructor and uses it in the `call()` method to track the mean reconstruction loss. Since we only want to do this during training, we add a `trai... | class ReconstructingRegressor(keras.Model):
def __init__(self, output_dim, **kwargs):
super().__init__(**kwargs)
self.hidden = [keras.layers.Dense(30, activation="selu",
kernel_initializer="lecun_normal")
for _ in range(5)]
sel... | Epoch 1/2
363/363 [==============================] - 1s 810us/step - loss: 1.6313 - reconstruction_error: 1.0474
Epoch 2/2
363/363 [==============================] - 0s 683us/step - loss: 0.4536 - reconstruction_error: 0.4022
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Computing Gradients with Autodiff | def f(w1, w2):
return 3 * w1 ** 2 + 2 * w1 * w2
w1, w2 = 5, 3
eps = 1e-6
(f(w1 + eps, w2) - f(w1, w2)) / eps
(f(w1, w2 + eps) - f(w1, w2)) / eps
w1, w2 = tf.Variable(5.), tf.Variable(3.)
with tf.GradientTape() as tape:
z = f(w1, w2)
gradients = tape.gradient(z, [w1, w2])
gradients
with tf.GradientTape() as tap... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Computing Gradients Using Autodiff | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
l2_reg = keras.regularizers.l2(0.05)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="elu", kernel_initializer="he_normal",
kernel_regularizer=l2_reg),
keras.layers.Dense(1, kernel_regularizer=l2_r... | 50/50 - loss: 0.0900 - mean_square: 858.5000
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
A fancier version with a progress bar: | def progress_bar(iteration, total, size=30):
running = iteration < total
c = ">" if running else "="
p = (size - 1) * iteration // total
fmt = "{{:-{}d}}/{{}} [{{}}]".format(len(str(total)))
params = [iteration, total, "=" * p + c + "." * (size - p - 1)]
return fmt.format(*params)
progress_bar(3... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
TensorFlow Functions | def cube(x):
return x ** 3
cube(2)
cube(tf.constant(2.0))
tf_cube = tf.function(cube)
tf_cube
tf_cube(2)
tf_cube(tf.constant(2.0)) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
TF Functions and Concrete Functions | concrete_function = tf_cube.get_concrete_function(tf.constant(2.0))
concrete_function.graph
concrete_function(tf.constant(2.0))
concrete_function is tf_cube.get_concrete_function(tf.constant(2.0)) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Exploring Function Definitions and Graphs | concrete_function.graph
ops = concrete_function.graph.get_operations()
ops
pow_op = ops[2]
list(pow_op.inputs)
pow_op.outputs
concrete_function.graph.get_operation_by_name('x')
concrete_function.graph.get_tensor_by_name('Identity:0')
concrete_function.function_def.signature | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
How TF Functions Trace Python Functions to Extract Their Computation Graphs | @tf.function
def tf_cube(x):
print("print:", x)
return x ** 3
result = tf_cube(tf.constant(2.0))
result
result = tf_cube(2)
result = tf_cube(3)
result = tf_cube(tf.constant([[1., 2.]])) # New shape: trace!
result = tf_cube(tf.constant([[3., 4.], [5., 6.]])) # New shape: trace!
result = tf_cube(tf.constant([[7.,... | print: 2
print: 3
print: Tensor("x:0", shape=(1, 2), dtype=float32)
print: Tensor("x:0", shape=(2, 2), dtype=float32)
WARNING:tensorflow:5 out of the last 5 calls to <function tf_cube at 0x7fbfc0363440> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creati... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
It is also possible to specify a particular input signature: | @tf.function(input_signature=[tf.TensorSpec([None, 28, 28], tf.float32)])
def shrink(images):
print("Tracing", images)
return images[:, ::2, ::2] # drop half the rows and columns
keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
img_batch_1 = tf.random.uniform(shape=[100, 28, 28])
img_batc... | Python inputs incompatible with input_signature:
inputs: (
tf.Tensor(
[[[0.7413678 0.62854624]
[0.01738465 0.3431449 ]]
[[0.51063764 0.3777541 ]
[0.07321596 0.02137029]]], shape=(2, 2, 2), dtype=float32))
input_signature: (
TensorSpec(shape=(None, 28, 28), dtype=tf.float32, name=None))
| Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Using Autograph To Capture Control Flow A "static" `for` loop using `range()`: | @tf.function
def add_10(x):
for i in range(10):
x += 1
return x
add_10(tf.constant(5))
add_10.get_concrete_function(tf.constant(5)).graph.get_operations() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
A "dynamic" loop using `tf.while_loop()`: | @tf.function
def add_10(x):
condition = lambda i, x: tf.less(i, 10)
body = lambda i, x: (tf.add(i, 1), tf.add(x, 1))
final_i, final_x = tf.while_loop(condition, body, [tf.constant(0), x])
return final_x
add_10(tf.constant(5))
add_10.get_concrete_function(tf.constant(5)).graph.get_operations() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
A "dynamic" `for` loop using `tf.range()` (captured by autograph): | @tf.function
def add_10(x):
for i in tf.range(10):
x = x + 1
return x
add_10.get_concrete_function(tf.constant(0)).graph.get_operations() | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Handling Variables and Other Resources in TF Functions | counter = tf.Variable(0)
@tf.function
def increment(counter, c=1):
return counter.assign_add(c)
increment(counter)
increment(counter)
function_def = increment.get_concrete_function(counter).function_def
function_def.signature.input_arg[0]
counter = tf.Variable(0)
@tf.function
def increment(c=1):
return counte... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Using TF Functions with tf.keras (or Not) By default, tf.keras will automatically convert your custom code into TF Functions, no need to use`tf.function()`: | # Custom loss function
def my_mse(y_true, y_pred):
print("Tracing loss my_mse()")
return tf.reduce_mean(tf.square(y_pred - y_true))
# Custom metric function
def my_mae(y_true, y_pred):
print("Tracing metric my_mae()")
return tf.reduce_mean(tf.abs(y_pred - y_true))
# Custom layer
class MyDense(keras.laye... | Epoch 1/2
Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
340/363 [=========================... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
You can turn this off by creating the model with `dynamic=True` (or calling `super().__init__(dynamic=True, **kwargs)` in the model's constructor): | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = MyModel(dynamic=True)
model.compile(loss=my_mse, optimizer="nadam", metrics=[my_mae]) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Not the custom code will be called at each iteration. Let's fit, validate and evaluate with tiny datasets to avoid getting too much output: | model.fit(X_train_scaled[:64], y_train[:64], epochs=1,
validation_data=(X_valid_scaled[:64], y_valid[:64]), verbose=0)
model.evaluate(X_test_scaled[:64], y_test[:64], verbose=0) | Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
Tracing MyModel.call()
Tracing MyDense.call(... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Alternatively, you can compile a model with `run_eagerly=True`: | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = MyModel()
model.compile(loss=my_mse, optimizer="nadam", metrics=[my_mae], run_eagerly=True)
model.fit(X_train_scaled[:64], y_train[:64], epochs=1,
validation_data=(X_valid_scaled[:64], y_valid[:64]), verbose=0)
model.evaluate(X_te... | Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
Tracing MyModel.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing MyDense.call()
Tracing loss my_mse()
Tracing metric my_mae()
Tracing MyModel.call()
Tracing MyDense.call(... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Custom Optimizers Defining custom optimizers is not very common, but in case you are one of the happy few who gets to write one, here is an example: | class MyMomentumOptimizer(keras.optimizers.Optimizer):
def __init__(self, learning_rate=0.001, momentum=0.9, name="MyMomentumOptimizer", **kwargs):
"""Call super().__init__() and use _set_hyper() to store hyperparameters"""
super().__init__(name, **kwargs)
self._set_hyper("learning_rate", kw... | Epoch 1/5
363/363 [==============================] - 0s 444us/step - loss: 4.9648
Epoch 2/5
363/363 [==============================] - 0s 444us/step - loss: 1.7888
Epoch 3/5
363/363 [==============================] - 0s 437us/step - loss: 1.0021
Epoch 4/5
363/363 [==============================] - 0s 451us/step - loss:... | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Exercises 1. to 11.See Appendix A. 12. Implement a custom layer that performs _Layer Normalization__We will use this type of layer in Chapter 15 when using Recurrent Neural Networks._ a._Exercise: The `build()` method should define two trainable weights *α* and *β*, both of shape `input_shape[-1:]` and data type `t... | class LayerNormalization(keras.layers.Layer):
def __init__(self, eps=0.001, **kwargs):
super().__init__(**kwargs)
self.eps = eps
def build(self, batch_input_shape):
self.alpha = self.add_weight(
name="alpha", shape=batch_input_shape[-1:],
initializer="ones")
... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Note that making _ε_ a hyperparameter (`eps`) was not compulsory. Also note that it's preferable to compute `tf.sqrt(variance + self.eps)` rather than `tf.sqrt(variance) + self.eps`. Indeed, the derivative of sqrt(z) is undefined when z=0, so training will bomb whenever the variance vector has at least one component eq... | X = X_train.astype(np.float32)
custom_layer_norm = LayerNormalization()
keras_layer_norm = keras.layers.LayerNormalization()
tf.reduce_mean(keras.losses.mean_absolute_error(
keras_layer_norm(X), custom_layer_norm(X))) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Yep, that's close enough. To be extra sure, let's make alpha and beta completely random and compare again: | random_alpha = np.random.rand(X.shape[-1])
random_beta = np.random.rand(X.shape[-1])
custom_layer_norm.set_weights([random_alpha, random_beta])
keras_layer_norm.set_weights([random_alpha, random_beta])
tf.reduce_mean(keras.losses.mean_absolute_error(
keras_layer_norm(X), custom_layer_norm(X))) | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Still a negligeable difference! Our custom layer works fine. 13. Train a model using a custom training loop to tackle the Fashion MNIST dataset_The Fashion MNIST dataset was introduced in Chapter 10._ a._Exercise: Display the epoch, iteration, mean training loss, and mean accuracy over each epoch (updated at each ite... | (X_train_full, y_train_full), (X_test, y_test) = keras.datasets.fashion_mnist.load_data()
X_train_full = X_train_full.astype(np.float32) / 255.
X_valid, X_train = X_train_full[:5000], X_train_full[5000:]
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
X_test = X_test.astype(np.float32) / 255.
keras.backend.... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
b._Exercise: Try using a different optimizer with a different learning rate for the upper layers and the lower layers._ | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
lower_layers = keras.models.Sequential([
keras.layers.Flatten(input_shape=[28, 28]),
keras.layers.Dense(100, activation="relu"),
])
upper_layers = keras.models.Sequential([
keras.layers.Dense(10, activation="softmax"),
])
model = keras.... | _____no_output_____ | Apache-2.0 | 12_custom_models_and_training_with_tensorflow.ipynb | mattkearns/handson-ml2 |
Binary classifiers for sold Ebay shoe listings Connect to database and retrieve data | from sqlalchemy import create_engine
import pandas as pd
from decouple import config
DATABASE_URL = config('DATABASE_URL')
engine = create_engine(DATABASE_URL)
df = pd.read_sql_query('select * from "shoes"',con=engine) | _____no_output_____ | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
Data Cleaning Replace missing values with average value | price_fillna_value = round(df["price"].mean(),2)
free_shipping_fillna_value = int(df["free_shipping"].mean())
total_images_fillna_value = int(df["total_images"].mean())
seller_rating_fillna_value = int(df["seller_rating"].mean())
shoe_size_fillna_value = int(df["shoe_size"].mean())
df["price"].fillna(price_fillna_valu... | _____no_output_____ | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
Define input and output features | from sklearn.model_selection import train_test_split
import numpy as np
features = ['price','free_shipping', 'total_images', 'seller_rating', 'shoe_size', 'desc_fre_score', 'desc_avg_grade_score']
X = np.array(df[features])
y = np.array(df['sold'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size ... | _____no_output_____ | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
Train Classification Models Logisitic Regression | from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import roc_curve, auc, roc_auc_score, f1_score
reg_log = LogisticRegression()
reg_log.fit(X_train, y_train)
y_pred = reg_log.predict(X_test)
print(metrics.classification_report(y_test, y_pred))
print("roc_auc_score: ... | precision recall f1-score support
False 0.70 1.00 0.83 45
True 0.00 0.00 0.00 19
accuracy 0.70 64
macro avg 0.35 0.50 0.41 64
weighted avg 0.49 0.70 0.58 ... | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
Random Forest | from sklearn.ensemble import RandomForestClassifier
reg_rf = RandomForestClassifier()
reg_rf.fit(X_train, y_train)
y_pred = reg_rf.predict(X_test)
print(metrics.classification_report(y_test, y_pred))
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))
print("f1 score: ", f1_score(y_test, y_pred))
feature_df = pd.... | Importance Features
0 0.172318 price
1 0.028320 free_shipping
2 0.177162 total_images
3 0.181760 seller_rating
4 0.130010 shoe_size
5 0.174685 desc_fre_score
6 0.135746 desc_avg_grade_score
| MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
Given these feature importance values, a seller's rating has the most influence on the whether a shoe will sell, while free shipping has the least influence. SVM | from sklearn.svm import SVC
reg_svc = SVC()
reg_svc.fit(X_train, y_train)
y_pred = reg_svc.predict(X_test)
print(metrics.classification_report(y_test, y_pred))
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))
print("f1 score: ", f1_score(y_test, y_pred)) | precision recall f1-score support
False 0.70 1.00 0.83 45
True 0.00 0.00 0.00 19
accuracy 0.70 64
macro avg 0.35 0.50 0.41 64
weighted avg 0.49 0.70 0.58 ... | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
K-Nearest Neighbors | from sklearn.neighbors import KNeighborsClassifier
reg_knn = KNeighborsClassifier()
reg_knn.fit(X_train, y_train)
y_pred = reg_knn.predict(X_test)
print(metrics.classification_report(y_test, y_pred))
print("roc_auc_score: ", roc_auc_score(y_test, y_pred))
print("f1 score: ", f1_score(y_test, y_pred)) | precision recall f1-score support
False 0.75 0.91 0.82 45
True 0.56 0.26 0.36 19
accuracy 0.72 64
macro avg 0.65 0.59 0.59 64
weighted avg 0.69 0.72 0.68 ... | MIT | ml-work/classification_problem.ipynb | numankh/HypeBeastHelper |
phageParser - Analysis of Spacer Lengths C.K. Yildirim (cemyildirim@fastmail.com)The latest version of this [IPython notebook](http://ipython.org/notebook.html) demo is available at [http://github.com/phageParser/phageParser](https://github.com/phageParser/phageParser/tree/django-dev/demos)To run this notebook locally... | %matplotlib inline
#Import packages
import requests
import json
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib import mlab
import seaborn as sns
import pandas as pd
from scipy.stats import poisson
sns.set_palette("husl")
#Url of the phageParser API
apiurl = 'https://phageparser.herokua... | Calculated mean basepair length for spacers is 35.11+/-3.95
| MIT | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser |
Across the roughly ~3000 sequenced organisms that have what looks like a CRISPR locus, what is the distribution of CRISPR spacer lengths? The histogram below shows that spacer length is peaked at about 35 base pairs. The standard deviation of spacer length is 4 base pairs, but the distribution has large tails - there a... | #Plot histogram of spacer lengths across all organisms
norm = False # change to false to show totals, true to show everything normalized to 1
plt.figure()
bins=range(5,100)
plt.hist(spacerbplengths,bins=bins,normed=norm,label='All organisms')
plt.yscale('log')
if norm == False:
plt.ylim(5*10**-1,10**5)
else:
... | _____no_output_____ | MIT | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser |
What the above plot suggests is that individual organisms and loci have narrow spacer length distributions but that the total distribution is quite broad. | #Calculate means and standard deviations of spacer length for all individual loci
means = []
stds = []
for org in org_spacer.values():
for arr in list(org.values()):
means.append(np.mean(arr))
stds.append(np.std(arr))
print("The mean of all individual locus standard deviations is "
+... | The mean of all individual locus standard deviations is 1.31, smaller than the spacer length standard deviations for all organisms combined.
| MIT | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser |
The following cumulative version of the total spacer length histogram shows again the deviation from normal distribution at large spacer lengths. | fig, ax = plt.subplots(figsize=(8,4), dpi=100)
#Plot cumulative probability of data
sorted_data = np.sort(spacerbplengths)
ax.step(sorted_data, 1-np.arange(sorted_data.size)/sorted_data.size, label='Data')
#Plot normal distribution
x=np.unique(sorted_data)
y = mlab.normpdf(x, mu, sigma).cumsum()
y /= y[-1]
ax.plot(x, 1... | _____no_output_____ | MIT | demos/Spacer Length Analysis.ipynb | nataliyah123/phageParser |
Fraud Detection for Automobile Claims: Create an End to End Pipeline BackgroundIn this notebook, we will build a SageMaker Pipeline that automates the entire end-to-end process of preparing, training, and deploying a model that detects automobile claim fraud. For a more detailed explanation of each step of the pipeli... | !python -m pip install -Uq pip
!python -m pip install -q awswrangler==2.2.0 imbalanced-learn==0.7.0 sagemaker==2.41.0 boto3==1.17.70 | _____no_output_____ | Apache-2.0 | end_to_end/fraud_detection/pipeline-e2e.ipynb | qidewenwhen/amazon-sagemaker-examples |
Import libraries | import json
import boto3
import pathlib
import sagemaker
import numpy as np
import pandas as pd
import awswrangler as wr
import string
import demo_helpers
from sagemaker.xgboost.estimator import XGBoost
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import CreateModelStep
from sagemake... | _____no_output_____ | Apache-2.0 | end_to_end/fraud_detection/pipeline-e2e.ipynb | qidewenwhen/amazon-sagemaker-examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.