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 |
|---|---|---|---|---|---|
Terminology (from [this post](https://towardsdatascience.com/scale-standardize-or-normalize-with-scikit-learn-6ccc7d176a02)): * Scale generally means to change the range of the values. The shape of the distribution doesn’t change. Think about how a scale model of a building has the same proportions as the original, ... | house_prices = pd.read_csv("data/house-prices.csv")
house_prices["AgeWhenSold"] = house_prices["YrSold"] - house_prices["YearBuilt"]
house_prices.head() | _____no_output_____ | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
Unscaled Housing Prices Age When Sold | sns.displot(house_prices["AgeWhenSold"])
plt.xticks(rotation=90)
plt.show() | _____no_output_____ | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
StandardScalerNote that DataFrame.var and DataFrame.std default to using 1 degree of freedom (ddof=1) but StandardScaler is using numpy's versions which default to ddof=0. That's why when printing the variance and standard deviation of the original data frame, we're specifying ddof=0. ddof=1 is known as Bessel's corre... | df = pd.DataFrame({
'col1': [1, 2, 3],
'col2': [10, 20, 30],
'col3': [0, 20, 22]
})
print("Original:\n")
print(df)
print("\nColumn means:\n")
print(df.mean())
print("\nOriginal variance:\n")
print(df.var(ddof=0))
print("\nOriginal standard deviations:\n")
print(df.std(ddof=0))
scaler = StandardScaler()
df1... | Original:
col1 col2 col3
0 1 10 0
1 2 20 20
2 3 30 22
Column means:
col1 2.0
col2 20.0
col3 14.0
dtype: float64
Original variance:
col1 0.666667
col2 66.666667
col3 98.666667
dtype: float64
Original standard deviations:
col1 0.816497
col2 8.164966
col... | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
Standard Scaler with Age When Sold | scaler = StandardScaler()
age_when_sold_scaled = scaler.fit_transform(house_prices["AgeWhenSold"].values.reshape(-1, 1))
sns.displot(age_when_sold_scaled)
plt.xticks(rotation=90)
plt.show() | _____no_output_____ | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
Whiten```x_new = x / std(x)``` | data = [5, 1, 3, 3, 2, 3, 8, 1, 2, 2, 3, 5]
print("Original:", data)
print("\nStd Dev:", np.std(data))
scaled = whiten(data)
print("\nScaled with Whiten:", scaled)
scaled_manual = data / np.std(data)
print("\nScaled Manuallly:", scaled_manual) | Original: [5, 1, 3, 3, 2, 3, 8, 1, 2, 2, 3, 5]
Std Dev: 1.9075871903765997
Scaled with Whiten: [2.62111217 0.52422243 1.5726673 1.5726673 1.04844487 1.5726673
4.19377947 0.52422243 1.04844487 1.04844487 1.5726673 2.62111217]
Scaled Manuallly: [2.62111217 0.52422243 1.5726673 1.5726673 1.04844487 1.5726673
4.1... | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
MinMaxScales to a value between 0 and 1.More suspectible to influence by outliers. Housing Prices Age When Sold | scaler = MinMaxScaler()
age_when_sold_scaled = scaler.fit_transform(house_prices["AgeWhenSold"].values.reshape(-1, 1))
sns.displot(age_when_sold_scaled)
plt.xticks(rotation=90)
plt.show() | _____no_output_____ | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
Robust Scaler | scaler = RobustScaler()
age_when_sold_scaled = scaler.fit_transform(house_prices["AgeWhenSold"].values.reshape(-1, 1))
sns.displot(age_when_sold_scaled)
plt.xticks(rotation=90)
plt.show() | _____no_output_____ | MIT | Scaling and Normalization.ipynb | dbl007/python-cheat-sheet |
Parsing out Cosmos Data JSON | import pandas as pd
import numpy as np
import yaml
import os
os.listdir('../data') | _____no_output_____ | MIT | notebooks/Exploring Json.ipynb | BillmanH/exoplanets |
Loading local data
I ran a query in the Cosmos DB Explorer and then load it in a json file. | res = yaml.safe_load(open('../data/example nodes.json'))
res[1] | _____no_output_____ | MIT | notebooks/Exploring Json.ipynb | BillmanH/exoplanets |
Now I just need to parse out the orbiting edges | [{"source":i['objid'][0],"target":i['orbitsId'][0],"label":"orbits"} for i in res] | _____no_output_____ | MIT | notebooks/Exploring Json.ipynb | BillmanH/exoplanets |
Tutorial 6.3. Advanced Topics on Extreme Value Analysis Description: Some advanced topics on Extreme Value Analysis are presented. Students are advised to complete the exercises. Project: Structural Wind Engineering WS19-20 Chair of Structural Analysis @ TUM - R. Wüchner, M. Péntek Author: anoop.kodak... | # import
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gumbel_r as gumbel
from ipywidgets import interactive
#external files
from peakpressure import maxminest
from blue4pressure import *
import custom_utilities as c_utils | _____no_output_____ | BSD-3-Clause | Ex06Advanced/3_ExtremeValueAnalysis/.ipynb_checkpoints/swe_ws1920_6_3_advanced_topics_on_extreme_value_analysis-checkpoint.ipynb | mpentek/StructuralWindEngineering |
1. Prediction of the extreme value of a time series - MaxMin Estimation This method is based on [the procedure (and sample Matlab file](https://www.itl.nist.gov/div898/winds/peakest_files/peakest.htm) by Sadek, F. and Simiu, E. (2002). "Peak non-gaussian wind effects for database-assisted low-rise building design." ... | # using as sample input some pre-generated generalized extreme value random series
given_series = np.loadtxt('test_data_gevrnd.dat', skiprows=0, usecols = (0,))
# print results
dur_ratio = 1
result = maxminest(given_series, dur_ratio)
maxv = result[0][0][0]
minv = result[1][0][0]
print('estimation of maximum value ', ... | _____no_output_____ | BSD-3-Clause | Ex06Advanced/3_ExtremeValueAnalysis/.ipynb_checkpoints/swe_ws1920_6_3_advanced_topics_on_extreme_value_analysis-checkpoint.ipynb | mpentek/StructuralWindEngineering |
Let us plot the pdf and cdf | [pdf_x, pdf_y] = c_utils.get_pdf(given_series)
ecdf_y = c_utils.get_ecdf(pdf_x, pdf_y)
plt.figure(num=2, figsize=(16, 6))
plt.subplot(1,2,1)
plt.plot(pdf_x, pdf_y)
plt.ylabel('PDF(Amplitude)')
plt.grid(True)
plt.subplot(1,2,2)
plt.plot(pdf_x, ecdf_y)
plt.vlines([maxv, minv], 0, 1)
plt.ylabel('CDF(Amplitude)')
plt.grid... | _____no_output_____ | BSD-3-Clause | Ex06Advanced/3_ExtremeValueAnalysis/.ipynb_checkpoints/swe_ws1920_6_3_advanced_topics_on_extreme_value_analysis-checkpoint.ipynb | mpentek/StructuralWindEngineering |
2. Lieblein's BLUE method From a time series of pressure coefficients, *blue4pressure.py* estimatesextremes of positive and negative pressures based on Lieblein's BLUE (Best Linear Unbiased Estimate) method applied to n epochs. Extremes are estimated for 1 and dur epochs for probabilities of non-exceedance P1 and P2 o... | # n = number of epochs (integer)of cp data, 4 <= n <= 100
n=4
# P1, P2 = probabilities of non-exceedance of extremes in EV1 (Gumbel).
P1=0.80
P2=0.5704 # this corresponds to the mean of gumbel distribution
# dur = number of epochs for estimation of extremes. Default dur = n
# dur need not be an integer
dur=1
# Call ... | estimation of maximum value with probability of non excedence of p1 2.055
estimation of maximum value with probability of non excedence of p2 1.908
estimation of minimum value with probability of non excedence of p1 -0.582
estimation of minimum value with probability of non excedence of p2 -0.547
| BSD-3-Clause | Ex06Advanced/3_ExtremeValueAnalysis/.ipynb_checkpoints/swe_ws1920_6_3_advanced_topics_on_extreme_value_analysis-checkpoint.ipynb | mpentek/StructuralWindEngineering |
Let us plot the pdf and cdf for the maximum values | max_pdf_x = np.linspace(1, 3, 100)
max_pdf_y = gumbel.pdf(max_pdf_x, umax, b_max)
max_ecdf_y = c_utils.get_ecdf(max_pdf_x, max_pdf_y)
plt.figure(num=3, figsize=(16, 6))
plt.subplot(1,2,1)
# PDF generated as a fitted curve using generalized extreme distribution
plt.plot(max_pdf_x, max_pdf_y, label = 'PDF from the fitte... | _____no_output_____ | BSD-3-Clause | Ex06Advanced/3_ExtremeValueAnalysis/.ipynb_checkpoints/swe_ws1920_6_3_advanced_topics_on_extreme_value_analysis-checkpoint.ipynb | mpentek/StructuralWindEngineering |
What's this TensorFlow business?You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.For the la... | import os
import tensorflow as tf
import numpy as np
import math
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
def load_cifar10(num_training=49000, num_validation=1000, num_test=10000):
"""
Fetch the CIFAR-10 dataset from the web and perform preprocessing to prepare
it for the two-layer ... | 0 (64, 32, 32, 3) (64,)
1 (64, 32, 32, 3) (64,)
2 (64, 32, 32, 3) (64,)
3 (64, 32, 32, 3) (64,)
4 (64, 32, 32, 3) (64,)
5 (64, 32, 32, 3) (64,)
6 (64, 32, 32, 3) (64,)
| MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
You can optionally **use GPU by setting the flag to True below**. Colab UsersIf you are using Colab, you need to manually switch to a GPU device. You can do this by clicking `Runtime -> Change runtime type` and selecting `GPU` under `Hardware Accelerator`. Note that you have to rerun the cells from the top since the ke... | # Set up some global variables
USE_GPU = True
if USE_GPU:
device = '/device:GPU:0'
else:
device = '/cpu:0'
# Constant to control how often we print when training models
print_every = 100
print('Using device: ', device) | Using device: /device:GPU:0
| MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Part II: Barebones TensorFlowTensorFlow ships with various high-level APIs which make it very convenient to define and train neural networks; we will cover some of these constructs in Part III and Part IV of this notebook. In this section we will start by building a model with basic TensorFlow constructs to help you b... | def flatten(x):
"""
Input:
- TensorFlow Tensor of shape (N, D1, ..., DM)
Output:
- TensorFlow Tensor of shape (N, D1 * ... * DM)
"""
N = tf.shape(x)[0]
return tf.reshape(x, (N, -1))
def test_flatten():
# Construct concrete values of the input data x using numpy
x_np = np... | x_np:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
x_flat_np:
tf.Tensor(
[[ 0 1 2 3 4 5 6 7 8 9 10 11]
[12 13 14 15 16 17 18 19 20 21 22 23]], shape=(2, 12), dtype=int32)
| MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: Define a Two-Layer NetworkWe will now implement our first neural network with TensorFlow: a fully-connected ReLU network with two hidden layers and no biases on the CIFAR10 dataset. For now we will use only low-level TensorFlow operators to define the network; later we will see how to use the hig... | def two_layer_fc(x, params):
"""
A fully-connected neural network; the architecture is:
fully-connected layer -> ReLU -> fully connected layer.
Note that we only need to define the forward pass here; TensorFlow will take
care of computing the gradients for us.
The input to the network will ... | (64, 10)
| MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: Three-Layer ConvNetHere you will complete the implementation of the function `three_layer_convnet` which will perform the forward pass of a three-layer convolutional network. The network should have the following architecture:1. A convolutional layer (with bias) with `channel_1` filters, each wit... | def three_layer_convnet(x, params):
"""
A three-layer convolutional network with the architecture described above.
Inputs:
- x: A TensorFlow Tensor of shape (N, H, W, 3) giving a minibatch of images
- params: A list of TensorFlow Tensors giving the weights and biases for the
network; shou... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
After defing the forward pass of the three-layer ConvNet above, run the following cell to test your implementation. Like the two-layer network, we run the graph on a batch of zeros just to make sure the function doesn't crash, and produces outputs of the correct shape.When you run this function, `scores_np` should have... | def three_layer_convnet_test():
with tf.device(device):
x = tf.zeros((64, 32, 32, 3))
conv_w1 = tf.zeros((5, 5, 3, 6))
conv_b1 = tf.zeros((6,))
conv_w2 = tf.zeros((3, 3, 6, 9))
conv_b2 = tf.zeros((9,))
fc_w = tf.zeros((32 * 32 * 9, 10))
fc_b = tf.zeros((1... | scores_np has shape: (64, 10)
| MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: Training StepWe now define the `training_step` function performs a single training step. This will take three basic steps:1. Compute the loss2. Compute the gradient of the loss with respect to all network weights3. Make a weight update step using (stochastic) gradient descent.We need to use a few... | def training_step(model_fn, x, y, params, learning_rate):
with tf.GradientTape() as tape:
scores = model_fn(x, params) # Forward pass of the model
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
total_loss = tf.reduce_mean(loss)
grad_params = tape.gradi... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: InitializationWe'll use the following utility method to initialize the weight matrices for our models using Kaiming's normalization method.[1] He et al, *Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification*, ICCV 2015, https://arxiv.org/abs/1502.01852 | def create_matrix_with_kaiming_normal(shape):
if len(shape) == 2:
fan_in, fan_out = shape[0], shape[1]
elif len(shape) == 4:
fan_in, fan_out = np.prod(shape[:3]), shape[3]
return tf.keras.backend.random_normal(shape) * np.sqrt(2.0 / fan_in) | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: Train a Two-Layer NetworkWe are finally ready to use all of the pieces defined above to train a two-layer fully-connected network on CIFAR-10.We just need to define a function to initialize the weights of the model, and call `train_part2`.Defining the weights of the network introduces another imp... | def two_layer_fc_init():
"""
Initialize the weights of a two-layer network, for use with the
two_layer_network function defined above.
You can use the `create_matrix_with_kaiming_normal` helper!
Inputs: None
Returns: A list of:
- w1: TensorFlow tf.Variable giving the weights for t... | Iteration 0, loss = 3.0406
Got 146 / 1000 correct (14.60%)
Iteration 100, loss = 2.0258
Got 377 / 1000 correct (37.70%)
Iteration 200, loss = 1.4799
Got 399 / 1000 correct (39.90%)
Iteration 300, loss = 1.8364
Got 361 / 1000 correct (36.10%)
Iteration 400, loss = 1.8527
Got 415 / 1000 correct (41.50%)
Iteration 500, lo... | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Barebones TensorFlow: Train a three-layer ConvNetWe will now use TensorFlow to train a three-layer ConvNet on CIFAR-10.You need to implement the `three_layer_convnet_init` function. Recall that the architecture of the network is:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding 22. ReLU3. Convo... | def three_layer_convnet_init():
"""
Initialize the weights of a Three-Layer ConvNet, for use with the
three_layer_convnet function defined above.
You can use the `create_matrix_with_kaiming_normal` helper!
Inputs: None
Returns a list containing:
- conv_w1: TensorFlow tf.Variable gi... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Part III: Keras Model Subclassing APIImplementing a neural network using the low-level TensorFlow API is a good way to understand how TensorFlow works, but it's a little inconvenient - we had to manually keep track of all Tensors holding learnable parameters. This was fine for a small network, but could quickly become... | class TwoLayerFC(tf.keras.Model):
def __init__(self, hidden_size, num_classes):
super(TwoLayerFC, self).__init__()
initializer = tf.initializers.VarianceScaling(scale=2.0)
self.fc1 = tf.keras.layers.Dense(hidden_size, activation='relu',
kernel_initi... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Model Subclassing API: Three-Layer ConvNetNow it's your turn to implement a three-layer ConvNet using the `tf.keras.Model` API. Your model should have the same architecture used in Part II:1. Convolutional layer with 5 x 5 kernels, with zero-padding of 22. ReLU nonlinearity3. Convolutional layer with 3 x 3 kerne... | class ThreeLayerConvNet(tf.keras.Model):
def __init__(self, channel_1, channel_2, num_classes):
super(ThreeLayerConvNet, self).__init__()
########################################################################
# TODO: Implement the __init__ method for a three-layer ConvNet. You #
... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Once you complete the implementation of the `ThreeLayerConvNet` above you can run the following to ensure that your implementation does not crash and produces outputs of the expected shape. | def test_ThreeLayerConvNet():
channel_1, channel_2, num_classes = 12, 8, 10
model = ThreeLayerConvNet(channel_1, channel_2, num_classes)
with tf.device(device):
x = tf.zeros((64, 3, 32, 32))
scores = model(x)
print(scores.shape)
test_ThreeLayerConvNet() | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Model Subclassing API: Eager TrainingWhile keras models have a builtin training loop (using the `model.fit`), sometimes you need more customization. Here's an example, of a training loop implemented with eager execution.In particular, notice `tf.GradientTape`. Automatic differentiation is used in the backend for... | def train_part34(model_init_fn, optimizer_init_fn, num_epochs=1, is_training=False):
"""
Simple training loop for use with models defined using tf.keras. It trains
a model for one epoch on the CIFAR-10 training set and periodically checks
accuracy on the CIFAR-10 validation set.
Inputs:
- m... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Model Subclassing API: Train a Two-Layer NetworkWe can now use the tools defined above to train a two-layer network on CIFAR-10. We define the `model_init_fn` and `optimizer_init_fn` that construct the model and optimizer respectively when called. Here we want to train the model using stochastic gradient descent... | hidden_size, num_classes = 4000, 10
learning_rate = 1e-2
def model_init_fn():
return TwoLayerFC(hidden_size, num_classes)
def optimizer_init_fn():
return tf.keras.optimizers.SGD(learning_rate=learning_rate)
train_part34(model_init_fn, optimizer_init_fn) | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Model Subclassing API: Train a Three-Layer ConvNetHere you should use the tools we've defined above to train a three-layer ConvNet on CIFAR-10. Your ConvNet should use 32 filters in the first convolutional layer and 16 filters in the second layer.To train the model you should use gradient descent with Nesterov ... | learning_rate = 3e-3
channel_1, channel_2, num_classes = 32, 16, 10
def model_init_fn():
model = None
############################################################################
# TODO: Complete the implementation of model_fn. #
###############################################... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Part IV: Keras Sequential APIIn Part III we introduced the `tf.keras.Model` API, which allows you to define models with any number of learnable layers and with arbitrary connectivity between layers.However for many models you don't need such flexibility - a lot of models can be expressed as a sequential stack of layer... | learning_rate = 1e-2
def model_init_fn():
input_shape = (32, 32, 3)
hidden_layer_size, num_classes = 4000, 10
initializer = tf.initializers.VarianceScaling(scale=2.0)
layers = [
tf.keras.layers.Flatten(input_shape=input_shape),
tf.keras.layers.Dense(hidden_layer_size, activation='relu',... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Abstracting Away the Training LoopIn the previous examples, we used a customised training loop to train models (e.g. `train_part34`). Writing your own training loop is only required if you need more flexibility and control during training your model. Alternately, you can also use built-in APIs like `tf.keras.Model.fi... | model = model_init_fn()
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),
loss='sparse_categorical_crossentropy',
metrics=[tf.keras.metrics.sparse_categorical_accuracy])
model.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val))
model.eva... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Sequential API: Three-Layer ConvNetHere you should use `tf.keras.Sequential` to reimplement the same three-layer ConvNet architecture used in Part II and Part III. As a reminder, your model should have the following architecture:1. Convolutional layer with 32 5x5 kernels, using zero padding of 22. ReLU nonlinear... | def model_init_fn():
model = None
############################################################################
# TODO: Construct a three-layer ConvNet using tf.keras.Sequential. #
############################################################################
# *****START OF YOUR CODE (DO NOT D... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
We will also train this model with the built-in training loop APIs provided by TensorFlow. | model = model_init_fn()
model.compile(optimizer='sgd',
loss='sparse_categorical_crossentropy',
metrics=[tf.keras.metrics.sparse_categorical_accuracy])
model.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val))
model.evaluate(X_test, y_test) | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Part IV: Functional API Demonstration with a Two-Layer Network In the previous section, we saw how we can use `tf.keras.Sequential` to stack layers to quickly build simple models. But this comes at the cost of losing flexibility.Often we will have to write complex models that have non-sequential data flows: a layer c... | def two_layer_fc_functional(input_shape, hidden_size, num_classes):
initializer = tf.initializers.VarianceScaling(scale=2.0)
inputs = tf.keras.Input(shape=input_shape)
flattened_inputs = tf.keras.layers.Flatten()(inputs)
fc1_output = tf.keras.layers.Dense(hidden_size, activation='relu',
... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Keras Functional API: Train a Two-Layer NetworkYou can now train this two-layer network constructed using the functional API.You don't need to perform any hyperparameter tuning here, but you should see validation accuracies above 40% after training for one epoch. | input_shape = (32, 32, 3)
hidden_size, num_classes = 4000, 10
learning_rate = 1e-2
def model_init_fn():
return two_layer_fc_functional(input_shape, hidden_size, num_classes)
def optimizer_init_fn():
return tf.keras.optimizers.SGD(learning_rate=learning_rate)
train_part34(model_init_fn, optimizer_init_fn) | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
Part V: CIFAR-10 open-ended challengeIn this section you can experiment with whatever ConvNet architecture you'd like on CIFAR-10.You should experiment with architectures, hyperparameters, loss functions, regularization, or anything else you can think of to train a model that achieves **at least 70%** accuracy on the ... | class CustomConvNet(tf.keras.Model):
def __init__(self):
super(CustomConvNet, self).__init__()
############################################################################
# TODO: Construct a model that performs well on CIFAR-10 #
###################################... | _____no_output_____ | MIT | assignment2/TensorFlow.ipynb | LOTEAT/CS231n |
paperspace tmux - multiple screens tensor = array | ## nomenclature
# error/loss = target - calculated
# non linear - activation functions | _____no_output_____ | Apache-2.0 | series2/week1/week1_class2.ipynb | s-ahuja/AI-Saturday |
Slide 24, Slide 25 of neuralNetwork.pptx | import numpy as np
#Slide 25
weights_1 = np.array([[0.71,0.112],[0.355,0.856],[0.268,0.468]])
x = np.array([1,1])
print(weights)
print(x)
y_linear_1 = np.dot(weights,x)
print(y_linear_1)
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
fn_sigmoid = np.vectorize(sigmoid)
y_nonlinear_1 = fn_sigmoid(y_linear_... | 0.6926974470214398
| Apache-2.0 | series2/week1/week1_class2.ipynb | s-ahuja/AI-Saturday |
Slide 26 | import math
weights_list = []
weights_list.append(np.array([[0.71,0.112],[0.355,0.856],[0.268,0.468]]))
weights_list.append(np.array([0.116,0.329,0.708]))
input_x = np.array([1,1])
def sigmoid(x):
return 1 / (1 + math.exp(-x))
fn_sigmoid = np.vectorize(sigmoid)
def calc(weight,x):
y_linear = np.dot(weight,x... | 0.6926974470214398
| Apache-2.0 | series2/week1/week1_class2.ipynb | s-ahuja/AI-Saturday |
ListsSequential, Ordered Collection Creating lists | x = [4,2,6,3] #Create a list with values
y = list() # Create an empty list
y = [] #Create an empty list
print(x)
print(y) | [4, 2, 6, 3]
[]
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Adding items to a list | x=list()
print(x)
x.append('One') #Adds 'One' to the back of the empty list
print(x)
x.append('Two') #Adds 'Two' to the back of the list ['One']
print(x)
x.insert(0,'Half') #Inserts 'Half' at location 0. Items will shift to make roomw
print(x)
x=list()
x.extend([1,2,3]) #Unpacks the list and adds each item to the back ... | [1, 2, 3]
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Indexing and slicing | x=[1,7,2,5,3,5,67,32]
print(len(x))
print(x[3])
print(x[2:5])
print(x[-1])
print(x[::-1]) | 8
5
[2, 5, 3]
32
[32, 67, 5, 3, 5, 2, 7, 1]
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Removing items from a list | x=[1,7,2,5,3,5,67,32]
x.pop() #Removes the last element from a list
print(x)
x.pop(3) #Removes element at item 3 from a list
print(x)
x.remove(7) #Removes the first 7 from the list
print(x) | [1, 7, 2, 5, 3, 5, 67]
[1, 7, 2, 3, 5, 67]
[1, 2, 3, 5, 67]
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Anything you want to remove must be in the list or the location must be inside the list | x.remove(20) | _____no_output_____ | MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Mutablility of lists | y=['a','b']
x = [1,y,3]
print(x)
print(y)
y[1] = 4
print(y)
print(x)
x="Hello"
print(x,id(x))
x+=" You!"
print(x,id(x)) #x is not the same object it was
y=["Hello"]
print(y,id(y))
y+=["You!"]
print(y,id(y)) #y is still the same object. Lists are mutable. Strings are immutable
def eggs(item,total=0):
total+=item
... | 1
2
[1]
[1, 2]
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Iteration Range iteration | #The for loop creates a new variable (e.g., index below)
#range(len(x)) generates values from 0 to len(x)
x=[1,7,2,5,3,5,67,32]
for index in range(len(x)):
print(x[index])
list(range(len(x))) | _____no_output_____ | MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
List element iteration | x=[1,7,2,5,3,5,67,32]
#The for draws elements - sequentially - from the list x and uses the variable "element" to store values
for element in x:
print(element) | 1
7
2
5
3
5
67
32
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Practice problem Write a function search_list that searches a list of tuple pairs and returns the value associated with the first element of the pair | def search_list(list_of_tuples,value):
#Write the function here
for t in prices:
if t[0] == value:
return t[1]
prices = [('AAPL',96.43),('IONS',39.28),('GS',159.53)]
ticker = 'IONS'
print(search_list(prices,ticker)) | 39.28
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Dictionaries | mktcaps = {'AAPL':538.7,'GOOG':68.7,'IONS':4.6}
mktcaps['AAPL'] #Returns the value associated with the key "AAPL"
mktcaps['GS'] #Error because GS is not in mktcaps
mktcaps.get('GS') #Returns None because GS is not in mktcaps
mktcaps['GS'] = 88.65 #Adds GS to the dictionary
print(mktcaps)
del(mktcaps['GOOG']) #Removes... | 4
4
| MIT | Week 2 - A Crash Course In Python Part 2/Collections.ipynb | 2series/Analytics-And-Python |
Julian's Code | start = time.time()
# 5m meter lakes
DEM40 = skimage.transform.resize(DEMflat, (DEMflat.shape[0] / 10, DEMflat.shape[1] / 10),
anti_aliasing=True)
DEM_inv = skimage.util.invert(DEM40)
DEMinv_gaus = gaussian_filter(DEM_inv,1)
marker = np.copy(DEMinv_gaus)
marker[1:-1, 1:-1] = -9999
Inan = np.argwh... | _____no_output_____ | Apache-2.0 | topocode2.ipynb | pangeo-data/pangeo-rema |
Lake Properties | lakemask = lakes>0
label_lakes = measure.label(lakemask)
LakeProps = measure.regionprops(label_lakes,lakes)
numLakes = len(LakeProps)
Area = np.zeros((numLakes,1))
Orientation= np.zeros((numLakes,1))
Volume = np.zeros((numLakes,1))
Max_Depth = np.zeros((numLakes,1))
Mean_Depth = np.zeros((numLakes,1))
Min_Depth = np.ze... | _____no_output_____ | Apache-2.0 | topocode2.ipynb | pangeo-data/pangeo-rema |
Elevation Data | ElevationProps = measure.regionprops(label_lakes,DEM40)
numLakes = len(LakeProps)
Max_Elev = np.zeros((numLakes,1))
Mean_Elev = np.zeros((numLakes,1))
Min_Elev = np.zeros((numLakes,1))
for lake in np.arange(0,numLakes):
Max_Elev[lake] =ElevationProps[lake].max_intensity
Mean_Elev[lake] = ElevationProps[lake].me... | _____no_output_____ | Apache-2.0 | topocode2.ipynb | pangeo-data/pangeo-rema |
Full Tiles | xlength = DEMflat.shape[0]
ylength = DEMflat.shape[1]
quarter_tile = np.empty([int(xlength/2),int(ylength/2),4])
inProj = Proj(init= geoDEM.crs)
outProj = Proj(init='epsg:4326') #Plate Carree
lon,lat = transform(inProj,outProj,list(geoDEM.x),list(geoDEM.y))
quarter_tile[:,:,0] = DEMflat[0:int(xlength/2), 0:int(yleng... | _____no_output_____ | Apache-2.0 | topocode2.ipynb | pangeo-data/pangeo-rema |
Authoring repeatable processes aka AzureML pipelines | from azureml.core import Workspace
ws = Workspace.from_config()
dataset = ws.datasets["diabetes-tabular"]
compute_target = ws.compute_targets["cpu-cluster"]
from azureml.core import RunConfiguration
# To simplify we are going to use a big demo environment instead
# of creating our own specialized environment. We will... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Step 1 - Convert data into LightGBM dataset | from azureml.pipeline.core import PipelineData
step01_output = PipelineData(
"training_data", datastore=ws.get_default_datastore(), is_directory=True
)
from azureml.pipeline.core import PipelineParameter
from azureml.data.dataset_consumption_config import DatasetConsumptionConfig
ds_pipeline_param = PipelineParam... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Step 2 - Train the LightGBM model | from azureml.pipeline.core import PipelineParameter
learning_rate_param = PipelineParameter(name="learning_rate", default_value=0.05)
step02_output = PipelineData(
"model_output", datastore=ws.get_default_datastore(), is_directory=True
)
step_02 = PythonScriptStep(
"step02_train.py",
source_directory="040_... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Step 3 - Register model | step_03 = PythonScriptStep(
"step03_register.py",
source_directory="040_scripts",
arguments=[
"--input-path",
step02_output,
"--dataset-id",
step01_input_dataset,
],
name="Register model",
runconfig=runconfig,
compute_target=compute_target,
inputs=[step01_... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Create pipeline | from azureml.pipeline.core import Pipeline
pipeline = Pipeline(workspace=ws, steps=[step_01, step_02, step_03]) | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Trigger pipeline through SDK | from azureml.core import Experiment
# Using the SDK
experiment = Experiment(ws, "pipeline-run")
pipeline_run = experiment.submit(pipeline, pipeline_parameters={"learning_rate": 0.5})
pipeline_run.wait_for_completion() | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Register pipeline to reuse | published_pipeline = pipeline.publish(
"Training pipeline", description="A pipeline to train a LightGBM model"
) | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Trigger published pipeline through REST | from azureml.core.authentication import InteractiveLoginAuthentication
auth = InteractiveLoginAuthentication()
aad_token = auth.get_authentication_header()
import requests
response = requests.post(
published_pipeline.endpoint,
headers=aad_token,
json={
"ExperimentName": "pipeline-run",
"Pa... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Scheduling a pipeline | from azureml.pipeline.core.schedule import ScheduleRecurrence, Schedule
from datetime import datetime
recurrence = ScheduleRecurrence(
frequency="Month", interval=1, start_time=datetime.now()
)
schedule = Schedule.create(
workspace=ws,
name="pipeline-schedule",
pipeline_id=published_pipeline.id,
e... | _____no_output_____ | MIT | fundamentals/src/notebooks/040_pipelines.ipynb | konabuta/fta-azure-machine-learning |
Local Feature MatchingBy the end of this exercise, you will be able to transform images of a flat (planar) object, or images taken from the same point into a common reference frame. This is at the core of applications such as panorama stitching.A quick overview:1. We will start with histogram representations for image... | %matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import imageio
import cv2
import math
from scipy import ndimage
from attrdict import AttrDict
from mpl_toolkits.mplot3d import Axes3D
# Many useful functions
def plot_multiple(images, titles=None, colormap='gray',
max_columns=np... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Histograms in 1DIf we have a grayscale image, creating a histogram of the gray values tells us how frequently each gray value appears in the image, at a certain discretization level, which is controlled by the number of bins.Implement `compute_1d_histogram(im, n_bins)`. Given an grayscale image `im` with shape `[heigh... | def compute_1d_histogram(im, n_bins):
histogram = np.zeros(n_bins)
# YOUR CODE HERE
raise NotImplementedError()
return histogram
fig, axes = plt.subplots(1,4, figsize=(10,2), constrained_layout=True)
bin_counts = [2, 25, 256]
gray_img = imageio.imread('terrain.png', as_gray=True
... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
What is the effect of the different bin counts? YOUR ANSWER HERE Histograms in 3DIf the pixel values are more than one-dimensional (e.g. three-dimensional RGB, for red, green and blue color channels), we can build a multi-dimensional histogram. In the R, G, B example this will tell us how frequently each *combination*... | def compute_3d_histogram(im, n_bins):
histogram = np.zeros([n_bins, n_bins, n_bins], dtype=np.float32)
# YOUR CODE HERE
raise NotImplementedError()
return histogram
def plot_3d_histogram(ax, data, axis_names='xyz'):
"""Plot a 3D histogram. We plot a sphere for each bin,
with volume propor... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Histograms in 2DNow modify your code to work in 2D. This can be useful, for example, for a gradient image that stores two values for each pixel: the vertical and horizontal derivative. Again, assume the values are in the range \[0,1).Since gradients can be negative, we need to pick a relevant range of values an map th... | def compute_2d_histogram(im, n_bins):
histogram = np.zeros([n_bins, n_bins], dtype=np.float32)
# YOUR CODE HERE
raise NotImplementedError()
return histogram
def compute_gradient_histogram(rgb_im, n_bins):
# Convert to grayscale
gray_im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY).astype(float)
#... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Similar to the function `compute_gradient_histogram` above, we can build a "Mag/Lap" histogram from the gradient magnitudes and the Laplacians at each pixel. Refer back to the first exercise to refresh your knowledge of the Laplacian. Implement this in `compute_maglap_histogram`!Make sure to map the relevant range of t... | def compute_maglap_histogram(rgb_im, n_bins):
# Convert to grayscale
gray_im = cv2.cvtColor(rgb_im, cv2.COLOR_RGB2GRAY).astype(float)
# Compute Gaussian derivatives
sigma = 2
kernel_radius = np.ceil(3.0 * sigma)
x = np.arange(-kernel_radius, kernel_radius + 1)[np.newaxis]
G = gauss(x, sigma)... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Comparing HistogramsThe above histograms looked different, but to quantify this objectively, we need a **distance measure**. The Euclidean distance is a common one.Implement the function `euclidean_distance`, which takes two histograms $P$ and $Q$ as input and returns their Euclidean distance:$$\textit{dist}_{\textit{... | def euclidean_distance(hist1, hist2):
# YOUR CODE HERE
raise NotImplementedError()
def chi_square_distance(hist1, hist2, eps=1e-3):
# YOUR CODE HERE
raise NotImplementedError() | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Now let's take the image `obj1__0.png` as reference and let's compare it to `obj91__0.png` and `obj94__0.png`, using an RGB histogram, both with Euclidean and chi-square distance. Can you interpret the results?You can also try other images from the "model" folder. | im1 = imageio.imread('model/obj1__0.png')
im2 = imageio.imread('model/obj91__0.png')
im3 = imageio.imread('model/obj94__0.png')
n_bins = 8
h1 = compute_3d_histogram(im1/256, n_bins)
h2 = compute_3d_histogram(im2/256, n_bins)
h3 = compute_3d_histogram(im3/256, n_bins)
eucl_dist1 = euclidean_distance(h1, h2)
chisq_dist1... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Keypoint DetectionNow we turn to finding keypoints in images. Harris DetectorThe Harris detector searches for points, around which the second-moment matrix $M$ of the gradient vector has two large eigenvalues (This $M$ is denoted by $C$ in the Grauman & Leibe script). This matrix $M$ can be written as:$$M(\sigma, \til... | def harris_scores(im, opts):
dx, dy = gauss_derivs(im, opts.sigma1)
# YOUR CODE HERE
raise NotImplementedError()
return scores
def nms(scores):
"""Non-maximum suppression"""
# YOUR CODE HERE
raise NotImplementedError()
return scores_out
def score_map_to_keypoints(scores, opts):
... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Now check the score maps and keypoints: | opts = AttrDict()
opts.sigma1=2
opts.sigma2=opts.sigma1*2
opts.alpha=0.06
opts.score_threshold=1e-8
paths = ['checkboard.jpg', 'graf.png', 'gantrycrane.png']
images = []
titles = []
for path in paths:
image = load_image(path)
score_map = harris_scores(image, opts)
score_map_nms = nms(score_map)
ke... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Hessian DetectorThe Hessian detector operates on the second-derivative matrix $H$ (called the “Hessian” matrix)$$H = \left[\begin{matrix}I_{xx}(\sigma) & I_{xy}(\sigma) \cr I_{xy}(\sigma) & I_{yy}(\sigma)\end{matrix}\right] \tag{6}$$Note that these are *second* derivatives, while the Harris detector computes *products... | def hessian_scores(im, opts):
height, width = im.shape
# YOUR CODE HERE
raise NotImplementedError()
return scores
opts = AttrDict()
opts.sigma1=3
opts.score_threshold=5e-4
paths = ['checkboard.jpg', 'graf.png', 'gantrycrane.png']
images = []
titles = []
for path in paths:
image = load_image(path)
... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Region Descriptor MatchingNow that we can detect robust keypoints, we can try to match them across different images of the same object. For this we need a way to compare the neighborhood of a keypoint found in one image with the neighborhood of a keypoint found in another. If the neighborhoods are similar, then the ke... | def compute_rgb_descriptors(rgb_im, points, opts):
"""For each (x,y) point in `points` calculate the 3D RGB histogram
descriptor and stack these into a matrix
of shape [num_points, descriptor_length]
"""
win_half = opts.descriptor_window_halfsize
descriptors = []
rgb_im_01 = rgb_im.astype(... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Now let's implement the distance computation between descriptors. Look at `compute_euclidean_distances`. It takes descriptors that were computed for keypoints found in two different images and returns the pairwise distances between all point pairs.Implement `compute_chi_square_distances` in a similar manner. | def compute_euclidean_distances(descriptors1, descriptors2):
distances = np.empty((len(descriptors1), len(descriptors2)))
for i, desc1 in enumerate(descriptors1):
distances[i] = np.linalg.norm(descriptors2-desc1, axis=-1)
return distances
def compute_chi_square_distances(descriptors1, descriptors2)... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Given the distances, a simple way to produce point matches is to take each descriptor extracted from a keypoint of the first image, and find the keypoint in the second image with the nearest descriptor. The full pipeline from images to point matches is implemented below in the function `find_point_matches(im1, im2, opt... | def find_point_matches(im1, im2, opts):
# Process first image
im1_gray = cv2.cvtColor(im1, cv2.COLOR_RGB2GRAY).astype(float)/255
score_map1 = nms(opts.score_func(im1_gray, opts))
points1 = score_map_to_keypoints(score_map1, opts)
descriptors1 = opts.descriptor_func(im1, points1, opts)
# Process... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
Homography EstimationNow that we have these pairs of matching points (also called point correspondences), what can we do with them? In the above case, the wall is planar (flat) and the camera was moved towards the left to take the second image compared to the first image. Therefore, the way that points on the wall are... | def estimate_homography(point_matches):
n_matches = len(point_matches)
A = np.empty((n_matches*2, 9))
for i, (x1, y1, x2, y2) in enumerate(point_matches):
# YOUR CODE HERE
raise NotImplementedError()
return H | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
The `point_matches` have already been sorted in the `find_point_matches` function according to the descriptor distances, so the more accurate pairs will be near the beginning. We can use the top $k$, e.g. $k=10$ pairs in the homography estimation and have a reasonably accurate estimate. What $k$ give the best result? W... | # See what happens if you change top_k below
top_k = 10
H = estimate_homography(point_matches[:top_k])
H_string = np.array_str(H, precision=5, suppress_small=True)
print('The estimated homography matrix H is\n', H_string)
im1_warped = cv2.warpPerspective(im1, H, (im2.shape[1], im2.shape[0]))
absdiff = np.abs(im2.asty... | _____no_output_____ | MIT | Exercise3/Exercise3/local_feature_matching.ipynb | danikhani/CV1-2020 |
SiteAlign featuresWe read the SiteAlign features from the respective [paper](https://onlinelibrary.wiley.com/doi/full/10.1002/prot.21858) and [SI table](https://onlinelibrary.wiley.com/action/downloadSupplement?doi=10.1002%2Fprot.21858&file=prot21858-SupplementaryTable.pdf) to verify `kissim`'s implementation of the S... | from kissim.definitions import SITEALIGN_FEATURES
SITEALIGN_FEATURES | _____no_output_____ | MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
Size SiteAlign's size definitions:> Natural amino acids have been classified into three groups according to the number of heavy atoms (6 heavy atoms: Arg, Phe, Trp, Tyr) and three values (“1,” “2,” “3”) are outputted according to the group to which the current residues belong to (Table I)https://onlinelibrary.wiley.co... | size = {
1.0: "Ala, Cys, Gly, Pro, Ser, Thr, Val".split(", "),
2.0: "Asn, Asp, Gln, Glu, His, Ile, Leu, Lys, Met".split(", "),
3.0: "Arg, Phe, Trp, Tyr".split(", "),
} | _____no_output_____ | MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
`kissim` definitions correct? | import pandas as pd
from IPython.display import display, HTML
# Format SiteAlign data
size_list = []
for value, amino_acids in size.items():
values = [(amino_acid.upper(), value) for amino_acid in amino_acids]
size_list = size_list + values
size_series = (
pd.DataFrame(size_list, columns=["amino_acid", "si... | KiSSim implementation of SiteAlign features is correct :)
| MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
HBA, HBD, charge, aromatic, aliphatic Parse table from SiteAlign SI | sitealign_table = """
Ala 0 0 0 1 0
Arg 3 0 +1 0 0
Asn 1 1 0 0 0
Asp 0 2 -1 0 0
Cys 1 0 0 1 0
Gly 0 0 0 0 0
Gln 1 1 0 0 0
Glu 0 2 -1 0 0
His/Hid/Hie 1 1 0 0 1
Hip 2 0 1 0 0
Ile 0 0 0 1 0
Leu 0 0 0 1 0
Lys 1 0 +1 0 0
Met 0 0 0 1 0
Phe 0 0 0 0 1
Pro 0 0 0 1 0
Ser 1 1 0 0 0
Thr 1 1 0 1 0
Trp 1 0 0 0 1
Tyr 1 1 0 0 1
Val 0 ... | _____no_output_____ | MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
`kissim` definitions correct? | from IPython.display import display, HTML
diff = sitealign_df == SITEALIGN_FEATURES.drop("size", axis=1).sort_index()
if not diff.all().all():
raise ValueError(
f"KiSSim implementation of SiteAlign features is incorrect!!!\n"
f"{display(HTML(diff.to_html()))}"
)
else:
print("KiSSim implemen... | KiSSim implementation of SiteAlign features is correct :)
| MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
Table style | from Bio.Data.IUPACData import protein_letters_3to1
for feature_name in SITEALIGN_FEATURES.columns:
print(feature_name)
for name, group in SITEALIGN_FEATURES.groupby(feature_name):
amino_acids = {protein_letters_3to1[i.capitalize()] for i in group.index}
amino_acids = sorted(amino_acids)
... | size
1.0 A C G P S T V
2.0 D E H I K L M N Q
3.0 F R W Y
hbd
0.0 A D E F G I L M P V
1.0 C H K N Q S T W Y
3.0 R
hba
0.0 A C F G I K L M P R V W
1.0 H N Q S T Y
2.0 D E
charge
-1.0 D E
0.0 A C F G H I L M N P Q S T V W Y
1.0 K R
aromatic
0.0 A C D E G I K L M N P Q R S T V
1.0 ... | MIT | notebooks/004_fingerprints/999_fetch_sitealign_features.ipynb | volkamerlab/kissim_app |
Fashion MNIST Generative Adversarial Network (GAN) [Мой блог](https://tiendil.org)[Пост об этом notebook](https://tiendil.org/generative-adversarial-network-implementation)[Все публичные notebooks](https://github.com/Tiendil/public-jupyter-notebooks)Учебная реализация [GAN](https://en.wikipedia.org/wiki/Generative_adv... | import os
import random
import logging
import datetime
import PIL
import PIL.Image
import jupyter_beeper
from IPython.display import display, Markdown, Image
import ipywidgets as ipw
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import ker... | _____no_output_____ | BSD-3-Clause | gan-fashion-mnist/notebook.ipynb | Tiendil/public-jupyter-notebooks |
Вспомогательные функции Можно пролистать. Смотрите при необходимости. | def split_dataset(data, *parts, cache):
data_size = data.cardinality()
assert data_size == sum(parts), \
f"dataset size must be equal to sum of parts: {data_size} != sum{parts}"
result = []
for part in parts:
data_part = data.take(part)
if cache:
... | _____no_output_____ | BSD-3-Clause | gan-fashion-mnist/notebook.ipynb | Tiendil/public-jupyter-notebooks |
Получение данных | # получаем картинки одежды средствами TensorFlow
(TRAIN_IMAGES, TRAIN_LABELS), (TEST_IMAGES, TEST_LABELS) = tf.keras.datasets.fashion_mnist.load_data()
# константы, описывающие данные
CHANNELS = 1
SPRITE_SIZE = 28
SPRITE_SHAPE = (SPRITE_SIZE, SPRITE_SIZE, CHANNELS)
# Подготавливаем данные. Для GAN нам нужны только кар... | _____no_output_____ | BSD-3-Clause | gan-fashion-mnist/notebook.ipynb | Tiendil/public-jupyter-notebooks |
Конструируем модель По-сути, GAN — это три сети:- Generator.- Discriminator.- GAN — объединение двух предыдущих.Сам GAN можно не оформлять отдельной сетью, достаточно правильно описать взаимодействие генератора и дискриминатора при обучения. Но, поскольку они учатся совместно, как одно целое, я вижу логичным работать ... | def construct_discriminator():
names = LayersNameGenerator('discriminator')
inputs = keras.Input(shape=SPRITE_SHAPE, name=names('Input'))
branch = inputs
n = 64
branch = layers.Conv2D(n, 4, 2, padding='same', name=names('Conv2D'))(branch)
branch = layers.... | _____no_output_____ | BSD-3-Clause | gan-fashion-mnist/notebook.ipynb | Tiendil/public-jupyter-notebooks |
**Important note:** You should always work on a duplicate of the course notebook. On the page you used to open this, tick the box next to the name of the notebook and click duplicate to easily create a new version of this notebook.You will get errors each time you try to update your course repository if you don't do th... | 1+1 | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
Cool huh? This combination of prose and code makes Jupyter Notebook ideal for experimentation: we can see the rationale for each experiment, the code and the results in one comprehensive document. In fast.ai, each lesson is documented in a notebook and you can later use that notebook to experiment yourself. Other renow... | 3/2 | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
Modes If you made a mistake in your *Markdown* cell and you have already ran it, you will notice that you cannot edit it just by clicking on it. This is because you are in **Command Mode**. Jupyter Notebooks have two distinct modes:1. **Edit Mode**: Allows you to edit a cell's content.2. **Command Mode**: Allows you t... | # Import necessary libraries
from fastai.vision import *
import matplotlib.pyplot as plt
from PIL import Image
a = 1
b = a + 1
c = b + a + 1
d = c + b + a + 1
a, b, c ,d
plt.plot([a,b,c,d])
plt.show() | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
We can also print images while experimenting. I am watching you. | Image.open('images/notebook_tutorial/cat_example.jpg') | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
Running the app locally You may be running Jupyter Notebook from an interactive coding environment like Gradient, Sagemaker or Salamander. You can also run a Jupyter Notebook server from your local computer. What's more, if you have installed Anaconda you don't even need to install Jupyter (if not, just `pip install j... | from fastai import*
from fastai.vision import * | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
There are also some tricks that you can code into a cell. `?function-name`: Shows the definition and docstring for that function | ?ImageDataBunch | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
`??function-name`: Shows the source code for that function | ??ImageDataBunch | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
`doc(function-name)`: Shows the definition, docstring **and links to the documentation** of the function(only works with fastai library imported) | doc(ImageDataBunch) | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
Line Magics Line magics are functions that you can run on cells and take as an argument the rest of the line from where they are called. You call them by placing a '%' sign before the command. The most useful ones are: `%matplotlib inline`: This command ensures that all matplotlib plots will be plotted in the output c... | %matplotlib inline
%reload_ext autoreload
%autoreload 2 | _____no_output_____ | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
`%timeit`: Runs a line a ten thousand times and displays the average time it took to run it. | %timeit [i+1 for i in range(1000)] | 39.6 µs ± 543 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
| Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
`%debug`: Allows to inspect a function which is showing an error using the [Python debugger](https://docs.python.org/3/library/pdb.html). | for i in range(1000):
a = i+1
b = 'string'
c = b+1
%debug | > [0;32m<ipython-input-15-8d78ff778454>[0m(4)[0;36m<module>[0;34m()[0m
[0;32m 1 [0;31m[0;32mfor[0m [0mi[0m [0;32min[0m [0mrange[0m[0;34m([0m[0;36m1000[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0m
[0m[0;32m 2 [0;31m [0ma[0m [0;34m=[0m [0mi[0m[0;34m+[0m[0;36m1[0m[0;34m[0m[0m
... | Apache-2.0 | nbs/dl1/00_notebook_tutorial.ipynb | jwdinius/course-v3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.