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 |
|---|---|---|---|---|---|
-> Converting time to datetime in order to make it easy to manipulate | dataset['Data/Hora'] = dataset['Data/Hora'].str.replace("/","-")
dataset['Data/Hora'] = pd.to_datetime(dataset['Data/Hora']) | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> Visualizing the data | dataset.head() | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> creating date dataframe and splitting its features date = dataset.iloc[:,0:1]date['day'] = date['Data/Hora'].dt.daydate['month'] = date['Data/Hora'].dt.monthdate['year'] = date['Data/Hora'].dt.yeardate = date.drop(columns = ['Data/Hora']) -> removing useless columns | dataset = dataset.drop(columns = ['Data/Hora','Unnamed: 7','Unnamed: 8','Unnamed: 9']) | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> transforming atributes to the correct format | for key, value in dataset.head().iteritems():
dataset[key] = dataset[key].str.replace(".","").str.replace(",",".").astype(float)
"""
for key, value in date.head().iteritems():
dataset[key] = date[key]
""" | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> Means | dataset.mean() | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> plotting graphics | plt.boxplot(dataset['Volume'])
plt.title('boxplot')
plt.xlabel('volume')
plt.ylabel('valores')
plt.ticklabel_format(style='sci', axis='y', useMathText = True)
dataset['Maxima'].median()
dataset['Minima'].mean() | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> Mรฉdia truncada | from scipy import stats
m = stats.trim_mean(dataset['Minima'], 0.1)
print(m) | 99109.76692307692
| MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> variancia e standard deviation | v = dataset['Cotacao'].var()
print(v)
d = dataset['Cotacao'].std()
print(v)
m = dataset['Cotacao'].mean()
print(m) | 99674.05773437498
| MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> covariancia dos atributos, mas antes fazer uma standard scaler pra facilitar a visรฃo e depois transforma de volta pra dataframe pandas correlation shows us the relationship between the two variables and how are they related while covariance shows us how the two variables vary from each other. | from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
dataset_cov = sc.fit_transform(dataset)
dataset_cov = pd.DataFrame(dataset_cov)
dataset_cov.cov() | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
-> plotting the graph may be easier to observe the correlation | corr = dataset.corr()
corr.style.background_gradient(cmap = 'coolwarm')
pd.plotting.scatter_matrix(dataset, figsize=(6, 6))
plt.show()
plt.matshow(dataset.corr())
plt.xticks(range(len(dataset.columns)), dataset.columns)
plt.yticks(range(len(dataset.columns)), dataset.columns)
plt.colorbar()
plt.show() | _____no_output_____ | MIT | drafts/exercises/ibovespa.ipynb | ItamarRocha/introduction-to-AI |
Exercise 02 - Functions and Getting Help ! 1. Complete Your Very First Function Complete the body of the following function according to its docstring.*HINT*: Python has a builtin function `round` | def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder,
# so that it will not raise any err... | The number after rounded to two decimal places is: 3.45
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
2. Explore the Built-in FunctionThe help for `round` says that `ndigits` (the second argument) may be negative.What do you think will happen when it is? Try some examples in the following cell?Can you think of a case where this would be useful? | print(round(122.3444,-3))
print(round(122.3456,-2))
print(round(122.5454,-1))
print(round(122.13432,0))
#round with ndigits <=0 - the rounding will begin from the decimal point to the left | 0.0
100.0
120.0
122.0
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
3. More FunctionGiving the problem of candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they will take 30 each and smash 1.Below is a simple function that will calc... | def to_smash(total_candies,n = 3):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
return total_candies % n
print('#no. of candies to smash = ', to_smash(31))
print('#no. of candies... | #no. of candies to smash = 1
#no. of candies to smash = 2
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
4. Taste some ErrorsIt may not be fun, but reading and understanding **error messages** will help you improve solving problem skills.Each code cell below contains some commented-out buggy code. For each cell...1. Read the code and predict what you think will happen when it's run.2. Then uncomment the code and run it t... | round_to_two_places(9.9999)
x = -10
y = 5
# Which of the two variables above has the smallest absolute value?
smallest_abs = min(abs(x),abs(y))
print(smallest_abs)
def f(x):
y = abs(x)
return y
print(f(5)) | 5
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
5. More and more FunctionsFor this question, we'll be using two functions imported from Python's `time` module. Time FunctionThe [time](https://docs.python.org/3/library/time.htmltime.time) function returns the number of seconds that have passed since the Epoch (aka [Unix time](https://en.wikipedia.org/wiki/Unix_time)... | # Importing the function 'time' from the module of the same name.
# (We'll discuss imports in more depth later)
from time import time
t = time()
print(t, "seconds since the Epoch") | 1621529220.6860213 seconds since the Epoch
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
Sleep FunctionWe'll also be using a function called [sleep](https://docs.python.org/3/library/time.htmltime.sleep), which makes us wait some number of seconds while it does nothing particular. (Sounds useful, right?)You can see it in action by running the cell below: | from time import sleep
duration = 5
print("Getting sleepy. See you in", duration, "seconds")
sleep(duration)
print("I'm back. What did I miss?") | Getting sleepy. See you in 5 seconds
I'm back. What did I miss?
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
Your Own FunctionWith the help of these functions, complete the function **`time_call`** below according to its docstring. | def time_call(fn, arg):
"""Return the amount of time the given function takes (in seconds) when called with the given argument.
"""
from time import time
start_time = time()
fn(arg)
end_time = time()
duration = end_time - start_time
return duration | _____no_output_____ | MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
How would you verify that `time_call` is working correctly? Think about it... | #solution? use sleep function? | _____no_output_____ | MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
6. ๐ถ๏ธ Reuse your Function*Note: this question depends on a working solution to the previous question.*Complete the function below according to its docstring. | def slowest_call(fn, arg1, arg2, arg3):
"""Return the amount of time taken by the slowest of the following function
calls: fn(arg1), fn(arg2), fn(arg3)
"""
slowest = min(time_call(fn, arg1), time_call(fn, arg2), time_call(fn,arg3))
return slowest
print(slowest_call(sleep,1,2,3))
| 1.012155294418335
| MIT | python-for-data/Ex02 - Functions and Getting Help.ipynb | hoaintp/atom-assignments |
Core> API details. | #hide
from nbdev.showdoc import *
# export
from attrdict import AttrDict
from fastcore.basics import Path
import subprocess | _____no_output_____ | Apache-2.0 | 00_core.ipynb | mgfrantz/dessiccate |
Running bash commands in Python | # export
def run_bash(cmd, return_output=True):
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if not error:
print(output.decode('utf-8'))
if return_output:
return output.decode('utf-8')
else:
print(error.decode('... | 00_core.ipynb
01_plotting.ipynb
02_pandas.ipynb
CONTRIBUTING.md
LICENSE
MANIFEST.in
Makefile
README.md
build
conda
dessiccate
dessiccate.egg-info
dist
docker-compose.yml
docs
index.ipynb
settings.ini
setup.py
| Apache-2.0 | 00_core.ipynb | mgfrantz/dessiccate |
Setting up in colabIf you're in colab, you may not have the proper packages installed.Running this function will set you up to work in colab. | # export
def colab_setup():
"""
Sets up for development in Google Colab.
Repo must be cloned in drive/colab/ directory.
"""
try:
from google.colab import drive
print('Running in colab')
drive.mount('/content/drive', force_remount=True)
_ = run_bash("pip install -Uqq n... | Working in /Users/michaelfrantz/Google Drive/colab/dessiccate
Running locally
| Apache-2.0 | 00_core.ipynb | mgfrantz/dessiccate |
PathOften, you want to create a new directory.Even if all you have is a file path, you can now call `mkdir_if_not_exists` to create the parent directory. | # export
def mkdir_if_not_exists(self, parents=True):
"""
Creates the directory of the path if ot doesn't exist.
If the path is a file, will not make the file itself,
but will create the parent directory.
"""
if path.is_dir():
p = path
else:
p = path.parent
if not p.exist... | _____no_output_____ | Apache-2.0 | 00_core.ipynb | mgfrantz/dessiccate |
Patricia Bay7277 Patricia Bay 48.6536ย 123.4515ย | get_tidal_stations(-123.4515, 48.6536, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Woodwards7610 Woodwards's Landing 49.1251ย 123.0754ย | get_tidal_stations(-123.0754, 49.1251, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
New Westminster7654 New Westminster 49.203683ย 122.90535ย | get_tidal_stations(-122.90535, 49.203683, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Sandy Cove7786 Sandy Cove 49.34ย 123.23ย | get_tidal_stations(-123.23, 49.34, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Port Renfrew check8525 Port Renfrew 48.555 124.421 | get_tidal_stations(-124.421, 48.555, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Victoria7120 Victoria 48.424666ย 123.3707ย | get_tidal_stations(-123.3707, 48.424666, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Sand Heads7594 Sand Heads 49.125 123.195 ย From Marlene's email 49ยบ 06โ 21.1857โโ, -123ยบ 18โ 12.4789โโwe are using 426, 292 end of jetty is 429, 295 | lat_sh = 49+6/60.+21.1857/3600.
lon_sh = -(123+18/60.+12.4789/3600.)
print(lon_sh, lat_sh)
get_tidal_stations(lon_sh, lat_sh, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=20) | -123.3034663611111 49.10588491666667
| Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Nanaimo7917 Nanaimo 49.17ย 123.93ย | get_tidal_stations(-123.93, 49.17, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10) | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
In our code its at 484, 208 with lon,lat at -123.93 and 49.16: leave as is for now Boundary BayGuesstimated from Map-122.925 49.0 | get_tidal_stations(-122.925, 49.0, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=15)
| _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Squamish49 41.675 N 123 09.299 W | print (49+41.675/60, -(123+9.299/60.))
print (model_lons.shape)
get_tidal_stations(-(123+9.299/60.), 49.+41.675/60., model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10)
| 49.694583333333334 -123.15498333333333
(898, 398)
| Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Half Moon Bay49 30.687 N 123 54.726 W | print (49+30.687/60, -(123+54.726/60.))
get_tidal_stations(-(123+54.726/60.), 49.+30.687/60., model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10)
| 49.51145 -123.9121
| Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Friday Harbour-123.016667, 48.55 | get_tidal_stations(-123.016667, 48.55, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10)
| _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Neah Bay-124.6, 48.4 | get_tidal_stations(-124.6, 48.4, model_lons, model_lats, wind_lons, wind_lats,
wave_lons, wave_lats, t_mask, wave_mask, size=10)
from salishsea_tools import places | _____no_output_____ | Apache-2.0 | notebooks/Tidal Station Locations.ipynb | SalishSeaCast/analysis-susan |
Plotting massive data setsThis notebook plots about half a million LIDAR points around Toronto from the KITTI data set. ([Source](http://www.cvlibs.net/datasets/kitti/raw_data.php)) The data is meant to be played over time. With pydeck, we can render these points and interact with them. Cleaning the dataFirst we need... | import pandas as pd
all_lidar = pd.concat([
pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_1.csv'),
pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_2.csv'),
pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/m... | _____no_output_____ | MIT | bindings/pydeck/examples/04 - Plotting massive data sets.ipynb | jcready/deck.gl |
Plotting the dataWe'll define a single `PointCloudLayer` and plot it.Pydeck by default expects the input of `get_position` to be a string name indicating a single position value. For convenience, you can pass in a string indicating the X/Y/Z coordinate, here `get_position='[x, y, z]'`. You also have access to a small ... | import pydeck as pdk
point_cloud = pdk.Layer(
'PointCloudLayer',
lidar[['x', 'y', 'z']],
get_position=['x', 'y', 'z * 10'],
get_normal=[0, 0, 1],
get_color=[255, 0, 100, 200],
pickable=True,
auto_highlight=True,
point_size=1)
view_state = pdk.data_utils.compute_view(lidar[['x', 'y'... | _____no_output_____ | MIT | bindings/pydeck/examples/04 - Plotting massive data sets.ipynb | jcready/deck.gl |
Seq2Seq with Attention for Korean-English Neural Machine Translation- Network architecture based on this [paper](https://arxiv.org/abs/1409.0473)- Fit to run on Google Colaboratory | import os
import io
import tarfile
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchtext
from torchtext.data import Dataset
from torchtext.data import Example
from torchtext.data import Field
from torchtext.data import BucketIterator | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
1. Upload Data to Colab Workspace๋ก์ปฌ์ ์กด์ฌํ๋ ๋ค์ 3๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ๋จธ์ ์ ์
๋ก๋. ํ์ผ์ ์๋ณธ์ [์ฌ๊ธฐ](https://github.com/jungyeul/korean-parallel-corpora/tree/master/korean-english-news-v1/)์์๋ ํ์ธ- korean-english-park.train.tar.gz- korean-english-park.dev.tar.gz- korean.english-park.test.tar.gz | # ํ์ฌ ์์
๊ฒฝ๋ก๋ฅผ ํ์ธ & 'data' ํด๋ ์์ฑ
!echo 'Current working directory:' ${PWD}
!mkdir -p data/
!ls -al
# ๋ก์ปฌ์ ๋ฐ์ดํฐ ์
๋ก๋
from google.colab import files
uploaded = files.upload()
# 'data' ํด๋ ํ์๋ก ์ด๋, ์ ์ฎ๊ฒจ์ก๋์ง ํ์ธ
!mv *.tar.gz data/
!ls -al data/ | total 8864
drwxr-xr-x 2 root root 4096 Aug 1 00:25 .
drwxr-xr-x 1 root root 4096 Aug 1 00:25 ..
-rw-r--r-- 1 root root 113461 Aug 1 00:23 korean-english-park.dev.tar.gz
-rw-r--r-- 1 root root 229831 Aug 1 00:23 korean-english-park.test.tar.gz
-rw-r--r-- 1 root root 8718893 Aug 1 00:24 korean-english-park.t... | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
2. Check Packages KoNLPy (์ค์น ํ์) | # Java 1.8 & KoNLPy ์ค์น
!apt-get update
!apt-get install g++ openjdk-8-jdk python-dev python3-dev
!pip3 install JPype1-py3
!pip3 install konlpy
from konlpy.tag import Okt
ko_tokens = Okt().pos('ํธ์ํฐ ๋ฐ์ดํฐ๋ก ํ์ตํ ํํ์ ๋ถ์๊ธฐ๊ฐ ์ ์คํ์ด ๋๋์ง ํ์ธํด๋ณผ๊น์?') # list of (word, POS TAG) tuples
ko_tokens = [t[0] for t in ko_tokens] # Only get w... | /usr/local/lib/python3.6/dist-packages/jpype/_core.py:210: UserWarning:
-------------------------------------------------------------------------------
Deprecated: convertStrings was not specified when starting the JVM. The default
behavior in JPype will be False starting in JPype 0.8. The recommended setting
for new ... | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Spacy (์ด๋ฏธ ์ค์น๋์ด ์์) | # ์ค์น๊ฐ ๋์ด์๋์ง ํ์ธ
!pip show spacy
# ์ค์น๊ฐ ๋์ด์๋์ง ํ์ธ (์๋ค๋ฉด ์๋์ค์น๋จ)
!python -m spacy download en_core_web_sm
import spacy
spacy_en = spacy.load('en_core_web_sm')
en_tokens = [t.text for t in spacy_en.tokenizer('Check that spacy tokenizer works.')]
print(en_tokens)
del en_tokens # ํ์ ์์ผ๋๊น ์ญ์ | ['Check', 'that', 'spacy', 'tokenizer', 'works', '.']
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
3. Define Tokenizing Functions๋ฌธ์ฅ์ ๋ฐ์ ๊ทธ๋ณด๋ค ์์ ์ด์ ํน์ ํํ์ ๋จ์์ ๋ฆฌ์คํธ๋ก ๋ฐํํด์ฃผ๋ ํจ์๋ฅผ ๊ฐ ์ธ์ด์ ๋ํด ์์ฑ- Korean: konlpy.tag.Okt() <- Twitter()์์ ๋ช
์นญ๋ณ๊ฒฝ- English: spacy.tokenizer Korean Tokenizer | #from konlpy.tag import Okt
class KoTokenizer(object):
"""For Korean."""
def __init__(self):
self.tokenizer = Okt()
def tokenize(self, text):
tokens = self.tokenizer.pos(text)
tokens = [t[0] for t in tokens]
return tokens
# Usage example
print(KoTokenizer().tokenize... | ['์ ', '์ฒ๋ฆฌ', '๋', '์ธ์ ๋', '์ง๊ฒจ์์', '.']
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
English Tokenizer | #import spacy
class EnTokenizer(object):
"""For English."""
def __init__(self):
self.spacy_en = spacy.load('en_core_web_sm')
def tokenize(self, text):
tokens = [t.text for t in self.spacy_en.tokenizer(text)]
return tokens
# Usage example
print(EnTokenizer().tokenize("What I... | ['What', 'I', 'can', 'not', 'create', ',', 'I', 'do', "n't", 'understand', '.']
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
4. Data Preprocessing Load data | # Current working directory & list of files
!echo 'Current working directory:' ${PWD}
!ls -al
DATA_DIR = './data/'
print('Data directory exists:', os.path.isdir(DATA_DIR))
print('List of files:')
print(*os.listdir(DATA_DIR), sep='\n')
def get_data_from_tar_gz(filename):
"""
Retrieve contents from a `tar.gz` fil... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Define Datasets | #from torchtext.data import Dataset
#from torchtext.data import Example
class KoEnTranslationDataset(Dataset):
"""A dataset for Korean-English Neural Machine Translation."""
@staticmethod
def sort_key(ex):
return torchtext.data.interleave_keys(len(ex.src), len(ex.trg))
def __init__(se... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Define Fields- Instantiate tokenizers; one for each language.- The 'tokenize' argument of `Field` requires a tokenizing function. | #from torchtext.data import Field
ko_tokenizer = KoTokenizer() # korean tokenizer
en_tokenizer = EnTokenizer() # english tokenizer
# Field instance for korean
KOREAN = Field(
init_token='<sos>',
eos_token='<eos>',
tokenize=ko_tokenizer.tokenize,
batch_first=True,
lower=False
)
# Field instance ... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Instantiate datasets- one for each set (train, dev, test) | # ํ์ต์๊ฐ ๋จ์ถ์ ์ํด ํ์ต ๋ฐ์ดํฐ ์ค์ด๊ธฐ
MAX_TRAIN_SAMPLES = 10000
# Instantiate with data
train_set = KoEnTranslationDataset(train_dict, field_dict, max_samples=MAX_TRAIN_SAMPLES)
print('Train set ready.')
print('#. examples:', len(train_set.examples))
dev_set = KoEnTranslationDataset(dev_dict, field_dict)
print('Dev set ready...')... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Build Vocabulary- ๊ฐ ์ธ์ด๋ณ ์์ฑ: `Field`์ ์ธ์คํด์ค๋ฅผ ํ์ฉ- ์ต์ ๋น๋์(`MIN_FREQ`) ๊ฐ์ ์๊ฒ ํ๋ฉด vocabulary์ ํฌ๊ธฐ๊ฐ ์ปค์ง.- ์ต์ ๋น๋์(`MIN_FREQ`) ๊ฐ์ ํฌ๊ฒ ํ๋ฉด vocabulary์ ํฌ๊ธฐ๊ฐ ์์์ง. | MIN_FREQ = 2 # TODO: try different values
# Build vocab for Korean
KOREAN.build_vocab(train_set, dev_set, test_set, min_freq=MIN_FREQ) # ko
print('Size of source vocab (ko):', len(KOREAN.vocab))
# Check indices of some important tokens
tokens = ['<unk>', '<pad>', '<sos>', '<eos>']
for token in tokens:
print(f"{to... | <unk> -> 0
<pad> -> 1
<sos> -> 2
<eos> -> 3
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Configure Device- *'๋ฐํ์' -> '๋ฐํ์ ์ ํ๋ณ๊ฒฝ'* ์์ ํ๋์จ์ด ๊ฐ์๊ธฐ๋ก **GPU** ์ ํ | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Device to use:', device) | Device to use: cuda
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Create Data Iterators- ๋ฐ์ดํฐ๋ฅผ ๋ฏธ๋๋ฐฐ์น(mini-batch) ๋จ์๋ก ๋ฐํํด์ฃผ๋ ์ญํ - `train_set`, `dev_set`, `test_set`์ ๋ํด ๊ฐ๋ณ์ ์ผ๋ก ์ ์ํด์ผ ํจ- `BATCH_SIZE`๋ฅผ ์ ์ํด์ฃผ์ด์ผ ํจ- `torchtext.data.BucketIterator`๋ ํ๋์ ๋ฏธ๋๋ฐฐ์น๋ฅผ ์๋ก ๋น์ทํ ๊ธธ์ด์ ๊ด์ธก์น๋ค๋ก ๊ตฌ์ฑํจ- [Bucketing](https://medium.com/@rashmi.margani/how-to-speed-up-the-training-of-the-sequence-model-using-bucketing-tech... | BATCH_SIZE = 128
#from torchtext.data import BucketIterator
# Train iterator
train_iterator = BucketIterator(
train_set,
batch_size=BATCH_SIZE,
train=True,
shuffle=True,
device=device
)
print(f'Number of minibatches per epoch: {len(train_iterator)}')
#from torchtext.data import BucketIterator
# D... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
5. Building Seq2Seq Model Hyperparameters | # Hyperparameters
INPUT_DIM = len(KOREAN.vocab)
OUTPUT_DIM = len(ENGLISH.vocab)
ENC_EMB_DIM = DEC_EMB_DIM = 100
ENC_HID_DIM = DEC_HID_DIM = 60
USE_BIDIRECTIONAL = False | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Encoder | class Encoder(nn.Module):
"""
Learns an embedding for the source text.
Arguments:
input_dim: int, size of input language vocabulary.
emb_dim: int, size of embedding layer output.
enc_hid_dim: int, size of encoder hidden state.
dec_hid_dim: int, size of decoder hidden stat... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Attention | class Attention(nn.Module):
def __init__(self, enc_hid_dim, dec_hid_dim, encoder_is_bidirectional=False):
super(Attention, self).__init__()
self.enc_hid_dim = enc_hid_dim
self.dec_hid_dim = dec_hid_dim
self.encoder_is_bidirectional = encoder_is_bidirectional
... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Decoder | class Decoder(nn.Module):
"""
Unlike the encoder, a single forward pass of
a `Decoder` instance is defined for only a single timestep.
Arguments:
output_dim: int,
emb_dim: int,
enc_hid_dim: int,
dec_hid_dim: int,
attention_module: torch.nn.Module,
encoder_... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Seq2Seq | class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, device):
super(Seq2Seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.device = device
def forward(self, src, trg, teacher_forcing_ratio=.5):
batch_size, max_seq... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Build Model | # Define encoder
enc = Encoder(
input_dim=INPUT_DIM,
emb_dim=ENC_EMB_DIM,
enc_hid_dim=ENC_HID_DIM,
dec_hid_dim=DEC_HID_DIM,
bidirectional=USE_BIDIRECTIONAL
)
print(enc)
# Define attention layer
attn = Attention(
enc_hid_dim=ENC_HID_DIM,
dec_hid_dim=DEC_HID_DIM,
encoder_is_bidirectional=... | The model has 5,500,930 trainable parameters.
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
6. Train Optimizer- Use `optim.Adam` or `optim.RMSprop`. | optimizer = optim.Adam(model.parameters(), lr=0.001)
#optimizer = optim.RMSprop(model.parameters(), lr=0.01) | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Loss function | # Padding indices should not be considered when loss is calculated.
PAD_IDX = ENGLISH.vocab.stoi['<pad>']
criterion = nn.CrossEntropyLoss(ignore_index=PAD_IDX) | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Train function | def train(seq2seq_model, iterator, optimizer, criterion, grad_clip=1.0):
seq2seq_model.train()
epoch_loss = .0
for i, batch in enumerate(iterator):
print('.', end='')
src = batch.src
trg = batch.trg
optimizer.zero_grad()
... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Evaluate function | def evaluate(seq2seq_model, iterator, criterion):
seq2seq_model.eval()
epoch_loss = 0.
with torch.no_grad():
for i, batch in enumerate(iterator):
print('.', end='')
src = batch.src
trg = batch.trg
... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Epoch time measure function | def epoch_time(start_time, end_time):
"""Returns elapsed time in mins & secs."""
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Train for multiple epochs | NUM_EPOCHS = 50
import time
import math
best_dev_loss = float('inf')
for epoch in range(NUM_EPOCHS):
start_time = time.time()
train_loss = train(model, train_iterator, optimizer, criterion)
dev_loss = evaluate(model, dev_iterator, criterion)
end_time = time.time()
epoch_mins, e... | .........................................................................................
Epoch: 01 | Time: 1m 19s
Train Loss: 7.2537 | Train Perplexity: 1413.394
Dev Loss: 6.5596 | Dev Perplexity: 705.983
.........................................................................................
Epoch: 02 | Time: 1m 1... | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Save last model (overfitted) | torch.save(model.state_dict(), './last_model.pt') | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
7. Test Function to convert indices to original text strings | def indices_to_text(src_or_trg, lang_field):
assert src_or_trg.dim() == 1, f'{src_or_trg.dim()}' #(seq_len, )
assert isinstance(lang_field, torchtext.data.Field)
assert hasattr(lang_field, 'vocab')
return [lang_field.vocab.itos[t] for t in src_or_trg] | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Function to make predictions- Returns a list of examples, where each example is a (src, trg, prediction) tuple. | def predict(seq2seq_model, iterator):
seq2seq_model.eval()
out = []
with torch.no_grad():
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
decoder_outputs = seq2seq_model(src, trg, teacher_forcing_ratio=... | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Load best model | !ls -al
# Load model
model.load_state_dict(torch.load('./best_model.pt')) | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
Make predictions | # Make prediction
test_predictions = predict(model, dev_iterator)
for i, prediction in enumerate(test_predictions):
src, trg, pred = prediction
src_text = indices_to_text(src, lang_field=KOREAN)
trg_text = indices_to_text(trg, lang_field=ENGLISH)
pred_text = indices_to_text(pred, lang_field=EN... | source:
['<sos>', '์ค๋ซ๋์', '์ดํ๋ฆฌ์', '์ ์ญ', '์ด', '๊ณคํน', '์ค๋ฌ์ ๋ค', '.', '<eos>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>']
target:
['<sos>', 'naples', ',', 'italy', '(', 'cnn', ')', 'for', 'years', ',', 'it', "'s", 'been', 'a', 'national', 'embarrassment', '.', '<eos>', '<pad>']
prediction:
['<... | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
8. Download Model | !ls -al
from google.colab import files
print('Downloading models...') # Known bug; if using Firefox, a print statement in the same cell is necessary.
files.download('./best_model.pt')
files.download('./last_model.pt') | Downloading models...
| MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch |
9. Discussions | _____no_output_____ | MIT | colab/NMT-Seq2SeqWithAttention.ipynb | drlego9/NMT-pytorch | |
Imports and Paths | import urllib3
http = urllib3.PoolManager()
from urllib import request
from bs4 import BeautifulSoup, Comment
import pandas as pd
from datetime import datetime
# from shutil import copyfile
# import time
import json | _____no_output_____ | MIT | notebooks/bgg_weekly_crawler.ipynb | MichoelSnow/BGG |
Load in previous list of games | df_gms_lst = pd.read_csv('../data/bgg_top2000_2018-10-06.csv')
df_gms_lst.columns
metadata_dict = {"title": "BGG Top 2000",
"subtitle": "Board Game Geek top 2000 games rankings",
"description": "Board Game Geek top 2000 games rankings and other info",
"id": "mseinstein/... | _____no_output_____ | MIT | notebooks/bgg_weekly_crawler.ipynb | MichoelSnow/BGG |
Get the id's of the top 2000 board games | pg_gm_rnks = 'https://boardgamegeek.com/browse/boardgame/page/'
def extract_gm_id(soup):
rows = soup.find('div', {'id': 'collection'}).find_all('tr')[1:]
id_list = []
for row in rows:
id_list.append(int(row.find_all('a')[1]['href'].split('/')[2]))
return id_list
def top_2k_gms(pg_gm_rnks):
g... | _____no_output_____ | MIT | notebooks/bgg_weekly_crawler.ipynb | MichoelSnow/BGG |
Extract the info for each game in the top 2k using the extracted game id's | bs_pg = 'https://www.boardgamegeek.com/xmlapi2/'
bs_pg_gm = f'{bs_pg}thing?type=boardgame&stats=1&ratingcomments=1&page=1&pagesize=10&id='
def extract_game_item(item):
gm_dict = {}
field_int = ['yearpublished', 'minplayers', 'maxplayers', 'playingtime', 'minplaytime', 'maxplaytime', 'minage']
field_categ = ... | _____no_output_____ | MIT | notebooks/bgg_weekly_crawler.ipynb | MichoelSnow/BGG |
Code for kagglekaggle datasets version -m "week of 2018-10-20" -p .\ -d | meta_dict
gm_list = []
idx_split = 4
idx_size = int(len(gm_ids)/idx_split)
for i in range(idx_split):
idx = str(gm_ids[i*idx_size:(i+1)*idx_size]).replace(' ','')[1:-1]
break
idx2 = '174430,161936,182028,167791,12333,187645,169786,220308,120677,193738,84876,173346,180263,115746,3076,102794,205637'
pg = reque... | _____no_output_____ | MIT | notebooks/bgg_weekly_crawler.ipynb | MichoelSnow/BGG |
Artificial Intelligence Nanodegree Voice User Interfaces Project: Speech Recognition with Neural Networks---In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included cod... | %load_ext autoreload
%autoreload 1
%pip install python_speech_features
!rm -rf AIND-VUI-Capstone/
!git clone https://github.com/RomansWorks/AIND-VUI-Capstone
!cp -r ./AIND-VUI-Capstone/* .
!wget https://filebin.net/archive/s14yfd2p3q0sj1r2/zip
!unzip zip
!7z x capstone-ds.zip
!mv aind-vui-capstone-ds-processed/* .
!rm ... | There are 2136 total training examples.
| MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
The following code cell visualizes the audio waveform for your chosen example, along with the corresponding transcript. You also have the option to play the audio in the notebook! | from IPython.display import Markdown, display
from data_generator import vis_train_features, plot_raw_audio
from IPython.display import Audio
%matplotlib inline
# plot audio signal
plot_raw_audio(vis_raw_audio)
# print length of audio signal
display(Markdown('**Shape of Audio Signal** : ' + str(vis_raw_audio.shape)))
... | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
STEP 1: Acoustic Features for Speech RecognitionFor this project, you won't use the raw audio waveform as input to your model. Instead, we provide code that first performs a pre-processing step to convert the raw audio to a feature representation that has historically proven successful for ASR models. Your acoustic ... | from data_generator import plot_spectrogram_feature
# plot normalized spectrogram
plot_spectrogram_feature(vis_spectrogram_feature)
# print shape of spectrogram
display(Markdown('**Shape of Spectrogram** : ' + str(vis_spectrogram_feature.shape))) | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Mel-Frequency Cepstral Coefficients (MFCCs)The second option for an audio feature representation is [MFCCs](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum). You do **not** need to dig deeply into the details of how MFCCs are calculated, but if you would like more information, you are welcome to peruse the [docu... | from data_generator import plot_mfcc_feature
# plot normalized MFCC
plot_mfcc_feature(vis_mfcc_feature)
# print shape of MFCC
display(Markdown('**Shape of MFCC** : ' + str(vis_mfcc_feature.shape))) | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
When you construct your pipeline, you will be able to choose to use either spectrogram or MFCC features. If you would like to see different implementations that make use of MFCCs and/or spectrograms, please check out the links below:- This [repository](https://github.com/baidu-research/ba-dls-deepspeech) uses spectrog... | #####################################################################
# RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK #
#####################################################################
# allocate 50% of GPU memory (if you like, feel free to change this)
# from keras.backend.tensorflow_backend ... | The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
| MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Model 0: RNNGiven their effectiveness in modeling sequential data, the first acoustic model you will use is an RNN. As shown in the figure below, the RNN we supply to you will take the time sequence of audio features as input.At each time step, the speaker pronounces one of 28 possible characters, including each of t... | model_0 = simple_rnn_model(input_dim=161) # change to 13 if you would like to use MFCC features | Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
the_input (InputLayer) [(None, None, 161)] 0
... | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
As explored in the lesson, you will train the acoustic model with the [CTC loss](http://www.cs.toronto.edu/~graves/icml_2006.pdf) criterion. Custom loss functions take a bit of hacking in Keras, and so we have implemented the CTC loss function for you, so that you can focus on trying out as many deep learning architec... | from tensorflow.keras.optimizers import Adam
train_model(input_to_softmax=model_0,
pickle_path='model_0.pickle',
save_model_path='model_0.h5',
minibatch_size=25,
optimizer=Adam(learning_rate=0.1, clipnorm=5), #SGD(lr=0.002, decay=1e-6, momentum=0.9, nesterov=True, clip... | /content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
callbacks=[checkpointer], verbose=verbose)
| MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
(IMPLEMENTATION) Model 1: RNN + TimeDistributed DenseRead about the [TimeDistributed](https://keras.io/layers/wrappers/) wrapper and the [BatchNormalization](https://keras.io/layers/normalization/) layer in the Keras documentation. For your next architecture, you will add [batch normalization](https://arxiv.org/pdf/1... | model_1 = rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features
units=200,
activation='relu') | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_1.h5`. The loss history is [saved](https://wiki.python.org/moin/Usi... | train_model(input_to_softmax=model_1,
pickle_path='model_1.pickle',
save_model_path='model_1.h5',
optimizer=Adam(clipvalue=0.5, clipnorm=1.0),
spectrogram=True) # change to False if you would like to use MFCC features | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
(IMPLEMENTATION) Model 2: CNN + RNN + TimeDistributed DenseThe architecture in `cnn_rnn_model` adds an additional level of complexity, by introducing a [1D convolution layer](https://keras.io/layers/convolutional/conv1d). This layer incorporates many arguments that can be (optionally) tuned when calling the `cnn_rnn_... | model_2 = cnn_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features
filters=200,
kernel_size=11,
conv_stride=2,
conv_border_mode='valid',
units=100) | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_2.h5`. The loss history is [saved](https://wiki.python.org/moin/Usi... | train_model(input_to_softmax=model_2,
pickle_path='model_2.pickle',
save_model_path='model_2.h5',
optimizer=Adam(clipvalue=0.5),
spectrogram=True) # change to False if you would like to use MFCC features | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
(IMPLEMENTATION) Model 3: Deeper RNN + TimeDistributed DenseReview the code in `rnn_model`, which makes use of a single recurrent layer. Now, specify an architecture in `deep_rnn_model` that utilizes a variable number `recur_layers` of recurrent layers. The figure below shows the architecture that should be returned... | model_3 = deep_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features
units=100,
recur_layers=2) | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_3.h5`. The loss history is [saved](https://wiki.python.org/moin/Usi... | train_model(input_to_softmax=model_3,
pickle_path='model_3.pickle',
save_model_path='model_3.h5',
optimizer=Adam(clipvalue=0.5),
spectrogram=True) # change to False if you would like to use MFCC features | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
(IMPLEMENTATION) Model 4: Bidirectional RNN + TimeDistributed DenseRead about the [Bidirectional](https://keras.io/layers/wrappers/) wrapper in the Keras documentation. For your next architecture, you will specify an architecture that uses a single bidirectional RNN layer, before a (`TimeDistributed`) dense layer. T... | model_4 = bidirectional_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features
units=100) | Model: "model_17"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
the_input (InputLayer) [(None, None, 161)] 0
... | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_4.h5`. The loss history is [saved](https://wiki.python.org/moin/Usi... | train_model(input_to_softmax=model_4,
pickle_path='model_4.pickle',
save_model_path='model_4.h5',
optimizer=Adam(clipvalue=0.5),
spectrogram=True) # change to False if you would like to use MFCC features | /content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
callbacks=[checkpointer], verbose=verbose)
| MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
(OPTIONAL IMPLEMENTATION) Models 5+If you would like to try out more architectures than the ones above, please use the code cell below. Please continue to follow the same convention for saving the models; for the $i$-th sample model, please save the loss at **`model_i.pickle`** and saving the trained model at **`mode... | ## (Optional) TODO: Try out some more models!
### Feel free to use as many code cells as needed.
model_5 = dilated_double_cnn_rnn_model(input_dim=161,
filters=200,
kernel_size=6,
conv_border_mode='valid'... | Model: "model_11"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
the_input (InputLayer) [(None, None, 161)] 0
... | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Compare the ModelsExecute the code cell below to evaluate the performance of the drafted deep learning models. The training and validation loss are plotted for each model. | from glob import glob
import numpy as np
import _pickle as pickle
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set_style(style='white')
# obtain the paths for the saved model history
all_pickles = sorted(glob("results/*.pickle"))
# extract the name of each model
model_names = [item[8:-7... | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
__Question 1:__ Use the plot above to analyze the performance of each of the attempted architectures. Which performs best? Provide an explanation regarding why you think some models perform better than others. __Answer:__ (IMPLEMENTATION) Final ModelNow that you've tried out many sample models, use what you've learn... | # specify the model
model_end = final_model() | Model: "model_7"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
the_input (InputLayer) [(None, None, 161)] 0
... | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_end.h5`. The loss history is [saved](https://wiki.python.org/moin/U... | train_model(input_to_softmax=model_end,
pickle_path='model_end.pickle',
save_model_path='model_end.h5',
optimizer=Adam(clipvalue=0.5, amsgrad=True),
spectrogram=True) # change to False if you would like to use MFCC features | /content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
callbacks=[checkpointer], verbose=verbose)
| MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
__Question 2:__ Describe your final model architecture and your reasoning at each step. __Answer:__ STEP 3: Obtain PredictionsWe have written a function for you to decode the predictions of your acoustic model. To use the function, please execute the code cell below. | import numpy as np
from data_generator import AudioGenerator
from keras import backend as K
from utils import int_sequence_to_text
from IPython.display import Audio
def get_predictions(index, partition, input_to_softmax, model_path):
""" Print a model's decoded predictions
Params:
index (int): The exam... | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Use the code cell below to obtain the transcription predicted by your final model for the first example in the training dataset. | get_predictions(index=0,
partition='train',
input_to_softmax=final_model(),
model_path='model_end.h5') | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Use the next code cell to visualize the model's prediction for the first example in the validation dataset. | get_predictions(index=0,
partition='validation',
input_to_softmax=final_model(),
model_path='model_end.h5') | _____no_output_____ | MIT | vui_notebook.ipynb | RomansWorks/AIND-VUI-Capstone |
Logistic Regression
ROMรNฤ
รn final, o sฤ observฤm dacฤ Google PlayStore a avut destule date pentru a putea prezice popularitatea unei aplicaศii de trading sau pentru topul jocurilor plฤtite.
Lucrul acesta se va face prin รฎmpฤrศirea descฤrcฤrilor รฎn 2 variabile dummy. Cu mai mult de 1.000.000 pentru variabila 1 ศi ... | from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
def Log_reg(x,y):
model = LogisticRegression(solver='... | Model accuracy 0.847457627118644
| Apache-2.0 | Code/LogisticRegression.ipynb | IulianRo3/Predicting-GooglePlayStore-Apps-Succes-Through-Logistic-Regression |
Import libraries and dataDataset was obtained in the capstone project description (direct link [here](https://d3c33hcgiwev3.cloudfront.net/_429455574e396743d399f3093a3cc23b_capstone.zip?Expires=1530403200&Signature=FECzbTVo6TH7aRh7dXXmrASucl~Cy5mlO94P7o0UXygd13S~Afi38FqCD7g9BOLsNExNB0go0aGkYPtodekxCGblpc3I~R8TCtWRrys~... | import pandas as pd
import numpy as np | _____no_output_____ | MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Preprocess dataFloat data came with ',' in the csv and python works with '.', so it treated the number as text. In order to convert them to numbers, I first replaced all the commas by punct and then converted the columns to float. | items = pd.read_csv('data/capstone/Capstone Data - Office Products - Items.csv', index_col=0)
actual_ratings = pd.read_csv('data/capstone/Capstone Data - Office Products - Ratings.csv', index_col=0)
content_based = pd.read_csv('data/capstone/Capstone Data - Office Products - CBF.csv', index_col=0)
user_user = pd.rea... | items.shape = (200, 7)
actual_ratings.shape = (200, 100)
content_based.shape = (200, 100)
user_user.shape = (200, 100)
item_item.shape = (200, 100)
matrix_fact.shape = (200, 100)
pers_bias.shape = (200, 100)
| MIT | notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb | sparsh-ai/reco-tut-asr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.