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 |
|---|---|---|---|---|---|
Hotel Map* Store into variable named `hotel_df`.* Add a "Hotel Name" column to the DataFrame.* Set parameters to search for hotels with 5000 meters.* Hit the Google Places API for each city's coordinates.* Store the first Hotel result into the DataFrame.* Plot markers on top of the heatmap. | #Search for hotel in cities and assign to a new column in hotel_df
hotelname = []
hotel_df = city_weather_df.copy()
params = {}
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
for index, row in hotel_df.iterrows():
# get city name, lat, lng from df
lat = row["lat"]
lng = row["lon... | _____no_output_____ | ADSL | VacationPy/VacationPy.ipynb | kdturner83/PythonAPI_Challenge |
To install basemap`conda install -c conda-forge proj4``conda install -c anaconda basemap` In this notebook we will preprocess data to be able to compute death rates by state due to covid. You will need this data for plotting a map in hw3. Dataframes A DataFrame object is a two-dimensional matrix with rows and column... | covid = pd.read_csv("data/us-states.csv")
covid.head() | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
This dataframe has population estimates and a lot of other info. See `data/nst-est2019-alldata.pdf` for a descrition of all columns. | population = pd.read_csv("data/nst-est2019-alldata.csv")
population.head()
## let's look at the columns. I am looking for the population of 2019 per state.
#list(population.columns) | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
Always look at shapes of objects before and after you manipulate them. You will get `(number of row, number of columns).` How many states in United States of America? | covid.shape, population.shape
covid.describe()
# note that the counts are different because there are missing values in some columns
# covid["confirmed_cases"]
covid["confirmed_cases"].isnull()
# count how many rows are null?
(covid["confirmed_cases"].isnull() == True).sum()
# similarly
(covid["confirmed_cases"].isnul... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
Exercise 1 How to fill NAs with different values for different columns? Subsetting and merging dataframesWe need info about deaths from the covid dataframe and info about population from other dataframe. Let's keep just that. Also we need a way to combine (merge) the two dataframes. The column `fips` is a unique ide... | covid.head()
# selecting columns
covid = covid[["state", "fips", "deaths"]]
covid.head()
population.head()
# from the pdf we have the following info
# STATE = State FIPS code
# NAME = State name
# POPESTIMATE2019 = 7/1/2019 resident total population estimate
population = population[["STATE", "NAME", "POPESTIMATE2019"]... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
There are various ways to merge two dataframes. At the moment we want to preserve all the data.`outer`: use union of keys from both frames | # Can we merge on state name?
rates = covid.merge(population, how="outer", left_on='fips', right_on='STATE')
rates.iloc[:15]
# let's look at rows with NAs
na_index = rates["POPESTIMATE2019"].isnull()
rates[na_index]
## Let's drop them
rates = rates.dropna()
rates.shape
# cleaning up some more
rates = rates[["state", "f... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
Dictionary of color per state | # iterate through rows
for i, row in rates.iterrows():
print(row["state"], row["color"])
# make a dictionary of color per state
state2color = {}
for i, row in rates.iterrows():
state2color[row["state"]] = row["color"]
# here is a shortcut of the same
# dictionary comprehension
state2color = {row["state"]: row["... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
Making a map in matplotlib Based on these exampleshttps://github.com/matplotlib/basemap/blob/master/examples/fillstates.pyhttps://stackoverflow.com/questions/39742305/how-to-use-basemap-python-to-plot-us-with-50-states | # Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
shape = m.readshapefile('st99_d00', name='states', drawbounds=True)
ax = plt.gca() # get current axes ins... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
How to make a column bar | colors = ["#ffffd4", "#fee391", "#fec44f", "#fe9929", "#ec7014", "#cc4c02", "#8c2d04"]
bounds = [1,2,3,4,5,6,7,8]
boundaries = [0.055, 0.139, 0.23, 0.316, 0.387, 0.588, 0.832, 1.804]
fig, ax = plt.subplots(figsize=(1, 8))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.colors.ListedColormap(colors)
cb2 = ColorbarBase(ax, ... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
Put it together | # rounding
boundaries = [0.00, 0.14, 0.23, 0.32, 0.39, 0.59, 0.83, 1.80]
# Lambert Conformal map of lower 48 states.
fig, ax = plt.subplots(figsize=(12,6))
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 's... | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
More on dataframe manipulation `.iloc` for slicing a dataframe | rates.head()
rates = rates.reset_index(drop=True)
rates.head()
## keep the first 7 rows
rates_top7 = rates.iloc[:7]
rates_top7
## keep columns 2 and 3
rates_top7_cols23 = rates_top7.iloc[:, 2:4]
rates_top7_cols23
# we can do it at the same time
rates.iloc[:7, 2:4] | _____no_output_____ | MIT | notebooks/preprocessing-data-covid-map.ipynb | aneridand/msds593 |
1. Meet Dr. Ignaz Semmelweis<!---->This is Dr. Ignaz Semmelweis, a Hungarian physician born in 1818 and active at the Vienna General Hospital. If Dr. Semmelweis looks troubled it's probably because he's thinking about childbed fever: A deadly disease affecting women that just have given birth. He is thinking about it ... | # Importing modules
import pandas as pd
# Read datasets/yearly_deaths_by_clinic.csv into yearly
yearly = pd.read_csv("datasets/yearly_deaths_by_clinic.csv")
# Print out yearly
yearly | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
2. The alarming number of deathsThe table above shows the number of women giving birth at the two clinics at the Vienna General Hospital for the years 1841 to 1846. You'll notice that giving birth was very dangerous; an alarming number of women died as the result of childbirth, most of them from childbed fever.We see ... | # Calculate proportion of deaths per no. births
yearly["proportion_deaths"] = yearly["deaths"] / yearly["births"]
# Extract Clinic 1 data into clinic_1 and Clinic 2 data into clinic_2
clinic_1 = yearly[yearly["clinic"] == "clinic 1"]
clinic_2 = yearly[yearly["clinic"] == "clinic 2"]
# Print out clinic_1
clinic_1 | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
3. Death at the clinicsIf we now plot the proportion of deaths at both Clinic 1 and Clinic 2 we'll see a curious pattern… | # This makes plots appear in the notebook
%matplotlib inline
# Plot yearly proportion of deaths at the two clinics
ax = clinic_1.plot(x="year", y="proportion_deaths", label="Clinic 1")
clinic_2.plot(x="year", y="proportion_deaths", label="Clinic 2", ax=ax, ylabel="Proportion deaths") | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
4. The handwashing beginsWhy is the proportion of deaths consistently so much higher in Clinic 1? Semmelweis saw the same pattern and was puzzled and distressed. The only difference between the clinics was that many medical students served at Clinic 1, while mostly midwife students served at Clinic 2. While the midwiv... | # Read datasets/monthly_deaths.csv into monthly
monthly = pd.read_csv("datasets/monthly_deaths.csv", parse_dates=["date"])
# Calculate proportion of deaths per no. births
monthly["proportion_deaths"] = monthly["deaths"] / monthly["births"]
# Print out the first rows in monthly
monthly.head() | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
5. The effect of handwashingWith the data loaded we can now look at the proportion of deaths over time. In the plot below we haven't marked where obligatory handwashing started, but it reduced the proportion of deaths to such a degree that you should be able to spot it! | # Plot monthly proportion of deaths
ax = monthly.plot(x="date", y="proportion_deaths", ylabel="Proportion deaths") | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
6. The effect of handwashing highlightedStarting from the summer of 1847 the proportion of deaths is drastically reduced and, yes, this was when Semmelweis made handwashing obligatory. The effect of handwashing is made even more clear if we highlight this in the graph. | # Date when handwashing was made mandatory
handwashing_start = pd.to_datetime('1847-06-01')
# Split monthly into before and after handwashing_start
before_washing = monthly[monthly["date"] < handwashing_start]
after_washing = monthly[monthly["date"] >= handwashing_start]
# Plot monthly proportion of deaths before and... | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
7. More handwashing, fewer deaths?Again, the graph shows that handwashing had a huge effect. How much did it reduce the monthly proportion of deaths on average? | # Difference in mean monthly proportion of deaths due to handwashing
before_proportion = before_washing["proportion_deaths"]
after_proportion = after_washing["proportion_deaths"]
mean_diff = after_proportion.mean() - before_proportion.mean()
mean_diff | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
8. A Bootstrap analysis of Semmelweis handwashing dataIt reduced the proportion of deaths by around 8 percentage points! From 10% on average to just 2% (which is still a high number by modern standards). To get a feeling for the uncertainty around how much handwashing reduces mortalities we could look at a confidence ... | # A bootstrap analysis of the reduction of deaths due to handwashing
boot_mean_diff = []
for i in range(3000):
boot_before = before_proportion.sample(frac=1, replace=True)
boot_after = after_proportion.sample(frac=1, replace=True)
boot_mean_diff.append( boot_after.mean() - boot_before.mean() )
# Calculatin... | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
9. The fate of Dr. SemmelweisSo handwashing reduced the proportion of deaths by between 6.7 and 10 percentage points, according to a 95% confidence interval. All in all, it would seem that Semmelweis had solid evidence that handwashing was a simple but highly effective procedure that could save many lives.The tragedy ... | # The data Semmelweis collected points to that:
doctors_should_wash_their_hands = True | _____no_output_____ | MIT | 24_Project_5_Dr. Semmelweis and the Discovery of Handwashing/notebook.ipynb | mohd-faizy/DataScience-With-Python |
Carnot efficiency as a function of temperatureassuming a fixed reference temperature | import numpy as np
import matplotlib.pyplot as plt
# standard temperature 0°C as reference
θ_0 = 273.15 # Kelvin
# temperature range: 0°C to 200°C
θ = np.linspace(θ_0, θ_0+200, num=500)
# Carnot efficiency
η = (θ - θ_0) / θ
fig, ax = plt.subplots(dpi=200)
ax.plot(θ, η); | _____no_output_____ | MIT | carnot_efficiency.ipynb | MarkusLohmayer/master-thesis-code |
Cleaning Up (& Stats About It) - For each annotator: - How many annotation files? - How many txt files? - Number of empty .ann files - How many non-empty .ann files have a `TranscriptionError_Document`/`DuplicatePage` tag? - How many .ann files have ONLY one of those two tags and are empty o/w? -> remove if ... | def get_all_files(annotator):
""" collapsing folder structure per annotator"""
data_dir = "../Data/"
ann_dir = data_dir+annotator+"/"
for cur_dir in glob(ann_dir+"/6*"):
txt_files = sorted(glob(cur_dir+"/*.txt"))
ann_files = sorted(glob(cur_dir+"/*.ann"))
yield from zip(txt_files... | _____no_output_____ | MIT | data_2/Notebooks/JaccardDistanceAnalysis.ipynb | budh333/UnSilence_VOC |
Make New Corpusby copying files | from shutil import copy2
already_copied = True
if not already_copied:
from tqdm import tqdm
os.makedirs('Keep')
for anno, ls in tqdm(keep.items()):
cur_dir = f"Keep/{anno}"
os.makedirs(cur_dir)
for txt, ann in ls:
copy2(txt, cur_dir)
copy2(ann, cur_dir)
e... | Already copied, doing nothing!
| MIT | data_2/Notebooks/JaccardDistanceAnalysis.ipynb | budh333/UnSilence_VOC |
Pairwise Intersections of Annotation Files | def only_names(file_list):
"returns only names of files in a particular list"
return [ann.split("/")[-1] for txt, ann in file_list]
ls = []
for a1, fs1 in keep.items():
for a2, fs2 in keep.items():
if not a1 == a2:
names1, names2 = only_names(fs1), only_names(fs2)
... | _____no_output_____ | MIT | data_2/Notebooks/JaccardDistanceAnalysis.ipynb | budh333/UnSilence_VOC |
Jaccard Distance to Understand Overlap Pages between Annotators | inter_stats_T = inter_stats.pivot_table(
values="Jaccard_distance",
index="Anno1", columns="Anno2"
)
sns.heatmap(inter_stats_T*100, annot=True, cmap="YlGnBu")
_ = plt.title("Before Clean Up: Jaccard Distance (percentage)")
plt.show()
inter_stats_T = inter_stats.pivot_table(
values... | _____no_output_____ | MIT | data_2/Notebooks/JaccardDistanceAnalysis.ipynb | budh333/UnSilence_VOC |
**Conclusion**: Each pair of annotators annotated on average have 6% overlap (over the total documents they annotated together). Check Tag Distributions | def get_lines(ann_file):
with open(ann_file) as handle:
for l in handle:
if not l.strip(): continue
yield l.strip().split("\t")
def get_entities(ann_file):
for line in get_lines(ann_file):
if line[0].startswith("T") and len(line) >= 2:
tag_type, tag, string =... | _____no_output_____ | MIT | data_2/Notebooks/JaccardDistanceAnalysis.ipynb | budh333/UnSilence_VOC |
flavio tutorial Part 5: Extending flavio Adding an observable: photon polarization in $B\to K\pi\pi\gamma$$$\lambda_\gamma = \frac{|G_L|^2 - |G_R|^2}{|G_L|^2 + |G_R|^2}$$$$G_L = C_7^\text{eff} + \ldots, \qquad G_L = C_7' + \ldots $$$\ldots$ refer to non-factorizable hadronic contributions - let's ignore them for simp... | import flavio
def ll_lgamma(wc_obj, par_dict):
scale = flavio.config['renormalization scale']['bvgamma']
wc_dict = flavio.physics.bdecays.wilsoncoefficients.wctot_dict(wc_obj, 'bsee', scale, par_dict)
delta_C7 = flavio.physics.bdecays.matrixelements.delta_C7(
par=par_dict, wc=wc_dict, q2=0, scale=s... | _____no_output_____ | MIT | 5 Extending.ipynb | DavidMStraub/flavio-tutorial |
Defining the `Observable` and `Prediction` instances | obs = 'lambda_gamma'
flavio.classes.Observable(obs)
flavio.classes.Prediction(obs, ll_lgamma);
flavio.sm_prediction('lambda_gamma')
wc = flavio.WilsonCoefficients()
wc.set_initial({'C7p_bs': 0.25}, 4.8)
flavio.np_prediction('lambda_gamma', wc) | _____no_output_____ | MIT | 5 Extending.ipynb | DavidMStraub/flavio-tutorial |
Adding a new parameter | flavio.classes.Parameter('my_fudge_factor')
flavio.default_parameters.set_constraint('my_fudge_factor', '0 +- 0.2')
flavio.default_parameters.get_central('my_fudge_factor')
[flavio.default_parameters.get_random_all()['my_fudge_factor'] for i in range(5)] | _____no_output_____ | MIT | 5 Extending.ipynb | DavidMStraub/flavio-tutorial |
Lambda School Data Science - Loading, Cleaning and Visualizing DataObjectives for today:- Load data from multiple sources into a Python notebook - From a URL (github or otherwise) - CSV upload method - !wget method- "Clean" a dataset using common Python libraries - Removing NaN values "Data Imputation"- Create basic ... | # Step 1 - find the actual file to download
# From navigating the page, clicking "Data Folder"
flag_data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/flags/flag.data'
# You can "shell out" in a notebook for more powerful tools
# https://jakevdp.github.io/PythonDataScienceHandbook/01.05-ipython-and... | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Yes, but what does it *mean*?This data is fairly nice - it was "donated" and is already "clean" (no missing values). But there are no variable names - so we have to look at the codebook (also from the site).```1. name: Name of the country concerned2. landmass: 1=N.America, 2=S.America, 3=Europe, 4=Africa, 4=Asia, 6=Oc... | dataset_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
column_headers = ['age', 'workclass', 'fnlwgt', 'education', 'education-num',
'marital-status', 'occupation', 'relationship', 'race', 'sex',
'capital-gain', 'capital-loss', 'hours-per-week',
... | (32561, 15)
| MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
From a local file | from google.colab import files
uploaded | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Using the `!wget` command | import wget
wget https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Part 2 - Deal with Missing Values Diagnose Missing ValuesLets use the Adult Dataset from UCI. | df.isnull().sum() | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Fill Missing Values | dataset_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
column_headers = ['age', 'workclass', 'fnlwgt', 'education', 'education-num',
'marital-status', 'occupation', 'relationship', 'race', 'sex',
'capital-gain', 'capital-loss', 'hours-per-week',
... | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Part 3 - Explore the Dataset: Look at "Summary Statistics Numeric | df.describe() | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Non-Numeric | df.describe(exclude="number") | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Look at Categorical Values Part 4 - Basic Visualizations (using the Pandas Library) Histogram | # Pandas Histogram | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Density Plot (KDE) | # Pandas Density Plot | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Scatter Plot | # Pandas Scatterplot | _____no_output_____ | MIT | module2-loadingdata/JeanFraga_LS_DS8_112_Loading_Data.ipynb | JeanFraga/DS-Unit-1-Sprint-1-Dealing-With-Data |
Sci-Fi IRL 1: Technology Terminology Velocity A Data Storytelling Project by Tobias Reaper ---- Datalogue 008 ---------- Imports and Configuration | # Three Musketeers
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# For using the API
import requests
# More advanced vizualizations with Bokeh
from bokeh.plotting import figure, output_file, output_notebook, show
from bokeh.layouts import column
from bokeh.models.glyphs... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Functions | def pushshift_api_request(query, subreddit, frequency="month", aggs="created_utc"):
"""
Returns the JSON response of a PushShift API aggregate comment search as a Python dictionary.
Note: if you're reading this note, that means that this function is still only written
with the intention of automati... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Term Velocity: AlgorithmThe velocity of the term "algorithm" in each of the target subreddits. | # Define keywords and subreddits as python lists
words = [
"algorithm",
]
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
"politics",
"philosophy",
"AskReddi... | (156, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Load csv
df_main = pd.read_csv("008-Session_Exports/algorithm-monthly.csv")
df_main["month"] = pd.to_datetime(df_main["month"], infer_datetime_format=True)
df_main.head()
df_main.dtypes
# Color assignments
subs_colors = {}
for i in range(len(subs)):
subs_colors[f"{subs[i]}"] = f"{palette[i]}"
# Output to current... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Term Velocity: AIThe velocity of the term "AI" (abbreviation of artificial intelligence) in each of the target subreddits. | # Define keywords and subreddits as python lists
words = [
"AI",
]
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
"politics",
"philosophy",
"AskReddit",
... | (156, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Color assignments
subs_colors = {}
for i in range(len(subs)):
subs_colors[f"{subs[i]}"] = f"{palette[i]}"
# Output to current notebook
output_notebook()
output_file(f"{words[0]}-velocity-viz.html")
p = {} # dict to hold plots
p_names = [] # list for plot names
for sub in subs_colors:
p[f"{sub}"] = figure... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Term Velocity: ARThe velocity of the term "AR" (abbreviation of augmented reality) in each of the target subreddits. | # Define keywords and subreddits as python lists
words = [
"AR",
]
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
"politics",
"philosophy",
"AskReddit",
... | (156, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Color assignments
subs_colors = {}
for i in range(len(subs)):
subs_colors[f"{subs[i]}"] = f"{palette[i]}"
# Output to current notebook
output_notebook()
output_file(f"{words[0]}-velocity-viz.html")
p = {} # dict to hold plots
p_names = [] # list for plot names
for sub in subs_colors:
p[f"{sub}"] = figure... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Term Velocity: AutomationThe velocity of the term "automation" in each of the target subreddits. | # Define keywords and subreddits as python lists
words = [
"automation",
]
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
"politics",
"philosophy",
"AskRedd... | (151, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Output to current notebook
output_notebook()
output_file(f"{words[0]}-velocity-viz.html")
p = {} # dict to hold plots
p_names = [] # list for plot names
for sub in subs_colors:
p[f"{sub}"] = figure(title=f"Comments that mention '{words[0]}' in r/{sub}",
plot_width=1000, plot_height=20... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Term Velocity: Big DataThe velocity of the term "big data" in each of the target subreddits. | # Define keywords and subreddits as python lists
words = [
"big data",
]
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
"politics",
"philosophy",
"AskReddit... | (153, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Output to current notebook
output_notebook()
output_file(f"{words[0].replace(' ', '')}-velocity-viz.html")
p = {} # dict to hold plots
p_names = [] # list for plot names
for sub in subs_colors:
p[f"{sub}"] = figure(title=f"Comments that mention '{words[0]}' in r/{sub}",
plot_width=100... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
------ Overall Subreddit Comment VelocityThe total number of comments made in each of the subreddits. This is one way I can normalize the data. | # Define keywords and subreddits as python lists
words = [""] # Passing in an empty list this time to look at all comments
subs = [
"Futurology",
"technology",
"science",
"askscience",
"gadgets",
"books",
"scifi",
"movies",
"gaming",
"television",
"news",
"worldnews",
... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- | def all_comments_monthly(subreddit, frequency="month", aggs="created_utc"):
"""
Returns the JSON response of a PushShift API aggregate comment search as a Python dictionary.
Note: if you're reading this note, that means that this function is still only written
with the intention of automating a spe... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- | # Run the function to create and save the dataset
df_main, df_comm = reddit_data_setter(words, subs, True)
# Take a look to be sure it worked as expected
print(df_main.shape)
df_main.head() | (156, 18)
| MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
--- Visualizations | # Output to current notebook
output_notebook()
output_file("overall-subreddit-velocity-viz.html")
p = {} # dict to hold plots
p_names = [] # list for plot names
for sub in subs_colors:
p[f"{sub}"] = figure(title=f"Comments in r/{sub}",
plot_width=1000, plot_height=200,
... | _____no_output_____ | MIT | projects/sci_fi_irl/008-Session/sci_fi_irl-008.ipynb | tobias-fyi/data-may-differ |
ORF recognition by CNNCompare to ORF_CNN_101.Use 2-layer CNN.Run on Mac. | PC_SEQUENCES=20000 # how many protein-coding sequences
NC_SEQUENCES=20000 # how many non-coding sequences
PC_TESTS=1000
NC_TESTS=1000
BASES=1000 # how long is each sequence
ALPHABET=4 # how many different letters are possible
INPUT_SHAPE_2D = (BASES,ALPHABET,1) # Conv2D needs 3D inputs
INPUT_SHA... | _____no_output_____ | MIT | Notebooks/ORF_CNN_104.ipynb | ShepherdCode/Soars2021 |
minGPT License*This notebook port's the [minGPT codebase](https://github.com/karpathy/minGPT) into equivalent NeMo code. The license for minGPT has therefore been attached here.*```The MIT License (MIT) Copyright (c) 2020 Andrej KarpathyPermission is hereby granted, free of charge, to any person obtaining a copy of th... | import torch
import nemo
from nemo.core import NeuralModule
from nemo.core import typecheck | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Neural ModuleWait, what's `NeuralModule`? Where is the wonderful `torch.nn.Module`? `NeuralModule` is a subclass of `torch.nn.Module`, and it brings with it a few additional functionalities.In addition to being a `torch.nn.Module`, thereby being entirely compatible with the PyTorch ecosystem, it has the following capa... | class MyEmptyModule(NeuralModule):
def forward(self):
print("Neural Module ~ hello world!")
x = MyEmptyModule()
x() | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Neural TypesNeural Types? You might be wondering what that term refers to.Almost all NeMo components inherit the class `Typing`. `Typing` is a simple class that adds two properties to the class that inherits it - `input_types` and `output_types`. A NeuralType, by its shortest definition, is simply a semantic tensor. I... | # Case 1:
embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=30)
x = torch.randint(high=10, size=(1, 5))
print("x :", x)
print("embedding(x) :", embedding(x).shape)
# Case 2
lstm = torch.nn.LSTM(1, 30, batch_first=True)
x = torch.randn(1, 5, 1)
print("x :", x)
print("lstm(x) :", lstm(x)[0].shape) # Let's ... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-------As you can see, the output of Case 1 is an embedding of shape [1, 5, 30], and the output of Case 2 is an LSTM output (state `h` over all time steps), also of the same shape [1, 5, 30].Do they have the same shape? **Yes**. If we do a Case 1 .shape == Case 2 .shape, will we get True as an output? **Yes**. Do they ... | from nemo.core.neural_types import NeuralType
from nemo.core.neural_types import *
class EmbeddingModule(NeuralModule):
def __init__(self):
super().__init__()
self.embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=30)
@typecheck()
def forward(self, x):
return self.embedding(x)
@prope... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
To show the benefit of Neural Types, we are going to replicate the above cases inside NeuralModules.Let's discuss how we added type checking support to the above class.1) `forward` has a decorator `@typecheck()` on it.2) `input_types` and `output_types` properties are defined.That's it! -------Let's expand on each of t... | embedding_module = EmbeddingModule() | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Now let's construct the equivalent of the Case 2 above, but as a `NeuralModule`. | class LSTMModule(NeuralModule):
def __init__(self):
super().__init__()
self.lstm = torch.nn.LSTM(1, 30, batch_first=True)
@typecheck()
def forward(self, x):
return self.lstm(x)
@property
def input_types(self):
return {
'x': NeuralType(axes=('B', 'T', 'C'), elements_type=SpectrogramTy... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Here, we define the LSTM module from the Case 2 above.We changed the input to be a rank three tensor, now representing a "SpectrogramType". We intentionally keep it generic - it can be a `MelSpectrogramType` or a `MFCCSpectrogramType` as it's input!The output of an LSTM is now an `EncodedRepresentation`. Practica... | lstm_module = LSTMModule() | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Now for the test ! | # Case 1 [ERROR CELL]
x1 = torch.randint(high=10, size=(1, 5))
print("x :", x1)
print("embedding(x) :", embedding_module(x1).shape) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----You might be wondering why we get a `TypeError` right off the bat. This `TypeError` is raised by design.Positional arguments can cause significant issues during model development, mostly when the model/module design is not finalized. To reduce the potential for mistakes caused by wrong positional arguments and enf... | # Case 1
print("x :", x1)
print("embedding(x) :", embedding_module(x=x1).shape) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Now let's try the same for the `LSTMModule` in Case 2 | # Case 2 [ERROR CELL]
x2 = torch.randn(1, 5, 1)
print("x :", x2)
print("lstm(x) :", lstm_module(x=x2)[0].shape) # Let's take all timestep outputs of the LSTM | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----Now we get a type error stating that the number of output arguments provided does not match what is expected.What exactly is going on here? Well, inside our `LSTMModule` class, we declare the output types to be a single NeuralType - an `EncodedRepresentation` of shape [B, T, C].But the output of an LSTM layer is a... | class CorrectLSTMModule(LSTMModule): # Let's inherit the wrong class to make it easy to override
@property
def output_types(self):
return {
'h': NeuralType(axes=('B', 'T', 'C'), elements_type=EncodedRepresentation()),
'c': NeuralType(axes=('B', 'T', 'C'), elements_type=EncodedRepresentation()),... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Great! So now, the type checking system is happy.If you looked closely, the outputs were ordinary Torch Tensors (this is good news; we don't want to be incompatible with torch Tensors after all!). So, where exactly is the type of information stored?When the `output_types` is overridden, and valid torch tensors ar... | emb_out = embedding_module(x=x1)
lstm_out = lstm_module(x=x2)[0]
assert hasattr(emb_out, 'neural_type')
assert hasattr(lstm_out, 'neural_type')
print("Embedding tensor :", emb_out.neural_type)
print("LSTM tensor :", lstm_out.neural_type) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-------So we see that these tensors now have this attribute called `neural_type` and are the same shape.This exercise's entire goal was to assert that the two outputs are semantically **not** the same object, even if they are the same shape. Let's test this! | emb_out.neural_type.compare(lstm_out.neural_type)
emb_out.neural_type == lstm_out.neural_type | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Neural Types - LimitationsYou might have noticed one interesting fact - our inputs were just `torch.Tensor` to both typed function calls, and they had no `neural_type` assigned to them.So why did the type check system not raise any error? This is to maintain compatibility - type checking is meant to work on a chain of... | embedding_module = EmbeddingModule()
x1 = torch.randint(high=10, size=(1, 5))
# Attach correct neural type
x1.neural_type = NeuralType(('B', 'T'), Index())
print("embedding(x) :", embedding_module(x=x1).shape)
# Attach wrong neural type [ERROR CELL]
x1.neural_type = NeuralType(('B', 'T'), LabelsType())
print("embedd... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Let's create the minGPT componentsNow that we have a somewhat firm grasp of neural type checking, let's begin porting the minGPT example code. Once again, most of the code will be a direct port from the [minGPT repository](https://github.com/karpathy/minGPT).Here, you will notice one thing. By just changing class impo... | import math
from typing import List, Set, Dict, Tuple, Optional
import torch
import torch.nn as nn
from torch.nn import functional as F | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Creating Element TypesTill now, we have used the Neural Types provided by the NeMo core. But we need not be restricted to the pre-defined element types !Users have total flexibility in defining any hierarchy of element types as they please! | class AttentionType(EncodedRepresentation):
"""Basic Attention Element Type"""
class SelfAttentionType(AttentionType):
"""Self Attention Element Type"""
class CausalSelfAttentionType(SelfAttentionType):
"""Causal Self Attention Element Type""" | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Creating the modulesNeural Modules are generally top-level modules but can be used at any level of the module hierarchy.For demonstration, we will treat an encoder comprising a block of Causal Self Attention modules as a typed Neural Module. Of course, we can also treat each Causal Self Attention layer itself as a neu... | class CausalSelfAttention(nn.Module):
"""
A vanilla multi-head masked self-attention layer with a projection at the end.
It is possible to use torch.nn.MultiheadAttention here but I am including an
explicit implementation here to show that there is nothing too scary here.
"""
def __init__(self,... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Building the NeMo ModelSince a NeMo Model is comprised of various parts, we are going to iterate on the model step by step inside this notebook. As such, we will have multiple intermediate NeMo "Models", which will be partial implementations, and they will inherit each other iteratively.In a complete implementation of... | import pytorch_lightning as ptl
from nemo.core import ModelPT
from omegaconf import OmegaConf | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Next, let's construct the bare minimum implementation of the NeMo Model - just the constructor, the initializer of weights, and the forward method.Initially, we will follow the steps followed by the minGPT implementation, and progressively refactor for NeMo | class PTLGPT(ptl.LightningModule):
def __init__(self,
# model definition args
vocab_size: int, # size of the vocabulary (number of possible tokens)
block_size: int, # length of the model's context window in time
n_layer: int, # depth of the model; nu... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Let's create a PyTorch Lightning Model above, just to make sure it works ! | m = PTLGPT(vocab_size=100, block_size=32, n_layer=1, n_embd=32, n_head=4) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Now, let's convert the above easily into a NeMo Model.A NeMo Model constructor generally accepts only two things - 1) `cfg`: An OmegaConf DictConfig object that defines precisely the components required by the model to define its neural network architecture, data loader setup, optimizer setup, and any additional ... | class GPTEmbedding(NeuralModule):
def __init__(self, vocab_size: int, n_embd: int, block_size: int, embd_pdrop: float = 0.0):
super().__init__()
# input embedding stem: drop(content + position)
self.tok_emb = nn.Embedding(vocab_size, n_embd)
self.pos_emb = nn.Parameter(torch.zeros(1, block_size, n_em... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Refactoring the EncoderNext, let's refactor the Encoder - the multi layer Transformer Encoder | class GPTTransformerEncoder(NeuralModule):
def __init__(self, n_embd: int, block_size: int, n_head: int, n_layer: int, attn_pdrop: float = 0.0, resid_pdrop: float = 0.0):
super().__init__()
self.blocks = nn.Sequential(*[Block(n_embd, block_size, n_head, attn_pdrop, resid_pdrop)
... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Refactoring the DecoderFinally, let's refactor the Decoder - the small one-layer feed-forward network to decode the answer.-------Note an interesting detail - The `input_types` of the Decoder accepts the generic `EncoderRepresentation()`, where as the `neural_type` of the `GPTTransformerEncoder` has the `output_type` ... | class GPTDecoder(NeuralModule):
def __init__(self, n_embd: int, vocab_size: int):
super().__init__()
self.ln_f = nn.LayerNorm(n_embd)
self.head = nn.Linear(n_embd, vocab_size, bias=False) # no need for extra bias due to one in ln_f
@typecheck()
def forward(self, encoding):
x = self.ln_f(encoding)... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Refactoring the NeMo GPT ModelNow that we have 3 NeuralModules for the embedding, the encoder, and the decoder, let's refactor the NeMo model to take advantage of this refactor!This time, we inherit from `ModelPT` instead of the general `LightningModule`. | class AbstractNeMoGPT(ModelPT):
def __init__(self, cfg: OmegaConf, trainer: ptl.Trainer = None):
super().__init__(cfg=cfg, trainer=trainer)
# input embedding stem: drop(content + position)
self.embedding = self.from_config_dict(self.cfg.embedding)
# deep transformer: just a sequence of transf... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Creating a config for a ModelAt first glance, not much changed compared to the PyTorch Lightning implementation above. Other than the constructor, which now accepts a config, nothing changed at all!NeMo operates on the concept of a NeMo Model being accompanied by a corresponding config dict (instantiated as an OmegaCo... | # model definition args (required)
# ================================
# vocab_size: int # size of the vocabulary (number of possible tokens)
# block_size: int # length of the model's context window in time
# n_layer: int # depth of the model; number of Transformer blocks in sequence
# n_embd: int # the "width" of the m... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------As we look at the required parameters above, we need a way to tell OmegaConf that these values are currently not set, but the user should set them before we use them.OmegaConf supports such behavior using the `MISSING` value. A similar effect can be achieved in YAML configs by using `???` as a placeholder. | from omegaconf import MISSING
# Let's create a utility for building the class path
def get_class_path(cls):
return f'{cls.__module__}.{cls.__name__}' | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Structure of a Model configLet's first create a config for the common components of the model level config - | common_config = OmegaConf.create({
'vocab_size': MISSING,
'block_size': MISSING,
'n_layer': MISSING,
'n_embd': MISSING,
'n_head': MISSING,
}) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----The model config right now is still being built - it needs to contain a lot more details!A complete Model Config should have the sub-configs of all of its top-level modules as well. This means the configs of the `embedding`, `encoder`, and the `decoder`. Structure of sub-module configFor top-level models, we gene... | embedding_config = OmegaConf.create({
'_target_': get_class_path(GPTEmbedding),
'vocab_size': '${model.vocab_size}',
'n_embd': '${model.n_embd}',
'block_size': '${model.block_size}',
'embd_pdrop': 0.1
})
encoder_config = OmegaConf.create({
'_target_': get_class_path(GPTTransformerEncoder),
... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
What is `_target_`?--------In the above config, we see a `_target_` in the config. `_target_` is usually a full classpath to the actual class in the python package/user local directory. It is required for Hydra to locate and instantiate the model from its path correctly.So why do we want to set a classpath?In general,... | model_config = OmegaConf.create({
'model': common_config
})
# Then let's attach the sub-module configs
model_config.model.embedding = embedding_config
model_config.model.encoder = encoder_config
model_config.model.decoder = decoder_config | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----Let's print this config! | print(OmegaConf.to_yaml(model_config)) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----Wait, why did OmegaConf not fill in the value of the variable interpolation for the configs yet?This is because OmegaConf takes a deferred approach to variable interpolation. To force it ahead of time, we can use the following snippet - | temp_config = OmegaConf.create(OmegaConf.to_container(model_config, resolve=True))
print(OmegaConf.to_yaml(temp_config)) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----Now that we have a config, let's try to create an object of the NeMo Model ! | import copy
# Let's work on a copy of the model config and update it before we send it into the Model.
cfg = copy.deepcopy(model_config)
# Let's set the values of the config (for some plausible small model)
cfg.model.vocab_size = 100
cfg.model.block_size = 128
cfg.model.n_layer = 1
cfg.model.n_embd = 32
cfg.model.n_hea... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----You will note that we added the `Abstract` tag for a reason to this NeMo Model and that when we try to instantiate it - it raises an error that we need to implement specific methods.1) `setup_training_data` & `setup_validation_data` - All NeMo models should implement two data loaders - the training data loader and... | from nemo.core.classes.common import PretrainedModelInfo
class BasicNeMoGPT(AbstractNeMoGPT):
@classmethod
def list_available_models(cls) -> PretrainedModelInfo:
return None
def setup_training_data(self, train_data_config: OmegaConf):
self._train_dl = None
def setup_validation_data(self, val_data_c... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------Now let's try to create an object of the `BasicNeMoGPT` model | m = BasicNeMoGPT(cfg.model) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Setting up train-val-test stepsThe above `BasicNeMoGPT` Model is a basic PyTorch Lightning Module, with some added functionality - 1) Neural Type checks support - as defined in the Model as well as the internal modules.2) Save and restore of the Model (in the trivial case) to a tarfile.But as the Model is right now, i... | class BasicNeMoGPTWithSteps(BasicNeMoGPT):
def step_(self, split, batch, batch_idx=None):
idx, targets = batch
logits = self(idx=idx)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
key = 'loss' if split == 'train' else f"{split}_loss"
return {key:... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Setup for Multi Validation and Multi Test data loadersAs discussed in the NeMo Primer, NeMo has in-built support for multiple data loaders for validation and test steps. Therefore, as an example of how easy it is to add such support, we include the `multi_validation_epoch_end` and `multi_test_epoch_end` overrides.It i... | class BasicNeMoGPTWithOptim(BasicNeMoGPTWithSteps):
def configure_optimizers(self):
"""
This long function is unfortunately doing something very simple and is being very defensive:
We are separating out all parameters of the model into two buckets: those that will experience
weight... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----Now let's setup the config for the optimizer ! | OmegaConf.set_struct(cfg.model, False)
optim_config = OmegaConf.create({
'lr': 3e-4,
'weight_decay': 0.1,
'betas': [0.9, 0.95]
})
cfg.model.optim = optim_config
OmegaConf.set_struct(cfg.model, True) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Setting up the dataset / data loadersSo we were able almost entirely to replicate the MinGPT implementation. Remember, NeMo models should contain all of the logic to load the Dataset and DataLoader for at least the train and validation step.We temporarily provided empty implementations to get around it till now, but l... | from nemo.core import Dataset
from torch.utils import data
from torch.utils.data.dataloader import DataLoader
class TinyShakespeareDataset(Dataset):
def __init__(self, data_path, block_size, crop=None, override_vocab=None):
# load the data and crop it appropriately
with open(data_path, 'r') as f:
... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
------We didn't have to change anything until here. How then is type-checking done? NeMo does type-checking inside of the collate function implementation itself! In this case, it is not necessary to override the `collate_fn` inside the Dataset, but if we did need to override it, **NeMo requires that the private method ... | import os
if not os.path.exists('tiny-shakespeare.txt'):
!wget https://raw.githubusercontent.com/jcjohnson/torch-rnn/master/data/tiny-shakespeare.txt
!head -n 5 tiny-shakespeare.txt
train_dataset = TinyShakespeareDataset('tiny-shakespeare.txt', cfg.model.block_size, crop=(0, int(1e6)))
val_dataset = TinySha... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Setting up dataset/data loader support in the ModelSo we now know our data loader works. Let's integrate it as part of the Model itself!To do this, we use the three special attributes of the NeMo Model - `self._train_dl`, `self._validation_dl` and `self._test_dl`. Once you construct your DataLoader, place your data lo... | class NeMoGPT(BasicNeMoGPTWithOptim):
def _setup_data_loader(self, cfg):
if self.vocab is None:
override_vocab = None
else:
override_vocab = self.vocab
dataset = TinyShakespeareDataset(
data_path=cfg.data_path,
block_size=cfg.block_size,
crop=tuple(cfg.crop) if 'crop'... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Creating the dataset / dataloader configThe final step to setup this model is to add the `train_ds`, `validation_ds` and `test_ds` configs inside the model config! | OmegaConf.set_struct(cfg.model, False)
# Set the data path and update vocabular size
cfg.model.data_path = 'tiny-shakespeare.txt'
cfg.model.vocab_size = train_dataset.vocab_size
OmegaConf.set_struct(cfg.model, True)
train_ds = OmegaConf.create({
'data_path': '${model.data_path}',
'block_size': '${model.block_... | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
-----All the data loaders load properly ! Yay! Evaluate the model - end to end!Now that the data loaders have been set up, all that's left is to train and test the model! We have most of the components required by this model - the train, val and test data loaders, the optimizer, and the type-checked forward step to pe... | if torch.cuda.is_available():
cuda = 1
else:
cuda = 0
trainer = ptl.Trainer(gpus=cuda, test_percent_check=1.0)
trainer.test(model) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Saving and restoring modelsNeMo internally keeps track of the model configuration, as well as the model checkpoints and parameters.As long as your NeMo follows the above general guidelines, you can call the `save_to` and `restore_from` methods to save and restore your models! | model.save_to('gpt_model.nemo')
!ls -d -- *.nemo
temp_model = NeMoGPT.restore_from('gpt_model.nemo')
# [ERROR CELL]
temp_model.setup_test_data(temp_model.cfg.test_ds) | _____no_output_____ | Apache-2.0 | tutorials/01_NeMo_Models.ipynb | mcdavid109/NeMo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.