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 |
|---|---|---|---|---|---|
Hydrogen atom\begin{equation}\label{eq1}-\frac{\hbar^2}{2 \mu} \left[ \frac{1}{r^2} \frac{\partial }{\partial r} \left( r^2 \frac{ \partial \psi}{\partial r}\right) + \frac{1}{r^2 \sin \theta} \frac{\partial }{\partial \theta} \left( \sin \theta \frac{\partial \psi}{\partial \theta}\right) + \frac{1}{r^2 \sin^2 \theta... | import k3d
from ipywidgets import interact, FloatSlider
import numpy as np
import scipy.special
import scipy.misc
r = lambda x,y,z: np.sqrt(x**2+y**2+z**2)
theta = lambda x,y,z: np.arccos(z/r(x,y,z))
phi = lambda x,y,z: np.arctan2(y,x)
a0 = 1.
R = lambda r,n,l: (2*r/(n*a0))**l * np.exp(-r/n/a0) * scipy.special.genla... | _____no_output_____ | MIT | atomic_orbitals_wave_function.ipynb | OpenDreamKit/k3d_demo |
animation single wave function is sent at a time | E = 4
for l in range(E):
for m in range(-l,l+1):
psi2 = WF(r(x,y,z),theta(x,y,z),phi(x,y,z),E,l,m).real.astype(np.float32)
plt_vol.volume = psi2/np.max(psi2)
plt_label.text = 'n=%d \quad l=%d \quad m=%d'%(E,l,m)
| _____no_output_____ | MIT | atomic_orbitals_wave_function.ipynb | OpenDreamKit/k3d_demo |
using time series - series of volumetric data are sent to k3d, - player interpolates between | E = 4
psi_t = {}
t = 0.0
for l in range(E):
for m in range(-l,l+1):
psi2 = WF(r(x,y,z),theta(x,y,z),phi(x,y,z),E,l,m)
psi_t[str(t)] = (psi2.real/np.max(np.abs(psi2))).astype(np.float32)
t += 0.3
plt_vol.volume = psi_t
| _____no_output_____ | MIT | atomic_orbitals_wave_function.ipynb | OpenDreamKit/k3d_demo |
 Demo text-mining: Pharma caseIn this demo, I will demonstrate what are the basic steps that you will have to use in most text-mining cases. This are also some of the steps that have been used in the ResuMe app, available here: [ResuMe](https:... | #import documents from PubMed
from Bio import Entrez
# Function to search for a certain number articles based on a certain keyword
def search(keyword,number=20):
Entrez.email = 'your.email@example.com'
handle = Entrez.esearch(db='pubmed',
sort='relevance',
... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Retrieving top 200 articles with Pharmacovigilance keyword | results = search('Pharmacovigilance', 200) #querying PubMed
id_list = results['IdList']
papers_pharmacov = fetch_details(id_list) #retrieving the info about the articles in nested lists & dictionary format
# checking article title for the first 10 retrieved articles
for i, paper in enumerate(papers_pharmacov['PubmedArt... | 1) FarmaREL: An Italian pharmacovigilance project to monitor and evaluate adverse drug reactions in haematologic patients.
2) Feasibility and Educational Value of a Student-Run Pharmacovigilance Programme: A Prospective Cohort Study.
3) Developing a Crowdsourcing Approach and Tool for Pharmacovigilance Education Materi... | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Retrieving top 1.000 articles with Pharma keywordThis will be our base of comparison, we want to separate them from the others | results = search('Pharma', 1000) #querying PubMed
id_list = results['IdList']
papers_pharma = fetch_details(id_list)#retrieving the info about the articles in nested lists & dictionary format
# checking article title for the first 10 retrieved articles
for i, paper in enumerate(papers_pharma['PubmedArticle'][:10]):
... | 1) Recent trends in specialty pharma business model.
2) The moderating role of absorptive capacity and the differential effects of acquisitions and alliances on Big Pharma firms' innovation performance.
3) Space-related pharma-motifs for fast search of protein binding motifs and polypharmacological targets.
4) Pharma W... | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Saving ID's, labels and title + abstracts of the articlesWhen an article was retrieved via the Pharmacovigilance keyword, it will receive the label = 1 and = 0 else. We'll per article put the article title and article abstract together as our text data on the article. | # Save ids & label 1 = pharmacovigilance , 0 = not pharmacovigilance
# & Save title + abstract in dico
ids = []
labels = []
data = []
for i, paper in enumerate(papers_pharmacov['PubmedArticle']):
if 'Abstract' in paper['MedlineCitation']['Article'].keys(): #check that abstract info is available
ids.append... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Transform to numeric attributesWe will now **transform** the **text into numeric attributes**. For this, we will convert every word to a number, but we first need to **split** the full text into **separate words**. This is done by using a ***Tokenizer***. The tokenizer will split the full text based on a certain patte... | from nltk.tokenize.regexp import RegexpTokenizer #import a tokenizer, to split the full text into separate words
def Tokenize_text_value(value):
tokenizer1 = RegexpTokenizer(r"[A-Za-z]+") # our self defined tokenizera
value = value.lower() # convert all words to lowercase
return tokenizer1.tokenize(value... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Using the ***bag-of-words*** method we can transform any document to a vector. Using this method you have **one column per word and one row per document** and either a binary value 1 if the word is present in a certain document, 0 if not or a count value of the number of times the word appears in the document. For inst... | # transform non-processed data to nummeric features:
from sklearn.feature_extraction.text import TfidfVectorizer
binary_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', binary = True,
tokenizer=Tokenize_text_value) # initialize the binary vectorizer
count_vect... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Check performance in a basic modelWe'll apply now a model on our 2 matrices. For this we will use the ***Naive Bayes model***, which (as the name tells) is based on the probabilistic Bayes theorem. It is used a lot in text-mining as it is really **fast** to train and apply and is able to **handle a lot of features**, ... | # apply cross validation Naive Bayes model
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import (cohen_kappa_score, make_scorer)
NB = MultinomialNB() # our Naive Bayes Model initialisation
scorer = make_scorer(cohen_kappa_score) # Our kappa score... | Cross validation on Count matrix with a mean kappa score of 0.064193 and variance of 0.000682
| MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
TF-IDF transformationAn alternative to the binary and count matrix is the **tf-idf transformation**. It stands for ***Term Frequency - Inverse Document Frequency*** and is a measure that will try to find the words that are unique to each document and that characterizes the document compared to the other documents. How... | # transform non-processed data to nummeric features:
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', use_idf=True, smooth_idf = True ,
tokenizer=Tokenize_text_value) # initialize the tf-idf vec... | Cross validation on TF-IDF matrix with a mean kappa score of 0.320332 and variance of 0.003960
| MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
How to improve this score? How come the TF-IDF works the best, followed closely by the binary matrix and with the count matrix far behind? Let's have a look at the words that occur the most in the different documents: | import numpy as np
# Find words with maximum occurence for each document in the count_matrix
max_counts_per_doc = np.asarray(np.argmax(count_matrix,axis = 1)).ravel()
# Count how many times every word is the most occuring word across all documents
unique, counts = np.unique(max_counts_per_doc,return_counts=True)
# Keep... | a
and
for
in
of
the
to
with
| MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
As you can see those words are all words without any added value as they are mostly used to link certain words together in sentences, but have no standalone value. This is what we call ***Stop words***. So knowing that, we can find an intuition of why the tf-idf and binary transformations worked better than the count o... | # Remove the stop words
binary_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', binary = True,
tokenizer=Tokenize_text_value, stop_words = 'english') # initialize the binary vectorizer
count_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', use_... | Cross validation on TF-IDF matrix by removing stop-words with a mean kappa score of 0.682766 and variance of 0.011562
| MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
We have a big improvement in our performance when we remove the stop words. How can we go a step further? Now the following steps are mostly domain dependent. You have to think about your problem and what you would need to solve it. In this case, if we are using only the abstracts and the titles, if we had to do it our... | # keep only words that appear at least in 5% of the documents:
binary_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', binary = True,
tokenizer=Tokenize_text_value, stop_words = 'english'
, min_df = 0.05) # initialize th... | Cross validation on TF-IDF matrix by keeping only keywords appearing in at least 5% of the documents with a mean kappa score of 0.916734 and variance of 0.001633
| MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
Final improvementsWe've made a big improvement with this one as well. We can even go further and add some extra fine-tunings. Let's have a look at the final key-words: | tfidf_vectorizer.get_feature_names() | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
We can see that some words all refer to the same thing: *report, reported, reporting, reports* all refer to one same thing *report* and should therefore be grouped together => this can be done by ***stemming*** StemmingStemming is a technique where we try to reduce words to a common base form, this is done by chopping ... | # Define a stemmer that will preprocess the text before transforming it
from nltk.stem.porter import PorterStemmer
def preprocess(value):
stemmer = PorterStemmer()
#split in tokens
return ' '.join([stemmer.stem(i) for i in Tokenize_text_value(value) ])
# Have a look at what it gives on the first arti... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
We can see that the performance slightly decreases with the stemming. Probably, because now when we are keeping words that appear in only 5% of the documents, we have more words than before, as before words with different endings were counted separately and now they are grouped together. So to correct for this we shoul... | # Preprocess the documents by stemming the words and keeping only words that appear in at least 10% of the documents:
binary_vectorizer = TfidfVectorizer(input=u'content', analyzer=u'word', binary = True,
tokenizer=Tokenize_text_value, stop_words = 'english'
... | _____no_output_____ | MIT | Text-Mining Hands-on.ipynb | tdekelver-bd/ResuMe |
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Challenge Notebook Problem: Implement a priority queue backed by an array.* [Constraints](Constraints)* [Test Cases](Test-Cases)* [Algorit... | class PriorityQueueNode(object):
def __init__(self, obj, key):
self.obj = obj
self.key = key
def __repr__(self):
return str(self.obj) + ': ' + str(self.key)
class PriorityQueue(object):
def __init__(self):
self.array = []
def __len__(self):
return len(self.a... | _____no_output_____ | Apache-2.0 | arrays_strings/priority_queue_(unsolved)/priority_queue_challenge.ipynb | zzong2006/interactive-coding-challenges |
Unit Test **The following unit test is expected to fail until you solve the challenge.** | # %load test_priority_queue.py
import unittest
class TestPriorityQueue(unittest.TestCase):
def test_priority_queue(self):
priority_queue = PriorityQueue()
self.assertEqual(priority_queue.extract_min(), None)
priority_queue.insert(PriorityQueueNode('a', 20))
priority_queue.insert(P... | _____no_output_____ | Apache-2.0 | arrays_strings/priority_queue_(unsolved)/priority_queue_challenge.ipynb | zzong2006/interactive-coding-challenges |
pIC50 Test | import numpy as np
import torch
import seaborn as sns
import malt
import pandas as pd
import dgllife
from dgllife.utils import smiles_to_bigraph, CanonicalAtomFeaturizer, CanonicalBondFeaturizer
df = pd.read_csv('../../../data/moonshot_pIC50.csv', index_col=0)
dgllife_dataset = dgllife.data.csv_dataset.MoleculeCSVData... | _____no_output_____ | MIT | scripts/supervised/pIC50_test.ipynb | choderalab/malt |
Make model | model_choice = 'nn' # 'nn'
if model_choice == "gp":
model = malt.models.supervised_model.GaussianProcessSupervisedModel(
representation=malt.models.representation.DGLRepresentation(
out_features=128,
),
regressor=malt.models.regressor.ExactGaussianProcessRegressor(
in... | _____no_output_____ | MIT | scripts/supervised/pIC50_test.ipynb | choderalab/malt |
Train and evaluate. | trainer = malt.trainer.get_default_trainer(
without_player=True,
batch_size=32,
n_epochs=3000,
learning_rate=1e-3
)
model = trainer(model, ds_tr)
r2 = malt.metrics.supervised_metrics.R2()(model, ds_te)
print(r2)
rmse = malt.metrics.supervised_metrics.RMSE()(model, ds_te)
print(rmse)
ds_te_loader = ds_... | _____no_output_____ | MIT | scripts/supervised/pIC50_test.ipynb | choderalab/malt |
Inference and ValidationNow that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen be... | import torch
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/... | _____no_output_____ | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
Here I'll create a model like normal, using the same one from my solution for part 4. | from torch import nn, optim
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
def forward(s... | _____no_output_____ | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.or... | model = Classifier()
images, labels = next(iter(testloader))
# Get the class probabilities
ps = torch.exp(model(images))
# Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples
print(ps.shape) | torch.Size([64, 10])
| MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as ... | top_p, top_class = ps.topk(1, dim=1)
# Look at the most likely classes for the first 10 examples
print(top_class[:10,:]) | tensor([[0],
[3],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0]])
| MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `l... | equals = top_class == labels.view(*top_class.shape) | _____no_output_____ | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a c... | accuracy = torch.mean(equals.type(torch.FloatTensor))
print(f'Accuracy: {accuracy.item()*100}%') | Accuracy: 20.3125%
| MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up our code by t... | model = Classifier()
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
epochs = 30
steps = 0
train_losses, test_losses = [], []
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
optimizer.zero_grad()
log_ps = model(images)... | Epoch: 1/30.. Training Loss: 0.511.. Test Loss: 0.455.. Test Accuracy: 0.839
Epoch: 2/30.. Training Loss: 0.392.. Test Loss: 0.411.. Test Accuracy: 0.846
Epoch: 3/30.. Training Loss: 0.353.. Test Loss: 0.403.. Test Accuracy: 0.853
Epoch: 4/30.. Training Loss: 0.333.. Test Loss: 0.376.. Test Accuracy: 0.867
... | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
OverfittingIf we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting.The network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the va... | ## TODO: Define your model with dropout added
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 = nn.Linear(64, 10)
self.dropout = nn.Dropou... | _____no_output_____ | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
InferenceNow that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context. | # Import helper module (should be in the repo)
import helper
# Test out your network!
model.eval()
dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[0]
# Convert 2D image to 1D vector
img = img.view(1, 784)
# Calculate the class probabilities (softmax) for img
with torch.no_grad():
outpu... | _____no_output_____ | MIT | intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb | adilfaiz001/deep-learning-v2-pytorch |
Requirements | # !pip install --upgrade transformers bertviz checklist | _____no_output_____ | Apache-2.0 | notebooks/old/DeprecatedTitles_t0_gpt.ipynb | IlyaGusev/NewsCausation |
Data loading | # !rm -rf ru_news_cause_v1.tsv*
# !wget https://www.dropbox.com/s/kcxnhjzfut4guut/ru_news_cause_v1.tsv.tar.gz
# !tar -xzvf ru_news_cause_v1.tsv.tar.gz
# !cat ru_news_cause_v1.tsv | wc -l
# !head ru_news_cause_v1.tsv | _____no_output_____ | Apache-2.0 | notebooks/old/DeprecatedTitles_t0_gpt.ipynb | IlyaGusev/NewsCausation |
GPTCause | from transformers import GPT2LMHeadModel, GPT2TokenizerFast
device = 'cuda'
model_id = 'sberbank-ai/rugpt3small_based_on_gpt2'
model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
import torch
max_length = model.config.n_positions
def gpt_assess(s1, s2... | 11.083624
23.637806
(1, 2.1326785)
(0, 0.46889395)
| Apache-2.0 | notebooks/old/DeprecatedTitles_t0_gpt.ipynb | IlyaGusev/NewsCausation |
Scoring | import csv
labels = []
texts = []
preds = []
confs = []
with open("ru_news_cause_v1.tsv", "r", encoding='utf-8') as r:
reader = csv.reader(r, delimiter="\t")
header = next(reader)
for row in reader:
r = dict(zip(header, row))
if float(r["confidence"]) < 0.69:
continue
r... | _____no_output_____ | Apache-2.0 | notebooks/old/DeprecatedTitles_t0_gpt.ipynb | IlyaGusev/NewsCausation |
CS224N Assignment 1: Exploring Word Vectors (25 Points) Due 4:30pm, Tue Jan 14 Welcome to CS224n! Before you start, make sure you read the README.txt in the same directory as this notebook. You will find many provided codes in the notebook. We highly encourage you to read and understand the provided codes as part of ... | # All Import Statements Defined Here
# Note: Do not add to this list.
# ----------------
import sys
assert sys.version_info[0]==3
assert sys.version_info[1] >= 5
from gensim.models import KeyedVectors
from gensim.test.utils import datapath
import pprint
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] =... | [nltk_data] Downloading package reuters to
[nltk_data] /usr/local/share/nltk_data...
[nltk_data] Package reuters is already up-to-date!
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Word VectorsWord Vectors are often used as a fundamental component for downstream NLP tasks, e.g. question answering, text generation, translation, etc., so it is important to build some intuitions as to their strengths and weaknesses. Here, you will explore two types of word vectors: those derived from *co-occurrence... | def read_corpus(category="crude"):
""" Read files from the specified Reuter's category.
Params:
category (string): category name
Return:
list of lists, with words from each of the processed files
"""
files = reuters.fileids(category)
return [[START_TOKEN] + [w.low... | _____no_output_____ | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Let's have a look what these documents are like…. | reuters_corpus = read_corpus()
pprint.pprint(reuters_corpus[:3], compact=True, width=100) | [['<START>', 'japan', 'to', 'revise', 'long', '-', 'term', 'energy', 'demand', 'downwards', 'the',
'ministry', 'of', 'international', 'trade', 'and', 'industry', '(', 'miti', ')', 'will', 'revise',
'its', 'long', '-', 'term', 'energy', 'supply', '/', 'demand', 'outlook', 'by', 'august', 'to',
'meet', 'a', 'foreca... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Question 1.1: Implement `distinct_words` [code] (2 points)Write a method to work out the distinct words (word types) that occur in the corpus. You can do this with `for` loops, but it's more efficient to do it with Python list comprehensions. In particular, [this](https://coderwall.com/p/rcmaea/flatten-a-list-of-lists... | def distinct_words(corpus):
""" Determine a list of distinct words for the corpus.
Params:
corpus (list of list of strings): corpus of documents
Return:
corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function)
... | --------------------------------------------------------------------------------
Passed All Tests!
--------------------------------------------------------------------------------
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Question 1.2: Implement `compute_co_occurrence_matrix` [code] (3 points)Write a method that constructs a co-occurrence matrix for a certain window-size $n$ (with a default of 4), considering words $n$ before and $n$ after the word in the center of the window. Here, we start to use `numpy (np)` to represent vectors, ma... | def compute_co_occurrence_matrix(corpus, window_size=4):
""" Compute co-occurrence matrix for the given corpus and window_size (default of 4).
Note: Each word in a document should be at the center of a window. Words near edges will have a smaller
number of co-occurring words.
... | --------------------------------------------------------------------------------
Passed All Tests!
--------------------------------------------------------------------------------
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Question 1.3: Implement `reduce_to_k_dim` [code] (1 point)Construct a method that performs dimensionality reduction on the matrix to produce k-dimensional embeddings. Use SVD to take the top k components and produce a new matrix of k-dimensional embeddings. **Note:** All of numpy, scipy, and scikit-learn (`sklearn`) p... | def reduce_to_k_dim(M, k=2):
""" Reduce a co-occurence count matrix of dimensionality (num_corpus_words, num_corpus_words)
to a matrix of dimensionality (num_corpus_words, k) using the following SVD function from Scikit-Learn:
- http://scikit-learn.org/stable/modules/generated/sklearn.decomposit... | Running Truncated SVD over 10 words...
Done.
--------------------------------------------------------------------------------
Passed All Tests!
--------------------------------------------------------------------------------
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Question 1.4: Implement `plot_embeddings` [code] (1 point)Here you will write a function to plot a set of 2D vectors in 2D space. For graphs, we will use Matplotlib (`plt`).For this example, you may find it useful to adapt [this code](https://www.pythonmembers.club/2018/05/08/matplotlib-scatter-plot-annotate-set-text-... | def plot_embeddings(M_reduced, word2Ind, words):
""" Plot in a scatterplot the embeddings of the words specified in the list "words".
NOTE: do not plot all the words listed in M_reduced / word2Ind.
Include a label next to each point.
Params:
M_reduced (numpy matrix of sh... | --------------------------------------------------------------------------------
Outputted Plot:
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
**Test Plot Solution** Question 1.5: Co-Occurrence Plot Analysis [written] (3 points)Now we will put together all the parts you have written! We will compute the co-occurrence matrix with fixed window of 4 (the default window size), over the Reuters "crude" (oil) corpus. Then we will use TruncatedSVD to compute 2-dim... | # -----------------------------
# Run This Cell to Produce Your Plot
# ------------------------------
reuters_corpus = read_corpus()
M_co_occurrence, word2Ind_co_occurrence = compute_co_occurrence_matrix(reuters_corpus)
M_reduced_co_occurrence = reduce_to_k_dim(M_co_occurrence, k=2)
# Rescale (normalize) the rows to m... | Running Truncated SVD over 8185 words...
Done.
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
The 'ecuador', 'energy', 'kuwait', 'oil', 'output', 'venezuela' cluster together which is intuitive.And the 'bpd', 'barrels' doesn't cluster together which should have. Part 2: Prediction-Based Word Vectors (15 points)As discussed in class, more recently prediction-based word vectors have demonstrated better performan... | def load_embedding_model():
""" Load GloVe Vectors
Return:
wv_from_bin: All 400000 embeddings, each lengh 200
"""
import gensim.downloader as api
wv_from_bin = api.load("glove-wiki-gigaword-200")
print("Loaded vocab size %i" % len(wv_from_bin.vocab.keys()))
return wv_from_bin... | Loaded vocab size 400000
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Note: If you are receiving reset by peer error, rerun the cell to restart the download. Reducing dimensionality of Word EmbeddingsLet's directly compare the GloVe embeddings to those of the co-occurrence matrix. In order to avoid running out of memory, we will work with a sample of 10000 GloVe vectors instead.Run th... | def get_matrix_of_vectors(wv_from_bin, required_words=['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']):
""" Put the GloVe vectors into a matrix M.
Param:
wv_from_bin: KeyedVectors object; the 400000 GloVe vectors loaded from file
R... | Shuffling words ...
Putting 10000 words into word2Ind and matrix M...
Done.
Running Truncated SVD over 10010 words...
Done.
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
**Note: If you are receiving out of memory issues on your local machine, try closing other applications to free more memory on your device. You may want to try restarting your machine so that you can free up extra memory. Then immediately run the jupyter notebook and see if you can load the word vectors properly. If yo... | words = ['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']
plot_embeddings(M_reduced_normalized, word2Ind, words) | _____no_output_____ | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
venezuela with ecuador and industry with energy cluster together. petroleum and oil shoulf cluster together.The plot contine more semantic information than the co-occurrence matrix method.Maybe the counter of word is small in the data set. Cosine SimilarityNow that we have word vectors, we need a way to quantify the s... | # ------------------
# Write your implementation here.
wv_from_bin.most_similar("run")
# ------------------ | _____no_output_____ | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
The run have running and start two meaning. Question 2.3: Synonyms & Antonyms (2 points) [code + written] When considering Cosine Similarity, it's often more convenient to think of Cosine Distance, which is simply 1 - Cosine Similarity.Find three words (w1,w2,w3) where w1 and w2 are synonyms and w1 and w3 are antonyms... | # ------------------
# Write your implementation here.
w1 = "design"
w2 = "proposal"
w3 = "borrow"
w12_dist = wv_from_bin.distance(w1, w2)
w13_dist = wv_from_bin.distance(w1, w3)
print("Synonyms {}, {} have cosine distance: {:.2f}".format(w1, w2, w12_dist))
print("Antonyms {}, {} have cosine distance: {:.2f}".format(w1... | Synonyms design, proposal have cosine distance: 0.69
Antonyms design, borrow have cosine distance: 0.90
| MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Comapring proposal and design, the cosine distrance is 0.69. And the cosine distance between design and borrow is 0.9. Solving Analogies with Word VectorsWord vectors have been shown to *sometimes* exhibit the ability to solve analogies. As an example, for the analogy "man : king :: woman : x" (read: man is to king as... | # Run this cell to answer the analogy -- man : king :: woman : x
pprint.pprint(wv_from_bin.most_similar(positive=['woman', 'king'], negative=['man'])) | [('queen', 0.6978678703308105),
('princess', 0.6081745028495789),
('monarch', 0.5889754891395569),
('throne', 0.5775108933448792),
('prince', 0.5750998854637146),
('elizabeth', 0.546359658241272),
('daughter', 0.5399125814437866),
('kingdom', 0.5318052768707275),
('mother', 0.5168544054031372),
('crown', 0.516... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Question 2.4: Finding Analogies [code + written] (2 Points)Find an example of analogy that holds according to these vectors (i.e. the intended word is ranked top). In your solution please state the full analogy in the form x:y :: a:b. If you believe the analogy is complicated, explain why the analogy holds in one or ... | # ------------------
# Write your implementation here.
pprint.pprint(wv_from_bin.most_similar(positive=['woman', 'waitress'], negative=['man']))
# ------------------ | [('barmaid', 0.6116799116134644),
('bartender', 0.5877381563186646),
('receptionist', 0.5782569646835327),
('waiter', 0.5508327484130859),
('waitresses', 0.5503603219985962),
('hostess', 0.5346562266349792),
('housekeeper', 0.5310243368148804),
('homemaker', 0.5298492908477783),
('prostitute', 0.525412440299987... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
woman:man::waitress:waiter, through the probability of waiter isn't the maximum. Question 2.5: Incorrect Analogy [code + written] (1 point)Find an example of analogy that does *not* hold according to these vectors. In your solution, state the intended analogy in the form x:y :: a:b, and state the (incorrect) value of ... | # ------------------
# Write your implementation here.
pprint.pprint(wv_from_bin.most_similar(positive=['high', 'jump'], negative=['low']))
# ------------------ | [('jumping', 0.6205310225486755),
('jumps', 0.5840020775794983),
('leap', 0.5402169823646545),
('jumper', 0.4817255735397339),
('climb', 0.4797284007072449),
('bungee', 0.464731365442276),
('championships', 0.4643418788909912),
('jumped', 0.46396756172180176),
('triple', 0.4550389349460602),
('throw', 0.451687... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
the high:low shoudle == jump:fall, but the fall not in the top 10 probability list. Question 2.6: Guided Analysis of Bias in Word Vectors [written] (1 point)It's important to be cognizant of the biases (gender, race, sexual orientation etc.) implicit in our word embeddings. Bias can be dangerous because it can reinfor... | # Run this cell
# Here `positive` indicates the list of words to be similar to and `negative` indicates the list of words to be
# most dissimilar from.
pprint.pprint(wv_from_bin.most_similar(positive=['woman', 'worker'], negative=['man']))
print()
pprint.pprint(wv_from_bin.most_similar(positive=['man', 'worker'], negat... | [('employee', 0.6375863552093506),
('workers', 0.6068919897079468),
('nurse', 0.5837947726249695),
('pregnant', 0.5363885164260864),
('mother', 0.5321309566497803),
('employer', 0.5127025842666626),
('teacher', 0.5099576711654663),
('child', 0.5096741914749146),
('homemaker', 0.5019454956054688),
('nurses', 0.... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
The word most similar to "woman" and "worker" and most dissimilar to "man" is nurses.Most nurses are woman.The word most similar to "man" and "worker" and most dissimilar to "woman" is factory.The factory have many worker man. Question 2.7: Independent Analysis of Bias in Word Vectors [code + written] (1 point)Use th... | # ------------------
# Write your implementation here.
pprint.pprint(wv_from_bin.most_similar(positive=['elephant', 'skyscraper'], negative=['ant']))
print()
pprint.pprint(wv_from_bin.most_similar(positive=['motorcycle', 'car'], negative=['bicycle']))
# ------------------ | [('tower', 0.49941301345825195),
('skyscrapers', 0.48599374294281006),
('tallest', 0.46377506852149963),
('statue', 0.4558914303779602),
('towers', 0.44428494572639465),
('40-story', 0.4247894287109375),
('monument', 0.4171640872955322),
('high-rise', 0.41149571537971497),
('bust', 0.408037006855011),
('gleami... | MIT | CS224n/assignment1/exploring_word_vectors.ipynb | iofu728/Task |
Plotting File for [Redistributing the Gains From Trade Through Progressive Taxation](http://www.waugheconomics.com/uploads/2/2/5/6/22563786/lw_tax.pdf)This notebook imports the output from the MATLAB code and then plots it. Description is below. | from IPython.display import display, Image # Displays things nicely
import pandas as pd
import weightedcalcs as wc
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from scipy.io import loadmat # this is the SciPy module that loads mat-files
#fig_... | C:\Program Files\Anaconda3\lib\site-packages\statsmodels\compat\pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
from pandas.core import datetools
| MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
--- Read in output from modelThis is the structure of the mat file and the naming conventions. Here it is assumed that the .mat files from Matlab are within the working directory. Then read it in, note the use of ``scipy`` package to get a .mat file into python. | #[params.trade_cost, trade, ls, move, output_per_hour, welfare, double(exit_flag)];
column_names = ["tau_p", "tau", "trade_volume", "ls", "migration", "output", "OPterm2", "welfare", "exitflag", "welfare_smth",
"trade_share"]
values = ["0.05","0.1", "0.2", "0.3", "0.4"]
all_df = pd.DataFrame([])
for ... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
Now define some functions that we will use... | def cons_eqiv(df):
maxwel = float(df["welfare_smth"][df["tau_p"] == 0.18])
df["cons_eqiv"] = 100*(np.exp((1-0.95)*(df["welfare_smth"] - maxwel))-1)
# These are consumptione equivialents.
return df | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
Group on the trade share values.... | grp = all_df.groupby("trade_share")
grp = grp.apply(cons_eqiv)
grp = grp.groupby("trade_share") | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
--- Optimal policy in the modelThen the next two code cells will replicate Figure 3 and Figure 6 in the paper... | fig, ax = plt.subplots(figsize = (10,7))
val = "0.1"
ax.plot(grp.get_group(val).tau_p, grp.get_group(val).cons_eqiv,
linewidth = 4, label = "Imports/GDP = " + val,
color = "blue",alpha = 0.70)
index_max = grp.get_group(val).cons_eqiv.idxmax()
tau_max = grp.get_group(val).tau_p.iloc[index_max]
ax.... | [0.10435983980994212, 0.34328431738519516, 0.7242843517205388, 1.3810768398272222]
[0.27, 0.32, 0.37, 0.44999999999999996]
[-0.8279921208671714, -1.3903253040046915, -1.9424125246026658, -2.628430117595859]
| MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
This finds the optimal tau... | opt_tau = []
tau = []
trade = []
for val in values:
index_max = grp.get_group(val).cons_eqiv.idxmax()
tau_star = grp.get_group(val).tau_p.iloc[index_max]
opt_tau.append(tau_star)
tau.append(grp.get_group(val).tau.iloc[index_max])
trade.append(float(val))
hold = ... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
This then generates the output cost figure, Figure 8 in the paper. | def smooth_reg(df, series):
specification = series + "~ tau_p + np.square(tau_p) + np.power(tau_p,3)+ np.power(tau_p,4)"
results = smf.ols(specification , # This is the model in variable names we want to estimate
data=df[df["exitflag"]==0]).fit()
pred = results.predict... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
This then generates the allocative efficiency (covariance term) figure, Figure 4 | fig, ax = plt.subplots(figsize = (10,7))
series = "output"
val = "0.1"
#baseline = float(grp.get_group(val)[grp.get_group(val).tau_p == 0.18][series])
ypred = smooth_reg(grp.get_group(val), series)
baseline = float(ypred[grp.get_group(val).tau_p == 0.18])
real = grp.get_group(val)[series]
index_max = grp.get_gro... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
Then the migration figure, Figure 5 | fig, ax = plt.subplots(figsize = (10,7))
series = "migration"
val = "0.1"
baseline = float(grp.get_group(val)[grp.get_group(val).tau_p == 0.18][series])
ypred = smooth_reg(grp.get_group(val), series)
ax.plot(grp.get_group(val).tau_p, 100*(ypred /baseline-1),
linewidth = 4, label = "Migration",
col... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
--- Marginal tax rates in the model | values_TAX = ["0.05","0.1b", "0.1", "0.2", "0.3", "0.4"]
mat = loadmat("opt_marg_rates")
marginal_rates = pd.DataFrame(mat["marg_rates"])
marginal_rates.columns = values_TAX
mat = loadmat("opt_incom_prct")
income_pct = pd.DataFrame(mat["incom_prct"])
income_pct.columns = values_TAX
def smooth_marg_rates(in... | _____no_output_____ | MIT | matlab/plot_model_data/plot_model_results.ipynb | mwaugh0328/redistributing_gains_from_trade |
在上面的例子中,数据存储为多维Numpy数组,也称为张量(tensor)。当前流行的机器学习系统都以张量作为基本数据结构。所以Google的TensorFlow也拿张量命名。那张量是什么呢?张量是数据的容器(container)。这里的数据一般是数值型数据,所以是数字的容器。大家所熟悉的矩阵是二维(2D)张量。张量是广义的矩阵,它的某一维也称为轴(axis)。 标量(Scalar,0D 张量)只包含一个数字的张量称为标量(或者数量张量,零维张量,0D张量)。在Numpy中,一个float32或者float64位的数值称为数量张量。Numpy张量可用其ndim属性显示轴的序数,数量张量有0个轴(ndim == 0)。张量的轴的序数也... | import numpy as np
x = np.array(12)
x
x.ndim | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
向量(1D张量)数字的数组也称为向量,或者一维张量(1D张量)。一维张量只有一个轴。 | x = np.array([12, 3, 6, 14])
x
x.ndim | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
该向量有5项,也称为5维的向量。但是不要混淆5D向量和5D张量!一个5D向量只有一个轴,以及沿该轴有5个维数(元素);然而一个5D张量有5个轴,并且沿每个轴可以有任意个的维数。维度既能表示沿某个轴的项的数量(比如,上面的5D向量),又能表示一个张量中轴的数量(比如,上面的5D张量),时常容易混淆。对于后者,用更准确地技术术语来讲,应该称为5阶张量(张量的阶即是轴的数量),但人们更常用的表示方式是5D张量。 矩阵(2D张量)向量的数组称为矩阵,或者二维张量(2D张量)。矩阵有两个轴,也常称为行和列。你可以将数字排成的矩形网格看成矩阵,下面是一个Numpy矩阵: | x = np.array([[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]])
x.ndim | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
沿着第一个轴的项称为行,沿着第二个轴的项称为列。上面的例子中,[5, 78, 2, 34, 0]是矩阵 x 第一行,[5, 6, 7]是第一列。矩阵的数组称为三维张量(3D张量),你可以将其看成是数字排列成的立方体,下面是一个Numpy三维张量(注意该三维张量内部的三个二维张量的shape一致,均为(3,5)。维度是一个自然数,形状则是一个元组): | x = np.array([[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]],
[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]],
[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]]])
x.ndim | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
题外话!若张量某维度的元素未对其,则这些元素成为list。 | x = np.array([[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]],
[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]],
[[5, 78, 2, 34, 0],
[7, 80, 4, 36, 2]]])
x
x.ndim | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
同理,将三维张量放进数组可以创建四维张量,其它更高维的张量亦是如此。深度学习中常用的张量是 0D 到 4D。如果处理视频数据,你会用到5D。 关键属性张量具有如下三个关键属性:1. 轴的数量(阶数,rank):一个三维张量有3个轴,矩阵有2个轴。Python Numpy中的张量维度为ndim。2. 形状(shape):它是一个整数元组,描述张量沿每个轴有多少维。例如,前面的例子中,矩阵的形状为(3,5),三维张量的形状为(3,3,5)。向量的形状只有一个元素,比如(5,),标量则是空形状,()。3. 数据类型:张量中包含的数据类型有float32,unit8,float64等等,调用Python的dtype属性获取。字符型张量是极... | from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data() | e:\program_files\miniconda3\envs\dl\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
U... | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
接着,用ndim属性显示张量train_images的轴数量: | print(train_images.ndim) | 3
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
打印形状: | print(train_images.shape) | (60000, 28, 28)
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
使用dtype属性打印数据类型: | print(train_images.dtype) | uint8
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
所以train_images是一个8-bit 整数的三维张量。更确切地说,它是一个包含60,000个矩阵的数组,其中每个矩阵是28 x 8 的整数。每个矩阵是一个灰度图,其值为0到255。下面使用Python Matplotlib库显示三维张量中的第四幅数字图,见图2.2: | #Listing 2.6 Dispalying the fourth digit
digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show() | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
注:这里使用 matplotlib.cm, cm 表示 colormap。 binary map:https://en.wikipedia.org/wiki/Binary_image digit 是从这个三维张量取出的一个矩阵(二维数组/张量): | print(digit.ndim,",",digit.shape) | 2 , (28, 28)
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Numpy中的张量操作上面的例子中,使用了train_images[i]沿第一个轴选择指定的数字图。选择张量的指定元素称为张量分片(tensor slicing),下面看Numpy数组中的张量切片操作: 选择10到100(不包括100)的数字图,对应的张量形状为(90,28,28): | my_slice = train_images[10:100]
print(my_slice.shape) | (90, 28, 28)
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
其等效的表示方法有,沿每个轴为张量分片指定起始索引和终止索引。注意,“:”等效于选择整个轴的数据: | my_slice = train_images[10:100, 0:28, 0:28]
my_slice.shape | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
一般,你可以沿着张量每个轴任意选择两个索引之间的元素。例如,选择所有图片的右下角的14 x 14的像素: | my_slice = train_images[:, 14:, 14:] | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
你也可以用负索引。就像Python list中的负索引一样,它表示相对于当前轴末端的位置。剪切图片中间14 x 14像素,使用如下的方法: | my_slice = train_images[:, 7:-7, 7:-7] | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
数据批(data batch)的概念总的来说,你在深度学习中即将接触的所有数据张量的第一轴(axis 0,since indexing starts at 0)就叫“样本轴”(samples axis,也叫“样本维”)。简单地说,MINIST例子中的“样本(samples)”就是那些数字图片。 另外,深度学习模型不会一次处理整个数据集,而是将数据集分解为若干个小批次。具体来讲,下面就是MNIST数据集中一个大小为128的批次。 | # Listing 2.23 Slicing a tensor into batches
batch = train_images[:128]
# and here's the next batch
batch = train_images[128:256]
# and the n-th batch:
#batch = train_images[128 * n: 128 * (n + 1)]
batch.shape | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
考虑这样一个批张量,第一轴(axis 0)就称为“批次轴”(batch axis)或“批次维数”(batch dimension)。这是一个术语,当你使用Keras或其他深度学习库时你会经常接触到。 现实中data tensors的例子让我们让数据张量更具体,还有一些类似于你稍后会遇到的例子。 你将操作的数据几乎总是属于下列类别之一:1. 向量数据:2D 张量,shape 为(samples,features)2. 时间序列数据或序列数据:3D 张量,shape 为(samples,timesteps,features)3. 图像: 4D 张量,shape 为(samples,width,height,channels)或者(... | #Listing 2.24 A Keras layer
#keras.layers.Dense(512, activation='relu') | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
这个神经网络层,可以用一个函数(function)来解释,这个函数输入一个2D张量,并返回另一个2D张量,这个张量是对输入张量的新描述。具体地,该方程为:  让我们来分解它。这个方程里面有三个张量操作:输入张量和W张量的点乘(dot),得到的2D张量和向量b的加(+)操作,最后是一个relu操作。rulu(x) 就是简单的 max(x,0)。 虽然这些操作完全是线性代数计算,但你会发现这里没有任何数学符号。因为我们发现当没有相应数学背景的编程人员使用Python语句而不是数学方程式时,他们更能够掌握。所以这里我们一直使用Numpy代码。 Element-w... | #Listing 2.25 A naive implemetation of an element-wise "relu" operation
def naive_relu(x):
# x is a 2D Numpy tensor
assert len(x.shape) == 2
x = x.copy() # Avoid overwrinting the input tensor
for i in range(x.shape[0]:
for j in range(x.shape[1]):
x[i, j] = max(x[i, j], 0)
... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
同样的,对于加法操作有: | #Listing 2.26 A naive implementation of element-wise addition
def naive_add(x, y):
# x and y are 2D Numpy tensors
assert len(x.shape) == 2
assert x.shape == y.shape
x = x.copy() # Avoid overwriting the input tensor
for i in range(x.shape[0]):
for j in range(x.shape[1]):
x[... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
使用相同的方法,我们可以实现element-wise multiplication,subtraction等运算。 In practice, when dealing with Numpy arrays, these operations are available as well-optimized built-in Numpy functions, which themselves delegate the heavy lifting to a BLAS implementation (Basic Linear Algebra Subprograms) if you have one installed, which yo... | # Listing 2.27 Naive element-wise operation in Numpy
import numpy as np
# Element-wise addtion
#z = x + y
# Element-wise relu
#z = np.maximum(z, 0.) | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Broadcasting In our naive implementation of above, we only support the addition of 2D naive_add tensors with identical shapes. But in the layer introduced earlier, we were adding a Dense 2D tensor with a vector. What happens with addition when the shape of the two tensors being added differ? When possible and if t... | # Y[i,:] = y for i in range(0, 32) | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
In terms of implementation, no new 2D tensor would actually be created since that would be terribly inefficient, so the repetition operation would be entirely virtual, i.e. it would be happening at the algorithmic level rather than at the memory level. But thinking of the vector being repeated 10 times alongside a new ... | def naive_add_matrix_and_vector(x, y):
# x is a 2D Numpy tensor
# y is a Numpy vector
assert len(x.shape) == 2
assert len(y.shape) == 1
assert x.shape[10] == y.shape[0]
x = x.copy() # Avoid overwriting the input tensor
for i in range(x.shape[0]):
for j in range(x.shape[1]):
... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
With broadcasting, you can generally apply two-tensor element-wise operations if one tensor has shape and the other has shape (a, b, … n, n + 1, … m) and the other has shpae (n, n + 1, ... m). The broadcasting would then automatically happen for axes a to n -1. You can thus do:(注意下面这里扩展的轴的维度为2,而不是1!) | ### Listing 2.29 Applying the element-wise operation to two tensors of maximum different shapes via broadcastin
import numpy as np
# x is a random tensor with shape (64, 3, 32, 10)
x = np.random.random((64, 3, 32, 10))
# y is a random tensor with shape (32, 10)
y = np.random.random((32, 10))
# The output z has shap... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Tensor dotdot操作, 也叫张量乘法(tensor product),不要将其和element-wise混淆。它是张量运算中最常见和最重要的。 与element-wise相反,它将输入张量中的元素组合在一起(组合有权重)。 Element-wise product is done with the * operator in Numpy, Keras, Theano and TensorFlow. uses a different syntax in TensorFlow, but in both Numpy and Keras it dot is done using the standard operator: | # Listing 2.30 Numpy operations between two tensors
import numpy as np
#z = np.dot(x, y) | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
In mathematical notation, you would note the operation with a dot . : z = x . y Mathematically, what does the dot operation do? Let’s start with the dot product of two vectors x and y. It is computed as such: | # Listing 2.31 A naive implementation of dot
def naive_vector_dot(x, y):
# x and y are Numpy vectors
assert len(x.shape) == 1
assert len(y.shape) == 1
assert x.shape[0] == y.shape[0]
z = 0.
for i in range(x.shape[0]):
z += x[i] * y[i]
return z | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
You will have noticed that the dot product between two vectors is a scalar, and that only vectors with the same number of elements are compatible for dot product. You can also take the dot product between a matrix x and a vector y, which returns a vector where coefficients are the dot products between y and the rows... | # Listing 2.32 A naive implementation of matrix-vector dot
import numpy as np
def naive_matrix_vector_dot(x, y):
# x is a Numpy matrix
# y is a Numpy vector
assert len(x.shape) == 2
assert len(y.shape) == 1
# The 1st dimension of x must be
# the same as the 0th dimension of y... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
You could also be reusing the code we wrote previously, which highlights the relationship between matrix-vector product and vector product: | # Listing 2.33 Alternative naive implementation of matrix-vector dot
def naive_matrix_vector_dot(x, y):
z = np.zeros(x.shape[0])
for i in range(x.shape[0]):
z[i] = naive_vector_dot(x[i, :], y)
return z | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Note that as soon as one of the two tensors has a higher than 1, is no longer ndim dot symmetric, which is to say that is not the same as . dot(x, y) dot(y, x) Of course, dot product generalizes to tensors with arbitrary number of axes. The most common applications may be the dot product between two matrices. You ca... | # Listing 2.34 A naive implementation of matrix-matrix dot
def naive_matrix_dot(x, y):
# x and y are Numpy matrices
assert len(x.shape) == 2
assert len(y.shape) == 2
# The 1st dimension of x must be
# the same as the 0th dimension of y!
assert x.shape[1] == y.shape[0]
... | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
To understand dot product shape compatibility, it helps to visualize the input and output tensors by aligning them in the following way: x, y and z are pictured as rectangles (literal boxes of coefficients). Because the rows and x and the columns of y must have the same size, it follow... | # Listing 2.35 MNIST image tensor reshaping
#train_images = train_images.reshape((60000, 28 * 28) | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Reshaping a tensor means re-arranging its rows and columns so as to match a target shape. Naturally the reshaped tensor will have the same total number of coefficients as the initial tensor. Reshaping is best understood via simple examples:对一个张量的reshape意味着重新调整张量的行和列,以适配目标shape。所以reshape后地张量和原始的张量自然而然地拥有着相同总数的参数。reshpe可... | # Listing 2.36 Tensor reshaping example
x = np.array([[0., 1.],
[2., 3.],
[4., 5.]])
print(x.shape)
x = x.reshape((6, 1))
x
x = x.reshape((2, 3))
x | _____no_output_____ | MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
A special case of reshaping that is commonly encountered is the transposition. "Transposing" a matrix means exchanging its rows and its columns, so that x[i, :] becomes : | # Listing 2.37 Matrix transposition
x = np.zeros((300, 20))
# Creates an all-zeros matrix of shape (300, 20)
x = np.transpose(x)
print(x.shape) | (20, 300)
| MIT | .ipynb_checkpoints/2.2&2.3 Data-representation-fo-neura-networks_cn &The-gears-of-neural-networks-tensor-operations -checkpoint.ipynb | ViolinLee/deep-learning-with-python-notebooks |
Neural Machine TranslationWelcome to your first programming assignment for this week! You will build a Neural Machine Translation (NMT) model to translate human readable dates ("25th of June, 2009") into machine readable dates ("2009-06-25"). You will do this using an attention model, one of the most sophisticated seq... | from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply
from keras.layers import RepeatVector, Dense, Activation, Lambda
from keras.optimizers import Adam
from keras.utils import to_categorical
from keras.models import load_model, Model
import keras.backend as K
import numpy as np
from... | Using TensorFlow backend.
| MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
1 - Translating human readable dates into machine readable datesThe model you will build here could be used to translate from one language to another, such as translating from English to Hindi. However, language translation requires massive datasets and usually takes days of training on GPUs. To give you a place to ex... | m = 10000
dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
dataset[:10] | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
You've loaded:- `dataset`: a list of tuples of (human readable date, machine readable date)- `human_vocab`: a python dictionary mapping all characters used in the human readable dates to an integer-valued index - `machine_vocab`: a python dictionary mapping all characters used in machine readable dates to an integer-va... | Tx = 30
Ty = 10
X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)
print("X.shape:", X.shape)
print("Y.shape:", Y.shape)
print("Xoh.shape:", Xoh.shape)
print("Yoh.shape:", Yoh.shape) | X.shape: (10000, 30)
Y.shape: (10000, 10)
Xoh.shape: (10000, 30, 37)
Yoh.shape: (10000, 10, 11)
| MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
You now have:- `X`: a processed version of the human readable dates in the training set, where each character is replaced by an index mapped to the character via `human_vocab`. Each date is further padded to $T_x$ values with a special character (). `X.shape = (m, Tx)`- `Y`: a processed version of the machine readable ... | index = 0
print("Source date:", dataset[index][0])
print("Target date:", dataset[index][1])
print()
print("Source after preprocessing (indices):", X[index])
print("Target after preprocessing (indices):", Y[index])
print()
print("Source after preprocessing (one-hot):", Xoh[index])
print("Target after preprocessing (one-... | Source date: 15 october 1986
Target date: 1986-10-15
Source after preprocessing (indices): [ 4 8 0 26 15 30 26 14 17 28 0 4 12 11 9 36 36 36 36 36 36 36 36 36 36
36 36 36 36 36]
Target after preprocessing (indices): [ 2 10 9 7 0 2 1 0 2 6]
Source after preprocessing (one-hot): [[ 0. 0. 0. ..., 0. 0.... | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
2 - Neural machine translation with attentionIf you had to translate a book's paragraph from French to English, you would not read the whole paragraph, then close the book and translate. Even during the translation process, you would read/re-read and focus on the parts of the French paragraph corresponding to the part... | # Defined shared layers as global variables
repeator = RepeatVector(Tx)
concatenator = Concatenate(axis=-1)
densor1 = Dense(10, activation = "tanh")
densor2 = Dense(1, activation = "relu")
activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook
dotor =... | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Now you can use these layers to implement `one_step_attention()`. In order to propagate a Keras tensor object X through one of these layers, use `layer(X)` (or `layer([X,Y])` if it requires multiple inputs.), e.g. `densor(X)` will propagate X through the `Dense(1)` layer defined above. | # GRADED FUNCTION: one_step_attention
def one_step_attention(a, s_prev):
"""
Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights
"alphas" and the hidden states "a" of the Bi-LSTM.
Arguments:
a -- hidden state output of the Bi-LSTM, numpy-... | _____no_output_____ | MIT | MOOCS/Deeplearing_Specialization/Notebooks/Neural machine translation with attention-v4.ipynb | itismesam/Courses-1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.