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 |
|---|---|---|---|---|---|
For 2D arrays, the `numpy.dot` function performs matrix multiplication rather than the dot product; so let's use the `numpy.sum` function: | a = np.array([[1, 2, 3], [1, 1, 1]])
b = np.array([[4, 5, 6], [7, 8, 9]])
np.sum(a*b, axis=1) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Vector productCross product or vector product between two vectors is a mathematical operation in three-dimensional space which results in a vector perpendicular to both of the vectors being multiplied and a length (norm) equal to the product of the perpendicular components of the vectors being multiplied (which is equ... | IFrame('https://faraday.physics.utoronto.ca/PVB/Harrison/Flash/Vectors/CrossProduct/CrossProduct.html',
width='100%', height=400) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
The Numpy function for the cross product is `numpy.cross`: | print('a =', a, '\nb =', b)
print('np.cross(a, b) =', np.cross(a, b)) | a = [[1 2 3]
[1 1 1]]
b = [[4 5 6]
[7 8 9]]
np.cross(a, b) = [[-3 6 -3]
[ 1 -2 1]]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
For 2D arrays with vectors in different rows: | a = np.array([[1, 2, 3], [1, 1, 1]])
b = np.array([[4, 5, 6], [7, 8, 9]])
np.cross(a, b, axis=1) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Gram–Schmidt processThe [Gram–Schmidt process](http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) is a method for orthonormalizing (orthogonal unit versors) a set of vectors using the scalar product. The Gram–Schmidt process works for any number of vectors. For example, given three vectors, $\overrightarrow{... | import numpy as np
a = np.array([1, 2, 0])
b = np.array([0, 1, 3])
c = np.array([1, 0, 1]) | _____no_output_____ | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
The first versor is: | ea = a/np.linalg.norm(a)
print(ea) | [ 0.4472136 0.89442719 0. ]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
The second versor is: | eb = b - np.dot(b, ea)*ea
eb = eb/np.linalg.norm(eb)
print(eb) | [-0.13187609 0.06593805 0.98907071]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
And the third version is: | ec = c - np.dot(c, ea)*ea - np.dot(c, eb)*eb
ec = ec/np.linalg.norm(ec)
print(ec) | [ 0.88465174 -0.44232587 0.14744196]
| CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Let's check the orthonormality between these versors: | print('Versors:', '\nea =', ea, '\neb =', eb, '\nec =', ec)
print('\nTest of orthogonality (scalar product between versors):',
'\nea x eb:', np.dot(ea, eb),
'\neb x ec:', np.dot(eb, ec),
'\nec x ea:', np.dot(ec, ea))
print('\nNorm of each versor:',
'\n||ea|| =', np.linalg.norm(ea),
'\n||eb... | Versors:
ea = [ 0.4472136 0.89442719 0. ]
eb = [-0.13187609 0.06593805 0.98907071]
ec = [ 0.88465174 -0.44232587 0.14744196]
Test of orthogonality (scalar product between versors):
ea x eb: 2.08166817117e-17
eb x ec: -2.77555756156e-17
ec x ea: 5.55111512313e-17
Norm of each versor:
||ea|| = 1.0
... | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Or, we can simply use the built-in QR factorization function from NumPy: | vectors = np.vstack((a,b,c)).T
Q, R = np.linalg.qr(vectors)
print(Q)
ea, eb, ec = Q[:, 0], Q[:, 1], Q[:, 2]
print('Versors:', '\nea =', ea, '\neb =', eb, '\nec =', ec)
print('\nTest of orthogonality (scalar product between versors):')
print(np.dot(Q.T, Q))
print('\nTest of orthogonality (scalar product between ... | Versors:
ea = [-0.4472136 -0.89442719 -0. ]
eb = [ 0.13187609 -0.06593805 -0.98907071]
ec = [ 0.88465174 -0.44232587 0.14744196]
Test of orthogonality (scalar product between versors):
[[ 1.00000000e+00 4.05428641e-17 1.77198775e-16]
[ 4.05428641e-17 1.00000000e+00 -3.05471126e-16]
[ 1.77198775... | CC-BY-4.0 | notebooks/ScalarVector.ipynb | gbiomech/BMC |
Import the library and create the trees | import mp3treesim as mp3
gv = '''
strict digraph G {
graph [name=G];
0 [label=root];
1 [label="C,M"];
0 -> 1;
2 [label="I,Q"];
0 -> 2;
3 [label=A];
0 -> 3;
1 -> 4;
2 -> 5;
6 [label=G];
3 -> 6;
7 [label="E,R"];
3 -> 7;
8 [label=F];
3 -> 8;
9 [label="L,N"];
4 -> 9;
10 [label="H,K"];
4 -> 10;... | _____no_output_____ | MIT | examples/similarity.ipynb | AlgoLab/mp3treesim |
Compute the similarity score | print(mp3.similarity(tree1, tree2)) | 0.05009996058703979
| MIT | examples/similarity.ipynb | AlgoLab/mp3treesim |
Let's consider the tree described in `gv` string as a partially-labeled tree | tree2_p = mp3.read_dotstring(gv, labeled_only=True)
mp3.draw_tree(tree2_p) | _____no_output_____ | MIT | examples/similarity.ipynb | AlgoLab/mp3treesim |
Let's compare the trees | print('Tree 1 vs Tree 2', mp3.similarity(tree1, tree2))
print('Tree 1 vs Tree 2p', mp3.similarity(tree1, tree2_p))
print('Tree 2 vs Tree 2p', mp3.similarity(tree2, tree2_p)) | Tree 1 vs Tree 2 0.05009996058703979
Tree 1 vs Tree 2p 0.061922490968955
Tree 2 vs Tree 2p 1.0
| MIT | examples/similarity.ipynb | AlgoLab/mp3treesim |
Let's exlude now some mutation from the computation, without having to modify the input. In particular let's remove mutations `A,G,F,H` from tree1 | tree1_r = mp3.read_dotfile('trees/tree1.gv', exclude='A,G,F,H')
mp3.draw_tree(tree1_r)
print('Tree 1r vs Tree 2', mp3.similarity(tree1_r, tree2))
print('Tree 1r vs Tree 2p', mp3.similarity(tree1_r, tree2_p))
print('Tree 1 vs Tree 1r', mp3.similarity(tree1, tree1_r)) | Tree 1r vs Tree 2 0.018792140154100388
Tree 1r vs Tree 2p 0.02475323155433422
Tree 1 vs Tree 1r 0.88
| MIT | examples/similarity.ipynb | AlgoLab/mp3treesim |
Задание 1.2 - Линейный классификатор (Linear classifier)В этом задании мы реализуем другую модель машинного обучения - линейный классификатор. Линейный классификатор подбирает для каждого класса веса, на которые нужно умножить значение каждого признака и потом сложить вместе.Тот класс, у которого эта сумма больше, и я... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
from dataset import load_svhn, random_split_train_val
from gradient_check import check_gradient
from metrics import multiclass_accuracy
import linear_classifer | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Как всегда, первым делом загружаем данныеМы будем использовать все тот же SVHN. | def prepare_for_linear_classifier(train_X, test_X):
train_flat = train_X.reshape(train_X.shape[0], -1).astype(float) / 255.0 # pixel normalize to the range 0-1
test_flat = test_X.reshape(test_X.shape[0], -1).astype(float) / 255.0
mean_image = np.mean(train_flat, axis=0)
# Subtract mean https://stat... | min: -0.48431568627450733
mean: 0.01875625032701183
max: 1.0
| MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Играемся с градиентами!В этом курсе мы будем писать много функций, которые вычисляют градиенты аналитическим методом.Все функции, в которых мы будем вычислять градиенты, будут написаны по одной и той же схеме. Они будут получать на вход точку, где нужно вычислить значение и градиент функции, а на выходе будут выдават... | # TODO: Implement check_gradient function in gradient_check.py
# All the functions below should pass the gradient check
def square(x):
return float(x*x), 2*x
check_gradient(square, np.array([3.0]))
def array_sum(x):
assert x.shape == (2,), x.shape
return np.sum(x), np.ones_like(x)
check_gradient(array_s... | 6.0 6.000000000039306
Gradient check passed!
1.0 0.9999999999621422
1.0 0.9999999999621422
Gradient check passed!
1.0 0.9999999999621422
1.0 0.9999999999621422
1.0 0.9999999999621422
1.0 0.9999999999621422
Gradient check passed!
| MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Начинаем писать свои функции, считающие аналитический градиентТеперь реализуем функцию softmax, которая получает на вход оценки для каждого класса и преобразует их в вероятности от 0 до 1:**Важно:** Практический а... | # TODO Implement softmax and cross-entropy for single sample
probs = linear_classifer.softmax(np.array([-10, 0, 10]))
# Make sure it works for big numbers too!
probs = linear_classifer.softmax(np.array([1000, 0, 0])) # [1. 0. 0.]
assert np.isclose(probs[0], 1.0) | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Кроме этого, мы реализуем cross-entropy loss, которую мы будем использовать как функцию ошибки (error function).В общем виде cross-entropy определена следующим образом:где x - все классы, p(x) - истинная вероятност... | probs = linear_classifer.softmax(np.array([-5, 0, 5]))
linear_classifer.cross_entropy_loss(probs, 1) | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
После того как мы реализовали сами функции, мы можем реализовать градиент.Оказывается, что вычисление градиента становится гораздо проще, если объединить эти функции в одну, которая сначала вычисляет вероятности через softmax, а потом использует их для вычисления функции ошибки через cross-entropy loss.Эта функция `sof... | # TODO Implement combined function or softmax and cross entropy and produces gradient
loss, grad = linear_classifer.softmax_with_cross_entropy(np.array([1, 0, 0]), 1)
check_gradient(lambda x: linear_classifer.softmax_with_cross_entropy(x, 1), np.array([1, 0, 0], float)) | 0.5761168847658291 0.5761168847651099
-0.7880584423829146 -0.7880584423691771
0.21194155761708544 0.2119415576151695
Gradient check passed!
| MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
В качестве метода тренировки мы будем использовать стохастический градиентный спуск (stochastic gradient descent или SGD), который работает с батчами сэмплов. Поэтому все наши функции будут получать не один пример, а батч, то есть входом будет не вектор из `num_classes` оценок, а матрица размерности `batch_size, num_cl... | # TODO Extend combined function so it can receive a 2d array with batch of samples
np.random.seed(42)
# Test batch_size = 1
num_classes = 4
batch_size = 1
predictions = np.random.randint(-1, 3, size=(batch_size, num_classes)).astype(float)
target_index = np.random.randint(0, num_classes, size=(batch_size, 1)).astype(in... | 0.20603190919001857 0.20603190920009948
0.5600527948339517 0.560052794829069
-0.9721166132139888 -0.9721166132292679
0.20603190919001857 0.20603190920009948
Gradient check passed!
0.2271508539361916 0.2271508539486433
0.011309175094739847 0.011309175063090036
0.011309175094739847 0.011309175063090036
-0.249769204125671... | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Наконец, реализуем сам линейный классификатор!softmax и cross-entropy получают на вход оценки, которые выдает линейный классификатор.Он делает это очень просто: для каждого класса есть набор весов, на которые надо умножить пиксели картинки и сложить. Получившееся число и является оценкой класса, идущей на вход softmax... | # TODO Implement linear_softmax function that uses softmax with cross-entropy for linear classifier
batch_size = 2
num_classes = 2
num_features = 3
np.random.seed(42)
W = np.random.randint(-1, 3, size=(num_features, num_classes)).astype(float)
X = np.random.randint(-1, 3, size=(batch_size, num_features)).astype(float)
... | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
И теперь регуляризацияМы будем использовать L2 regularization для весов как часть общей функции ошибки.Напомним, L2 regularization определяется какl2_reg_loss = regularization_strength * sumij W[i, j]2Реализуйте функцию для его вычисления и вычисления соотвествующих градиентов. | # TODO Implement l2_regularization function that implements loss for L2 regularization
linear_classifer.l2_regularization(W, 0.01)
check_gradient(lambda w: linear_classifer.l2_regularization(w, 0.01), W) | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Тренировка! Градиенты в порядке, реализуем процесс тренировки! | # TODO: Implement LinearSoftmaxClassifier.fit function
classifier = linear_classifer.LinearSoftmaxClassifier()
loss_history = classifier.fit(train_X, train_y, epochs=10, learning_rate=1e-3, batch_size=300, reg=1e1)
# let's look at the loss history!
plt.plot(loss_history);
# Let's check how it performs on validation set... | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Как и раньше, используем кросс-валидацию для подбора гиперпараметтов.В этот раз, чтобы тренировка занимала разумное время, мы будем использовать только одно разделение на тренировочные (training) и проверочные (validation) данные.Теперь нам нужно подобрать не один, а два гиперпараметра! Не ограничивайте себя изначальн... | num_epochs = 200
batch_size = 300
learning_rates = [1e-3, 1e-4, 1e-5]
reg_strengths = [1e-4, 1e-5, 1e-6]
best_classifier = None
best_val_accuracy = None
# TODO use validation set to find the best hyperparameters
# hint: for best results, you might need to try more values for learning rate and regularization strength... | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Какой же точности мы добились на тестовых данных? | test_pred = best_classifier.predict(test_X)
test_accuracy = multiclass_accuracy(test_pred, test_y)
print('Linear softmax classifier test set accuracy: %f' % (test_accuracy, )) | _____no_output_____ | MIT | assignments/assignment1/Linear classifier.ipynb | venera111/dlcourse |
Pandas - Delete Columns from a DataFrame | import pandas as pd
df = pd.read_csv('iris.data', names=['A','B','C','D','Label'])
df | _____no_output_____ | MIT | Pandas/Pandas - Delete Columns from DataFrame.ipynb | AmanKumar05032005/Python-1 |
1) to drop a single columndf.drop('col_name', axis=1) To save changes you must either set df = df.drop(), or add inplace=True. | df.drop('B', axis=1)
df | _____no_output_____ | MIT | Pandas/Pandas - Delete Columns from DataFrame.ipynb | AmanKumar05032005/Python-1 |
2) to drop multiple axes by namedf.drop(['col_name1', 'col_name2'], axis=1, inplace=True) | df.drop(['A','Label'], axis=1, inplace=True)
df | _____no_output_____ | MIT | Pandas/Pandas - Delete Columns from DataFrame.ipynb | AmanKumar05032005/Python-1 |
3) to drop multiple axes by numerical column indexdf.drop(df.columns[[idx1, idx2]], axis=1, inplace=True) | df.drop(df.columns[[0, 2]], axis=1, inplace=True)
df | _____no_output_____ | MIT | Pandas/Pandas - Delete Columns from DataFrame.ipynb | AmanKumar05032005/Python-1 |
Preface In this notebook I continue the work of https://www.kaggle.com/christofhenkel/how-to-preprocessing-for-glove-part1-eda unfortunatly I had to split the kernel into two due to memory issues.Since I am rather lazy, I forked Benjamins https://www.kaggle.com/bminixhofer/speed-up-your-rnn-with-sequence-bucketing to ... | # Put these at the top of every notebook, to get automatic reloading and inline plotting
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import fastai
from fastai.train import Learner
from fastai.train import DataBunch
from fastai.callbacks import *
from fastai.basic_data import DatasetType
import fastprogress... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Here, compared to most other public kernels I replace the pretrained embedding files with their pickle corresponds. Loading a pickled version extremly improves timing ;) | CRAWL_EMBEDDING_PATH = '../input/pickled-crawl300d2m-for-kernel-competitions/crawl-300d-2M.pkl'
GLOVE_EMBEDDING_PATH = '../input/pickled-glove840b300d-for-10sec-loading/glove.840B.300d.pkl' | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Of course we also need to adjust the load_embeddings function, to now handle the pickled dict. | NUM_MODELS = 2
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
MAX_LEN = 220
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
def load_embeddings(path):
with open(path,'rb') as f:
emb_arr = pickle.load(f)
return emb_arr
| _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
The next function is really important. Although we put a lot of effort in making the preprocessing right there are stil some out of vocabulary words we could easily fix. One example I implement here is to try a "lower/upper case version of a" word if an embedding is not found, which sometimes gives us an embedding. Sor... | def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
embedding_matrix = np.zeros((max_features + 1, 300))
unknown_words = []
for word, i in word_index.items():
if i <= max_features:
try:
embedding_matrix[i] = embedding_index[word]
... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Let's discuss the function, which is most popular in most public kernels. In principle this functions just deletes some special characters. Which is not optimal and I will explain why in a bit. What is additionally inefficient is that later the keras tokenizer with its default parameters is used which has its own with ... | train = pd.read_csv('../input/jigsaw-unintended-bias-in-toxicity-classification/train.csv')
test = pd.read_csv('../input/jigsaw-unintended-bias-in-toxicity-classification/test.csv') | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Preprocessing See part1 for an explanation how I came to the list of symbols and contraction function. I copied them from that kernel. | symbols_to_isolate = '.,?!-;*"…:—()%#$&_/@\・ω+=”“[]^–>\\°<~•≠™ˈʊɒ∞§{}·τα❤☺ɡ|¢→̶`❥━┣┫┗O►★©―ɪ✔®\x96\x92●£♥➤´¹☕≈÷♡◐║▬′ɔː€۩۞†μ✒➥═☆ˌ◄½ʻπδηλσερνʃ✬SUPERIT☻±♍µº¾✓◾؟.⬅℅»Вав❣⋅¿¬♫CMβ█▓▒░⇒⭐›¡₂₃❧▰▔◞▀▂▃▄▅▆▇↙γ̄″☹➡«φ⅓„✋:¥̲̅́∙‛◇✏▷❓❗¶˚˙)сиʿ✨。ɑ\x80◕!%¯−flfi₁²ʌ¼⁴⁄₄⌠♭✘╪▶☭✭♪☔☠♂☃☎✈✌✰❆☙○‣⚓年∎ℒ▪▙☏⅛casǀ℮¸w‚∼‖ℳ❄←☼⋆ʒ⊂、⅔¨͡๏⚾⚽Φ×θ₩?(℃⏩☮⚠月✊❌⭕▸■⇌☐☑⚡☄ǫ╭∩╮... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
So lets apply that preprocess function to our text | #train['comment_text'] = train['comment_text'].progress_apply(lambda x:preprocess(x))
#test['comment_text'] = test['comment_text'].progress_apply(lambda x:preprocess(x))
train['comment_text'].head()
x_train = train['comment_text'].progress_apply(lambda x:preprocess(x))
y_aux_train = train[['target', 'severe_toxicity', ... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Its really important that you intitialize the keras tokenizer correctly. Per default it does lower case and removes a lot of symbols. We want neither of that! | tokenizer = text.Tokenizer(num_words = max_features, filters='',lower=False)
tokenizer.fit_on_texts(list(x_train) + list(x_test))
crawl_matrix, unknown_words_crawl = build_matrix(tokenizer.word_index, CRAWL_EMBEDDING_PATH)
print('n unknown words (crawl): ', len(unknown_words_crawl))
glove_matrix, unknown_words_glove... | n unknown words (crawl): 148783
n unknown words (glove): 152316
| MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Sequence Bucketing | x_train = tokenizer.texts_to_sequences(x_train)
x_test = tokenizer.texts_to_sequences(x_test)
lengths = torch.from_numpy(np.array([len(x) for x in x_train]))
#maxlen = lengths.max()
maxlen = 300
x_train_padded = torch.from_numpy(sequence.pad_sequences(x_train, maxlen=maxlen))
x_train_padded.shape
class SequenceBucket... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Method 1 is quite a bit solower than the rest, but method 2 and 3 are pretty close to each other (keep in mind that the majority of the time it takes to train the NN is spent in the actual computation anyway, not while loading). I am going to use method 3 because it is much more elegant and can be used as a drop-in rep... | class NeuralNet(nn.Module):
def __init__(self, embedding_matrix, num_aux_targets):
super(NeuralNet, self).__init__()
embed_size = embedding_matrix.shape[1]
self.embedding = nn.Embedding(max_features, embed_size)
self.embedding.weight = nn.Parameter(torch.tensor(embedding_mat... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Training For training in this kernel, I will use sequence bucketing with maximum length. Now we can instantiate a test, train and valid dataset and train the network. The validation dataset is only added so that the fast.ai DataBunch works as expected and it consists of only 2 samples. | # lengths = torch.from_numpy(np.array([len(x) for x in x_train]))
test_lengths = torch.from_numpy(np.array([len(x) for x in x_test]))
# maxlen = 299
# x_train_padded = torch.from_numpy(sequence.pad_sequences(x_train, maxlen=maxlen))
x_test_padded = torch.from_numpy(sequence.pad_sequences(x_test, maxlen=maxlen))
batch_... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Now, train the model and see that it is faster than before!On my local machine, one epoch with statically padded sequences takes 7:25 to train (445 seconds). With sequence bucketing, one batch takes 6:26 (386 seconds). So the version with sequence bucketing is 1.15x faster. | all_test_preds = []
for model_idx in range(NUM_MODELS):
print('Model ', model_idx)
seed_everything(1 + model_idx)
model = NeuralNet(embedding_matrix, y_aux_train.shape[-1])
learn = Learner(databunch, model, loss_func=custom_loss)
test_preds = train_model(learn,test_dataset,output_dim=7)
all... | _____no_output_____ | MIT | 4 jigsaw/how-to-preprocessing-for-glove-part2-usage.ipynb | MLVPRASAD/KaggleProjects |
Calculate Detector Counts: Low-frequency Nanoflares and Ionization Equilibrium | import os
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import matplotlib.colors
import dask
import distributed
import synthesizAR
from synthesizAR.instruments import InstrumentSDOAIA
from synthesizAR.atomic import EmissionModel
import synthesizA... | _____no_output_____ | MIT | notebooks/low_frequency/detect_ieq.ipynb | rice-solar-physics/synthetic-observables-paper-models |
Image DisplayThe native SimpleITK approach to displaying images is to use an external viewing program. In the notebook environment it is convenient to use matplotlib to display inline images and if the need arises we can implement some reasonably rich inline graphical user interfaces, combining control components from ... | from __future__ import print_function
import SimpleITK as sitk
%matplotlib notebook
import matplotlib.pyplot as plt
import gui
# Utility method that either downloads data from the Girder repository or
# if already downloaded returns the file name for reading from disk (cached data).
%run update_path_to_download_scri... | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
Image Display with An External ViewerSimpleITK provides two options for invoking an external viewer, use a procedural interface or an object oriented one. Procedural interfaceSimpleITK provides a built in ``Show`` method. This function writes the image out to disk and than launches a program for visualization. By def... | mr_image = sitk.ReadImage(fdata('training_001_mr_T1.mha'))
sitk.Show?
try:
sitk.Show(mr_image)
except RuntimeError:
print('SimpleITK Show method could not find the viewer (ImageJ not installed or ' +
'environment variable pointing to non existant viewer).') | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
Use a different viewer by setting environment variable(s). Do this from within your Jupyter notebook using 'magic' functions, or set in a more permanent manner using your OS specific convention. | %env SITK_SHOW_COMMAND /Applications/ITK-SNAP.app/Contents/MacOS/ITK-SNAP
try:
sitk.Show(mr_image)
except RuntimeError:
print('SimpleITK Show method could not find the viewer (ITK-SNAP not installed or ' +
'environment variable pointing to non existant viewer).')
%env SITK_SHOW_COMMAND '/Application... | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
Object Oriented interfaceThe [Image Viewer](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ImageViewer.html) class provides a more standard approach to controlling image viewing by setting various instance variable values. Also, it ensures that all of your viewing settings are documented, as they are ... | # Which external viewer will the image_viewer use if we don't specify the external viewing application?
# (see caveat above)
image_viewer = sitk.ImageViewer()
image_viewer.SetApplication('/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx')
image_viewer.SetTitle('MR image')
# Use the default image viewer.
image_view... | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
Inline display with matplotlib | mr_image = sitk.ReadImage(fdata('training_001_mr_T1.mha'))
npa = sitk.GetArrayViewFromImage(mr_image)
# Display the image slice from the middle of the stack, z axis
z = int(mr_image.GetDepth()/2)
npa_zslice = sitk.GetArrayViewFromImage(mr_image)[z,:,:]
# Three plots displaying the same data, how do we deal with the h... | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
Inline display with matplotlib and ipywidgetsDisplay two volumes side by side, with sliders to control the displayed slice. The menu on the bottom left allows you to home (return to original view), back and forward between views, pan, zoom and save a view. A variety of interfaces combining matplotlib display and ipywi... | ct_image = sitk.ReadImage(fdata('training_001_ct.mha'))
ct_window_level = [720,80]
mr_window_level = [790,395]
gui.MultiImageDisplay([mr_image, ct_image], figure_size=(10,3), window_level_list=[mr_window_level,ct_window_level]); | _____no_output_____ | Apache-2.0 | Python/04_Image_Display.ipynb | Ivana144/SimpleITK-Notebooks |
from PIL import ImageFont, ImageDraw, Image
from google.colab.patches import cv2_imshow
import numpy as np
import cv2
text= "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ... | _____no_output_____ | MIT | ufabc/img_with_text.ipynb | BrunoASNascimento/image-processing-study | |
Open data- from this study- from Lidar validation data sets (Margolis et al 2015 and Neigh et al 2015)- Spawn et al 2020 (for year 2010)- Hansen et al 2007 (for year 2000)To do:- Jon Wang- FIA | def open_biomass_data(tiles=None, min_lat=-90, max_lat=90, min_lon=-180, max_lon=180):
folder = "s3://carbonplan-climatetrace/v1/data/intermediates/biomass/"
if not tiles:
s3fs = fsspec.get_filesystem_class("s3")()
tiles = [
os.path.splitext(os.path.split(path)[-1])[0]
fo... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
Compare biomass on scatter plots + error metrics - index gridded study to gridded hansen and spawn, check for bias, MAE, r2, visual inspection | def index_point_cloud_to_reference(ds, format_grid, name):
gridded_df = format_grid.sel(lat=ds.lat, lon=ds.lon, method="nearest")
for v in ds:
if v not in ["lat", "lon"]:
gridded_df[v] = ds[v]
grouped = gridded_df.to_dataframe().reset_index(drop=True).dropna().groupby(["lat", "lon"])
... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
R squared, bias, and MAE compared to Hansen and Spawn datasets- overall score- score by Realm | for name, df in zip(["Hansen", "Spawn"], [gridded_study_df_hansen, gridded_study_df_spawn]):
for count_threshold in [0, 10, 20]:
col_name = f"{name.lower()}_biomass"
sub = df.loc[df.n_shots_in_grid >= count_threshold, [col_name, "biomass"]].dropna()
ytrue = sub[col_name].values
ypred... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
Scatter plots compared to Hansen and Spawn datasets- overall- by Realm | def plot_scatter_comparison(
ax,
x_col,
y_col,
reference_name,
comparison_name,
plot_params,
c="k",
s=0.01,
alpha=0.1,
):
tot = np.hstack((x_col, y_col))
xmax = np.percentile(tot, 99.5)
xmin = plot_params["xmin"]
unit = plot_params["unit"]
ax.plot([xmin, xmax], [... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
index study to margolis, check for bias, MAE, r2 | study_df = study[["lat", "lon", "biomass"]].to_dataframe().reset_index()
margolis_df = (
margolis[["lat", "lon", "biomass"]]
.to_dataframe()
.reset_index()
.rename(columns={"biomass": "margolis_biomass"})
)
precision = 4
study_df["lat_round"] = study_df.lat.round(precision)
study_df["lon_round"] = study... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
Plot biomass data on maps | from cartopy.io import shapereader
import geopandas as gpd
def cartopy_proj_albers():
return ccrs.AlbersEqualArea(
central_longitude=-96,
central_latitude=23,
standard_parallels=(29.5, 45.5),
)
def cartopy_borders(projection=utils.projections("albers", "conus")):
states_df = gpd.... | _____no_output_____ | MIT | notebooks/analysis/validate_biomass_training_data.ipynb | carbonplan/trace |
The UML Class Diagrams 1 The Project Of Student and Grade **If the project have `many different type modules`,you may feel `confused`.** The fine-organized module structures will help you understand softwareWe arrange modules to the suitable folders.* The `edu` package: `grade.py student.py````python\mit \edu __... | # %load ./mit/distinmulti/main_app.py
from edu.grade import *
ug1 = UG('Jane Doe', 2014)
# 1 creat the course named sixHundred
sixHundred = Grades()
# 2 some students taking a course named sixHundred
sixHundred.addStudent(ug1)
# 3 add Grades of students
sixHundred.addGrade(ug1, 85)
sixHundred.addGrade(ug1, 90)
print... | _____no_output_____ | MIT | notebook/Unit3-3-UML.ipynb | alex-treebeard/home |
Let us create some characters Latin lowercase | for c in range(ord('a'),ord('z')+1):
print('c.add("' + chr(c) + '")')
| c.add("a")
c.add("b")
c.add("c")
c.add("d")
c.add("e")
c.add("f")
c.add("g")
c.add("h")
c.add("i")
c.add("j")
c.add("k")
c.add("l")
c.add("m")
c.add("n")
c.add("o")
c.add("p")
c.add("q")
c.add("r")
c.add("s")
c.add("t")
c.add("u")
c.add("v")
c.add("w")
c.add("x")
c.add("y")
c.add("z")
| MIT | [ideas]/utf8.ipynb | batthias/mammal-brainstorming |
Latin Uppercase | for c in range(ord('A'),ord('Z')+1):
print('c.add("' + chr(c) + '")') | c.add("A")
c.add("B")
c.add("C")
c.add("D")
c.add("E")
c.add("F")
c.add("G")
c.add("H")
c.add("I")
c.add("J")
c.add("K")
c.add("L")
c.add("M")
c.add("N")
c.add("O")
c.add("P")
c.add("Q")
c.add("R")
c.add("S")
c.add("T")
c.add("U")
c.add("V")
c.add("W")
c.add("X")
c.add("Y")
c.add("Z")
| MIT | [ideas]/utf8.ipynb | batthias/mammal-brainstorming |
Greek lowercase | for c in range(ord('α'),ord('ω')+1):
print('c.add("' + chr(c) + '")') | c.add("α")
c.add("β")
c.add("γ")
c.add("δ")
c.add("ε")
c.add("ζ")
c.add("η")
c.add("θ")
c.add("ι")
c.add("κ")
c.add("λ")
c.add("μ")
c.add("ν")
c.add("ξ")
c.add("ο")
c.add("π")
c.add("ρ")
c.add("ς")
c.add("σ")
c.add("τ")
c.add("υ")
c.add("φ")
c.add("χ")
c.add("ψ")
c.add("ω")
| MIT | [ideas]/utf8.ipynb | batthias/mammal-brainstorming |
Anomaly Detection* What are Outliers ?* Statistical Methods for Univariate Data* Using Gaussian Mixture Models* Isolation Forest* Local Outlier Factor Outliers* New data which doesn't belong to general trend (or distribution) of entire data are known as outliers.* Data belonging to general trend are known as inliners... | import numpy as np
data = np.random.normal(size=1000) | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
* Adding More Outliers | data[-5:] = [3.5,3.6,4,3.56,4.2]
from scipy.stats import zscore | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
* Detecting Outliers | data[np.abs(zscore(data)) > 3] | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Using Interquartile Range* For univariate data not following Gaussian Distribution IQR is a way to detect outliers | from scipy.stats import iqr
data = np.random.normal(size=1000)
data[-5:]=[-2,9,11,-3,-21]
iqr_value = iqr(data)
lower_threshold = np.percentile(data,25) - iqr_value*1.5
upper_threshold = np.percentile(data,75) + iqr_value*1.5
upper_threshold
lower_threshold
data[np.where(data < lower_threshold)]
data[np.where(data > up... | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Using Gaussian Mixture Models | # Number of samples per component
n_samples = 500
# Generate random sample, two components
np.random.seed(0)
C = np.array([[0., -0.1], [1.7, .4]])
C2 = np.array([[1., -0.1], [2.7, .2]])
#X = np.r_[np.dot(np.random.randn(n_samples, 2), C)]
#.7 * np.random.randn(n_samples, 2) + np.array([-6, 3])]
X = np.r_[np.... | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Fitting Elliptical Envelope* The assumption here is, regular data comes from known distribution ( Gaussion distribution )* Inliner location & variance will be calculated using `Mahalanobis distances` which is less impacted by outliers.* Calculate robust covariance fit of the data. | from sklearn.datasets import make_blobs
X,_ = make_blobs(n_features=2, centers=2, cluster_std=2.5, n_samples=1000)
plt.scatter(X[:,0], X[:,1],s=10)
from sklearn.covariance import EllipticEnvelope
ev = EllipticEnvelope(contamination=.1)
ev.fit(X)
cluster = ev.predict(X)
plt.scatter(X[:,0], X[:,1],s=10,c=cluster) | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Isolation Forest* Based on RandomForest* Useful in detecting outliers in high dimension datasets.* This algorithm randomly selects a feature & splits further.* Random partitioning produces shorter part for anomolies.* When a forest of random trees collectively produce shorter path lengths for particular samples, they ... | rng = np.random.RandomState(42)
# Generate train data
X = 0.3 * rng.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * rng.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))
from skle... | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Local Outlier Factor* Based on nearest neighbours* Suited for moderately high dimension datasets* LOF computes a score reflecting degree of abnormility of a data.* LOF Calculation - Local density is calculated from k-nearest neighbors. - LOF of each data is equal to the ratio of the average local density of his k-ne... | from sklearn.neighbors import LocalOutlierFactor
lof = LocalOutlierFactor(n_neighbors=25,contamination=.1)
pred = lof.fit_predict(data)
s = np.abs(lof.negative_outlier_factor_)
plt.scatter(data[:,0], data[:,1],s=s*10,c=pred) | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Outlier Detection using DBSCAN* DBSCAN is a clustering method based on density* Groups data which are closer to each other.* Doesn't use distance vector calculation method* Data not close enough to any cluster is not assigned any cluster & these can be anomalies | from sklearn.cluster import DBSCAN
dbscan = DBSCAN(eps=.3)
dbscan.fit(data)
plt.scatter(data[:,0], data[:,1],s=s*10,c=dbscan.labels_) | _____no_output_____ | MIT | SII/ML/5-Anomaly_Detection.ipynb | vafaei-ar/alzahra-workshop-2019 |
Transforms Helpers | #exports
def type_hints(f):
"Same as `typing.get_type_hints` but returns `{}` if not allowed type"
return typing.get_type_hints(f) if isinstance(f, typing._allowed_types) else {}
#export
def anno_ret(func):
"Get the return annotation of `func`"
if not func: return None
ann = type_hints(func)
if ... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Types | #export
@delegates(plt.subplots, keep=True)
def subplots(nrows=1, ncols=1, **kwargs):
fig,ax = plt.subplots(nrows,ncols,**kwargs)
if nrows*ncols==1: ax = array([ax])
return fig,ax
#export
class TensorImageBase(TensorBase):
_show_args = {'cmap':'viridis'}
def show(self, ctx=None, **kwargs):
r... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
TypeDispatch - | #export
class TypeDispatch:
"Dictionary-like object; `__getitem__` matches keys of types using `issubclass`"
def __init__(self, *funcs):
self.funcs,self.cache = {},{}
for f in funcs: self.add(f)
self.inst = None
def _reset(self):
self.funcs = {k:self.funcs[k] for k in sorted... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Transform - | #export
class _TfmDict(dict):
def __setitem__(self,k,v):
if k=='_': k='encodes'
if k not in ('encodes','decodes') or not isinstance(v,Callable): return super().__setitem__(k,v)
if k not in self: super().__setitem__(k,TypeDispatch())
res = self[k]
res.add(v)
#export
class _Tfm... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Base class that delegates `__call__` and `decode` to `encodes` and `decodes`, doing nothing if param annotation doesn't match type. If called with listy `x` then it calls function with each item (unless `whole_typle`, in which case it's passed directly as a whole). The function (if matching 1st param type) will cast th... | class A(Transform): pass
@A
def encodes(self, x): return x+1
f1 = A()
test_eq(f1(1), 2)
class B(A): pass
f2 = B()
test_eq(f2(1), 2)
class A(Transform): pass
f3 = A()
test_eq_type(f3(2), 2)
test_eq_type(f3.decode(2.0), 2.0) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
`Transform` can be used as a decorator, to turn a function into a `Transform`. | @Transform
def f(x): return x//2
test_eq_type(f(2), 1)
test_eq_type(f.decode(2.0), 2.0) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
You can derive from `Transform` and use either `_` or `encodes` for your encoding function. | class A(Transform):
def _(self, x:TensorImage): return -x
f = A()
t = f(im_t)
test_eq(t, -im_t)
test_eq(f(1), 1)
test_eq(type(t), TensorImage)
f | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Without return annotation we get an `Int` back since that's what was passed. | class A(Transform): pass
@A
def _(self, x:Int): return x//2 # `_` is an abbreviation for `encodes`
@A
def encodes(self, x:float): return x+1
f = A()
test_eq_type(f(Int(2)), Int(1))
test_eq_type(f(2), 2)
test_eq_type(f(2.), 3.) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Without return annotation we don't cast if we're not a subclass of the input type. | class A(Transform):
def encodes(self, x:Int): return x/2
def _(self, x:float): return x+1
f = A()
test_eq_type(f(Int(2)), 1.)
test_eq_type(f(2), 2)
test_eq_type(f(Float(2.)), Float(3.)) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
With return annotation `None` we get back whatever Python creates usually. | def func(x)->None: return x/2
f = Transform(func)
test_eq_type(f(2), 1.)
test_eq_type(f(2.), 1.) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Since `decodes` has no return annotation, but `encodes` created an `Int` and we pass that result here to `decode`, we end up with an `Int`. | def func(x): return Int(x+1)
def dec (x): return x-1
f = Transform(func,dec)
t = f(1)
test_eq_type(t, Int(2))
test_eq_type(f.decode(t), Int(1)) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
If the transform has `filt` then it's only applied if `filt` param matches. | f.filt = 1
test_eq(f(1, filt=1),2)
test_eq_type(f(1, filt=0), 1)
class A(Transform):
def encodes(self, xy): x,y=xy; return (x+y,y)
def decodes(self, xy): x,y=xy; return (x-y,y)
f = A(as_item=True)
t = f((1,2))
test_eq(t, (3,2))
test_eq(f.decode(t), (1,2))
f.filt = 1
test_eq(f((1,2), filt=1), (3,2))
test_eq(f(... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
TupleTransform | #export
class TupleTransform(Transform):
"`Transform` that always treats `as_item` as `False`"
as_item_force=False
#export
class ItemTransform (Transform):
"`Transform` that always treats `as_item` as `True`"
as_item_force=True
def float_to_int(x:(float,int)): return Int(x)
f = TupleTransform(float_to_... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Non-type-constrained functions are applied to all elements of a tuple. | class A(TupleTransform): pass
@A
def _(self, x): return x+1
@A
def decodes(self, x): return x-1
f = A()
t = f((1,2.0))
test_eq_type(t, (2,3.0))
test_eq_type(f.decode(t), (1,2.0)) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Type-constrained functions are applied to only matching elements of a tuple, and return annotations are only applied where matching. | class B(TupleTransform):
def encodes(self, x:int): return Int(x+1)
def encodes(self, x:str): return x+'1'
def decodes(self, x:Int): return x//2
f = B()
start = (1.,2,'3')
t = f(start)
test_eq_type(t, (1.,Int(3),'31'))
test_eq(f.decode(t), (1.,Int(1),'31')) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
The same behavior also works with `typing` module type classes. | class A(Transform): pass
@A
def _(self, x:numbers.Integral): return x+1
@A
def _(self, x:float): return x*3
@A
def decodes(self, x:int): return x-1
f = A()
start = 1.0
t = f(start)
test_eq(t, 3.)
test_eq(f.decode(t), 3)
f = A(as_item=False)
start = (1.,2,3.)
t = f(start)
test_eq(t, (3.,3,9.))
test_eq(f.decode(t), (3.... | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Transform accepts lists | def a(x): return L(x_+1 for x_ in x)
def b(x): return L(x_-1 for x_ in x)
f = TupleTransform(a,b)
t = f((L(1,2),))
test_eq(t, (L(2,3),))
test_eq(f.decode(t), (L(1,2),)) | _____no_output_____ | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Export - | #hide
from local.notebook.export import notebook2script
notebook2script(all_fs=True) | Converted 00_test.ipynb.
Converted 01_core.ipynb.
Converted 01a_torch_core.ipynb.
Converted 01b_script.ipynb.
Converted 01c_dataloader.ipynb.
Converted 02_data_transforms.ipynb.
Converted 03_data_pipeline.ipynb.
Converted 05_data_core.ipynb.
Converted 06_data_source.ipynb.
Converted 07_vision_core.ipynb.
Converted 08_p... | Apache-2.0 | dev/02_data_transforms.ipynb | davidpfahler/fastai_dev |
Face and Facial Keypoint detectionAfter you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.1. Detect all t... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
| _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | pmobbs/facial-keypoints |
Select an image Select an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory. | import cv2
# load in color image for face detection
image = cv2.imread('images/obamas.jpg')
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot the image
fig = plt.figure(figsize=(9,9))
plt.imshow(i... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | pmobbs/facial-keypoints |
Detect all faces in an imageNext, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.In the code below, we loop over each face in the original image and draw a red square on each face (in a copy... | # load in a haar cascade classifier for detecting frontal faces
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# run the detector
# the output here is an array of detections; the corners of each detection box
# if necessary, modify these parameters until you successf... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | pmobbs/facial-keypoints |
Loading in a trained modelOnce you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.First, load your best model by its filename. | import torch
from models import Net
net = Net()
## TODO: load the best saved model parameters (by your path name)
## You'll need to un-comment the line below and add the correct name for *your* saved model
net.load_state_dict(torch.load('saved_models/keypoints_model_1.pt'))
## print out your net and prepare it for t... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | pmobbs/facial-keypoints |
Keypoint detectionNow, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images. TODO: Transform each detected face into an input TensorYou'll need to perform the following steps for each detected face:1. Convert the face f... | image_copy = np.copy(image)
# loop over the detected faces from your haar cascade
for (x,y,w,h) in faces:
# Select the region of interest that is the face in the image
roi = image_copy[y:y+h, x:x+w]
## TODO: Convert the face region from RGB to grayscale
gray_roi = cv2.cvtColor(roi, cv2.COLOR... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | pmobbs/facial-keypoints |
import cv2
import numpy as np
from urllib.request import urlopen
import matplotlib.pyplot as plt
def show_im(img):
plt.figure(figsize = (10, 6))
plt.axis("off")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
req = urlopen("https://raw.githubusercontent.com/jafetimbre/ms-school-stuff/master/image-processin... | _____no_output_____ | MIT | image-processing/watershed-obj-segmentation/watershed.ipynb | jafetimbre/ms-school-stuff | |
NOTE:In the cell below you **MUST** use a batch size of 10 (`batch_size=10`) for the `train_generator` and the `validation_generator`. Using a batch size greater than 10 will exceed memory limits on the Coursera platform. |
TRAINING_DIR = '/tmp/cats-v-dogs/training'
train_datagen = ImageDataGenerator( rescale = 1/255)
# NOTE: YOU MUST USE A BATCH SIZE OF 10 (batch_size=10) FOR THE
# TRAIN GENERATOR.
train_generator = train_datagen.flow_from_directory(
TRAINING_DIR , batch_size = 10 , class_mode = 'binary' , target_size = (150,150)
)
V... | _____no_output_____ | MIT | Convolutional Neural Networks/Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | ornob39/Tensor-Flow-in-Practice-Specialization |
Submission Instructions | # Now click the 'Submit Assignment' button above. | _____no_output_____ | MIT | Convolutional Neural Networks/Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | ornob39/Tensor-Flow-in-Practice-Specialization |
When you're done or would like to take a break, please run the two cells below to save your work and close the Notebook. This will free up resources for your fellow learners. | %%javascript
<!-- Save the notebook -->
IPython.notebook.save_checkpoint();
%%javascript
IPython.notebook.session.delete();
window.onbeforeunload = null
setTimeout(function() { window.close(); }, 1000); | _____no_output_____ | MIT | Convolutional Neural Networks/Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | ornob39/Tensor-Flow-in-Practice-Specialization |
Group15 members names: Or Nir Elad Mor Eitan Hameiri Hananel Yefet Data source: https://www.kaggle.com/ahmedterry/cristiano-ronald-vs-lionel-messi-weekly-updated **RONALDO vs MESSI** | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('https://raw.githubusercontent.com/verticale3185/FINEL-PROJECT/main/cristiano_vs_messi.csv')
df | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
this data Data explanation: This dataset summarizes goals scored by Messi and Ronaldo of all their careers until 2020. Each row introduce as one goal. There are 1300 rows and 10 columns. Columns:**Player** = Ronaldo / Messi. **Comp** = competition. **Round** = the round of the match in the competition. **Date*... | columns =['comp', 'round', 'date', 'venue', 'opp', 'pos']
for x in columns:
df[x]=df[x].fillna(method='ffill') | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
1. **assisted column:** Every NaN meaning to non assisted goal - solo attack. So we replaced all NaN with "Solo". 2. **date column:** We changed the type to dateime type and made new "year" column. 3. **min column:** We changed the type to integer and cleaned signs like ' and +. 4. **pos column:** Cleaned not n... | df.assisted = df.assisted.fillna('Solo')
df.date = pd.to_datetime(df.date)
df['year'] = pd.DatetimeIndex(df['date']).year
df['year'].fillna(method = 'ffill', inplace = True)
df['year'] = df['year'].astype(int)
df['min'] = df['min'].astype(str)
df['min'] = df['min'].str.replace("'", "")
new_time = df['min'].str.extract... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.