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 |
|---|---|---|---|---|---|
Anonymizing Personally Identifiable Information (PII)There will be many cases where the data will contain PersonallyIdentifiable Information which we cannot disclose. In these cases, wewill want our Tabular Models to replace the information within thesefields with fake, simulated data that looks similar to the real on... | data_pii = load_tabular_demo('student_placements_pii')
data_pii.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
If we use our tabular model on this new data we will see how thesynthetic data that it generates discloses the addresses from the realstudents: | model = TVAE(
primary_key='student_id',
)
model.fit(data_pii)
new_data_pii = model.sample(200)
new_data_pii.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
More specifically, we can see how all the addresses that have beengenerated actually come from the original dataset: | new_data_pii.address.isin(data_pii.address).sum() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
In order to solve this, we can pass an additional argument`anonymize_fields` to our model when we create the instance. This`anonymize_fields` argument will need to be a dictionary that contains:- The name of the field that we want to anonymize.- The category of the field that we want to use when we generate fake ... | model = TVAE(
primary_key='student_id',
anonymize_fields={
'address': 'address'
}
)
model.fit(data_pii) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
As a result, we can see how the real `address` values have been replacedby other fake addresses: | new_data_pii = model.sample(200)
new_data_pii.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
Which means that none of the original addresses can be found in thesampled data: | data_pii.address.isin(new_data_pii.address).sum() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
As we can see, in this case these modifications changed the obtainedresults slightly, but they did neither introduce dramatic changes in theperformance. Conditional SamplingAs the name implies, conditional sampling allows us to sample from a conditional distribution using the `TVAE` model, which means we can generate ... | from sdv.sampling import Condition
condition = Condition({
'gender': 'M'
}, num_rows=5)
model.sample_conditions(conditions=[condition]) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
It's also possible to condition on multiple columns, such as `gender = M, 'experience_years': 0`. | condition = Condition({
'gender': 'M',
'experience_years': 0
}, num_rows=5)
model.sample_conditions(conditions=[condition]) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
In the `sample_remaining_columns` method, `conditions` is passed as a dataframe. In that case, the model will generate one sample for each row of the dataframe, sorted in the same order. Since the model already knows how many samples to generate, passing it as a parameter is unnecessary. For example, if we want to gene... | import pandas as pd
conditions = pd.DataFrame({
'gender': ['M', 'M', 'M', 'F', 'F', 'F'],
})
model.sample_remaining_columns(conditions) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
`TVAE` also supports conditioning on continuous values, as long as the values are within the range of seen numbers. For example, if all the values of the dataset are within 0 and 1, `TVAE` will not be able to set this value to 1000. | condition = Condition({
'degree_perc': 70.0
}, num_rows=5)
model.sample_conditions(conditions=[condition]) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
Lesson 1 - Introduction Getting to know the Notebook Two types of cells:* Code cells* Text cells Hi hello! Hi hello. (shift + enter = executes) This is a **text** cell. It can be formatted with **images**, **HTML**, **LaTeX**. For example **LaTeX**:$Y_t - Y_{t-1} = \rho Y_{t-1} - Y_{t-1} + \epsilon $$\Delta ... | # Header 1
## Section 1.1
### Sub-section 1.1.1
#### And we can continue
# this is number
# comment
5
6+2
2 + 2
5 + 2
# Pay attention to the execution order!
5 / 2 | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Note It has some differences to the standard implementation of Jupyter Notebook (ex. shortcuts)--- Basic Types (part 1) Numbers | # integers
265
# Real (called float)
235.45
# Binary (called Boolean)
True, False
# complex
2 + 4j
# function(123123)
type(2 + 4j)
type(2), type(2.)
type(3/2)
3/2 | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
OperationsAll arithmetic operators: * +, -, *, /* %, **, // | # % -> Modulus operator
print(13/5)
print(13%5)
# // -> Floor division
13//2
# ** -> expoent
3**3
# operators precedence
print( 2*2**2 )
print( (2*2)**2 ) | 8
16
| MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
**Note:** Don't use square brackets [ ].or curly brackets to write expressions Comparison Operators==, !=, >, =, <= | # the result is always a boolean
2 == 3
1>2
int(True)
float(2)
123 >= 122.99
# comparing two objects
123 == "123", 123 != "123"
int("234")
# Remove int to raise error
123 <= int("234")
| _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Logical OperatorsAlways compare booleans and, or, not | not True
2 < 5 and (3 < 4)
not (2 > 5) or (3 < 4) | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
https://www.programiz.com/python-programming/precedence-associativity | # it doesn't matter the precedence
# True and True or False and not False | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Bitwise operators* & - AND* | - OR* ^ - XOR* ~ - NOT* << Left shift* '>>' Right shiftIf you thought you could skip this class....https://medium.com/analytics-vidhya/python-for-geosciences-raster-bit-masks-explained-step-by-step-8620ed27141e
12/ 33333 | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Variables | a = 23
b = 7.89
type(a), type(b)
a + b
s = "Hello world!"
print(s)
type(s)
a < b | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
ListsUp to now, everything could be done with a good calculator... now things will get better.Ordered, accepts duplicates (diff from set) and can contain different data types. | lst = [1, "Hello", 3.5, 4, ["innerList_item1", "innerList_item2"], 6]
lst
len(lst) | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Indexing/SlicingIt's a way to refer to individual/subset of items within a list.Python indexing is Zero-Based | # Examples of indexing
# Get the first item and the last item
lst[0], lst[-1]
lst[5]
# Get second and penultimate itens
lst[1], lst[-2]
# Examples of slicing
# OBS: The slicing don't include the last item. So, 0:3 will return the 3 first
# elements
# [1, 10) - > 1.....9
# Syntax is: list[first index:last_index (excl... | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Acessing object members | type(lst)
# crtl+space
lst.index?
lst.index(4)
help(lst.append)
lst.append?
lst.append('last element')
lst
len(lst)
lst.index('Hello')
lst[-1] = 'last'
lst | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
String Members | s.replace('Hello', 'Hi')
s.lower()
s.swapcase()
'234'.isnumeric()
s.isnumeric? | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
We will now see how to control the flow execution of a program. There are important structures missing like **tuples**, **dictionaries**, **sets**, etc... We will come back to them afterwards. Flow control If-statement (if-then-else) **basic usage is:** if condition:> flow if condition is satisfiedelse:> flow if cond... | # indent
x = 18276748451
if x % 2 == 0:
print(x)
print('This number is even')
else:
print(x)
print('This number is odd')
x = input("Please, enter an integer:")
# The result of the input function is always a string.
# We have to convert it to an integer before proceeding.
x = int(x)
if x < 0:
... | Please, enter an integer:2
Positive
finished
| MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
While statement while condition (is met):> do something | # good to count
start = 1
end = 1000
while start <= end:
print(start)
start = start + 1
# combine flow control and loops (printing just numbers divisable by 3)
i = 0
while i <= 100:
if i % 3 == 0:
print(i)
i = i + 1
# Create a list with number divisible by 3 from 0 to 100
current_number = 0
lst = []... | 0
9
36
81
144
225
324
441
576
729
900
1089
1296
1521
1764
2025
2304
2601
2916
3249
3600
3969
4356
4761
5184
5625
6084
6561
7056
7569
8100
8649
9216
9801
| MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
For statement **Basic usage:**for variable in "list" (Iterable):> do something | # to calculate the square of these...
for anything in lst:
print(anything/2) | 0.0
1.5
3.0
4.5
6.0
7.5
9.0
10.5
12.0
13.5
15.0
16.5
18.0
19.5
21.0
22.5
24.0
25.5
27.0
28.5
30.0
31.5
33.0
34.5
36.0
37.5
39.0
40.5
42.0
43.5
45.0
46.5
48.0
49.5
| MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
That's something different from older (lower level) languages like C, C++, Pascal, Fortran, etc. **Note: There is no condition in Python's `for statement`** | # range(start, end, step)
for i in range(10, 0, -2):
print(i) | 10
8
6
4
2
| MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Exercise We have the precipitation for one month and corresponding days. | import random
random.randint?
# create the days and daily rain
random.seed(1)
daily_rain = []
day_of_month = []
for i in range(1, 32, 1):
day_of_month.append(i)
daily_rain.append(random.randint(0, 100))
str(day_of_month), str(daily_rain)
import matplotlib.pyplot as plt
plt.figure(figsize=(18, 9))
plt.bar(day... | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
Answer these questions:* number of days with rain* day of the maximum rain and day of the minimum rain* total rain* mean rain* Challenge: order the days according to the rain precipitation. Descending order (from highest to lowest). Ex: [12, 7, ...] Extra - n-dimensional matrices as combination of lists | # create a checkerboard
l1 = [0, 1, 0, 1, 0, 1, 0, 1]
l2 = [1, 0, 1, 0, 1, 0, 1, 0]
l3 = [0, 1, 0, 1, 0, 1, 0, 1]
l4 = [1, 0, 1, 0, 1, 0, 1, 0]
l5 = [0, 1, 0, 1, 0, 1, 0, 1]
l6 = [1, 0, 1, 0, 1, 0, 1, 0]
l7 = [0, 1, 0, 1, 0, 1, 0, 1]
l8 = [1, 0, 1, 0, 1, 0, 1, 0]
m = [l1, l2, l3, l4, l5, l6, l7, l8]
m
m[2][2]
type(m[2... | _____no_output_____ | MIT | Python4Scientists_Lesson1.ipynb | cordmaur/PythonForScientists |
_*H2 ground state energy computation using Iterative QPE*_This notebook demonstrates using Qiskit Chemistry to plot graphs of the ground state energy of the Hydrogen (H2) molecule over a range of inter-atomic distances using IQPE (Iterative Quantum Phase Estimation) algorithm. It is compared to the same energies as co... | import numpy as np
import pylab
from qiskit import LegacySimulators
from qiskit_chemistry import QiskitChemistry
import time
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator'... | _____no_output_____ | Apache-2.0 | community/aqua/chemistry/h2_iqpe.ipynb | Chibikuri/qiskit-tutorials |
ML Pipeline PreparationFollow the instructions below to help you create your ML pipeline. 1. Import libraries and load data from database.- Import Python libraries- Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)- Define feature and ... | # import necessary libraries
import pandas as pd
import numpy as np
import os
import pickle
import nltk
import re
from sqlalchemy import create_engine
import sqlite3
from nltk.tokenize import word_tokenize, RegexpTokenizer
from nltk.stem import WordNetLemmatizer
from sklearn.metrics import confusion_matrix
from sklea... | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
2. Write a tokenization function to process your text data | # Proprocess text by removing unwanted properties
def tokenize(text):
'''
input:
text: input text data containing attributes
output:
clean_tokens: cleaned text without unwanted texts
'''
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'... | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
3. Build a machine learning pipelineThis machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) h... | pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier())),
])
# Visualize model parameters
pipeline.get_params() | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
4. Train pipeline- Split data into train and test sets- Train pipeline | # use sklearn split function to split dataset into train and 20% test sets
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2)
# Train pipeline using RandomForest Classifier algorithm
pipeline.fit(X_train, y_train) | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
5. Test your modelReport the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's classification_report on each. | # Output result metrics of trained RandomForest Classifier algorithm
def evaluate_model(model, X_test, y_test):
'''
Input:
model: RandomForest Classifier trained model
X_test: Test training features
Y_test: Test training response variable
Output:
None:
Display mo... | related
precision recall f1-score support
0 0.65 0.38 0.48 1193
1 0.83 0.94 0.88 4016
2 0.50 0.43 0.46 35
avg / total 0.79 0.81 0.79 5244
request
precision recall f1... | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
6. Improve your modelUse grid search to find better parameters. | parameters = {'clf__estimator__max_depth': [10, 50, None],
'clf__estimator__min_samples_leaf':[2, 5, 10]}
cv = GridSearchCV(pipeline, parameters) | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
7. Test your modelShow the accuracy, precision, and recall of the tuned model.Since this project focuses on code quality, process, and pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - especi... | # Train pipeline using the improved model
cv.fit(X_train, y_train)
# # classification_report to display model precision, recall, f1-score, support
evaluate_model(cv, X_test, y_test)
cv.best_estimator_ | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
8. Try improving your model further. Here are a few ideas:* try other machine learning algorithms* add other features besides the TF-IDF | # Improve model using DecisionTree Classifier
new_pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(DecisionTreeClassifier()))
])
# Train improved model
new_pipeline.fit(X_train, y_train)
# Run result metric score display... | related
precision recall f1-score support
0 0.47 0.45 0.46 1193
1 0.84 0.85 0.84 4016
2 0.31 0.40 0.35 35
avg / total 0.75 0.75 0.75 5244
request
precision recall f1... | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
9. Export your model as a pickle file | # save a copy file of the the trained model to disk
trained_model_file = 'trained_model.sav'
pickle.dump(cv, open(trained_model_file, 'wb')) | _____no_output_____ | FTL | ML Pipeline Preparation.ipynb | Sanmilee/Disaster-Response-Pipeline |
Total de Casos y Mortalidad padecimiento | import matplotlib.pyplot as plt
cv19_confirmed_cases = covid_pd[covid_pd['RESULTADO_LAB'] == YES]
pneumonia_confirmed_cases = cv19_confirmed_cases[cv19_confirmed_cases['NEUMONIA'] == YES]
diabetes_confirmed_cases = cv19_confirmed_cases[cv19_confirmed_cases['DIABETES'] == YES]
epoc_confirmed_cases = cv19_confirmed... | _____no_output_____ | MIT | 001-000-general-overview/run.ipynb | devlabmexico/reporte-covid |
Computer Vision Nanodegree Project: Image Captioning---In this notebook, you will learn how to load and pre-process data from the [COCO dataset](http://cocodataset.org/home). You will also design a CNN-RNN model for automatically generating image captions.Note that **any amendments that you make to this notebook will ... | # install PixieDebugger - A Visual Python Debugger for Jupyter Notebooks
# https://medium.com/codait/the-visual-python-debugger-for-jupyter-notebooks-youve-always-wanted-761713babc62
# https://www.analyticsvidhya.com/blog/2018/07/pixie-debugger-python-debugging-tool-jupyter-notebooks-data-scientist-must-use/
!pip insta... | [nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data] Package punkt is already up-to-date!
PyTorch Version: 1.2.0
CUDA available: True
Pixiedust database opened successfully
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
When you ran the code cell above, the data loader was stored in the variable `data_loader`. You can access the corresponding dataset as `data_loader.dataset`. This dataset is an instance of the `CoCoDataset` class in **data_loader.py**. If you are unfamiliar with data loaders and datasets, you are encouraged to revi... | sample_caption = 'A person doing a trick on a rail while riding a skateboard.' | _____no_output_____ | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In **`line 1`** of the code snippet, every letter in the caption is converted to lowercase, and the [`nltk.tokenize.word_tokenize`](http://www.nltk.org/) function is used to obtain a list of string-valued tokens. Run the next code cell to visualize the effect on `sample_caption`. | sample_tokens = nltk.tokenize.word_tokenize(str(sample_caption).lower())
print(sample_tokens) | ['a', 'person', 'doing', 'a', 'trick', 'on', 'a', 'rail', 'while', 'riding', 'a', 'skateboard', '.']
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In **`line 2`** and **`line 3`** we initialize an empty list and append an integer to mark the start of a caption. The [paper](https://arxiv.org/pdf/1411.4555.pdf) that you are encouraged to implement uses a special start word (and a special end word, which we'll examine below) to mark the beginning (and end) of a cap... | sample_caption = []
start_word = data_loader.dataset.vocab.start_word
print('Special start word:', start_word)
sample_caption.append(data_loader.dataset.vocab(start_word))
print(sample_caption) | Special start word: <start>
[0]
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In **`line 4`**, we continue the list by adding integers that correspond to each of the tokens in the caption. | sample_caption.extend([data_loader.dataset.vocab(token) for token in sample_tokens])
print(sample_caption) | [0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3, 753, 18]
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In **`line 5`**, we append a final integer to mark the end of the caption. Identical to the case of the special start word (above), the special end word (`""`) is decided when instantiating the data loader and is passed as a parameter (`end_word`). You are **required** to keep this parameter at its default value (`en... | end_word = data_loader.dataset.vocab.end_word
print('Special end word:', end_word)
sample_caption.append(data_loader.dataset.vocab(end_word))
print(sample_caption) | Special end word: <end>
[0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3, 753, 18, 1]
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
Finally, in **`line 6`**, we convert the list of integers to a PyTorch tensor and cast it to [long type](http://pytorch.org/docs/master/tensors.htmltorch.Tensor.long). You can read more about the different types of PyTorch tensors on the [website](http://pytorch.org/docs/master/tensors.html). | sample_caption = torch.Tensor(sample_caption).long()
print(sample_caption) | tensor([ 0, 3, 98, 754, 3, 396, 39, 3, 1009, 207, 139, 3,
753, 18, 1])
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
And that's it! In summary, any caption is converted to a list of tokens, with _special_ start and end tokens marking the beginning and end of the sentence:```[, 'a', 'person', 'doing', 'a', 'trick', 'while', 'riding', 'a', 'skateboard', '.', ]```This list of tokens is then turned into a list of integers, where every d... | # Preview the word2idx dictionary.
dict(list(data_loader.dataset.vocab.word2idx.items())[:10]) | _____no_output_____ | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
We also print the total number of keys. | # Print the total number of keys in the word2idx dictionary.
print('Total number of tokens in vocabulary:', len(data_loader.dataset.vocab)) | Total number of tokens in vocabulary: 8855
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
As you will see if you examine the code in **vocabulary.py**, the `word2idx` dictionary is created by looping over the captions in the training dataset. If a token appears no less than `vocab_threshold` times in the training set, then it is added as a key to the dictionary and assigned a corresponding unique integer. ... | # Modify the minimum word count threshold.
vocab_threshold = 4
# Obtain the data loader.
data_loader = get_loader(transform=transform_train,
mode='train',
batch_size=batch_size,
vocab_threshold=vocab_threshold,
vocab_fr... | Total number of tokens in vocabulary: 9955
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
There are also a few special keys in the `word2idx` dictionary. You are already familiar with the special start word (`""`) and special end word (`""`). There is one more special token, corresponding to unknown words (`""`). All tokens that don't appear anywhere in the `word2idx` dictionary are considered unknown wo... | unk_word = data_loader.dataset.vocab.unk_word
print('Special unknown word:', unk_word)
print('All unknown words are mapped to this integer:', data_loader.dataset.vocab(unk_word)) | Special unknown word: <unk>
All unknown words are mapped to this integer: 2
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
Check this for yourself below, by pre-processing the provided nonsense words that never appear in the training captions. | print(data_loader.dataset.vocab('jfkafejw'))
print(data_loader.dataset.vocab('ieowoqjf')) | 2
2
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
The final thing to mention is the `vocab_from_file` argument that is supplied when creating a data loader. To understand this argument, note that when you create a new data loader, the vocabulary (`data_loader.dataset.vocab`) is saved as a [pickle](https://docs.python.org/3/library/pickle.html) file in the project fol... | # Obtain the data loader (from file). Note that it runs much faster than before!
data_loader = get_loader(transform=transform_train,
mode='train',
batch_size=batch_size,
vocab_from_file=True) | Vocabulary successfully loaded from vocab.pkl file!
loading annotations into memory...
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In the next section, you will learn how to use the data loader to obtain batches of training data. Step 2: Use the Data Loader to Obtain BatchesThe captions in the dataset vary greatly in length. You can see this by examining `data_loader.dataset.caption_lengths`, a Python list with one entry for each training captio... | from collections import Counter
# Tally the total number of training captions with each length.
counter = Counter(data_loader.dataset.caption_lengths)
lengths = sorted(counter.items(), key=lambda pair: pair[1], reverse=True)
for value, count in lengths:
print('value: %2d --- count: %5d' % (value, count)) | value: 10 --- count: 86334
value: 11 --- count: 79948
value: 9 --- count: 71934
value: 12 --- count: 57637
value: 13 --- count: 37645
value: 14 --- count: 22335
value: 8 --- count: 20771
value: 15 --- count: 12841
value: 16 --- count: 7729
value: 17 --- count: 4842
value: 18 --- count: 3104
value: 19 --- count: 2... | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
To generate batches of training data, we begin by first sampling a caption length (where the probability that any length is drawn is proportional to the number of captions with that length in the dataset). Then, we retrieve a batch of size `batch_size` of image-caption pairs, where all captions have the sampled length... | import numpy as np
import torch.utils.data as data
# Randomly sample a caption length, and sample indices with that length.
indices = data_loader.dataset.get_train_indices()
print('selected caption length:', set(data_loader.dataset.caption_lengths[i] for i in indices))
print('batch size:', data_loader.dataset.batch_si... | selected caption length: {11}
batch size: 64
sampled indices: [163258, 37144, 380255, 317957, 192582, 360740, 10195, 2809, 162865, 309252, 293693, 333283, 35401, 403582, 103488, 93114, 234377, 135463, 281449, 85137, 73144, 43331, 279550, 9538, 215758, 166348, 288499, 375568, 226201, 77114, 139807, 66138, 349567, 316866... | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
Each time you run the code cell above, a different caption length is sampled, and a different batch of training data is returned. Run the code cell multiple times to check this out!You will train your model in the next notebook in this sequence (**2_Training.ipynb**). This code for generating training batches will be ... | # Watch for any changes in model.py, and re-load it automatically.
% load_ext autoreload
% autoreload 2 | _____no_output_____ | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
In the next code cell we define a `device` that you will use move PyTorch tensors to GPU (if CUDA is available). Run this code cell before continuing. | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | _____no_output_____ | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
Run the code cell below to instantiate the CNN encoder in `encoder`. The pre-processed images from the batch in **Step 2** of this notebook are then passed through the encoder, and the output is stored in `features`. | from model import EncoderCNN
# Specify the dimensionality of the image embedding.
embed_size = 256
#-#-#-# Do NOT modify the code below this line. #-#-#-#
# Initialize the encoder. (Optional: Add additional arguments if necessary.)
encoder = EncoderCNN(embed_size)
# Move the encoder to GPU if CUDA is available.
enc... | ----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Conv2d-1 [-1, 64, 112, 112] 9,408
BatchNorm2d-2 [-1, 64, 112, 112] 12... | MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
The encoder that we provide to you uses the pre-trained ResNet-50 architecture (with the final fully-connected layer removed) to extract features from a batch of pre-processed images. The output is then flattened to a vector, before being passed through a `Linear` layer to transform the feature vector to have the same... | from model import DecoderRNN
# Specify the number of features in the hidden state of the RNN decoder.
hidden_size = 512
#-#-#-# Do NOT modify the code below this line. #-#-#-#
# Store the size of the vocabulary.
vocab_size = len(data_loader.dataset.vocab)
# Initialize the decoder.
decoder = DecoderRNN(embed_size, h... | features.shape: torch.Size([64, 256])
captions.shape: torch.Size([64, 13])
DecoderRNN(
(embedding): Embedding(9955, 256)
(lstm): LSTM(256, 512, batch_first=True)
(linear): Linear(in_features=512, out_features=9955, bias=True)
)
type(outputs): <class 'torch.Tensor'>
outputs.shape: torch.Size([64, 13, 9955])
| MIT | 1_Preliminaries.ipynb | zhulingchen/CVND---Image-Captioning-Project |
**Student BENREKIA Mohamed Ali (IASD 2021-2022)** | %matplotlib inline
import numpy as np
from scipy.linalg import norm
import matplotlib.pyplot as plt
import seaborn as sns
%load_ext autoreload
%autoreload 2 | The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
| MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Loading data | !wget https://raw.githubusercontent.com/nishitpatel01/predicting-age-of-abalone-using-regression/master/Abalone_data.csv
# Use this code to read from a CSV file.
import pandas as pd
U = pd.read_csv('/content/Abalone_data.csv')
U.shape
U.info()
U.head()
U.tail()
U.Sex=U.Sex.astype('category').cat.codes
U.head()
U.descri... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Problem definition (Linear regression) | class RegPb(object):
'''
A class for regression problems with linear models.
Attributes:
X: Data matrix (features)
y: Data vector (labels)
n,d: Dimensions of X
loss: Loss function to be considered in the regression
'l2': Least-... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**PCA** | U, s, V = np.linalg.svd(x_train.T.dot(x_train))
eig_values, eig_vectors = s, U
explained_variance=(eig_values / np.sum(eig_values))*100
plt.figure(figsize=(8,4))
plt.bar(range(8), explained_variance, alpha=0.6)
plt.ylabel('Percentage of explained variance')
plt.xlabel('Dimensions')
# calculating our new axis
pc1 = x_... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Btach Gradietn Descent | def batch_grad(w0,problem, stepchoice=0, lr= 0.01, n_iter=1000,verbose=False):
# objective history
objvals = []
# Number of samples
n = problem.n
# Initial value of current iterate
w = w0.copy()
nw = norm(w)
# Current objective
obj = problem.fun(w)
objvals.append(obj);
# Initi... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Different Learning rates** | nb_epochs = 100
n = pblinreg.n
d = pblinreg.d
w0 = np.zeros(d)
valsstep0 = [0.1,0.01,0.001,0.0001,0.00001]
nvals = len(valsstep0)
objs = np.zeros((nvals,nb_epochs+1))
for val in range(nvals):
w_temp, objs_temp = batch_grad(w0,pblinreg, lr=valsstep0[val], n_iter=nb_epochs)
objs[val] = objs_temp
epochs = range(... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Accelerated Gradient Descent | def accelerated_grad(w_0,problem,lr=0.001,method="nesterov",momentum=None,n_iter=100,verbose=False):
"""
A generic code for Nesterov's accelerated gradient method.
Inputs:
w0: Initial vector
problem: Problem structure
lr: Learning rate
method... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**GD Vs NAGD** | nb_epochs = 100
n = pblinreg.n
d = pblinreg.d
w0 = np.zeros(d)
learning_rate = 0.01
w_g, obj_g = batch_grad(w0,pblinreg, lr=learning_rate, n_iter=nb_epochs)
w_n, obj_n = accelerated_grad(w0,pblinreg, lr=learning_rate, n_iter=nb_epochs)
epochs = range(1,102)
plt.figure(figsize=(7, 5))
plt.plot(epochs, obj_g, label="... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Stochastic gradient Descent | def stoch_grad(w0,problem, stepchoice=0, lr= 0.01, n_iter=1000,nb=1,average=0,scaling=0,with_replace=False,verbose=False):
"""
A code for gradient descent with various step choices.
Inputs:
w0: Initial vector
problem: Problem structure
problem.fun() ... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Constant Vs Decreasing LR** | nb_epochs = 60
n = pblinreg.n
d = pblinreg.d
w0 = np.zeros(d)
# Run a - GD with constant stepsize
w_a, obj_a = stoch_grad(w0,pblinreg, n_iter=nb_epochs,nb=n)
# Run b - Stochastic gradient with constant stepsize
# The version below may diverges, in which case the bound on norm(w) in the code will be triggered
w_b, ob... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Different Constant LR** | nb_epochs = 60
n = pblinreg.n
d = pblinreg.d
w0 = np.zeros(d)
valsstep0 = [0.01,0.001,0.0001,0.00001]
nvals = len(valsstep0)
objs = np.zeros((nvals,nb_epochs+1))
for val in range(nvals):
w_temp, objs_temp = stoch_grad(w0,pblinreg, lr=valsstep0[val], n_iter=nb_epochs*n,nb=1)
objs[val] = objs_temp
plt.figure(fi... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Different decreasing LR** | nb_epochs = 60
n = pblinreg.n
nbset = 1
w0 = np.zeros(d)
decstep = [1,2,10,20,100]
nvals = len(decstep)
objs = np.zeros((nvals,nb_epochs+1))
for val in range(nvals):
_, objs[val] = stoch_grad(w0,pblinreg,stepchoice=decstep[val],lr=0.02, n_iter=nb_epochs*n,nb=1)
plt.figure(figsize=(7, 5))
for val in range(nval... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Different Batch size** | nb_epochs = 100
n = pblinreg.n
w0 = np.zeros(d)
# Stochastic gradient (batch size 1)
w_a, obj_a= stoch_grad(w0,pblinreg, lr=0.0001, n_iter=nb_epochs*n,nb=1)
# Batch stochastic gradient (batch size n/100)
nbset=int(n/100)
w_b, obj_b = stoch_grad(w0,pblinreg, lr=0.0001, n_iter=nb_epochs*100,nb=nbset)
# Batch stochasti... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Other variants for SGD **batch with replacement** | #Batch with replacement for GD, SGD and Batch SGD
nb_epochs = 100
n = pblinreg.n
w0 = np.zeros(d)
nruns = 3
for i in range(nruns):
# Run standard stochastic gradient (batch size 1)
_, obj_a= stoch_grad(w0,pblinreg, lr=0.0001, n_iter=nb_epochs*n,nb=1,with_replace=True)
# Batch stochastic gradient (batch si... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Averaging** | # Comparison of stochastic gradient with and without averaging
nb_epochs = 100
n = pblinreg.n
w0 = np.zeros(d)
# Run standard stochastic gradient without averaging
_, obj_a =stoch_grad(w0,pblinreg, lr=0.0001, n_iter=nb_epochs*n,nb=1)
# Run stochastic gradient with averaging
_, obj_b =stoch_grad(w0,pblinreg, l... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
**Diagonal Scaling** | # Comparison of stochastic gradient with and without diagonal scaling
nb_epochs = 60
n = pblinreg.n
w0 = np.zeros(d)
# Stochastic gradient (batch size 1) without diagonal scaling
w_a, obj_a= stoch_grad(w0,pblinreg, lr=0.0001, n_iter=nb_epochs*n,nb=1)
# Stochastic gradient (batch size 1) with RMSProp diagonal scaling
... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Regression (Lasso with iterative soft thersholding) **Lasso regression with ISTA** | #Minimization fucntion with l1 norm (Lasso regression)
def cost(w, X, y, lbda):
return np.square(X.dot(w) - y).mean() + lbda * norm(w,1)
def ista_solve( A, d, lbdaa ):
"""
Iterative soft-thresholding solves the minimization problem
Minimize |Ax-d|_2^2 + lambda*|x|_1 (Lasso regression)
"""
max_... | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
Performance on Test set | #MSE on lasso-ISTA
cost(w_star, x_valid, y_valid, 0.00001)
# MSE on best sgd algo
cost(w_b, x_valid, y_valid, 0.00001) | _____no_output_____ | MIT | Optim_Project.ipynb | iladan0/Abalone_Age_Prediction |
The Monte Carlo Simulation of Radiation Transport WE will discuss essentiall physics and method to do gamma quanta (photons with high enough energy) radiation transport using Monte Carlo methods. We will covers interactions processes, basics of radiation passing through matter as well as Monte Carlo method and how it ... | h = 6.625e-34
c = 3e8
hw = 1.0 * 1.6e-19 # eV
λ = h*c/hw
print(f"Photon wavelength = {λ*1.0e9} nanometers") | Photon wavelength = 1242.1875 nanometers
| MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Thus, for 1keV photon we will get wave length about 1.2 nm, and for 1MeV photon we will get wave length about $1.2\times10^{-3}$nm. FOr comparison, typical atom size is from 0.1nm (He) to 0.4nm (Fr and other heavy). Therefore, for most interactions between photon and atoms in our enery range we could consider it partic... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
N = 1000 # number of points to sample
x = 2.0*np.random.random(N) - 1.0
y = 2.0*np.random.random(N) - 1.0
unitCircle = plt.Circle((0, 0), 1.0, color='r', fill=False)
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, 'bo', label='Sampling in square')
a... | 3.08
| MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Result shall be close to $\pi$ Basic Photons Interactions with atoms There are several interaction processess of photons with media. Compton Scattering Compton scattering is described by Klein-Nishina formula with energy of scattered photon directly tied to incoming energy and scattering angle$$\hbar \omega'=\frac{\h... | # usefule constants
MeC2 = 0.511 # in MeV
Re = 2.82 # femtometers
# main functions to deal with cross-sections
def hw_prime(hw, cos_theta):
"""computes outgoing photon energy vs cosine of the scattered angle"""
hwp = hw/(1.0 + (1.0 - cos_theta)*hw/MeC2)
return hwp
def cosθ_from_hwp(hw, hwp):
return ... | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Cross-sections Microscopic and Macroscopic cross-sections We learned about so-called microscopic cross-sections, which is oneabout one photon scattering on one electron. It is very small, measured in barns which is $10^{-24}$ cm$^2$. In real life photons interacti with material objects measured in grams and kilograms... | lines = None
with open('H2o.data', "r") as f:
lines = f.readlines()
header_len = 3
lines = lines[header_len:41] # remove header, and limit energy to 10MeV
energy = np.empty(len(lines)) # energy scale
coh_xs = np.empty(len(lines)) # coherent cross-section
inc_xs = np.empty(len(lines)) # incoherent cross-section
... | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Now we will plot together photoeffect, coherent, incoherent and total mass attenuation cross-sections. | plt.xscale("log")
plt.yscale("log")
plt.plot(energy, coh_xs, 'g-', linewidth=2)
plt.plot(energy, inc_xs, 'r-', linewidth=2)
plt.plot(energy, pht_xs, 'b-', linewidth=2)
plt.plot(energy, pht_xs+coh_xs+inc_xs, 'o-', linewidth=2) # total cross-section
#plt.plot(energy, npp_xs, 'c-', linewidth=2)
#plt.plot(energy, epp_xs, '... | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
One can see that for all practical reasons considering only photo-effect and compton (aka incoherent) scatterin is good enough approximation, Compton Scattering Sampling W will use Khan's method to sample Compton scattering. | def KhanComptonSampling(hw, rng):
"""Sample scattering energy after Compton interaction"""
α = 2.0*hw/MeC2 # double relative incoming photon energy
t = (α + 1.0)/(α + 9.0)
x = 0.0
while True:
y = 1.0 + α*rng.random()
if rng.random() < t:
if rng.random() < 4.0*(1.0 - 1.0/... | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Let's test Compton sampling and compare it with microscopic differential cross-section | hw = 1.0 # MeV
hwm = hwp_minimum(hw)
Nt = 1000000
hwp = np.empty(Nt)
rng = np.random.default_rng(312345)
for k in range(0, len(hwp)):
hwp[k] = KhanComptonSampling(hw, rng) | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Ok, lets check first the minimum energy in sampled values, should be within allowed range. | hwm_sampled = np.min(hwp)
print(f"Minimum allowed scattered energy: {hwm} vs actual sampled minimum {hwm_sampled}")
if hwm_sampled < hwm:
print("We have a problem with kinematics!")
count, bins, ignored = plt.hist(hwp, 20, density=True)
plt.show()
# plotting angular distribution
cosθ = cosθ_from_hwp(hw, hwp)
count,... | _____no_output_____ | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Monte Carlo photon transport code | # several helper functions and constants
X = 0
Y = 1
Z = 2
def isotropic_source(rng):
cosθ = 2.0*rng.random() - 1.0 # uniform cosine of the azimuth angle
sinθ = np.sqrt((1.0 - cosθ)*(1.0 + cosθ))
φ = 2.0*np.pi*rng.random() # uniform polar angle
return np.array((sinθ*np.cos(φ), sinθ*np.sin(φ), cosθ))
d... | Particle # 0
Particle # 1
Particle # 2
Particle # 3
Particle # 4
Particle # 5
Particle # 6
Particle # 7
Particle # 8
Particle # 9
Particle # 10
Particle # 11
Particle # 12
Particle # 13
Particle # 14
Particle # 15
Particle # 16
Particle # 17
Particle # 18
Particle # 19
Particle # 20
Particle # 21
Particle # 22
Particle... | MIT | GammaTransport.ipynb | Tatiana-Krivosheev/Radiation-Transport-with-Monte-Carlo |
Random Signals*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* Auto-Power Spectral DensityThe (auto-) [power spectral density](htt... | import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
# read audio file
fs, x = wavfile.read('../data/vocal_o_8k.wav')
x = np.asarray(x, dtype=float)
N = len(x)
# compute ACF
acf = 1/N * np.correlate(x, x, mode='full')
# compute PSD
psd = np.fft.fft(acf)
psd = psd * np.exp(1j*np.arange(2*N-1... | _____no_output_____ | MIT | random_signals/power_spectral_densities.ipynb | TA1DB/digital-signal-processing-lecture |
**Exercise*** What does the PSD tell you about the average spectral contents of a speech signal?Solution: The speech signal exhibits a harmonic structure with the dominant fundamental frequency $f_0 \approx 100$ Hz and a number of harmonics $f_n \approx n \cdot f_0$ for $n > 0$. This due to the fact that vowels generat... | N = 64 # length of x
M = 512 # length of y
# generate two uncorrelated random signals
np.random.seed(1)
x = 2 + np.random.normal(size=N)
y = 3 + np.random.normal(size=M)
N = len(x)
M = len(y)
# compute cross PSD via CCF
acf = 1/N * np.correlate(x, y, mode='full')
psd = np.fft.fft(acf)
psd = psd * np.exp(1j*np.arang... | _____no_output_____ | MIT | random_signals/power_spectral_densities.ipynb | TA1DB/digital-signal-processing-lecture |
Otter-Grader TutorialThis notebook is part of the Otter-Grader tutorial. For more information about Otter, see our [documentation](https://otter-grader.rtfd.io). | import pandas as pd
import numpy as np
%matplotlib inline
import otter
grader = otter.Notebook() | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
**Question 1:** Write a function `square` that returns the square of its argument. | def square(x):
return x**2
grader.check("q1") | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
**Question 2:** Write an infinite generator of the Fibonacci sequence `fibferator` that is *not* recursive. | def fiberator():
yield 0
yield 1
while True:
yield 1
grader.check("q2") | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
**Question 3:** Create a DataFrame mirroring the table below and assign this to `data`. Then group by the `flavor` column and find the mean price for each flavor; assign this **series** to `price_by_flavor`.| flavor | scoops | price ||-----|-----|-----|| chocolate | 1 | 2 || vanilla | 1 | 1.5 || chocolate | 2 | 3 || st... | data = pd.DataFrame({
"flavor": ["chocolate", "vanilla", "chocolate", "strawberry", "strawberry", "vanilla", "mint",
"mint", "chocolate"],
"scoops": [1, 1, 2, 1, 3, 2, 1, 2, 3],
"price": [2, 1.5, 3, 2, 4, 2, 4, 5, 5]
})
price_by_flavor = data.groupby("flavor").mean()["price"]
price_by_flavor... | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
**Question 1.4:** Create a barplot of `price_by_flavor`. | price_by_flavor.plot.bar() | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
**Question 1.5:** What do you notice about the bar plot? _Type your answer here, replacing this text._ The cell below allows you run all checks again. | grader.check_all()
grader.export() | _____no_output_____ | BSD-3-Clause | docs/tutorial/submissions/ipynbs/demo-fails2Hidden.ipynb | chrispyles/otter-grader |
Table of Contents | #!python
"""
Find the brightest pixel coordinate of a image.
@author: Bhishan Poudel
@date: Oct 27, 2017
@email: bhishanpdl@gmail.com
"""
# Imports
import time
import numpy as np
from astropy.io import fits
import subprocess
from scipy.ndimage import measurements
def brightest_coord():
with open('centroids_... | _____no_output_____ | MIT | Useful_Codes/find_centroid.ipynb | bhishanpdl/Research |
Poland* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Poland.ipynb) | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview("Poland", weeks=5);
overview("Poland");
compare_plot("Poland", normalise=True);... | _____no_output_____ | CC-BY-4.0 | ipynb/Poland.ipynb | oscovida/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Poland.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on how ... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Poland.ipynb | oscovida/oscovida.github.io |
Implementation of VGG16> In this notebook I have implemented VGG16 on CIFAR10 dataset using Pytorch | #importing libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
import torch.optim as optim
import tqdm
import matplotlib.pyplot as plt
from torchvision.datasets import CIFAR10
from torch.utils.data import random_split
from torch.utils.data.dataloader import Da... | _____no_output_____ | MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
Load the data and do standard preprocessing steps,such as resizing and converting the images into tensor | transform = transforms.Compose([transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225])])
train_ds = CIFAR10(root='data/',train = True,down... | Files already downloaded and verified
Files already downloaded and verified
| MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
A custom utility class to print out the accuracy and losses during training and testing | def accuracy(outputs,labels):
_,preds = torch.max(outputs,dim=1)
return torch.tensor(torch.sum(preds==labels).item()/len(preds))
class ImageClassificationBase(nn.Module):
def training_step(self,batch):
images, labels = batch
out = self(images)
loss = F.cross_entropy(out,labels)
return loss
... | _____no_output_____ | MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
Creating a network | VGG_types = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'VGG19': [64, 64, 'M', 128, 128,... | _____no_output_____ | MIT | VGG/VGG.ipynb | gowriaddepalli/papers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.