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 |
|---|---|---|---|---|---|
Use scikit-learn StandardScaler to normalize the data. Needed for k-means. | from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(X)
plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.3)
from sklearn.cluster import KMeans
clf = KMeans(n_clusters=4, random_state=1).fit(X)
y_pred = clf.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=y_pred, alpha=0.3)
clf.iner... | _____no_output_____ | Apache-2.0 | notebooks/Intro_to_machine_learning_kmeans.ipynb | michael-scarn/geocomp-0118 |
___ ___ NumPy Exercises Now that we've learned about NumPy let's test your knowledge. We'll start off with a few simple tasks, and then you'll be asked some more complicated questions. Import NumPy as np | import numpy as np | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of 10 zeros | np.zeros(10) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of 10 ones | np.ones(10) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of 10 fives | np.full(10, 5, dtype=float) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of the integers from 10 to 50 | np.arange(10, 51) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of all the even integers from 10 to 50 | np.arange(10,51,2) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create a 3x3 matrix with values ranging from 0 to 8 | np.arange(9).reshape(3,3) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create a 3x3 identity matrix | np.eye(3) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Use NumPy to generate a random number between 0 and 1 | np.random.rand(1) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution | np.random.randn(25) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create the following matrix: | np.linspace(0.01,1,100).reshape(10,10) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Create an array of 20 linearly spaced points between 0 and 1: | np.linspace(0,1,20) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Numpy Indexing and SelectionNow you will be given a few matrices, and be asked to replicate the resulting matrix outputs: | mat = np.arange(1,26).reshape(5,5)
mat
mat[2:,1:]
mat[-2,-1]
mat[:3,1:2]
mat[-1]
mat[-2:] | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Now do the following Get the sum of all the values in mat | mat.sum() | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Get the standard deviation of the values in mat | mat.std() | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Get the sum of all the columns in mat | mat.sum(axis=0) | _____no_output_____ | MIT | udemy/python-for-data-science-and-machine-learning-bootcamp/my_progress/Python-for-Data-Analysis/NumPy/Numpy Exercise .ipynb | djrgit/coursework |
Beating the betting firms with linear models* **Data Source:** [https://www.kaggle.com/hugomathien/soccer](https://www.kaggle.com/hugomathien/soccer)* **Author:** Anders Munk-Nielsen**Result:** It is possible to do better than the professional betting firms in terms of predicting each outcome (although they may be max... | import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme()
# Read
d = pd.read_csv('football_probs.csv')
# Data types
d.date = pd.to_datetime(d.date)
cols_to_cat = ['league', 'season', 'team', 'country']
for c in cols_to_cat:
... | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Visualizing the home field advantage. | sns.histplot(data=d, x='goal_diff', hue='home', discrete=True);
plt.xlim([-7,7]); | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Outcome variables | # Lose, Draw, Win
d['outcome'] = 'L'
d.loc[d.goal_diff == 0.0, 'outcome'] = 'D'
d.loc[d.goal_diff > 0.0, 'outcome'] = 'W'
# Win dummy (as float (will become useful later))
d['win'] = (d.goal_diff > 0.0).astype(float) | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Odds to probabilities Convenient lists of variable names* `cols_common`: All variables that are unrelated to betting * `betting_firms`: The prefix that defines the name of the betting firms, e.g. B365 for Bet365* `firm_vars`: A dictionary returning the variables for a firm, e.g. `firm_vars['BW']` returns `BWA`, `BWD`... | # # List of the names of all firms that we have betting prices for
betting_firms = np.unique([c[:-4] for c in d.columns if c[-1] in ['A', 'H', 'D']])
betting_firms
# find all columns in our dataframe that are *not* betting variables
cols_common = [c for c in d.columns if (c[-4:-1] != '_Pr') & (c[-9:] != 'overround')]... | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Is there more information in the mean? If all firms are drawing random IID signals, then the average prediction should be a better estimator than any individual predictor. | firms_drop = ['BS', 'GB', 'PS', 'SJ'] # these are missing in too many years
cols_prW = [f'{c}_PrW' for c in betting_firms if c not in firms_drop]
d['avg_PrW'] = d[cols_prW].mean(1)
cols_prW += ['avg_PrW']
I = d.win == True
fig, ax = plt.subplots();
ax.hist(d.loc[I,'avg_PrW'], bins=30, alpha=0.3, label='Avg. predictio... | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
RMSE comparison* RMSE: Root Mean Squared Error. Whenever we have a candidate prediction guess, $\hat{y}_i$, we can evaluate $$ RMSE = \sqrt{ N^{-1}\sum_{i=1}^N (y_i - \hat{y}_i)^2 }. $$ | def RMSE(yhat, y) -> float:
'''Root mean squared error: between yvar and y'''
q = (yhat - y)**2
return np.sqrt(np.mean(q))
def RMSE_agg(data: pd.core.frame.DataFrame, y: str) -> pd.core.series.Series:
'''RMSE_agg: Aggregates all columns, computing RMSE against the variable y for each column
'''
... | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Linear Probability ModelsEstimate a bunch of models where $y_i = 1(\text{win})$. Using `numpy` | d['home_'] = d.home.astype(float)
I = d[['home_', 'win'] + cols_prW].notnull().all(axis=1)
X = d.loc[I, ['home_'] + cols_prW].values
y = d.loc[I, 'win'].values.reshape(-1,1)
N = I.sum()
oo = np.ones((N,1))
X = np.hstack([oo, X])
betahat = np.linalg.inv(X.T @ X) @ X.T @ y
pd.DataFrame({'beta':betahat.flatten()}, index=... | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Using `statsmodels` (Cheating, but faster...) | reg_addition = ' + '.join(cols_prW)
model_string = f'win ~ {reg_addition} + home + team'
cols_all = cols_prW + ['win', 'home']
I = d[cols_all].notnull().all(1) # no missings in any variables used in the prediction model
Itrain = I & (d.date < '2015-01-01') # for estimating our prediction model
Iholdout = I & (d.d... | Estimates with Team FE
| MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Plot estimates, $\hat{\beta}$ | ax = r.params.loc[cols_prW].plot.bar();
ax.set_ylabel('Coefficient (loading in optimal prediction)');
ax.set_xlabel('Betting firm prediction'); | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Plot model fit out of sample: avg. 1(win) vs. avg. $\hat{y}$ | # predicted win rates from all firms and our new predicted probability
cols = cols_prW + ['AMN_PrW'] | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
**Home matches:** `home == True` | x_ = d.loc[(d.win == 1.0) & (d.home == True) & (Iholdout == True), cols].mean()
ax = x_.plot(kind='bar');
ax.set_ylim([x_.min()*0.995, x_.max()*1.005]);
ax.set_title('Out of sample fit: won matches as Home');
ax.set_xlabel('Betting firm prediction');
ax.set_ylabel('Pr(win) (only won home matches)'); | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
**Away matches:** `home == False` | x_ = d.loc[(d.win == 1.0) & (d.home == False) & (Iholdout == True), cols].mean()
ax = x_.plot(kind='bar');
ax.set_ylim([x_.min()*0.995, x_.max()*1.005]);
ax.set_ylabel('Pr(win) (only won away matches)');
ax.set_title('Out of sample fit: won matches as Away'); | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
RMSE (evaluated in the holdout sample, of course.) | cols_ = cols_prW + ['AMN_PrW', 'win']
I = Iholdout & d[cols_].notnull().all(1) # only run comparison on subsample where all odds were observed
x_ = RMSE_agg(d.loc[I,cols_], y='win');
ax = x_.plot.bar();
ax.set_ylim([x_.min()*.999, x_.max()*1.001]);
ax.set_ylabel('RMSE (out of sample)'); | _____no_output_____ | MIT | Football/linear.ipynb | AndersMunkN/PublicData |
Assignment 2: Naive BayesWelcome to week two of this specialization. You will learn about Naive Bayes. Concretely, you will be using Naive Bayes for sentiment analysis on tweets. Given a tweet, you will decide if it has a positive sentiment or a negative one. Specifically you will: * Train a naive bayes model on a sen... | from utils import process_tweet, lookup
import pdb
from nltk.corpus import stopwords, twitter_samples
import numpy as np
import pandas as pd
import nltk
import string
from nltk.tokenize import TweetTokenizer
from os import getcwd | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
If you are running this notebook in your local computer,don't forget to download the twitter samples and stopwords from nltk.```nltk.download('stopwords')nltk.download('twitter_samples')``` | # add folder, tmp2, from our local workspace containing pre-downloaded corpora files to nltk's data path
filePath = f"{getcwd()}/../tmp2/"
nltk.data.path.append(filePath)
# get the sets of positive and negative tweets
all_positive_tweets = twitter_samples.strings('positive_tweets.json')
all_negative_tweets = twitter_sa... | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Part 1: Process the DataFor any machine learning project, once you've gathered the data, the first step is to process it to make useful inputs to your model.- **Remove noise**: You will first want to remove noise from your data -- that is, remove words that don't tell you much about the content. These include all comm... | custom_tweet = "RT @Twitter @chapagain Hello There! Have a great day. :) #good #morning http://chapagain.com.np"
# print cleaned tweet
print(process_tweet(custom_tweet)) | ['hello', 'great', 'day', ':)', 'good', 'morn']
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Part 1.1 Implementing your helper functionsTo help train your naive bayes model, you will need to build a dictionary where the keys are a (word, label) tuple and the values are the corresponding frequency. Note that the labels we'll use here are 1 for positive and 0 for negative.You will also implement a `lookup()` h... | # UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def count_tweets(result, tweets, ys):
'''
Input:
result: a dictionary that will be used to map each pair to its frequency
tweets: a list of tweets
ys: a list corresponding to the sentiment of each tweet (either 0 or 1)
Output:
re... | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
**Expected Output**: {('happi', 1): 1, ('trick', 0): 1, ('sad', 0): 1, ('tire', 0): 2} Part 2: Train your model using Naive BayesNaive bayes is an algorithm that could be used for sentiment analysis. It takes a short time to train and also has a short prediction time. So how do you train a Naive Bayes classifier?- The... | # Build the freqs dictionary for later uses
freqs = count_tweets({}, train_x, train_y) | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
InstructionsGiven a freqs dictionary, `train_x` (a list of tweets) and a `train_y` (a list of labels for each tweet), implement a naive bayes classifier. Calculate $V$- You can then compute the number of unique words that appear in the `freqs` dictionary to get your $V$ (you can use the `set` function). Calculate $fre... | # UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def train_naive_bayes(freqs, train_x, train_y):
'''
Input:
freqs: dictionary from (word, label) to how often the word appears
train_x: a list of tweets
train_y: a list of labels correponding to the tweets (0,1)
Output:
logprior: ... | 0.0
9089
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
**Expected Output**:0.09089 Part 3: Test your naive bayesNow that we have the `logprior` and `loglikelihood`, we can test the naive bayes function by making predicting on some tweets! Implement `naive_bayes_predict`**Instructions**:Implement the `naive_bayes_predict` function to make predictions on tweets.* The functi... | # UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def naive_bayes_predict(tweet, logprior, loglikelihood):
'''
Input:
tweet: a string
logprior: a number
loglikelihood: a dictionary of words mapping to numbers
Output:
p: the sum of all the logliklihoods of each word in the tweet ... | The expected output is 1.5740278623499175
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
**Expected Output**:- The expected output is around 1.57- The sentiment is positive. Implement test_naive_bayes**Instructions**:* Implement `test_naive_bayes` to check the accuracy of your predictions.* The function takes in your `test_x`, `test_y`, log_prior, and loglikelihood* It returns the accuracy of your model.*... | # UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def test_naive_bayes(test_x, test_y, logprior, loglikelihood):
"""
Input:
test_x: A list of tweets
test_y: the corresponding labels for the list of tweets
logprior: the logprior
loglikelihood: a dictionary with the loglikelihoods for... | Naive Bayes accuracy = 0.9940
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
**Expected Accuracy**:0.9940 | # UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# You do not have to input any code in this cell, but it is relevant to grading, so please do not change anything
# Run this cell to test your function
for tweet in ['I am happy', 'I am bad', 'this movie should have been great.', 'great', 'great great', 'great great great... | I am happy -> 2.15
I am bad -> -1.29
this movie should have been great. -> 2.14
great -> 2.14
great great -> 4.28
great great great -> 6.41
great great great great -> 8.55
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
**Expected Output**:- I am happy -> 2.15- I am bad -> -1.29- this movie should have been great. -> 2.14- great -> 2.14- great great -> 4.28- great great great -> 6.41- great great great great -> 8.55 | # Feel free to check the sentiment of your own tweet below
my_tweet = 'you are bad :('
naive_bayes_predict(my_tweet, logprior, loglikelihood) | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Part 4: Filter words by Ratio of positive to negative counts- Some words have more positive counts than others, and can be considered "more positive". Likewise, some words can be considered more negative than others.- One way for us to define the level of positiveness or negativeness, without calculating the log like... | # UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_ratio(freqs, word):
'''
Input:
freqs: dictionary containing the words
word: string to lookup
Output: a dictionary with keys 'positive', 'negative', and 'ratio'.
Example: {'positive': 10, 'negative': 20, 'ratio': 0.5}
'''
... | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Implement `get_words_by_threshold(freqs,label,threshold)`* If we set the label to 1, then we'll look for all words whose threshold of positive/negative is at least as high as that threshold, or higher.* If we set the label to 0, then we'll look for all words whose threshold of positive/negative is at most as low as th... | # UNQ_C9 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_words_by_threshold(freqs, label, threshold):
'''
Input:
freqs: dictionary of words
label: 1 for positive, 0 for negative
threshold: ratio that will be used as the cutoff for including a word in the returned dictionary
Output:
... | _____no_output_____ | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Notice the difference between the positive and negative ratios. Emojis like :( and words like 'me' tend to have a negative connotation. Other words like 'glad', 'community', and 'arrives' tend to be found in the positive tweets. Part 5: Error AnalysisIn this part you will see some tweets that your model missclassified... | # Some error analysis done for you
print('Truth Predicted Tweet')
for x, y in zip(test_x, test_y):
y_hat = naive_bayes_predict(x, logprior, loglikelihood)
if y != (np.sign(y_hat) > 0):
print('%d\t%0.2f\t%s' % (y, np.sign(y_hat) > 0, ' '.join(
process_tweet(x)).encode('ascii', 'ignore'))) | Truth Predicted Tweet
1 0.00 b''
1 0.00 b'truli later move know queen bee upward bound movingonup'
1 0.00 b'new report talk burn calori cold work harder warm feel better weather :p'
1 0.00 b'harri niall 94 harri born ik stupid wanna chang :D'
1 0.00 b''
1 0.00 b''
1 0.00 b'park get sunlight'
1 0.00 b'uff itna miss karh... | Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
Part 6: Predict with your own tweetIn this part you can predict the sentiment of your own tweet. | # Test with your own tweet - feel free to modify `my_tweet`
my_tweet = 'I am happy because I am learning :)'
p = naive_bayes_predict(my_tweet, logprior, loglikelihood)
print(p) | 9.574768961173339
| Apache-2.0 | 1. Natural Language Processing with Classification and Vector Spaces/Week2/C1_W2_Assignment.ipynb | nirav8403/coursera-natural-language-processing-specialization-II |
DEALING WITH UNKNOWN TOKENS1. See what words have characters outside the vocab2. replace these chars with (??)3. create a mapping (like Taej ?? n to Taejŏn)4. Map them back together in the sentence (if it has Taej ?? n, replace with Taejŏn) | import time
inputs = [
'translate Graph to English: <H> Elisavet <R> profession <T> researcher',
]
inputs_encoding = model_ckp.tokenizer.prepare_seq2seq_batch(
inputs, max_length=args.max_source_length, return_tensors='pt'
)
print(inputs_encoding['input_ids'])
now = time.time()
model_ckp.model.eval()
with ... | _____no_output_____ | CC0-1.0 | Verbalisation/T5-Verbalisation-For-Crowdsourcing.ipynb | gabrielmaia7/WDV |
STRATEGY TO REPLACE UNKS:- TREAT CASE WHERE THE WHOLE LABEL IS MADE OF UNKNOWNS- IF IT ISNT, THERE MUST BE SPACE BEFORE AND AFTER THAT IS KNOWN - GROUP UNKNOWNS INTO CONTINUOUS UNK TOKENS (?? ?? -> ??) - LOOK TO SEE IF IT IS IN THE BEGINNING OF THE SENTENCE - TREAT CASE - LOOK TO SEE IF IT IS IN T... | import re
vocab = model_ckp.tokenizer.get_vocab()
convert_some_japanese_characters = True
N = 2
class UnknownCharReplacer():
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.vocab = tokenizer.get_vocab()
self.unknowns = []
def read_label(self, label):
self.... | _____no_output_____ | CC0-1.0 | Verbalisation/T5-Verbalisation-For-Crowdsourcing.ipynb | gabrielmaia7/WDV |
Pilot Sample | import time
verbalisations = []
start_idx = 0
for idx, batch in enumerate(sample_dataloader):
if idx < start_idx:
print(f'Skipping idx {idx}')
continue
print(idx,end=': ')
inputs_encoding = model_ckp.tokenizer.prepare_seq2seq_batch(
batch, max_length=args.max_source_length, ret... | _____no_output_____ | CC0-1.0 | Verbalisation/T5-Verbalisation-For-Crowdsourcing.ipynb | gabrielmaia7/WDV |
Full Data | import time
start_idx = 0
for idx, batch in enumerate(dataloader):
if idx < start_idx:
print(f'Skipping idx {idx}')
continue
print(idx,end=': ')
inputs_encoding = model_ckp.tokenizer.prepare_seq2seq_batch(
batch, max_length=args.max_source_length, return_tensors='pt'
)
... | tensor([[13959, 3, 21094, 12, 1566, 10, 32100, 1181, 8020, 235,
32101, 2663, 13, 32102, 4338, 4316, 1]])
['Antipasto is an Italian dish.']
10.492921352386475
| CC0-1.0 | Verbalisation/T5-Verbalisation-For-Crowdsourcing.ipynb | gabrielmaia7/WDV |
BINARY REPRESENTATION | binary_vectorizer = CountVectorizer(binary=True)
binary_matrix = binary_vectorizer.fit_transform(corpus)
binary_queries_matrix = binary_vectorizer.transform(queries) | _____no_output_____ | MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
cosine similarity | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(cosine_similarity(binary_queries_matrix[r], binary_matrix)[0])
retrieved = sim.argsort()[-min_q:][::-1]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
els... | min max avg mean
Precision: 0.000 0.750 0.172 0.125
Recalls : 0.000 1.000 0.206 0.167
F-Measure: 0.000 0.800 0.174 0.154
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
euclidean distance | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(euclidean_distances(binary_queries_matrix[r], binary_matrix)[0])
retrieved = sim.argsort()[:min_q]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
else:
... | min max avg mean
Precision: 0.000 0.250 0.011 0.000
Recalls : 0.000 0.333 0.013 0.000
F-Measure: 0.000 0.286 0.011 0.000
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
TERM FRENQUENCY | count_vectorizer = CountVectorizer()
count_matrix = count_vectorizer.fit_transform(corpus)
count_queries_matrix = count_vectorizer.transform(queries) | _____no_output_____ | MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
cosine similarity | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(cosine_similarity(count_queries_matrix[r], count_matrix)[0])
retrieved = sim.argsort()[-min_q:][::-1]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
else:... | min max avg mean
Precision: 0.000 0.875 0.145 0.125
Recalls : 0.000 1.000 0.162 0.111
F-Measure: 0.000 0.778 0.143 0.118
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
euclidean distance | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(euclidean_distances(count_queries_matrix[r], count_matrix)[0])
retrieved = sim.argsort()[:min_q]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
else:
... | min max avg mean
Precision: 0.000 0.250 0.012 0.000
Recalls : 0.000 0.333 0.013 0.000
F-Measure: 0.000 0.182 0.011 0.000
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
TF-IDF | tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)
tfidf_queries_matrix = tfidf_vectorizer.transform(queries) | _____no_output_____ | MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
cosine similarity | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(cosine_similarity(tfidf_queries_matrix[r], tfidf_matrix)[0])
retrieved = sim.argsort()[-min_q:][::-1]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
else:... | min max avg mean
Precision: 0.000 0.875 0.273 0.250
Recalls : 0.000 1.000 0.322 0.286
F-Measure: 0.000 0.824 0.274 0.267
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
euclidean distance | precisions = []
recalls = []
f_measures = []
for r in range(len(reference)-1):
sim = np.array(euclidean_distances(tfidf_queries_matrix[r], tfidf_matrix)[0])
retrieved = sim.argsort()[:min_q]+1
tp = 0
fp = 0
for doc in retrieved:
if doc in reference[r]:
tp += 1
else:
... | min max avg mean
Precision: 0.000 0.750 0.229 0.250
Recalls : 0.000 1.000 0.271 0.200
F-Measure: 0.000 0.769 0.230 0.200
| MIT | hw2.ipynb | EnyMan/MI-DDW-hw2 |
Using a pre-trained convnetThis notebook contains the code sample found in Chapter 5, Section 3 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in particular further explanations and figures: in t... | from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False,
input_shape=(150, 150, 3)) | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
We passed three arguments to the constructor:* `weights`, to specify which weight checkpoint to initialize the model from* `include_top`, which refers to including or not the densely-connected classifier on top of the network. By default, this densely-connected classifier would correspond to the 1000 classes from Image... | conv_base.summary() | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 150, 150, 3) 0
________________________________________________________... | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
The final feature map has shape `(4, 4, 512)`. That's the feature on top of which we will stick a densely-connected classifier.At this point, there are two ways we could proceed: * Running the convolutional base over our dataset, recording its output to a Numpy array on disk, then using this data as input to a standalo... | import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
base_dir = '/Users/fchollet/Downloads/cats_and_dogs_small'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
test_dir = os.path.join(base_dir, 'test')
datagen = ImageDataGenerator(res... | Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
| MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
The extracted features are currently of shape `(samples, 4, 4, 512)`. We will feed them to a densely-connected classifier, so first we must flatten them to `(samples, 8192)`: | train_features = np.reshape(train_features, (2000, 4 * 4 * 512))
validation_features = np.reshape(validation_features, (1000, 4 * 4 * 512))
test_features = np.reshape(test_features, (1000, 4 * 4 * 512)) | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
At this point, we can define our densely-connected classifier (note the use of dropout for regularization), and train it on the data and labels that we just recorded: | from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(layers.Dense(256, activation='relu', input_dim=4 * 4 * 512))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer=optimizers.RMSprop(lr=2e-5),
... | Train on 2000 samples, validate on 1000 samples
Epoch 1/30
2000/2000 [==============================] - 1s - loss: 0.6253 - acc: 0.6455 - val_loss: 0.4526 - val_acc: 0.8300
Epoch 2/30
2000/2000 [==============================] - 0s - loss: 0.4490 - acc: 0.7965 - val_loss: 0.3784 - val_acc: 0.8450
Epoch 3/30
2000/2000 [... | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
Training is very fast, since we only have to deal with two `Dense` layers -- an epoch takes less than one second even on CPU.Let's take a look at the loss and accuracy curves during training: | import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
We reach a validation accuracy of about 90%, much better than what we could achieve in the previous section with our small model trained from scratch. However, our plots also indicate that we are overfitting almost from the start -- despite using dropout with a fairly large rate. This is because this technique does not... | from keras import models
from keras import layers
model = models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid')) | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
This is what our model looks like now: | model.summary() | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
vgg16 (Model) (None, 4, 4, 512) 14714688
________________________________________________________... | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
As you can see, the convolutional base of VGG16 has 14,714,688 parameters, which is very large. The classifier we are adding on top has 2 million parameters.Before we compile and train our model, a very important thing to do is to freeze the convolutional base. "Freezing" a layer or set of layers means preventing their... | print('This is the number of trainable weights '
'before freezing the conv base:', len(model.trainable_weights))
conv_base.trainable = False
print('This is the number of trainable weights '
'after freezing the conv base:', len(model.trainable_weights)) | This is the number of trainable weights after freezing the conv base: 4
| MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
With this setup, only the weights from the two `Dense` layers that we added will be trained. That's a total of four weight tensors: two per layer (the main weight matrix and the bias vector). Note that in order for these changes to take effect, we must first compile the model. If you ever modify weight trainability aft... | from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
# Note that the val... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
Let's plot our results again: | acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.le... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
As you can see, we reach a validation accuracy of about 96%. This is much better than our small convnet trained from scratch. Fine-tuningAnother widely used technique for model reuse, complementary to feature extraction, is _fine-tuning_. Fine-tuning consists in unfreezing a few of the top layers of a frozen model bas... | conv_base.summary() | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 150, 150, 3) 0
________________________________________________________... | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
We will fine-tune the last 3 convolutional layers, which means that all layers up until `block4_pool` should be frozen, and the layers `block5_conv1`, `block5_conv2` and `block5_conv3` should be trainable.Why not fine-tune more layers? Why not fine-tune the entire convolutional base? We could. However, we need to consi... | conv_base.trainable = True
set_trainable = False
for layer in conv_base.layers:
if layer.name == 'block5_conv1':
set_trainable = True
if set_trainable:
layer.trainable = True
else:
layer.trainable = False | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
Now we can start fine-tuning our network. We will do this with the RMSprop optimizer, using a very low learning rate. The reason for using a low learning rate is that we want to limit the magnitude of the modifications we make to the representations of the 3 layers that we are fine-tuning. Updates that are too large ma... | model.compile(loss='binary_crossentropy',
optimizer=optimizers.RMSprop(lr=1e-5),
metrics=['acc'])
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=100,
validation_data=validation_generator,
validation_steps=50)
model.save('cats_and_do... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
Let's plot our results using the same plotting code as before: | acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.le... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
These curves look very noisy. To make them more readable, we can smooth them by replacing every loss and accuracy with exponential moving averages of these quantities. Here's a trivial utility function to do this: | def smooth_curve(points, factor=0.8):
smoothed_points = []
for point in points:
if smoothed_points:
previous = smoothed_points[-1]
smoothed_points.append(previous * factor + point * (1 - factor))
else:
smoothed_points.append(point)
return smoothed_points
plt.plot(epochs,
smooth... | _____no_output_____ | MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
These curves look much cleaner and more stable. We are seeing a nice 1% absolute improvement.Note that the loss curve does not show any real improvement (in fact, it is deteriorating). You may wonder, how could accuracy improve if the loss isn't decreasing? The answer is simple: what we display is an average of pointwi... | test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
test_loss, test_acc = model.evaluate_generator(test_generator, steps=50)
print('test acc:', test_acc) | Found 1000 images belonging to 2 classes.
test acc: 0.967999992371
| MIT | first_edition/5.3-using-a-pretrained-convnet.ipynb | tocheng/deep-learning-with-python-notebooks |
Filled Julia set___Let $C\in \mathbb{C}$ is fixed. A *Filled Julia set* $K_C$ is the set of $z\in \mathbb{C}$ which satisfy $\ f^n_C(z)$ $(n \ge 1)$is bounded :$$K_C = \bigl\{ z\in \mathbb{C}\bigm|\{f^n_C(z)\}_{n\ge 1} : bounded\bigr\},$$where $\ \ f^1_C(z) = f_C(z) = z^2 + C $, $\ \ f^n_C = f^{n-1}_C \circ f_C$. F... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def filledjulia(x_min, x_max, y_min, y_max, C, N, x_pix, y_pix, R):
'''
calculate where of z is in the Filled Julia set
'''
x = np.linspace(x_min, x_max, x_pix).astype(np.float32)
y = np.linspace(y_max, y_min, y_pix).reshape(y... | _____no_output_____ | MIT | julia.ipynb | mo-mo-666/dynamics |
The complement of a Filled Julia set is called a *Fatou set*. Julia set___A *Julia set* $J_C$ is the **boundary** of a Filled Julia set:$$J_C = \partial K_C.$$ For more details, see [Wikipedia--Julia set](https://en.wikipedia.org/wiki/Julia_set).___ | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def find_1_boundary(pix, boolean):
'''
for each row,
if five or more "True" are arranged continuously,
rewrite it to "False" except two at each end.
'''
boolean = np.copy(boolean)
for i in range(pix):
if not... | _____no_output_____ | MIT | julia.ipynb | mo-mo-666/dynamics |
)```If the dataset doesn't present any duplicated values, this piece of code should return, as output, 150.000 data entries. Neverthele... | # Checking the number of unique values.
len(df.index.unique())
# Checking the number of duplicated entries.
len(df) - len(df.index.unique()) | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Exploratory AnalysisSection aimed on checking the data distribution and data behaviour.- N.A. values?- Outliers?- Min.- Max.- Mean.- Stdev.------------------------- | df.describe() | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Describe Analysis ResultThis section summarizes the initial analysis on this dataset.The command below allows to summarize each variable and retrieve the main statistical characteristics. ```pythondf.describe()```The first thing to be noticed is at 'Sacado' variable - the amount of money withdrawn. | Statistical Measu... | df.describe().loc['std'].sort_values(ascending=False).head()
df[df.Sacado >= 0] | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Some plotsOn this section are plots for visualizing the dispersion of some 'random' variables.---------------- | df[['PP1', 'PP2', 'PP6', 'PP21']].hist()
# As it can be observed. The Sacado variable has a lot of outliers - removing and analysing it alone
# (for not disturbing the scale)
df[['PP1', 'PP2', 'PP21', 'PP6', 'Sacado']].boxplot()
# There are outliers on it - predicted it on histogram.
df[['PP1', 'PP2', 'PP6', 'PP21']].... | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Seeking for N.A. valuesThis dataset does not present N.A./Blank values.---------------------------- | sum(df.index.isna())
dict_na = {
'columns': list(df.columns),
'na': []
}
for i in range(len(df.columns)):
dict_na.get('na').append(sum(df[df.columns[i]].isna()))
pandas.DataFrame(dict_na).set_index('columns') | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Does this dataset is non-balanced?This section aims on checking if the dataset is non-balanced - are more frauds than non-frauds? Vice-Versa?Table below assumes that the y variable - Fraude - has only 2 unique values - presented in table.```pythondf.Fraude.unique()```| Value | Meaning | Total | Percentage || :---... | # Checking how many unique entries this variable presents.
df.Fraude.unique()
# Checking how many data entries are non-fraud or 0
print(len(df[df['Fraude'] == 0]))
# Checking the percentage of non-fraud transactions
print(len(df[df['Fraude'] == 0])/len(df.Fraude))
# Checking how many data entries are fraud or 1
len(df... | 0.00158
| MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Dimensionality ReductionThis section aims on reduct the dimensionality of this dataset.__It can be used:__- linear regression, correlation and statistically relevance;- PCA;_obs: despite the robustness of PCA, some articles presents issues on its performance - losing to simpler techniques._----------------------- | occurrence = pandas.Series(df.index)
x = pandas.DataFrame(df[df.columns[1:-1]])
y = pandas.DataFrame(df[df.columns[-1]])
# Multiple Linear Regression
lm = linear_model.LinearRegression().fit(x, y)
attr_reduction = SelectFromModel(lm, prefit=True)
df_pca = pandas.DataFrame(attr_reduction.transform(x)) | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Building PredictorsThree models will be implemented - if none of them supply the needs, new models could be choosen - and compared. Not only the assertiveness rate will be considered. The most problematic issue are False Negatives occurences - when the occurrence is Fraudulent however the model classified it as a Non-... | def data_separation(df, proportion=0.2):
"""
Data separation method.
"""
return train_test_split(df, test_size=proportion)
def time_screening(dt):
"""
Fitting time performance calculator.
"""
print(datetime.datetime.now() - dt)
results = {
'linear_model': {
'train': [],
... | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Using selected model in "production" environment- Normalize data- Split data- fit and predict model----------------------------------------------------- | # Data Normalization
scaler = preprocessing.MinMaxScaler().fit(df_pca)
df_pca_norm = pandas.DataFrame(scaler.transform(df_pca))
df_pca_norm['Occurrence'] = occurrence
df_pca_norm.set_index('Occurrence', drop=True, inplace=True)
# Data separation
df_pca_norm['Fraude'] = y
train, test = data_separation(df_pca_norm)
tes... | _____no_output_____ | MIT | src/analysis.ipynb | Brunopaes/sherock-holmes-picpay |
Setting Node CapacitiesCapacities of a FABRIC node are basic characteristics of the virtual machine including number of compute core, amount of memory, and amount of local disk. This notebook will demonstrate the options for setting these node capciites. Configure the Environment | import os
from fabrictestbed.slice_manager import SliceManager, Status, SliceState
import json
ssh_key_file_priv=os.environ['HOME']+"/.ssh/id_rsa"
ssh_key_file_pub=os.environ['HOME']+"/.ssh/id_rsa.pub"
ssh_key_pub = None
with open (ssh_key_file_pub, "r") as myfile:
ssh_key_pub=myfile.read()
ssh_key_pub=ssh_key... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Create Slice Manager Object | slice_manager = SliceManager(oc_host=orchestrator_host,
cm_host=credmgr_host ,
project_name='all',
scope='all')
# Initialize the slice manager
slice_manager.initialize() | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Configure Slice Parameters | slice_name='MySlice'
node_name='node1'
site='RENC'
image_name='default_centos_8'
image_type='qcow2' | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Setting CapacitiesWe are going to be creating slices that contain one node each.We need to specify the resources (number of cores, amount of ram and amount of disk space) that we want to allocate to our node.We can do that in two ways: - Using Capacities() - Using capacity hints. Example 1: Exact CapacitiesLet's crea... | from fabrictestbed.slice_editor import ExperimentTopology, Capacities, ComponentType
# Create topology
t = ExperimentTopology()
# Add node
n1 = t.add_node(name=node_name, site=site)
# Set capacities
cap = Capacities()
cap.set_fields(core=2, ram=8, disk=10)
# Set Properties
n1.set_properties(capacities=cap, image_typ... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Get the slice and topology | import time
def wait_for_slice(slice,timeout=180,interval=10,progress=False):
timeout_start = time.time()
if progress: print("Waiting for slice .", end = '')
while time.time() < timeout_start + timeout:
return_status, slices = slice_manager.slices(excludes=[SliceState.Dead])
if return_stat... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Print the allocated capacities | for node_name, node in experiment_topology.nodes.items():
print("Node {}: ".format(node.name))
print(" Cores : {}".format(node.get_property(pname='capacity_allocations').core))
print(" RAM : {}".format(node.get_property(pname='capacity_allocations').ram))
print(" Disk ... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
It says that our node has 2 cores, 8GB of RAM and 10GB of disk space, which is what we requested.Now let's delete the slice. | return_status, result = slice_manager.delete(slice_object=slice)
print("Response Status {}".format(return_status)) | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Example 2: Rounded CapacitiesNow let's try something else. Let's try to request 2 cores, 8GB of RAM, and 50GB of disk space.Again, we are going to use `cap.set_fields(core=2, ram=8, disk=50)`. | from fabrictestbed.slice_editor import ExperimentTopology, Capacities, ComponentType
# Create topology
t = ExperimentTopology()
# Add node
n1 = t.add_node(name=node_name, site=site)
# Set capacities
cap = Capacities()
cap.set_fields(core=2, ram=8, disk=50)
# Set Properties
n1.set_properties(capacities=cap, image_typ... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Get the slice and topology | return_status, slices = slice_manager.slices(excludes=[SliceState.Dead,SliceState.Closing])
if return_status == Status.OK:
slice = list(filter(lambda x: x.slice_name == slice_name, slices))[0]
slice = wait_for_slice(slice, progress=True)
return_status, experiment_topology = slice_manager.get_slice_topology... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Print the allocated capacities | for node_name, node in experiment_topology.nodes.items():
print("Node {}: ".format(node.name))
print(" Cores : {}".format(node.get_property(pname='capacity_allocations').core))
print(" RAM : {}".format(node.get_property(pname='capacity_allocations').ram))
print(" Disk ... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
We can see that we were allocated 2 cores, 8GB of ram, but 100GB of disk space instead of 50GB.The reason for this is that we have discrete "capacity hints". The node can only be an instance of one of those capacity hints.See the very last cell in this notebook for the complete list of available capacity hints.This is ... | return_status, result = slice_manager.delete(slice_object=slice)
print("Response Status {}".format(return_status)) | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Example 3: Capacity HintsFinally, we can directly set the resources that we need using a "capacity hint" string. _Please see the very last cell in this notebook for the complete list of available capacity hints._We can set the needed resources like so:`capacity_hints=CapacityHints().set_fields(instance_type='fabric.c2... | from fabrictestbed.slice_editor import ExperimentTopology, Capacities, ComponentType, CapacityHints
# Create topology
t = ExperimentTopology()
# Add node
n1 = t.add_node(name=node_name, site=site)
# Set capacities
cap = Capacities()
cap.set_fields(core=2, ram=8, disk=50)
# Set Properties
n1.set_properties(capacities... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Get the slice and topology | return_status, slices = slice_manager.slices(excludes=[SliceState.Dead,SliceState.Closing])
if return_status == Status.OK:
slice = list(filter(lambda x: x.slice_name == slice_name, slices))[0]
return_status, experiment_topology = slice_manager.get_slice_topology(slice_object=slice)
slice = wait_for_slice(s... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Print the allocated capacities | for node_name, node in experiment_topology.nodes.items():
print("Node {}: ".format(node.name))
print(" Cores : {}".format(node.get_property(pname='capacity_allocations').core))
print(" RAM : {}".format(node.get_property(pname='capacity_allocations').ram))
print(" Disk ... | _____no_output_____ | MIT | fabric_examples/basic_examples/setting_node_capaciites.ipynb | fabric-testbed/jupyternb-template |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.