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 |
|---|---|---|---|---|---|
Create a scatter plot presenting the relationship between total_bill and tip--- | _____no_output_____ | MIT | Copy_of_Workshop2Final.ipynb | feliz10/papus | |
Create one plot with the relationship of size and tip. | _____no_output_____ | MIT | Copy_of_Workshop2Final.ipynb | feliz10/papus | |
Importing Packages | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import os
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import Decision... | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Exploratory Data Analysis | plt.figure(figsize=(10,6))
data.groupby('def_pay')['AGE'].hist(legend=True)
plt.show()
#here we can see that, between age 20 to 45 most of the people will fall into..
sns.distplot(data['AGE'])
plt.title('Age Distribution')
sns.boxplot('def_pay','LIMIT_BAL',data=data)
data[data['LIMIT_BAL']>700000].sort_values(ascending... | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Model Creation We know that we have a dataset where we have imbalance in the target variable you get a pretty high accuracy just by predicting the majority class, but you fail to capture the minority class which is most often the point of creating the model in the first place. Hence we try to create more model to get ... | x= data2.drop(['def_pay'],1)
y = data2['def_pay']
x_train,x_test, y_train, y_test = train_test_split(x,y,test_size=0.30, random_state=1)
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
# Accuracy is not the best metric to use when evaluating imbalanced datasets as it can be misle... | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Logistic model | log_model= LogisticRegression()
log_model.fit(x_train,y_train)
y_pred_log = log_model.predict(x_test)
y_pred_train = log_model.predict(x_train)
res(y_pred_log,y_pred_train)
plot_roc_curve(log_model,x_test,y_test)
plt.show()
# log model using Threshold
threshold = 0.36
y_log_prob = log_model.predict_proba(x_test)
y_tra... | precision recall f1-score support
0 0.85 0.93 0.89 4663
1 0.64 0.41 0.50 1337
accuracy 0.82 6000
macro avg 0.74 0.67 0.69 6000
weighted avg 0.80 0.82 0.80 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
using Decision Tree model | dec_model = DecisionTreeClassifier()
dec_model.fit(x_train,y_train)
y_pred_dec = dec_model.predict(x_test)
y_pred_dec_train = dec_model.predict(x_train)
res(y_pred_dec,y_pred_dec_train) | precision recall f1-score support
0 0.82 0.81 0.81 4663
1 0.37 0.40 0.38 1337
accuracy 0.71 6000
macro avg 0.60 0.60 0.60 6000
weighted avg 0.72 0.71 0.72 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Hyper parameter tuning for DecisionTree | parameters = {'max_depth':[1,2,3,4,5,6],'min_samples_split':[3,4,5,6,7],'min_samples_leaf':[1,2,3,4,5,6]}
tree = GridSearchCV(dec_model, parameters,cv=10)
tree.fit(x_train,y_train)
tree.best_params_
# We know that Decision tree will have high variance due to which the model overfit hence we can reduce this by "Pruning"... | precision recall f1-score support
0 0.84 0.95 0.89 4663
1 0.68 0.35 0.46 1337
accuracy 0.82 6000
macro avg 0.76 0.65 0.68 6000
weighted avg 0.80 0.82 0.79 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Random Forest Model | rf_model = RandomForestClassifier(n_estimators=200, criterion='entropy', max_features='log2', max_depth=15, random_state=42)
rf_model.fit(x_train,y_train)
y_pred_rf = rf_model.predict(x_test)
y_pred_rf_train = rf_model.predict(x_train)
#res(y_pred_rf,y_pred_rf_train)
from sklearn.metrics import confusion_matrix
import ... | Recall score:0.359
| MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Again hyper parameter tuning for Random Forest | parameters = {'n_estimators':[60,70,80],'max_depth':[1,2,3,4,5,6],'min_samples_split':[3,4,5,6,7],
'min_samples_leaf':[1,2,3,4,5,6]}
clf = GridSearchCV(rf_model, parameters,cv=10)
clf.fit(x_train,y_train)
clf.best_params_
# {'max_depth': 5,
# 'min_samples_leaf': 4,
# 'min_samples_split': 3,
# 'n_e... | Recall score:0.347
| MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
KNN model | # finding the K value
error = []
for i in range(1,21,2):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(x_train,y_train)
preds = knn.predict(x_test)
error.append(np.mean(preds!=y_test))
plt.plot(range(1,21,2), error, linestyle = 'dashed', marker ='o', mfc= 'red')
# By using the elbow graph we can ... | precision recall f1-score support
0 0.83 0.92 0.87 4663
1 0.55 0.34 0.42 1337
accuracy 0.79 6000
macro avg 0.69 0.63 0.65 6000
weighted avg 0.77 0.79 0.77 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
SVM Model | # use penalized learning algorithms that increase the cost of classification mistakes on the minority class.
svm_model = SVC(class_weight='balanced', probability=True)
svm_model.fit(x_train,y_train)
y_pred_svm = svm_model.predict(x_test)
y_pred_svm_train = svm_model.predict(x_train)
res(y_pred_svm,y_pred_svm_train)
# w... | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Naive Bayes | nb_model = GaussianNB()
nb_model.fit(x_train,y_train)
y_pred_nb = nb_model.predict(x_test)
y_pred_nb_train = nb_model.predict(x_train)
res(y_pred_nb,y_pred_nb_train)
# But here Naive bayes out performs every other model though over accuracy is acceptable, checkout the recall | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Boosting model XGB Classifier | from xgboost import XGBClassifier
xgb_model = XGBClassifier()
xgb_model.fit(x_train, y_train)
xgb_y_predict = xgb_model.predict(x_test)
xgb_y_predict_train = xgb_model.predict(x_train)
res(xgb_y_predict,xgb_y_predict_train)
# Even Boosting technique gives low recall for our target variable
# So from the above model we... | _____no_output_____ | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Random under-sampling Let’s apply some of these resampling techniques, using the Python library imbalanced-learn. | from collections import Counter
from imblearn.under_sampling import RandomUnderSampler
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import TomekLinks
x= data2.drop(['def_pay'],1)
y = data2['def_pay']
rus = RandomUnderSampler(random_state=1)
x_rus, y_rus = rus.fit_resample(x,y)
pri... | precision recall f1-score support
0 0.70 0.84 0.76 1364
1 0.78 0.62 0.69 1291
accuracy 0.73 2655
macro avg 0.74 0.73 0.72 2655
weighted avg 0.74 0.73 0.73 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Random over-sampling | x= data2.drop(['def_pay'],1)
y = data2['def_pay']
ros = RandomOverSampler(random_state=42)
x_ros, y_ros = ros.fit_resample(x, y)
print('Original dataset shape', Counter(y))
print('Resample dataset shape', Counter(y_ros))
x_train,x_test, y_train, y_test = train_test_split(x_ros,y_ros,test_size=0.20, random_state=1)
x_... | precision recall f1-score support
0 0.67 0.82 0.74 4607
1 0.77 0.62 0.69 4739
accuracy 0.71 9346
macro avg 0.72 0.72 0.71 9346
weighted avg 0.72 0.71 0.71 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Under-sampling: Tomek links | x= data2.drop(['def_pay'],1)
y = data2['def_pay']
tl = TomekLinks(sampling_strategy='majority')
x_tl, y_tl = tl.fit_resample(x,y)
print('Original dataset shape', Counter(y))
print('Resample dataset shape', Counter(y_tl))
x_train,x_test, y_train, y_test = train_test_split(x_tl,y_tl,test_size=0.20, random_state=1)
x_tr... | precision recall f1-score support
0 0.83 0.95 0.89 4286
1 0.71 0.38 0.49 1337
accuracy 0.81 5623
macro avg 0.77 0.66 0.69 5623
weighted avg 0.80 0.81 0.79 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Synthetic Minority Oversampling Technique (SMOTE) | from imblearn.over_sampling import SMOTE
smote = SMOTE()
x_smote, y_smote = smote.fit_resample(x, y)
print('Original dataset shape', Counter(y))
print('Resample dataset shape', Counter(y_smote))
x_train,x_test, y_train, y_test = train_test_split(x_smote,y_smote,test_size=0.20, random_state=1)
x_train = sc.fit_transfo... | precision recall f1-score support
0 0.80 0.87 0.84 4607
1 0.87 0.79 0.83 4739
accuracy 0.83 9346
macro avg 0.83 0.83 0.83 9346
weighted avg 0.83 0.83 0.83 ... | MIT | Model/99_kaggle_credit_card_analysis_and_prediction.ipynb | skawns0724/KOSA-Big-Data_Vision |
Sequence to Sequence Learning:label:`sec_seq2seq`As we have seen in :numref:`sec_machine_translation`,in machine translationboth the input and output are a variable-length sequence.To address this type of problem,we have designed a general encoder-decoder architecturein :numref:`sec_encoder-decoder`.In this section,w... | import collections
import math
from mxnet import autograd, gluon, init, np, npx
from mxnet.gluon import nn, rnn
from d2l import mxnet as d2l
npx.set_np() | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
EncoderTechnically speaking,the encoder transforms an input sequence of variable length into a fixed-shape *context variable* $\mathbf{c}$, and encodes the input sequence information in this context variable.As depicted in :numref:`fig_seq2seq`,we can use an RNN to design the encoder.Let us consider a sequence example... | #@save
class Seq2SeqEncoder(d2l.Encoder):
"""The RNN encoder for sequence to sequence learning."""
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
dropout=0, **kwargs):
super(Seq2SeqEncoder, self).__init__(**kwargs)
# Embedding layer
self.embedding = ... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
The returned variables of recurrent layershave been explained in :numref:`sec_rnn-concise`.Let us still use a concrete exampleto [**illustrate the above encoder implementation.**]Belowwe instantiate a two-layer GRU encoderwhose number of hidden units is 16.Givena minibatch of sequence inputs `X`(batch size: 4, number o... | encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
encoder.initialize()
X = np.zeros((4, 7))
output, state = encoder(X)
output.shape | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Since a GRU is employed here,the shape of the multilayer hidden statesat the final time stepis(number of hidden layers, batch size, number of hidden units).If an LSTM is used,memory cell information will also be contained in `state`. | len(state), state[0].shape | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
[**Decoder**]:label:`sec_seq2seq_decoder`As we just mentioned,the context variable $\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \ldots, x_T$. Given the output sequence $y_1, y_2, \ldots, y_{T'}$ from the training dataset,for each time step $t'$(the symbol differs from the time step $t$ ... | class Seq2SeqDecoder(d2l.Decoder):
"""The RNN decoder for sequence to sequence learning."""
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
dropout=0, **kwargs):
super(Seq2SeqDecoder, self).__init__(**kwargs)
self.embedding = nn.Embedding(vocab_size, embed_si... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
To [**illustrate the implemented decoder**],below we instantiate it with the same hyperparameters from the aforementioned encoder.As we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),where the last dimension of the tensor stores the predicted token distribution. | decoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
decoder.initialize()
state = decoder.init_state(encoder(X))
output, state = decoder(X, state)
output.shape, len(state), state[0].shape | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
To summarize,the layers in the above RNN encoder-decoder model are illustrated in :numref:`fig_seq2seq_details`.:label:`fig_seq2seq_details` Loss FunctionAt each time step, the decoderpredicts a probability distribution for the output tokens.Similar ... | X = np.array([[1, 2, 3], [4, 5, 6]])
npx.sequence_mask(X, np.array([1, 2]), True, axis=1) | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
(**We can also mask all the entries across the lastfew axes.**)If you like, you may even specifyto replace such entries with a non-zero value. | X = np.ones((2, 3, 4))
npx.sequence_mask(X, np.array([1, 2]), True, value=-1, axis=1) | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Now we can [**extend the softmax cross-entropy lossto allow the masking of irrelevant predictions.**]Initially,masks for all the predicted tokens are set to one.Once the valid length is given,the mask corresponding to any padding tokenwill be cleared to zero.In the end,the loss for all the tokenswill be multipled by th... | #@save
class MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss):
"""The softmax cross-entropy loss with masks."""
# `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
# `label` shape: (`batch_size`, `num_steps`)
# `valid_len` shape: (`batch_size`,)
def forward(self, pred, label, valid_len):
... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
For [**a sanity check**], we can create three identical sequences.Then we canspecify that the valid lengths of these sequencesare 4, 2, and 0, respectively.As a result,the loss of the first sequenceshould be twice as large as that of the second sequence,while the third sequence should have a zero loss. | loss = MaskedSoftmaxCELoss()
loss(np.ones((3, 4, 10)), np.ones((3, 4)), np.array([4, 2, 0])) | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
[**Training**]:label:`sec_seq2seq_training`In the following training loop,we concatenate the special beginning-of-sequence tokenand the original output sequence excluding the final token asthe input to the decoder, as shown in :numref:`fig_seq2seq`.This is called *teacher forcing* becausethe original output sequence (... | #@save
def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
"""Train a model for sequence to sequence."""
net.initialize(init.Xavier(), force_reinit=True, ctx=device)
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': lr})
loss = MaskedSo... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Now we can [**create and train an RNN encoder-decoder model**]for sequence to sequence learning on the machine translation dataset. | embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1
batch_size, num_steps = 64, 10
lr, num_epochs, device = 0.005, 300, d2l.try_gpu()
train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = Seq2SeqEncoder(
len(src_vocab), embed_size, num_hiddens, num_layers, dropout)
decoder... | loss 0.023, 5661.3 tokens/sec on gpu(0)
| MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
[**Prediction**]To predict the output sequencetoken by token,at each decoder time stepthe predicted token from the previoustime step is fed into the decoder as an input.Similar to training,at the initial time stepthe beginning-of-sequence ("<bos>") tokenis fed into the decoder.This prediction processis illustrat... | #@save
def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
device, save_attention_weights=False):
"""Predict for sequence to sequence."""
src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
src_vocab['<eos>']]
enc_valid_len = np.array([len(src_tokens)]... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Evaluation of Predicted SequencesWe can evaluate a predicted sequenceby comparing it with thelabel sequence (the ground-truth).BLEU (Bilingual Evaluation Understudy),though originally proposed for evaluatingmachine translation results :cite:`Papineni.Roukos.Ward.ea.2002`,has been extensively used in measuringthe quali... | def bleu(pred_seq, label_seq, k): #@save
"""Compute the BLEU."""
pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')
len_pred, len_label = len(pred_tokens), len(label_tokens)
score = math.exp(min(0, 1 - len_label / len_pred))
for n in range(1, k + 1):
num_matches, label_su... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
In the end,we use the trained RNN encoder-decoderto [**translate a few English sentences into French**]and compute the BLEU of the results. | engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
translation, attention_weight_seq = predict_seq2seq(
net, eng, src_vocab, tgt_vocab, num_steps, device)
print(f'{eng} => {translation}, ble... | go . => va !, bleu 1.000
i lost . => j'ai perdu ., bleu 1.000
he's calm . => il est malade ., bleu 0.658
i'm home . => je suis fainéante ?, bleu 0.418
| MIT | python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Seaborn In ActionSeaborn is a data visualization library that is based on **Matplotlib**. It is tightly integrated with Pandas library and provides a high level interface for making attractive and informative statistical graphics in Python.This Notebook introduces the basic and essential functions in the seaborn libra... | import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
?sns.relplot | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Loading the Data and Inspection | cs = pd.read_csv('data/c_scores.csv')
cs
cs.sample(5)
cs.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 21 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 checking_status 979 non-null object
1 duration 1000 non-null int64
2... | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Scatter Plots We shall plot the **age** and **credit_amount** columns using the **jointplot** function. | sns.jointplot(x='age', y='credit_amount', data=cs) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Let's plot the **age** and **credit_amount** again but this time let's break that with **job**. For this, we shall used the **relplot()**. This functions provides access to several axes-level functions that show the relationship between two variables which can also come with semantic mappings. It also come with the **k... | sns.relplot(x="age", y="credit_amount", height= 8, aspect=1, hue="job", data=cs) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
We can also plot the above visualization where we compare what it looks like over two or more categorical elements. For example, in the below visualization, we shall compare the above visualization over **class** using the **col** parameter in the **relplot()** function. | sns.relplot(x="age", y="credit_amount", height= 8, aspect=1, hue="job", col='class',data=cs) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Boxplots A boxplot is used to show the distribution of numerical variables and facilitates comparisons across multiple categorical variables.We would like to visualize the distribution of **age** of the customers with respect to **class**. | sns.boxplot(x='class', y='age', data=cs) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Let's visualize the distribution of **credit_amount** with respect to **purpose** using **class** as the **hue** | fig, ax = plt.subplots(figsize=(18,7))
sns.boxplot(x='purpose', y='credit_amount', hue='class', ax = ax, data=cs) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Histogram A histrogram represents the distribution of data by forming bins along the range of the data and drawing lines to represents the number of observations that fall within each bin.Let's plot the histogram of **credit_amount**. | sns.distplot(cs['credit_amount']) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Let's plot the histogram of the **age** | sns.distplot(cs['age']) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Let's get the histogram of the **credit_amount** of the customers, this time across the **class** dimension as a faceted histogram. | facet = sns.FacetGrid(cs, height=6, col='class')
facet = facet.map(sns.distplot, 'credit_amount', color='r') | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
It will however be a fantastic idea to compare the distribution of **class_amount** across **class** overlaid on the same plot. | facet = sns.FacetGrid(cs, height=6, hue='class')
facet = facet.map(sns.distplot, 'credit_amount') | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Line Plots To make meaningful line plots, we are going to generate a dataframe to be used to help us understand line plots.We will randomly generate some dates from (1970) to (1970+36) over 12 months period. We will then go ahead and select the first 36 rows for the **duration** and **age** columns to form our new dat... | new_series = pd.DataFrame({'time': pd.date_range('1970-12-31', periods=36, freq='12M'),
'duration': cs['duration'].iloc[0:36],
'age': cs['age'].iloc[0:36]})
new_series.head() | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Next, we are going to move the **duration** and the **age** columns to rows so that we can plot both on the graph. We are going to do that using the the pandas **melt()** method.The **melt()** method allows us to unpivot a dataframe from a wide to a long format, optionally leaving the identifiers set. It takes in the ... | series = pd.melt(new_series, id_vars=['time'],
var_name='Variables',
value_name='values')
series.sample(10)
lp = sns.lineplot(x='time', y='values', hue='Variables', data=series)
#Position the legend out the graph
lp.legend(bbox_to_anchor=(1.02, 1),
loc=2,
borderaxe... | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Regression Plot In the regression plotting, we are going to use the **lmplot()**. This function combines the the **regplot()** and FacetGrid. It is intended as a convenient interface to fit regression models across subsets of datasets.We will use the famous iris flower dataset for the regression plot. It is available ... | iris = sns.load_dataset('iris')
iris.sample(8) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Let's plot the **sepal_length** vs the **sepal_withth** only | g = sns.lmplot(x='petal_length', y='petal_width', order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" ) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Using the species, lets break the regression line with respect to the species and fit a first order regression to each species' respective data point. | g = sns.lmplot(x='petal_length', y='petal_width', hue='species',height=8, order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" ) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Now, let's use the **species** as the **col**, column parameter | g = sns.lmplot(x='petal_length', y='petal_width', col='species',height=10, order=1, data=iris)
g.set_axis_labels("Petal Length(mm)", "Petal Width(mm)" ) | _____no_output_____ | Apache-2.0 | Day 4/Seaborn In Action.ipynb | Abuton/10-Academy-5days-Challenge |
Percentiles | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
vals = np.random.normal(0, 0.25, 10000)
plt.hist(vals, 50)
plt.show()
np.percentile(vals, 50)
np.percentile(vals, 99)
np.percentile(vals, 10) | _____no_output_____ | MIT | mlcourse/Percentiles.ipynb | chauhanr/DLTFpT |
Watch Me Code 2: String Formatting | name = "Mike"
age = 45
salary = 15.75
# string formatting
print("Hello there %s. How are you? " % (name))
# formatting redux
print("%s makes %f per hour." % (name, salary))
# let's use spacing
print("%s makes %.2f per hour." % (name, salary))
# right alignment
print("-" * 10) # print 10 dashes
print("%10d" %(age))
#... | ----------
45
| MIT | content/lessons/02/Watch-Me-Code/WMC2-String-Formatting.ipynb | MahopacHS/spring-2020-oubinam0717 |
**[Image Tools](2_Image_Tools.ipynb)** Selective Fourier Transformpart of **pyTEMlib**, a **pycroscopy** library Notebook by Gerd DuscherMaterials Science & EngineeringJoint Institute of Advanced MaterialsThe University of Tennessee, KnoxvilleAn introduction into Fourier Filtering of images. Install pyTEMlibIf you h... | import sys
from pkg_resources import get_distribution, DistributionNotFound
def test_package(package_name):
"""Test if package exists and returns version or -1"""
try:
version = (get_distribution(package_name).version)
except (DistributionNotFound, ImportError) as err:
version = '-1'
re... | _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Loading of necessary librariesPlease note, that we only need to load the pyTEMlib library, which is based on sidpy Datsets. | %pylab notebook
from matplotlib.widgets import RectangleSelector
sys.path.insert(0,'../../')
import pyTEMlib
import pyTEMlib.file_tools as ft
import pyTEMlib.image_tools as it
print('pyTEMlib version: ', pyTEMlib.__version__)
note_book_version = '2021.10.25'
note_book_name='pyTEMib/notebooks/Imaging/Adaptive_Fourier_... | Populating the interactive namespace from numpy and matplotlib
pyTEMlib version: 0.2021.10.2
| MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Open FileThese datasets are stored in the pyNSID data format (extension: hf5) automatically. All results can be stored in that file. First we select the file | file_widget = ft.FileWidget() | _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Now, we open and plot themSelect with the moue an area; rectangle will apear! | try:
dataset.h5_dataset.file.close()
except:
pass
dataset= ft.open_file(file_widget.file_name)
print(file_widget.file_name)
if dataset.data_type.name != 'IMAGE':
print('We really would need an image here')
dataset.plot()
selector = RectangleSelector(dataset.view.axis, None,interactive=True , drawtype='box')... | _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Power Spectrum of Image | power_spectrum = it.power_spectrum(selection, smoothing=1)
power_spectrum.view_metadata()
print('source: ', power_spectrum.source)
power_spectrum.plot()
| fft :
smoothing : 1
minimum_intensity : 0.04261075359154022
maximum_intensity : 1.5140884612372518
source: /Measurement_000/Channel_000/2_HAADF/2_HAADF_new
| MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Spot Detection in Fourier Transform | # ------Input----------
spot_threshold=0.1
# ---------------------
spots = it.diffractogram_spots(power_spectrum, spot_threshold=spot_threshold)
spots = spots[np.linalg.norm(spots[:,:2],axis=1)<8,:]
spots = spots[np.linalg.norm(spots[:,:2],axis=1)>0.5,:]
power_spectrum.plot()
plt.gca().scatter(spots[:,0],spots[:,1], ... | (0, 1, 0) [0.42925305 0.21462653 0.34491887 0.34491887 0.24014125 0.2897209
0.24014125]
(0, 1, 1) [0.29838947 0.29838947 0.22268168 0.2897209 0.22268168]
(0, 1, 2) [0.24443554 0.22521644 0.37365047 0.37365047 0.22521644 0.24924007
0.2897209 0.24924007]
(0, 2, 5) [0.37434128 0.37434128 0.24944479 0.2897209 0.249444... | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Log the result | # results_channel = ft.log_results(dataset.h5_dataset.parent.parent, filtered_dataset)
| _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
A tree-like plot of the file | ft.h5_tree(dataset.h5_dataset.file) | _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Close Filelet's close the file but keep the filename | dataset.h5_dataset.file.close() | _____no_output_____ | MIT | notebooks/Imaging/Selective_Fourier_Transform.ipynb | gduscher/pyTEMlib |
Stage 1: Correlation for individual enhancers | import pandas as pd
import numpy as np
import time, re, datetime
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from scipy.stats import zscore
import random
from multiprocessing import Pool,cpu_count
num_processors = cpu_count()
print('Starting analysis; %d processors; %s' % (num_process... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
Stage 1.5: Compare ATAC and mC | print(all_cc_1.shape, best_cc_1.shape, sig_1.shape, best_cc_1[sig_1].shape, best_ensid_1.shape, best_enh_1.shape)
# best_cc_1[sig_1]
all_cc_2[best_enh_1[sig_1].index.values].shape
fig, ax = plt.subplots()
ax.scatter(all_cc_1, all_cc_2,
color='lightgray', s=1, alpha=0.3,
rasterized=True,)
ax.sc... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
Stage 2: Regression modeling across sig. genes | # Are there any duplicate enhancers?
_x = genes2enhu.iloc[(best_enh_1[sig_1].values),:]
nenh_sig = len(_x)
nenh_sig_unique = len(_x['enh_pos'].unique())
nenh_sig_genes_unique = len(_x['ensid'].unique())
print(nenh_sig, nenh_sig_unique, nenh_sig_genes_unique)
# best_enh_1[sig_1]
# get sig. mC enhancer-gene pairs (1 for... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
Apply the nonlinear model to all enhancer | mc_u = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()
atac_u = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()
genes2enhu_u = genes2enhu.copy()
genes2enhu_u = genes2enhu_u.drop('ensid',axis=1).reset_index()
rna_u = rnau.loc[genes2enhu['ensid'],:].to_numpy()
rna_u.shape, mc_u.shape, atac_u.shape
X = np.concate... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
Average over all the enhancers linked to a single gene | def myz(x):
z = zscore(x, axis=1, nan_policy='omit', ddof=0)
return z
def make_df(z):
z_df = pd.DataFrame(data=z, columns=df_mlevelu.columns, index=rnau.index)
return z_df
multiEnh = {}
multiEnh['rna'] = myz(rnau.values);
multiEnh['rna_hat_1Enh'] = myz(yhat[best_enh2,:])
multiEnh['rna_hat_AllEnh'] = my... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
Nonlinear model fitting | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
X = np.concatenate((mc_u,atac_u),axis=1).copy()
y = np.log10(rna_u+1).copy()
ngenes,ncells = y.shape
X.shape, y.shape
# Define a class fo... | _____no_output_____ | MIT | eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb | FangmingXie/scf_enhancer_paper |
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Right now this requires the current master branch of both. Uncomment the following cell and run it. | #! pip install git+https://github.com/huggingface/transformers.git
#! pip install git+https://github.com/huggingface/datasets.git | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.To be able to share your model with the community, there are a few more steps to follow.First you have to store your authentication token from the Hugging Face website (sign up [here](https://hugg... | from huggingface_hub import notebook_login
notebook_login() | Login successful
Your token has been saved to /home/matt/.huggingface/token
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email: | # !apt install git-lfs
# !git config --global user.email "you@example.com"
# !git config --global user.name "Your Name" | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Make sure your version of Transformers is at least 4.8.1 since the functionality was introduced in that version: | import transformers
print(transformers.__version__) | 4.12.0.dev0
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it. Fine-tuning a model on a multiple choice task In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) mo... | model_checkpoint = "bert-base-uncased"
batch_size = 16 | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Loading the dataset We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data. This can be easily done with the functions `load_dataset`. | from datasets import load_dataset, load_metric | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
`load_dataset` will cache the dataset to avoid downloading it again the next time you run this cell. | datasets = load_dataset("swag", "regular") | Reusing dataset swag (/home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c)
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.htmldatasetdict), which contains one key for the training, validation and test set (with more keys for the mismatched validation and test set in the special case of `mnli`). | datasets | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
To access an actual element, you need to select a split first, then give an index: | datasets["train"][0] | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset. | from datasets import ClassLabel
import random
import pandas as pd
from IPython.display import display, HTML
def show_random_elements(dataset, num_examples=10):
assert num_examples <= len(
dataset
), "Can't pick more elements than there are in the dataset."
picks = []
for _ in range(num_example... | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Each example in the dataset has a context composed of a first sentence (in the field `sent1`) and an introduction to the second sentence (in the field `sent2`). Then four possible endings are given (in the fields `ending0`, `ending1`, `ending2` and `ending3`) and the model must pick the right one (indicated in the fiel... | def show_one(example):
print(f"Context: {example['sent1']}")
print(f" A - {example['sent2']} {example['ending0']}")
print(f" B - {example['sent2']} {example['ending1']}")
print(f" C - {example['sent2']} {example['ending2']}")
print(f" D - {example['sent2']} {example['ending3']}")
print(f"\nG... | Context: Now it's someone's turn to rain blades on his opponent.
A - Someone pats his shoulder and spins wildly.
B - Someone lunges forward through the window.
C - Someone falls to the ground.
D - Someone rolls up his fast run from the water and tosses in the sky.
Ground truth: option C
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Preprocessing the data Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model... | from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
You can directly call this tokenizer on one sentence or a pair of sentences: | tokenizer("Hello, this one sentence!", "And this sentence goes with it.") | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Depending on the model you selected, you will see different keys in the dictionary returned by the cell above. They don't matter much for what we're doing here (just know they are required by the model we will instantiate later), you can learn more about them in [this tutorial](https://huggingface.co/transformers/prepr... | ending_names = ["ending0", "ending1", "ending2", "ending3"]
def preprocess_function(examples):
# Repeat each first sentence four times to go with the four possibilities of second sentences.
first_sentences = [[context] * 4 for context in examples["sent1"]]
# Grab all second sentences possible for each con... | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
This function works with one or several examples. In the case of several examples, the tokenizer will return a list of lists of lists for each key: a list of all examples (here 5), then a list of all choices (4) and a list of input IDs (length varying here since we did not apply any padding): | examples = datasets["train"][:5]
features = preprocess_function(examples)
print(
len(features["input_ids"]),
len(features["input_ids"][0]),
[len(x) for x in features["input_ids"][0]],
) | 5 4 [30, 25, 30, 28]
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
To check we didn't do anything group when grouping all possibilites then unflattening, let's have a look at the decoded inputs for a given example: | idx = 3
[tokenizer.decode(features["input_ids"][idx][i]) for i in range(4)] | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
We can compare it to the ground truth: | show_one(datasets["train"][3]) | Context: A drum line passes by walking down the street playing their instruments.
A - Members of the procession are playing ping pong and celebrating one left each in quick.
B - Members of the procession wait slowly towards the cadets.
C - Members of the procession makes a square call and ends by jumping down int... | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
This seems alright, so we can apply this function on all the examples in our dataset, we just use the `map` method of our `dataset` object we created earlier. This will apply the function on all the elements of all the splits in `dataset`, so our training, validation and testing data will be preprocessed in one single ... | encoded_datasets = datasets.map(preprocess_function, batched=True) | Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c/cache-ce78ab0ead9f175e.arrow
Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38c... | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Even better, the results are automatically cached by the 🤗 Datasets library to avoid spending time on this step the next time you run your notebook. The 🤗 Datasets library is normally smart enough to detect when the function you pass to map has changed (and thus requires to not use the cache data). For instance, it w... | from transformers import TFAutoModelForMultipleChoice
model = TFAutoModelForMultipleChoice.from_pretrained(model_checkpoint) | All model checkpoint layers were used when initializing TFBertForMultipleChoice.
Some layers of TFBertForMultipleChoice were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['classifier']
You should probably TRAIN this model on a down-stream task to be able to use it for predi... | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
The warning is telling us we are throwing away some weights (the `vocab_transform` and `vocab_layer_norm` layers) and randomly initializing some other (the `pre_classifier` and `classifier` layers). This is absolutely normal in this case, because we are removing the head used to pretrain the model on a masked language ... | model_name = model_checkpoint.split("/")[-1]
push_to_hub_model_id = f"{model_name}-finetuned-swag"
learning_rate = 5e-5
batch_size = batch_size
num_train_epochs = 2
weight_decay = 0.01 | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Next we need to tell our `Dataset` how to form batches from the pre-processed inputs. We haven't done any padding yet because we will pad each batch to the maximum length inside the batch (instead of doing so with the maximum length of the whole dataset). This will be the job of the *data collator*. A data collator ta... | from dataclasses import dataclass
from transformers.tokenization_utils_base import (
PreTrainedTokenizerBase,
PaddingStrategy,
)
from typing import Optional, Union
import tensorflow as tf
@dataclass
class DataCollatorForMultipleChoice:
"""
Data collator that will dynamically pad the inputs for multipl... | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
When called on a list of examples, it will flatten all the inputs/attentions masks etc. in big lists that it will pass to the `tokenizer.pad` method. This will return a dictionary with big tensors (of shape `(batch_size * 4) x seq_length`) that we then unflatten.We can check this data collator works on a list of featur... | accepted_keys = ["input_ids", "attention_mask", "label"]
features = [
{k: v for k, v in encoded_datasets["train"][i].items() if k in accepted_keys}
for i in range(10)
]
batch = DataCollatorForMultipleChoice(tokenizer)(features)
encoded_datasets["train"].features["attention_mask"].feature.feature | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Again, all those flatten/un-flatten are sources of potential errors so let's make another sanity check on our inputs: | [tokenizer.decode(batch["input_ids"][8][i].numpy().tolist()) for i in range(4)]
show_one(datasets["train"][8]) | Context: Someone walks over to the radio.
A - Someone hands her another phone.
B - Someone takes the drink, then holds it.
C - Someone looks off then looks at someone.
D - Someone stares blearily down at the floor.
Ground truth: option D
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
All good! Now we can use this collator as a collation function for our dataset. The best way to do this is with the `to_tf_dataset()` method. This converts our dataset to a `tf.data.Dataset` that Keras can take as input. It also applies our collation function to each batch. | data_collator = DataCollatorForMultipleChoice(tokenizer)
train_set = encoded_datasets["train"].to_tf_dataset(
columns=["attention_mask", "input_ids", "labels"],
shuffle=True,
batch_size=batch_size,
collate_fn=data_collator,
)
validation_set = encoded_datasets["validation"].to_tf_dataset(
columns=["a... | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Now we can create our model. First, we specify an optimizer. Using the `create_optimizer` function we can get a nice `AdamW` optimizer with weight decay and a learning rate decay schedule set up for free - but to compute that schedule, it needs to know how long training will take. | from transformers import create_optimizer
total_train_steps = (len(encoded_datasets["train"]) // batch_size) * num_train_epochs
optimizer, schedule = create_optimizer(
init_lr=learning_rate, num_warmup_steps=0, num_train_steps=total_train_steps
) | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
All Transformers models have a `loss` output head, so we can simply leave the loss argument to `compile()` blank to train on it. | import tensorflow as tf
model.compile(optimizer=optimizer) | No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! Please ensure your labels are passed as the 'labels' key of the input dict so that they are accessible to the model during the forward pass. To ... | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
Now we can train our model. We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! Make sure to change the `username` if you do. If you don't want to do this, simply remove the callbacks ar... | from transformers.keras_callbacks import PushToHubCallback
username = "Rocketknight1"
callback = PushToHubCallback(
output_dir="./mc_model_save",
tokenizer=tokenizer,
hub_model_id=f"{username}/{push_to_hub_model_id}",
)
model.fit(
train_set,
validation_data=validation_set,
epochs=num_train_ep... | huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
- Avoid using `tokenizers` before the fork if possible
- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | fal... | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
One downside of using the internal loss, however, is that we can't use Keras metrics with it. So let's compute accuracy after the fact, to see how our model is performing. First, we need to get our model's predicted answers on the validation set. | predictions = model.predict(validation_set)["logits"]
labels = encoded_datasets["validation"]["label"] | _____no_output_____ | Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
And now we can compute our accuracy with Numpy. | import numpy as np
preds = np.argmax(predictions, axis=1)
print({"accuracy": (preds == labels).astype(np.float32).mean().item()}) | {'accuracy': 0.7951614260673523}
| Apache-2.0 | examples/multiple_choice-tf.ipynb | HAMZA310/notebooks |
How to recover a known planet in Kepler data This tutorial demonstrates the basic steps required to recover a transiting planet candidate in the Kepler data.We will show how you can recover the signal of [Kepler-10b](https://en.wikipedia.org/wiki/Kepler-10b), the first rocky planet that was discovered by Kepler! Keple... | from lightkurve import KeplerTargetPixelFile
tpf = KeplerTargetPixelFile.from_archive("Kepler-10", quarter=3) | Downloading URL https://mast.stsci.edu/api/v0/download/file?uri=mast:Kepler/url/missions/kepler/target_pixel_files/0119/011904151/kplr011904151-2009350155506_lpd-targ.fits.gz to ./mastDownload/Kepler/kplr011904151_lc_Q111111110111011101/kplr011904151-2009350155506_lpd-targ.fits.gz ... [Done]
| MIT | docs/source/tutorials/2.02-recover-a-planet.ipynb | ceb8/lightkurve |
Let's use the `plot` method and pass along an aperture mask and a few plotting arguments. | tpf.plot(scale='log'); | _____no_output_____ | MIT | docs/source/tutorials/2.02-recover-a-planet.ipynb | ceb8/lightkurve |
The target pixel file contains one bright star with approximately 50,000 counts. Now, we will use the ``to_lightcurve`` method to create a simple aperture photometry lightcurve using themask defined by the pipeline which is stored in `tpf.pipeline_mask`. | lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask) | _____no_output_____ | MIT | docs/source/tutorials/2.02-recover-a-planet.ipynb | ceb8/lightkurve |
Let's take a look at the output lightcurve. | lc.plot(); | _____no_output_____ | MIT | docs/source/tutorials/2.02-recover-a-planet.ipynb | ceb8/lightkurve |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.