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 |
|---|---|---|---|---|---|
Lab Task 1. In the cell below we define the pipeline for training and deploying our taxifare model. Fill in the code to accomplish four things:1. define the approrpriate `worker_pool_spec` for the training job1. use `ModelUploadOp` to upload the model artifacts after training to create the model in Vertex AI1. create ... | @kfp.dsl.pipeline(name="taxifare--train-upload-endpoint-deploy")
def pipeline(
project: str = PROJECT,
model_display_name: str = MODEL_DISPLAY_NAME,
):
train_task = training_op("taxifare training pipeline")
experimental.run_as_aiplatform_custom_job(
train_task,
display_name=f"pipelines-t... | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Compile and run the pipelineNow, you're ready to compile the pipeline: | if not os.path.isdir("vertex_pipelines"):
os.mkdir("vertex_pipelines")
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="./vertex_pipelines/train_upload_endpoint_deploy.json",
) | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
The pipeline compilation generates the `train_upload_endpoint_deploy.json` job spec file.Next, instantiate the pipeline job object: Lab Task 2.Complete the code in the cell below to fill in the missing arguments. | pipeline_job = aiplatform.pipeline_jobs.PipelineJob(
display_name= # TODO: Your code goes here.
template_path= # TODO: Your code goes here.
pipeline_root= # TODO: Your code goes here.
project=PROJECT,
location=REGION,
) | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Then, you run the defined pipeline like this: | pipeline_job.run() | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Project 3: Smart Beta Portfolio and Portfolio Optimization OverviewSmart beta has a broad meaning, but we can say in practice that when we use the universe of stocks from an index, and then apply some weighting scheme other than market cap weighting, it can be considered a type of smart beta fund. A Smart Beta portfo... | import sys
!{sys.executable} -m pip install -r requirements.txt | Requirement already satisfied: colour==0.1.5 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 1)) (0.1.5)
Requirement already satisfied: cvxpy==1.0.3 in /opt/conda/lib/python3.6/site-packages (from -r requirements.txt (line 2)) (1.0.3)
Requirement already satisfied: cycler==0.10.0 in /opt/conda... | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Load Packages | import pandas as pd
import numpy as np
import helper
import project_helper
import project_tests | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Market Data Load DataFor this universe of stocks, we'll be selecting large dollar volume stocks. We're using this universe, since it is highly liquid. | df = pd.read_csv('../../data/project_3/eod-quotemedia.csv')
percent_top_dollar = 0.2
high_volume_symbols = project_helper.large_dollar_volume_stocks(df, 'adj_close', 'adj_volume', percent_top_dollar)
df = df[df['ticker'].isin(high_volume_symbols)]
close = df.reset_index().pivot(index='date', columns='ticker', values=... | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataTo see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix. | project_helper.print_dataframe(close) | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Part 1: Smart Beta PortfolioIn Part 1 of this project, you'll build a portfolio using dividend yield to choose the portfolio weights. A portfolio such as this could be incorporated into a smart beta ETF. You'll compare this portfolio to a market cap weighted index to see how well it performs. Note that in practice, y... | def generate_dollar_volume_weights(close, volume):
"""
Generate dollar volume weights.
Parameters
----------
close : DataFrame
Close price for each ticker and date
volume : str
Volume for each ticker and date
Returns
-------
dollar_volume_weights : DataFrame
... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's generate the index weights using `generate_dollar_volume_weights` and view them using a heatmap. | index_weights = generate_dollar_volume_weights(close, volume)
project_helper.plot_weights(index_weights, 'Index Weights') | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Portfolio WeightsNow that we have the index weights, let's choose the portfolio weights based on dividend. You would normally calculate the weights based on trailing dividend yield, but we'll simplify this by just calculating the total dividend yield over time.Implement `calculate_dividend_weights` to return the weigh... | def calculate_dividend_weights(dividends):
"""
Calculate dividend weights.
Parameters
----------
dividends : DataFrame
Dividend for each stock and date
Returns
-------
dividend_weights : DataFrame
Weights for each stock and date
"""
#TODO: Implement function
... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataJust like the index weights, let's generate the ETF weights and view them using a heatmap. | etf_weights = calculate_dividend_weights(dividends)
project_helper.plot_weights(etf_weights, 'ETF Weights') | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
ReturnsImplement `generate_returns` to generate returns data for all the stocks and dates from price data. You might notice we're implementing returns and not log returns. Since we're not dealing with volatility, we don't have to use log returns. | def generate_returns(prices):
"""
Generate returns for ticker and date.
Parameters
----------
prices : DataFrame
Price for each ticker and date
Returns
-------
returns : Dataframe
The returns for each ticker and date
"""
#TODO: Implement function
return pri... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's generate the closing returns using `generate_returns` and view them using a heatmap. | returns = generate_returns(close)
project_helper.plot_returns(returns, 'Close Returns') | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Weighted ReturnsWith the returns of each stock computed, we can use it to compute the returns for an index or ETF. Implement `generate_weighted_returns` to create weighted returns using the returns and weights. | def generate_weighted_returns(returns, weights):
"""
Generate weighted returns.
Parameters
----------
returns : DataFrame
Returns for each ticker and date
weights : DataFrame
Weights for each ticker and date
Returns
-------
weighted_returns : DataFrame
Weigh... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's generate the ETF and index returns using `generate_weighted_returns` and view them using a heatmap. | index_weighted_returns = generate_weighted_returns(returns, index_weights)
etf_weighted_returns = generate_weighted_returns(returns, etf_weights)
project_helper.plot_returns(index_weighted_returns, 'Index Returns')
project_helper.plot_returns(etf_weighted_returns, 'ETF Returns') | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Cumulative ReturnsTo compare performance between the ETF and Index, we're going to calculate the tracking error. Before we do that, we first need to calculate the index and ETF comulative returns. Implement `calculate_cumulative_returns` to calculate the cumulative returns over time given the returns. | def calculate_cumulative_returns(returns):
"""
Calculate cumulative returns.
Parameters
----------
returns : DataFrame
Returns for each ticker and date
Returns
-------
cumulative_returns : Pandas Series
Cumulative returns for each date
"""
#TODO: Implement funct... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's generate the ETF and index cumulative returns using `calculate_cumulative_returns` and compare the two. | index_weighted_cumulative_returns = calculate_cumulative_returns(index_weighted_returns)
etf_weighted_cumulative_returns = calculate_cumulative_returns(etf_weighted_returns)
project_helper.plot_benchmark_returns(index_weighted_cumulative_returns, etf_weighted_cumulative_returns, 'Smart Beta ETF vs Index') | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Tracking ErrorIn order to check the performance of the smart beta portfolio, we can calculate the annualized tracking error against the index. Implement `tracking_error` to return the tracking error between the ETF and benchmark.For reference, we'll be using the following annualized tracking error function:$$ TE = \sq... | def tracking_error(benchmark_returns_by_date, etf_returns_by_date):
"""
Calculate the tracking error.
Parameters
----------
benchmark_returns_by_date : Pandas Series
The benchmark returns for each date
etf_returns_by_date : Pandas Series
The ETF returns for each date
Return... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's generate the tracking error using `tracking_error`. | smart_beta_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(etf_weighted_returns, 1))
print('Smart Beta Tracking Error: {}'.format(smart_beta_tracking_error)) | Smart Beta Tracking Error: 0.10207614832007529
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Part 2: Portfolio OptimizationNow, let's create a second portfolio. We'll still reuse the market cap weighted index, but this will be independent of the dividend-weighted portfolio that we created in part 1.We want to both minimize the portfolio variance and also want to closely track a market cap weighted index. In... | def get_covariance_returns(returns):
"""
Calculate covariance matrices.
Parameters
----------
returns : DataFrame
Returns for each ticker and date
Returns
-------
returns_covariance : 2 dimensional Ndarray
The covariance of the returns
"""
#TODO: Implement func... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
View DataLet's look at the covariance generated from `get_covariance_returns`. | covariance_returns = get_covariance_returns(returns)
covariance_returns = pd.DataFrame(covariance_returns, returns.columns, returns.columns)
covariance_returns_correlation = np.linalg.inv(np.diag(np.sqrt(np.diag(covariance_returns))))
covariance_returns_correlation = pd.DataFrame(
covariance_returns_correlation.do... | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
portfolio varianceWe can write the portfolio variance $\sigma^2_p = \mathbf{x^T} \mathbf{P} \mathbf{x}$Recall that the $\mathbf{x^T} \mathbf{P} \mathbf{x}$ is called the quadratic form.We can use the cvxpy function `quad_form(x,P)` to get the quadratic form. Distance from index weightsWe want portfolio weights that tr... | import cvxpy as cvx
def get_optimal_weights(covariance_returns, index_weights, scale=2.0):
"""
Find the optimal weights.
Parameters
----------
covariance_returns : 2 dimensional Ndarray
The covariance of the returns
index_weights : Pandas Series
Index weights for all tickers at... | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Optimized PortfolioUsing the `get_optimal_weights` function, let's generate the optimal ETF weights without rebalanceing. We can do this by feeding in the covariance of the entire history of data. We also need to feed in a set of index weights. We'll go with the average weights of the index over time. | raw_optimal_single_rebalance_etf_weights = get_optimal_weights(covariance_returns.values, index_weights.iloc[-1])
optimal_single_rebalance_etf_weights = pd.DataFrame(
np.tile(raw_optimal_single_rebalance_etf_weights, (len(returns.index), 1)),
returns.index,
returns.columns) | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
With our ETF weights built, let's compare it to the index. Run the next cell to calculate the ETF returns and compare it to the index returns. | optim_etf_returns = generate_weighted_returns(returns, optimal_single_rebalance_etf_weights)
optim_etf_cumulative_returns = calculate_cumulative_returns(optim_etf_returns)
project_helper.plot_benchmark_returns(index_weighted_cumulative_returns, optim_etf_cumulative_returns, 'Optimized ETF vs Index')
optim_etf_tracking... | _____no_output_____ | MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Rebalance Portfolio Over TimeThe single optimized ETF portfolio used the same weights for the entire history. This might not be the optimal weights for the entire period. Let's rebalance the portfolio over the same period instead of using the same weights. Implement `rebalance_portfolio` to rebalance a portfolio.Rebla... | def rebalance_portfolio(returns, index_weights, shift_size, chunk_size):
"""
Get weights for each rebalancing of the portfolio.
Parameters
----------
returns : DataFrame
Returns for each ticker and date
index_weights : DataFrame
Index weight for each ticker and date
shift_si... | Tests Passed
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
Run the following cell to get the portfolio turnover from `get_portfolio turnover`. | chunk_size = 250
shift_size = 5
all_rebalance_weights = rebalance_portfolio(returns, index_weights, shift_size, chunk_size)
print(get_portfolio_turnover(all_rebalance_weights, shift_size, len(all_rebalance_weights) - 1)) | 16.72683266050277
| MIT | Smart_Beta_and_Portfolio_Optimization.ipynb | parinp/Ai-for-Trading |
**In this notebook, we embed the abstract of the papers into a low dimensional space (using either sentencetransformers library or doc2vec from Gensim) and associate to each author his abstracts embedding** | !pip install -U sentence-transformers
from tqdm import tqdm_notebook as tqdm
from sentence_transformers import SentenceTransformer
import pandas as pd
import gzip
import pickle
import numpy as np
import torch
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from string import digits, ascii_letters, punctuation... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Load Abstracts | tmp = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/files_generated/preprocess_abstracts.txt')
## Cleaning V2 (before conditioned on word with word.isalpha() as a condition)
valid = ascii_letters + digits + punctuation + printable
paper_id = []
text = []
for key in tqdm(tmp.keys()):
txt = ''.joi... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Abstract Embedding STSB Roberta Base | model = SentenceTransformer('stsb-roberta-base')
model.cuda()
embeddings = model.encode(text)
emb_per_paper = {}
for idx, id in enumerate(paper_id):
emb_per_paper[id] = embeddings[idx]
save(emb_per_paper, '/content/drive/MyDrive/altegrad_datachallenge/embedding_per_paper_clean.txt') | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Doc2Vec | stop_words = set(stopwords.words('english'))
doc = []
for txt in tqdm(text):
p = txt.split()
p_clean = [l for l in p if l not in stop_words]
doc.append(p_clean)
del text
tagged_data = [TaggedDocument(d, [i]) for i, d in enumerate(doc)]
model = Doc2Vec(tagged_data, vector_size = 256, window = 5, min_count ... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Abstract Per Author EmbeddingAssociate each author with his articles | # read the file to create a dictionary with author key and paper list as value
f = open("/content/drive/MyDrive/altegrad_datachallenge/author_papers.txt","r")
papers_set = set()
d = {}
for l in f:
auth_paps = [paper_id.strip() for paper_id in l.split(":")[1].replace("[","").replace("]","").replace("\n","").replace(... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Using Roberta Embedding | emb_per_paper = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/embedding_per_paper_clean.txt')
df = open("/content/drive/MyDrive/altegrad_datachallenge/author_embedding_clean.csv","w")
for id_author in tqdm(d.keys()):
tot_embedding = np.zeros(768)
c = 0
for id_paper in d[id_author]:
... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Using Doc2Vec | emb_per_paper = load_dataset_file('/content/drive/MyDrive/altegrad_datachallenge/doc2vec_paper_embedding.txt')
df = open("/content/drive/MyDrive/altegrad_datachallenge/doc2vec_author_embedding.csv","w")
for id_author in tqdm(d.keys()):
tot_embedding = np.zeros(256)
c = 0
for id_paper in d[id_author]:
... | _____no_output_____ | MIT | notebook_utils/abstracts_2_vec_per_author.ipynb | omarsou/altegrad_challenge_hindex |
Visualization using the Graphviz Library**Goal:** Visualize all (or some) of the DAG defining the LSHTC3 data.Source: https://graphviz.readthedocs.io/en/stable/examples.html Load the Data | with open("./data/hierarchyWikipediaMedium.txt", 'r') as edges:
lines = []
for line in edges.readlines():
line = line.rstrip('\r\n')
line = line.split(' ')
lines.append(line)
print(lines[0:100])
from graphviz import Graph
g = Graph('G', filename='process.gv', engine='sfdp')
for edge ... | _____no_output_____ | MIT | DAG_viz.ipynb | djliden/LSHTC3_DAG |
The aim of this is to be able to classify names as either being African in origin or not | import pandas as pd
import ast
from ethnicolr import pred_wiki_ln, pred_wiki_name | Using TensorFlow backend.
| Apache-2.0 | working_ipynbs/name_classification.ipynb | TamatiB/restitution_africa2021 |
Load puplications, get authors and how many publications of theirs we have | from collections import Counter
data = pd.read_csv("bb_pulications.csv")
data['author'] = data['bib'].apply(lambda x: ast.literal_eval(x)['author'])
data['year'] = data['bib'].apply(lambda x: ast.literal_eval(x)['pub_year'])
data['title'] = data['bib'].apply(lambda x: ast.literal_eval(x)['title']) | _____no_output_____ | Apache-2.0 | working_ipynbs/name_classification.ipynb | TamatiB/restitution_africa2021 |
Clean author names a little bit | def clean_author(x):
"""
x list of authors for a publication
"""
clean_list = []
for item in x:
clean_list.append(item.lower())
return clean_list
data['author_cleaned'] = data['author'].apply(lambda x: clean_author(x))
authors = data['author_cleaned'].sum()
Counter(authors) | _____no_output_____ | Apache-2.0 | working_ipynbs/name_classification.ipynb | TamatiB/restitution_africa2021 |
Get surnames | # first have to searate from initials and then put back togetehr again
surnames = []
for name in authors:
surname = name.split(' ')[1:]
surname_str = ' '.join(surname)
surnames.append(surname_str)
Counter(surnames) | _____no_output_____ | Apache-2.0 | working_ipynbs/name_classification.ipynb | TamatiB/restitution_africa2021 |
Hokay, lets try this Classifier | #drop duplicates
surnames = list(set(surnames))
df = pd.DataFrame(surnames, columns=["surnames"])
preds = pred_wiki_ln(df, "surnames")
preds
preds['race'].value_counts()
preds[preds['race'] == 'GreaterAfrican,Africans'] | _____no_output_____ | Apache-2.0 | working_ipynbs/name_classification.ipynb | TamatiB/restitution_africa2021 |
Text drift detection on IMDB movie reviews MethodWe detect drift on text data using both the [Maximum Mean Discrepancy](https://docs.seldon.io/projects/alibi-detect/en/latest/methods/mmddrift.html) and [Kolmogorov-Smirnov (K-S)](https://docs.seldon.io/projects/alibi-detect/en/latest/methods/ksdrift.html) detectors. In... | import nlp
import numpy as np
import os
import tensorflow as tf
from transformers import AutoTokenizer
from alibi_detect.cd import KSDrift, MMDDrift
from alibi_detect.utils.saving import save_detector, load_detector | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Load tokenizer | model_name = 'bert-base-cased'
tokenizer = AutoTokenizer.from_pretrained(model_name) | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Load data | def load_dataset(dataset: str, split: str = 'test'):
data = nlp.load_dataset(dataset)
X, y = [], []
for x in data[split]:
X.append(x['text'])
y.append(x['label'])
X = np.array(X)
y = np.array(y)
return X, y
X, y = load_dataset('imdb', split='train')
print(X.shape, y.shape) | INFO:nlp.load:Checking /home/avl/.cache/huggingface/datasets/d3b7716978cb901261e59327d43b04c52d6d29e50eeac39bea0816865a584081.7c39fd6270c5ee55bcf2e4de23af77ef299e0df65be3f3e84454dcef7175844a.py for additional imports.
INFO:filelock:Lock 140070637965264 acquired on /home/avl/.cache/huggingface/datasets/d3b7716978cb90126... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Let's take a look at respectively a negative and positive review: | labels = ['Negative', 'Positive']
print(labels[y[-1]])
print(X[-1])
print(labels[y[2]])
print(X[2]) | Positive
Brilliant over-acting by Lesley Ann Warren. Best dramatic hobo lady I have ever seen, and love scenes in clothes warehouse are second to none. The corn on face is a classic, as good as anything in Blazing Saddles. The take on lawyers is also superb. After being accused of being a turncoat, selling out his boss... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
We split the original test set in a reference dataset and a dataset which should not be rejected under the *H0* of the statistical test. We also create imbalanced datasets and inject selected words in the reference set. | def random_sample(X: np.ndarray, y: np.ndarray, proba_zero: float, n: int):
if len(y.shape) == 1:
idx_0 = np.where(y == 0)[0]
idx_1 = np.where(y == 1)[0]
else:
idx_0 = np.where(y[:, 0] == 1)[0]
idx_1 = np.where(y[:, 1] == 1)[0]
n_0, n_1 = int(n * proba_zero), int(n * (1 - pro... | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Reference, *H0* and imbalanced data: | # proba_zero = fraction with label 0 (=negative sentiment)
n_sample = 1000
X_ref = random_sample(X, y, proba_zero=.5, n=n_sample)[0]
X_h0 = random_sample(X, y, proba_zero=.5, n=n_sample)[0]
n_imb = [.1, .9]
X_imb = {_: random_sample(X, y, proba_zero=_, n=n_sample)[0] for _ in n_imb} | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Inject words in reference data: | words = ['fantastic', 'good', 'bad', 'horrible']
perc_chg = [1., 5.] # % of tokens to change in an instance
words_tf = tokenizer(words)['input_ids']
words_tf = [token[1:-1][0] for token in words_tf]
max_len = 100
tokens = tokenizer(list(X_ref), pad_to_max_length=True,
max_length=max_len, return_te... | Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precise... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
PreprocessingFirst we need to specify the type of embedding we want to extract from the BERT model. We can extract embeddings from the ...- **pooler_output**: Last layer hidden-state of the first token of the sequence (classification token; CLS) further processed by a Linear layer and a Tanh activation function. The L... | from alibi_detect.models.tensorflow import TransformerEmbedding
emb_type = 'hidden_state'
n_layers = 8
layers = [-_ for _ in range(1, n_layers + 1)]
embedding = TransformerEmbedding(model_name, emb_type, layers) | Some layers from the model checkpoint at bert-base-cased were not used when initializing TFBertModel: ['nsp___cls', 'mlm___cls']
- This IS expected if you are initializing TFBertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification m... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Let's check what an embedding looks like: | tokens = tokenizer(list(X[:5]), pad_to_max_length=True,
max_length=max_len, return_tensors='tf')
x_emb = embedding(tokens)
print(x_emb.shape) | (5, 768)
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
So the BERT model's embedding space used by the drift detector consists of a $768$-dimensional vector for each instance. We will therefore first apply a dimensionality reduction step with an Untrained AutoEncoder (*UAE*) before conducting the statistical hypothesis test. We use the embedding model as the input for the ... | tf.random.set_seed(0)
from alibi_detect.cd.tensorflow import UAE
enc_dim = 32
shape = (x_emb.shape[1],)
uae = UAE(input_layer=embedding, shape=shape, enc_dim=enc_dim) | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Let's test this again: | emb_uae = uae(tokens)
print(emb_uae.shape) | (5, 32)
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
K-S detector InitializeWe proceed to initialize the drift detector. From here on the detector works the same as for other modalities such as images. Please check the [images](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/cd_ks_cifar10.html) example or the [K-S detector documentation](https://docs.sel... | from functools import partial
from alibi_detect.cd.tensorflow import preprocess_drift
# define preprocessing function
preprocess_fn = partial(preprocess_drift, model=uae, tokenizer=tokenizer,
max_len=max_len, batch_size=32)
# initialize detector
cd = KSDrift(X_ref, p_val=.05, preprocess_fn=pr... | WARNING:alibi_detect.utils.saving:Directory my_path does not exist and is now created.
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Detect driftLet’s first check if drift occurs on a similar sample from the training set as the reference data. | preds_h0 = cd.predict(X_h0)
labels = ['No!', 'Yes!']
print('Drift? {}'.format(labels[preds_h0['data']['is_drift']]))
print('p-value: {}'.format(preds_h0['data']['p_val'])) | Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precise... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Detect drift on imbalanced and perturbed datasets: | for k, v in X_imb.items():
preds = cd.predict(v)
print('% negative sentiment {}'.format(k * 100))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('')
for w, probas in X_word.items():
for p, v in probas.items():
preds ... | Word: fantastic -- % perturbed: 1.0
Drift? No!
p-value: [0.9540582 0.01293455 0.26338065 0.722555 0.34099194 0.04281518
0.04841881 0.31356168 0.14833806 0.96887016 0.85929435 0.50035924
0.00532228 0.8879386 0.9998709 0.99870795 0.85929435 0.9882611
0.06155144 0.7590978 0.79439443 0.2406036 0.10828251 0.722555... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
MMD TensorFlow detector InitializeAgain check the [images](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/cd_mmd_cifar10.html) example or the [MMD detector documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/methods/mmddrift.html) for more information about each of the possible param... | cd = MMDDrift(X_ref, p_val=.05, preprocess_fn=preprocess_fn,
n_permutations=100, input_shape=(max_len,)) | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Detect drift*H0*: | preds_h0 = cd.predict(X_h0)
labels = ['No!', 'Yes!']
print('Drift? {}'.format(labels[preds_h0['data']['is_drift']]))
print('p-value: {}'.format(preds_h0['data']['p_val'])) | Drift? No!
p-value: 0.9
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Imbalanced data: | for k, v in X_imb.items():
preds = cd.predict(v)
print('% negative sentiment {}'.format(k * 100))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('') | % negative sentiment 10.0
Drift? Yes!
p-value: 0.0
% negative sentiment 90.0
Drift? Yes!
p-value: 0.0
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Perturbed data: | for w, probas in X_word.items():
for p, v in probas.items():
preds = cd.predict(v)
print('Word: {} -- % perturbed: {}'.format(w, p))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('') | Word: fantastic -- % perturbed: 1.0
Drift? Yes!
p-value: 0.01
Word: fantastic -- % perturbed: 5.0
Drift? Yes!
p-value: 0.0
Word: good -- % perturbed: 1.0
Drift? No!
p-value: 0.57
Word: good -- % perturbed: 5.0
Drift? Yes!
p-value: 0.0
Word: bad -- % perturbed: 1.0
Drift? No!
p-value: 0.4
Word: bad -- % perturbed: ... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
MMD PyTorch detector InitializeWe can run the same detector with *PyTorch* backend for both the preprocessing step and MMD implementation: | import torch
import torch.nn as nn
# set random seed and device
seed = 0
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
from alibi_detect.cd.pytorch import preprocess_drift
from alibi_detect.models.pytorch import TransformerEmbe... | INFO:filelock:Lock 140068554309968 acquired on /home/avl/.cache/huggingface/transformers/092cc582560fc3833e556b3f833695c26343cb54b7e88cd02d40821462a74999.1f48cab6c959fc6c360d22bea39d06959e90f5b002e77e836d2da45464875cda.lock
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Detect drift*H0*: | preds_h0 = cd.predict(X_h0)
labels = ['No!', 'Yes!']
print('Drift? {}'.format(labels[preds_h0['data']['is_drift']]))
print('p-value: {}'.format(preds_h0['data']['p_val'])) | Drift? No!
p-value: 0.3400000035762787
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Imbalanced data: | for k, v in X_imb.items():
preds = cd.predict(v)
print('% negative sentiment {}'.format(k * 100))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('') | % negative sentiment 10.0
Drift? Yes!
p-value: 0.0
% negative sentiment 90.0
Drift? Yes!
p-value: 0.0
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Perturbed data: | for w, probas in X_word.items():
for p, v in probas.items():
preds = cd.predict(v)
print('Word: {} -- % perturbed: {}'.format(w, p))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('') | Word: fantastic -- % perturbed: 1.0
Drift? No!
p-value: 0.07999999821186066
Word: fantastic -- % perturbed: 5.0
Drift? Yes!
p-value: 0.0
Word: good -- % perturbed: 1.0
Drift? No!
p-value: 0.7099999785423279
Word: good -- % perturbed: 5.0
Drift? Yes!
p-value: 0.0
Word: bad -- % perturbed: 1.0
Drift? No!
p-value: 0.1... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Train embeddings from scratchSo far we used pre-trained embeddings from a BERT model. We can however also use embeddings from a model trained from scratch. First we define and train a simple classification model consisting of an embedding and LSTM layer in *TensorFlow*. Load data and train model | from tensorflow.keras.datasets import imdb, reuters
from tensorflow.keras.layers import Dense, Embedding, Input, LSTM
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.utils import to_categorical
INDEX_FROM = 3
NUM_WORDS = 10000
def print_sentence(tokenized_sentence: str, id2w: dict):
pri... | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Load and tokenize data: | (X_train, y_train), (X_test, y_test), (word2token, token2word) = \
get_dataset(dataset='imdb', max_len=max_len) | <string>:6: VisibleDeprecationWarning:
Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
/home/avl/anaconda3/envs/detect/lib/pytho... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Let's check out an instance: | print_sentence(X_train[0], token2word) | cry at a film it must have been good and this definitely was also <UNK> to the two little boy's that played the <UNK> of norman and paul they were just brilliant children are often left out of the <UNK> list i think because the stars that play them all grown up are such a big profile for the whole film but these childr... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Define and train a simple model: | model = imdb_model(X=X_train, num_words=NUM_WORDS, emb_dim=256, lstm_dim=128, output_dim=2)
model.fit(X_train, y_train, batch_size=32, epochs=2,
shuffle=True, validation_data=(X_test, y_test)) | Epoch 1/2
782/782 [==============================] - 96s 121ms/step - loss: 0.5019 - accuracy: 0.7397 - val_loss: 0.3452 - val_accuracy: 0.8514
Epoch 2/2
782/782 [==============================] - 93s 118ms/step - loss: 0.2649 - accuracy: 0.8943 - val_loss: 0.3628 - val_accuracy: 0.8454
| ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Extract the embedding layer from the trained model and combine with UAE preprocessing step: | embedding = tf.keras.Model(inputs=model.inputs, outputs=model.layers[1].output)
x_emb = embedding(X_train[:5])
print(x_emb.shape)
tf.random.set_seed(0)
shape = tuple(x_emb.shape[1:])
uae = UAE(input_layer=embedding, shape=shape, enc_dim=enc_dim) | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Again, create reference, *H0* and perturbed datasets. Also test against the *Reuters* news topic classification dataset. | X_ref, y_ref = random_sample(X_test, y_test, proba_zero=.5, n=n_sample)
X_h0, y_h0 = random_sample(X_test, y_test, proba_zero=.5, n=n_sample)
tokens = [word2token[w] for w in words]
X_word = {}
for i, t in enumerate(tokens):
X_word[words[i]] = {}
for p in perc_chg:
X_word[words[i]][p] = inject_word(t, X... | /home/avl/anaconda3/envs/detect/lib/python3.7/site-packages/tensorflow/python/keras/datasets/reuters.py:148: VisibleDeprecationWarning:
Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Initialize detector and detect drift | from alibi_detect.cd.tensorflow import preprocess_drift
# define preprocessing function
preprocess_fn = partial(preprocess_drift, model=uae, batch_size=128)
# initialize detector
cd = KSDrift(X_ref, p_val=.05, preprocess_fn=preprocess_fn) | _____no_output_____ | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
*H0*: | preds_h0 = cd.predict(X_h0)
labels = ['No!', 'Yes!']
print('Drift? {}'.format(labels[preds_h0['data']['is_drift']]))
print('p-value: {}'.format(preds_h0['data']['p_val'])) | Drift? No!
p-value: [0.93558097 0.64755726 0.50035924 0.85929435 0.04281518 0.93558097
0.9801618 0.50035924 0.8879386 0.43243074 0.5726548 0.6852314
0.60991895 0.9134755 0.18111965 0.722555 0.5726548 0.21933001
0.5360543 0.6852314 0.85929435 0.31356168 0.9801618 0.18111965
0.34099194 0.722555 0.04841881... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
Perturbed data: | for w, probas in X_word.items():
for p, v in probas.items():
preds = cd.predict(v)
print('Word: {} -- % perturbed: {}'.format(w, p))
print('Drift? {}'.format(labels[preds['data']['is_drift']]))
print('p-value: {}'.format(preds['data']['p_val']))
print('') | Word: fantastic -- % perturbed: 1.0
Drift? No!
p-value: [0.9882611 0.79439443 0.9999727 0.9882611 0.7590978 0.8879386
0.996931 0.82795686 0.64755726 0.7590978 0.85929435 0.99870795
0.93558097 0.82795686 0.99365413 0.996931 0.85929435 0.8879386
0.85929435 0.9540582 0.96887016 0.9801618 0.50035924 0.9998709... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
The detector is not as sensitive as the Transformer-based K-S drift detector. The embeddings trained from scratch only trained on a small dataset and a simple model with cross-entropy loss function for 2 epochs. The pre-trained BERT model on the other hand captures semantics of the data better.Sample from the Reuters d... | preds_ood = cd.predict(X_ood)
labels = ['No!', 'Yes!']
print('Drift? {}'.format(labels[preds_ood['data']['is_drift']]))
print('p-value: {}'.format(preds_ood['data']['p_val'])) | Drift? Yes!
p-value: [5.72654784e-01 7.26078229e-04 2.73716728e-15 3.49877549e-09
1.29345525e-02 2.24637091e-02 4.95470906e-14 1.34916729e-04
8.27956855e-01 4.00471032e-01 6.20218972e-03 1.97469308e-09
6.15514442e-02 5.06567594e-04 5.46463318e-02 7.59097815e-01
1.97830971e-07 4.56308130e-10 4.15714254e-08 4.3243074... | ECL-2.0 | examples/cd_text_imdb.ipynb | cliveseldon/alibi-detect |
# 1.2.1 신경망 추론 전체 그림
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
x=np.random.randn(10,2)
W1=np.random.randn(2,4)
b1=np.random.randn(4)
W2=np.random.randn(4,3)
b2=np.random.randn(3)
h=np.matmul(x,W1)+b1
a=sigmoid(h)
s=np.matmul(a,W2)+b2
# 1.2.2 계층으로 클래스화 및 순전파 구현
class Sigmoid:
def __init__(self)... | _____no_output_____ | MIT | ch01/1-2.ipynb | jjhsnail0822/deep-learning-from-scratch-2 | |
https://github.com/cyberFund/ethdrain Python script allowing to copy the Ethereum blockchain towards ElasticSearch, PostgreSQL and csv in an efficient way by connecting to a local RPC node | import requests
import json
def print_json(json_for_print):
print(json.dumps(json_for_print, indent=4, sort_keys=True))
return | _____no_output_____ | Apache-2.0 | Ethereum API.ipynb | Snedashkovsky/Course_blockchain_data |
Request function | def http_post_request(url, request):
print('url: {}'.format(str(url)))
print('request: {} \n'.format(str(request)))
return requests.post(url, data=request, headers={"content-type": "application/json"}).json() | _____no_output_____ | Apache-2.0 | Ethereum API.ipynb | Snedashkovsky/Course_blockchain_data |
APIEthereum JSON RPC API: https://github.com/ethereum/wiki/wiki/JSON-RPC getBlockByNumber | def make_request_getBlockByNumber(block_nb, use_hex=True):
return json.dumps({
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [hex(block_nb) if use_hex else block_nb, True],
"id": 1
... | url: https://mainnet.infura.io/TzMi1NSXsXK2SzUuEY9Q
request: {"params": ["latest", true], "method": "eth_getBlockByNumber", "id": 1, "jsonrpc": "2.0"}
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"difficulty": "0xb91590c441438",
"extraData": "0x6e616e6f706f6f6c2e6f7267",
"gasLimit": "0... | Apache-2.0 | Ethereum API.ipynb | Snedashkovsky/Course_blockchain_data |
eth_getBalance | def make_request_eth_getBalance(address, block_nb = 'latest', use_hex=False):
return json.dumps({
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [address, hex(block_nb) if use_hex else block_nb],
... | url: https://mainnet.infura.io/TzMi1NSXsXK2SzUuEY9Q
request: {"params": ["0xc8f88d1c1259060a799af77120db270cdce07e37", "0x517025"], "method": "eth_getBalance", "id": 1, "jsonrpc": "2.0"}
{
"id": 1,
"jsonrpc": "2.0",
"result": "0x1b9c02a0a23a70"
}
| Apache-2.0 | Ethereum API.ipynb | Snedashkovsky/Course_blockchain_data |
**Name:** Omar Khaled Mahmoud Safwat Mohamed Safwat**Group:** Alex group 3 | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
from sklearn.preprocessing import StandardScaler # Standardize data for faster convergence
import seaborn as sns
import Linear_Regression as lr
sns.set() | _____no_output_____ | MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
Data generation | X = np.array([list(range(1, 20))]).T
y = -1 * X + 2
# Plot data
plt.scatter(X, y)
plt.xlabel("x")
plt.ylabel("y") | _____no_output_____ | MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
Adagrad 1st trial | lr_adagrad = lr.Linear_Regression(X, y)
theta = lr_adagrad.fit(solver="Adagrad", alpha=0.01, max_epochs=1e3, standardize=False, stop_criteria=1e-3, eps=1e-8)
lr_adagrad.show_summary()
lr_adagrad.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_adagrad.plot_MSE() | Solver summary:
===============
Number of iterations: 1000
MSE: 6.797968808367863
Stop criteria was reached first: False
Model Training accuracy: 0.5468020794421424
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
2nd Trial | lr_adagrad = lr.Linear_Regression(X, y)
theta = lr_adagrad.fit(solver="Adagrad", alpha=0.01, max_epochs=1e4, standardize=False, stop_criteria=1e-5, eps=1e-8)
lr_adagrad.show_summary()
lr_adagrad.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_adagrad.plot_MSE() | Solver summary:
===============
Number of iterations: 10000
MSE: 0.7111622267407923
Stop criteria was reached first: False
Model Training accuracy: 0.9525891848839472
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
RMSprop 1st trial | lr_rms = lr.Linear_Regression(X, y)
theta = lr_rms.fit(solver="RMSprop", alpha=0.01, max_epochs=1e3, standardize=False, stop_criteria=1e-3, eps=1e-8, beta_grad=0.9)
lr_rms.show_summary()
lr_rms.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_rms.plot_MSE() | Solver summary:
===============
Number of iterations: 300
MSE: 0.32095489048071413
Stop criteria was reached first: True
Model Training accuracy: 0.9786030073012857
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
2nd Trial | lr_rms = lr.Linear_Regression(X, y)
theta = lr_rms.fit(solver="RMSprop", alpha=0.001, max_epochs=1e4, standardize=False, stop_criteria=1e-4, eps=1e-8, beta_grad=0.9)
lr_rms.show_summary()
lr_rms.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_rms.plot_MSE() | Solver summary:
===============
Number of iterations: 3117
MSE: 0.022779696979792863
Stop criteria was reached first: True
Model Training accuracy: 0.9984813535346805
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
Adam 1st trial | lr_adam = lr.Linear_Regression(X, y)
theta = lr_adam.fit(
solver="Adam",
alpha=0.001,
max_epochs=1e3,
standardize=False,
stop_criteria=1e-3,
eps=1e-7,
beta_grad=0.9,
beta_nu=0.8)
lr_adam.show_summary()
lr_adam.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_adam.plot_MSE() | Solver summary:
===============
Number of iterations: 909
MSE: 0.8091644884352912
Stop criteria was reached first: True
Model Training accuracy: 0.9460557007709806
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
2nd trial | lr_adam = lr.Linear_Regression(X, y)
theta = lr_adam.fit(
solver="Adam",
alpha=0.01,
max_epochs=1e4,
standardize=False,
stop_criteria=1e-3,
eps=1e-7,
beta_grad=0.9,
beta_nu=0.8)
lr_adam.show_summary()
lr_adam.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_adam.plot_MSE() | Solver summary:
===============
Number of iterations: 424
MSE: 0.023983926232788545
Stop criteria was reached first: True
Model Training accuracy: 0.9984010715844808
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
Compare between three algorithmsAt * alpha = 0.01* max_epochs=1e4, * standardize=False, * stop_criteria=1e-4, * eps=1e-7, * beta_grad=0.9, * beta_nu=0.8 | # Adagrad
lr_adagrad = lr.Linear_Regression(X, y)
theta = lr_adagrad.fit(solver="Adagrad", alpha=0.01, max_epochs=1e4, standardize=False, stop_criteria=1e-4, eps=1e-7)
lr_adagrad.show_summary()
lr_adagrad.plot_LR_2D(show_trials=True, N_trials_to_show= 10)
lr_adagrad.plot_MSE()
# RMS
lr_rms = lr.Linear_Regression(X, y)
... | Solver summary:
===============
Number of iterations: 473
MSE: 0.0004158716712860208
Stop criteria was reached first: True
Model Training accuracy: 0.9999722752219142
| MIT | Optimization in ML/Gradient_descent/Practical_4.ipynb | Omar-Safwat/Numerical_Methods_Projects |
Character-Level LSTM in PyTorchIn this notebook, I'll construct a character-level LSTM with PyTorch. The network will train character by character on some text, then generate new text character by character. As an example, I will train on Anna Karenina. **This model will be able to generate new text based on the text ... | import numpy as np
import torch
from torch import nn
import torch.nn.functional as F | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Load in DataThen, we'll load the Anna Karenina text file and convert it into integers for our network to use. | # open text file and read in data as `text`
with open('data/anna.txt', 'r') as f:
text = f.read() | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Let's check out the first 100 characters, make sure everything is peachy. According to the [American Book Review](http://americanbookreview.org/100bestlines.asp), this is the 6th best first line of a book ever. | text[:100] | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
TokenizationIn the cells, below, I'm creating a couple **dictionaries** to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network. | # encode the text and map each character to an integer and vice versa
# we create two dictionaries:
# 1. int2char, which maps integers to characters
# 2. char2int, which maps characters to unique integers
chars = tuple(set(text))
int2char = dict(enumerate(chars))
char2int = {ch: ii for ii, ch in int2char.items()}
# e... | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
And we can see those same characters from above, encoded as integers. | encoded[:100] | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Pre-processing the dataAs you can see in our char-RNN image above, our LSTM expects an input that is **one-hot encoded** meaning that each character is converted into an integer (via our created dictionary) and *then* converted into a column vector where only it's corresponding integer index will have the value of 1 a... | def one_hot_encode(arr, n_labels):
# Initialize the the encoded array
one_hot = np.zeros((arr.size, n_labels), dtype=np.float32)
# Fill the appropriate elements with ones
one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1.
# Finally reshape it to get back to the original array
... | [[[0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]]]
| Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Making training mini-batchesTo train on this data, we also want to create mini-batches for training. Remember that we want our batches to be multiple sequences of some desired number of sequence steps. Considering a simple example, our batches would look like this:In this example, we'll take the encoded characters (pa... | def get_batches(arr, batch_size, seq_length):
'''Create a generator that returns batches of size
batch_size x seq_length from arr.
Arguments
---------
arr: Array you want to make batches from
batch_size: Batch size, the number of sequences per batch
seq_length: Numb... | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Test Your ImplementationNow I'll make some data sets and we can check out what's going on as we batch data. Here, as an example, I'm going to use a batch size of 8 and 50 sequence steps. | batches = get_batches(encoded, 8, 50)
x, y = next(batches)
# printing out the first 10 items in a sequence
print('x\n', x[:10, :10])
print('\ny\n', y[:10, :10]) | x
[[52 66 23 3 30 72 76 2 26 36]
[71 50 82 2 30 66 23 30 2 23]
[72 82 57 2 50 76 2 23 2 20]
[71 2 30 66 72 2 48 66 25 72]
[ 2 71 23 29 2 66 72 76 2 30]
[48 33 71 71 25 50 82 2 23 82]
[ 2 74 82 82 23 2 66 23 57 2]
[34 14 56 50 82 71 0 44 65 2]]
y
[[66 23 3 30 72 76 2 26 36 36]
[50 82 2 30 6... | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
If you implemented `get_batches` correctly, the above output should look something like ```x [[25 8 60 11 45 27 28 73 1 2] [17 7 20 73 45 8 60 45 73 60] [27 20 80 73 7 28 73 60 73 65] [17 73 45 8 27 73 66 8 46 27] [73 17 60 12 73 8 27 28 73 45] [66 64 17 17 46 7 20 73 60 20] [73 76 20 20 60 73 8 60 80 73] [4... | # check if GPU is available
train_on_gpu = torch.cuda.is_available()
if(train_on_gpu):
print('Training on GPU!')
else:
print('No GPU available, training on CPU; consider making n_epochs very small.')
class CharRNN(nn.Module):
def __init__(self, tokens, n_hidden=256, n_layers=2,
... | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Time to trainThe train function gives us the ability to set the number of epochs, the learning rate, and other parameters.Below we're using an Adam optimizer and cross entropy loss since we are looking at character class scores as output. We calculate the loss and perform backpropagation, as usual!A couple of details ... | from tqdm import tqdm
def train(net, data, epochs=10, batch_size=10, seq_length=50,
lr=0.001, clip=5, val_frac=0.1, print_every=10):
''' Training a network
Arguments
---------
net: CharRNN network
data: text data to train the network
epochs: Nu... | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Instantiating the modelNow we can actually train the network. First we'll create the network itself, with some given hyperparameters. Then, define the mini-batches sizes, and start training! | # define and print the net
n_hidden=256
n_layers=2
net = CharRNN(chars, n_hidden, n_layers)
print(net) | CharRNN(
(lstm): LSTM(83, 256, num_layers=2, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.5)
(fc): Linear(in_features=256, out_features=83, bias=True)
)
| Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Set your training hyperparameters! | batch_size = 128
seq_length = 75
n_epochs = 5 # start small if you are just testing initial behavior
# train the model
train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001, print_every=10) |
0%| | 0/5 [00:00<?, ?it/s][A | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Getting the best modelTo set your hyperparameters to get the best performance, you'll want to watch the training and validation losses. If your training loss is much lower than the validation loss, you're overfitting. Increase regularization (more dropout) or use a smaller network. If the training and validation losse... | # change the name, for saving multiple files
model_name = 'rnn_sayak_5.net'
checkpoint = {'n_hidden': net.n_hidden,
'n_layers': net.n_layers,
'state_dict': net.state_dict(),
'tokens': net.chars}
with open(model_name, 'wb') as f:
torch.save(checkpoint, f) | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
--- Making PredictionsNow that the model is trained, we'll want to sample from it and make predictions about next characters! To sample, we pass in a character and have the network predict the next character. Then we take that character, pass it back in, and get another predicted character. Just keep doing this and you... | def predict(net, char, h=None, top_k=None):
''' Given a character, predict the next character.
Returns the predicted character and the hidden state.
'''
# tensor inputs
x = np.array([[net.char2int[char]]])
x = one_hot_encode(x, len(net.chars))
inputs ... | _____no_output_____ | Apache-2.0 | Recurrent Neural Networks/Character_Level_RNN_Exercise.ipynb | sayakpaul/Favorite-Execises-from-Udacity-s-Deep-Learning-Course |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.