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 |
|---|---|---|---|---|---|
File and network functions | #export
#NB: Please don't move this to a different line or module, since it's used in testing `get_source_link`
@patch
def ls(self:Path, file_type=None, file_exts=None):
"Contents of path as a list"
extns=L(file_exts)
if file_type: extns += L(k for k,v in mimetypes.types_map.items() if v.startswith(file_typ... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
We add an `ls()` method to `pathlib.Path` which is simply defined as `list(Path.iterdir())`, mainly for convenience in REPL environments such as notebooks. | path = Path()
t = path.ls()
assert len(t)>0
t[0] | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
You can also pass an optional `file_type` MIME prefix and/or a list of file extensions. | txt_files=path.ls(file_type='text')
assert len(txt_files) > 0 and txt_files[0].suffix=='.py'
ipy_files=path.ls(file_exts=['.ipynb'])
assert len(ipy_files) > 0 and ipy_files[0].suffix=='.ipynb'
txt_files[0],ipy_files[0]
#hide
pkl = pickle.dumps(path)
p2 =pickle.loads(pkl)
test_eq(path.ls()[0], p2.ls()[0])
def bunzip(fn)... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Tensor functions | #export
def apply(func, x, *args, **kwargs):
"Apply `func` recursively to `x`, passing on args"
if is_listy(x): return type(x)(apply(func, o, *args, **kwargs) for o in x)
if isinstance(x,dict): return {k: apply(func, v, *args, **kwargs) for k,v in x.items()}
return retain_type(func(x, *args, **kwargs),... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
This decorator is particularly useful for using numpy functions as fastai metrics, for instance: | from sklearn.metrics import f1_score
@np_func
def f1(inp,targ): return f1_score(targ, inp)
a1,a2 = array([0,1,1]),array([1,0,1])
t = f1(tensor(a1),tensor(a2))
test_eq(f1_score(a1,a2), t)
assert isinstance(t,Tensor)
class Module(nn.Module, metaclass=PrePostInitMeta):
"Same as `nn.Module`, but no need for subclasse... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Sorting objects from before/after Transforms and callbacks will have run_after/run_before attributes, this function will sort them to respect those requirements (if it's possible). Also, sometimes we want a tranform/callback to be run at the end, but still be able to use run_after/run_before behaviors. For those, the ... | #export
def _is_instance(f, gs):
tst = [g if type(g) in [type, 'function'] else g.__class__ for g in gs]
for g in tst:
if isinstance(f, g) or f==g: return True
return False
def _is_first(f, gs):
for o in L(getattr(f, 'run_after', None)):
if _is_instance(o, gs): return False
for g i... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Other helpers | #export
def round_multiple(x, mult, round_down=False):
"Round `x` to nearest multiple of `mult`"
def _f(x_): return (int if round_down else round)(x_/mult)*mult
res = L(x).mapped(_f)
return res if is_listy(x) else res[0]
test_eq(round_multiple(63,32), 64)
test_eq(round_multiple(50,32), 64)
test_eq(round... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Image helpers This is a quick way to generate, for instance, *train* and *valid* versions of a property. See `DataBunch` definition for an example of this. | #export
def make_cross_image(bw=True):
"Create a tensor containing a cross image, either `bw` (True) or color"
if bw:
im = torch.zeros(5,5)
im[2,:] = 1.
im[:,2] = 1.
else:
im = torch.zeros(3,5,5)
im[0,2,:] = 1.
im[1,:,2] = 1.
return im
plt.imshow(make_cros... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
`show_image` can show b&w images... | im = make_cross_image()
ax = show_image(im, cmap="Greys", figsize=(2,2)) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
...and color images with standard `c*h*w` dim order... | im2 = make_cross_image(False)
ax = show_image(im2, figsize=(2,2)) | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
...and color images with `h*w*c` dim order... | im3 = im2.permute(1,2,0)
ax = show_image(im3, figsize=(2,2))
ax = show_image(im, cmap="Greys", figsize=(2,2))
show_title("Cross", ax)
#export
def show_titled_image(o, **kwargs):
"Call `show_image` destructuring `o` to `(img,title)`"
show_image(o[0], title=str(o[1]), **kwargs)
#export
def show_image_batch(b, sho... | _____no_output_____ | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
Export - | #hide
from local.notebook.export import notebook2script
notebook2script(all_fs=True) | Converted 00_test.ipynb.
Converted 01_core.ipynb.
Converted 01a_dataloader.ipynb.
Converted 01a_script.ipynb.
Converted 02_transforms.ipynb.
Converted 03_pipeline.ipynb.
Converted 04_data_external.ipynb.
Converted 05_data_core.ipynb.
Converted 06_data_source.ipynb.
Converted 07_vision_core.ipynb.
Converted 08_pets_tuto... | Apache-2.0 | dev/01_core.ipynb | nareshr8/fastai_dev |
2์ฐจ์ ์ต์ ํTwo dimensional optimizations๋ค์๊ณผ ๊ฐ์ ๋น์ฉ ํจ์๋ฅผ ์๊ฐํด ๋ณด์.Let's think about a cost function as follows.$$C(x_0, x_1) = \frac{x_0^2}{2^2} + \frac{x_1^2}{1^2}$$ํ์ด์ฌ์ผ๋ก๋ ๋ค์๊ณผ ๊ฐ์ด ๊ตฌํํ ์ ์์ ๊ฒ์ด๋ค.We may implement in python as follows. | def c(x:np.ndarray, a:float=2, b:float=1) -> float:
x0 = x[0]
x1 = x[1]
return (x0 * x0) / (a * a) + (x1 * x1) / (b * b)
| _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
์๊ฐํ ํด ๋ณด์.Let's visualize. | def plot_cost():
# ref : https://matplotlib.org/stable/gallery/
fig = plt.figure(figsize=(15, 6))
ax1 = plt.subplot(1, 2, 1)
ax2 = plt.subplot(1, 2, 2, projection="3d")
x = np.linspace(-4, 4)
y = np.linspace(-2, 2)
X, Y = np.meshgrid(x, y)
Z = c((X, Y))
cset = ax1.contour(X, Y, Z... | _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
์ค๊ฐ ๊ณผ์ ์ ๊ทธ๋ํ๋ฅผ ๊ทธ๋ ค ์ฃผ๋ ๋น์ฉ ํจ์๋ฅผ ์ ์ธDeclare another cost function that will plot intermediate results | def get_cost_with_plot(a=2, b=1, b_triangle=True):
x0_history = []
x1_history = []
c_history = []
def cost_with_plot(x, a=a, b=b):
'''
์ด๋ฐ ํจ์๋ฅผ ํด๋ก์ ธ ๋ผ๊ณ ๋ถ๋ฆ. ๋ค๋ฅธ ํจ์์ ๋ด๋ถ ํจ์์ด๋ฉด์ ํด๋น ํจ์์ ๋ฐํ๊ฐ.
This is a closuer; an internal function being a return value
'''
ax1, ax2 = plot_... | _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
Nelder-Mead ๋ฒref : [[0]](https://en.wikipedia.org/wiki/Nelder-Mead_method)Nelder-Mead ๋ฒ์ ๋น์ฉํจ์์ ๋
๋ฆฝ๋ณ์๊ฐ $n$ ์ฐจ์์ธ ๊ฒฝ์ฐ, $n+1$ ๊ฐ์ ์ ์ผ๋ก ์ด๋ฃจ์ด์ง **simplex**๋ฅผ ์ด์ฉํ๋ค.If the independend variables of the cost function is $n$-dimensional, the Nelder-Mead method uses a **simplex** of $n+1$ vertices. | fmin_result = so.fmin(cost_with_plot, [3.0, 1.0])
fmin_result
| _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
Newton-CG ๋ฒ๋น์ฉํจ์๋ฅผ ๊ฐ๊ฐ $x_0$, $x_1$์ ๋ํด ํธ๋ฏธ๋ถ ํด ๋ณด์.Let's get the partial derivatives of the cost function over $x_0$ and $x_1$.$$C(x_0, x_1) = \frac{x_0^2}{2^2} + \frac{x_1^2}{1^2} \\\frac{\partial C}{\partial x_0} = 2 \cdot \frac{x_0}{2^2} \\\frac{\partial C}{\partial x_1} = 2 \cdot \frac{x_1}{1^2}$$ํ์ด์ฌ์ผ๋ก๋ ๋ค์๊ณผ ๊ฐ์ด ๊ตฌํํ ์ ์์... | def jacobian(x, a=2, b=1):
x0 = x[0]
x1 = x[1]
return (2 * x0 / (a*a), 2 * x1 / (b*b),)
| _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
์ต์ ํ์๋ ๊ธฐ์ธ๊ธฐ๋ฅผ ์ฌ์ฉํ ์ ์๋ค.We can also use the slopes in the optimization. | cost_with_plot = get_cost_with_plot(b_triangle=False)
fmin_newton = so.minimize(cost_with_plot, [3.0, 1.0], jac=jacobian, method="newton-cg")
fmin_newton
| _____no_output_____ | BSD-3-Clause | 15_Optimization/015_two_dimensional_optimization.ipynb | kangwonlee/2109eca-nmisp-template |
Build a medium size KG from a CSV dataset First let's initialize the KG object as we did previously: | import kglab
namespaces = {
"wtm": "http://purl.org/heals/food/",
"ind": "http://purl.org/heals/ingredient/",
"skos": "http://www.w3.org/2004/02/skos/core#",
}
kg = kglab.KnowledgeGraph(
name = "A recipe KG example based on Food.com",
base_uri = "https://www.food.com/recipe/",
namespaces... | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Here's a way to describe the namespaces that are available to use: | kg.describe_ns() | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Next, we'll define a dictionary that maps (somewhat magically) from strings (i.e., "labels") to ingredients defined in the vocabulary: | common_ingredient = {
"water": kg.get_ns("ind").Water,
"salt": kg.get_ns("ind").Salt,
"pepper": kg.get_ns("ind").BlackPepper,
"black pepper": kg.get_ns("ind").BlackPepper,
"dried basil": kg.get_ns("ind").Basil,
"butter": kg.get_ns("ind").Butter,
"milk": kg.get_ns("ind").CowMilk,
"egg": ... | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
This is where use of NLP work to produce *annotations* begins to overlap with KG pratices. Now let's load our dataset of recipes โ the `dat/recipes.csv` file in CSV format โ into a `pandas` dataframe: | import pandas as pd
df = pd.read_csv("../dat/recipes.csv")
df.head() | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Then iterate over the rows in the dataframe, representing a recipe in the KG for each row: | import rdflib
for index, row in df.iterrows():
recipe_id = row["id"]
node = rdflib.URIRef("https://www.food.com/recipe/{}".format(recipe_id))
kg.add(node, kg.get_ns("rdf").type, kg.get_ns("wtm").Recipe)
recipe_name = row["name"]
kg.add(node, kg.get_ns("skos").definition, rdflib.Literal(recipe_name... | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Notice how the `xsd:duration` literal is now getting used to represent cooking times.We've structured this example such that each of the recipes in the CSV file has a known representation for all of its ingredients.There are nearly 250K recipes in the full dataset from so the `common_ingredient` dictionary would need ... | VIS_STYLE = {
"wtm": {
"color": "orange",
"size": 20,
},
"ind":{
"color": "blue",
"size": 35,
},
}
subgraph = kglab.SubgraphTensor(kg)
pyvis_graph = subgraph.build_pyvis_graph(notebook=True, style=VIS_STYLE)
pyvis_graph.force_atlas_2based()
pyvis_graph.show("tmp.fig01.h... | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Given the defaults for this kind of visualization, there's likely a dense center mass of orange (recipes) at the center, with a close cluster of common ingredients (dark blue), surrounded by less common ingredients and cooking times (light blue). Performance analysis of serialization methods Let's serialize this recip... | import time
write_times = []
t0 = time.time()
kg.save_rdf("tmp.ttl")
write_times.append(round((time.time() - t0) * 1000.0, 2)) | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
Let's also serialize the KG into the other formats that we've been using, to compare relative sizes for a medium size KG: | t0 = time.time()
kg.save_rdf("tmp.xml", format="xml")
write_times.append(round((time.time() - t0) * 1000.0, 2))
t0 = time.time()
kg.save_jsonld("tmp.jsonld")
write_times.append(round((time.time() - t0) * 1000.0, 2))
t0 = time.time()
kg.save_parquet("tmp.parquet")
write_times.append(round((time.time() - t0) * 1000.0, ... | _____no_output_____ | MIT | examples/ex2_0.ipynb | vzkqwvku/kglab |
https://colab.research.google.com/drive/1OmAdxU_Lw7r-tMXiTOeSI7NWgB3AF9QF Issue with image translation | from keras.datasets import mnist
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
import matplotlib.pyplot as plt
%matplotlib inline
(X_train, y_train), (X_test, y_test) = mnist.load_data()
... | _____no_output_____ | MIT | Chapter04/Issue_with_image_translation.ipynb | PacktPublishing/Neural-Networks-with-Keras-Cookbook |
Deep Learining project* Gianfranco Di Marco - 1962292* Giacomo Colizzi Coin - 1794538\**- Trajectory Prediction -**Is the problem of predicting the short-term (1-3 seconds) and long-term (3-5 seconds) spatial coordinates of various road-agents such as cars, buses, pedestrians, rickshaws, and animals, etc. These ro... | # Necessary since Google Colab supports only Python 3.7
# -> some libraries can be different from local and Colab
try:
import google.colab
from google.colab import drive
ENVIRONMENT = 'colab'
%pip install tf-estimator-nightly==2.8.0.dev2021122109
%pip install folium==0.2.1
except:
ENVIRONMENT = ... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Libraries** | %pip install nuscenes-devkit
%pip install pytorch-lightning
# Learning
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet50
from torchvision.transforms import Normalize
from torchmetrics import functional
import pytorch_lightning as pl
from pytorch_lightning.callbac... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Configuration **Generic Parameters** | # Environment-dependent parameters
if ENVIRONMENT == 'colab':
ROOT = '/content/drive/MyDrive/DL/Trajectory-Prediction-PyTorch/'
MAX_NUM_WORKERS = 0
MAX_BATCH_SIZE = 8
PROGRESS_BAR_REFRESH_RATE = 20
elif ENVIRONMENT == 'local':
ROOT = os.getcwd()
# TODO: solve problem with VRAM with PL
if os.... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Network Parameters** | # TODO: add other baselines
PREDICTION_MODEL = 'CoverNet'
if PREDICTION_MODEL == 'CoverNet':
# - Architecture parameters
BACKBONE_WEIGHTS = 'ImageNet'
BACKBONE_MODEL = 'ResNet18'
K_SIZE = 20000
# - Trajectory parameters
AGENT_HISTORY = 1
SHORT_TERM_HORIZON = 3
LONG_TERM_HORIZON = 6
T... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Dataset Parameters** | # Organization parameters
PREPARE_DATASET = False
PREPROCESSED = True
# File system parameters
PL_SEED = 42
DATAROOT = os.path.join(ROOT, 'data', 'sets', 'nuscenes')
PREPROCESSED_FOLDER = 'preprocessed'
GT_SUFFIX = '-gt'
FILENAME_EXT = '.pt'
DATASET_VERSION = 'v1.0-trainval'
AGGREGATORS = [{'name': "RowMean"}]
# Othe... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Dataset **Initialization**N.B: The download links in function *urllib.request.urlretrieve()* should be replaced periodically because it expires. Steps to download correctly are (on Firefox):1. Dowload Map Expansion pack (or Trainval metadata) from the website2. Stop the download3. Right-click on the file -> copy... | # Drive initialization
if ENVIRONMENT == 'colab':
drive.mount('/content/drive')
if PREPARE_DATASET:
# Creating dataset dir
os.makedirs(DATAROOT, exist_ok=True)
os.chdir(DATAROOT)
# Downloading Map Expansion Pack
os.mkdir('maps')
os.chdir('maps')
print("Downloading and extracting Map Ex... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Dataset definition** | class TrajPredDataset(torch.utils.data.Dataset):
""" Trajectory Prediction Dataset
Base Class for Trajectory Prediction Datasets
"""
def __init__(self, dataset, name, data_type, preprocessed, split,
dataroot, preprocessed_folder, filename_ext,
gt_suffix, traj_horizon, ... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Models **Covernet** | class CoverNet(pl.LightningModule):
""" CoverNet model for Trajectory Prediction """
def __init__(self, K_size, epsilon, traj_link, traj_dir, device,
lr=LEARNING_RATE, momentum=MOMENTUM,
traj_samples=SAMPLES_PER_SECOND*TRAJ_HORIZON):
""" CoverNet initialization
... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Utilities **Metrics** | def compute_metrics(predictions: List[data_classes.Prediction], ground_truths: List[np.ndarray],
helper, aggregators=AGGREGATORS) -> Dict[str, Any]:#Dict[str, Dict[str, List[float]]]:
""" Utility eval function to compute dataset metrics
Parameters
----------
predictions: list of pr... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Plotting** | def plot_train_data(train_iterations, val_iterations, epoches, train_losses, val_losses):
""" Plot a graph with the training trend
Parameters
----------
train_iterations: number of iterations for each epoch [train]
val_iterations: number of iterations for each epoch [val]
epoches: actual epoch ... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Main **Initialization** | # ---------- Dataset initialization ---------- #
# Initialize nuScenes helper
print("nuScenes Helper initialization ...")
start_time = time.time()
pl.seed_everything(PL_SEED)
if ENVIRONMENT == 'local':
if PREPARE_DATASET:
nusc = NuScenes(version=DATASET_VERSION, dataroot=DATAROOT, verbose=True)
with... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Training loop** | trainer.fit(model, trainval_dm) | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Testing** | # Dataloader initialization
print("Loading test dataloader ...")
trainval_dm.setup(stage='test')
test_dataloader = trainval_dm.test_dataloader()
test_generator = iter(test_dataloader)
# Trained model initialization
# TODO: istantiate kwargs for network in a better way
print("\nCoverNet trained model initialization ...... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
Code Debugging **Training loop** (manual - debug only) | if DEBUG_MODE:
# Dataset preparation
train_dataloader = torch.utils.data.DataLoader(train_dataset, BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS, drop_last=True)
val_dataloader = torch.utils.data.DataLoader(val_dataset, BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS, drop_last=True)
# Training... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Dataset debugging** | # Initialize nuScenes
HELPER_NEEDED = True
if ENVIRONMENT == 'local':
if PREPARE_DATASET:
nusc = NuScenes(version=DATASET_VERSION, dataroot=DATAROOT, verbose=True)
with open(os.path.join(ROOT, 'nuscenes_checkpoint'+FILENAME_EXT), 'wb') as f:
pickle.dump(nusc, f, protocol=pickle.HIGHEST_P... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
**Network debugging** | test_states, test_imgs, test_gts, _ = next(train_generator)
test_states = torch.flatten(test_states, 0, 1)
print(test_imgs.size())
print(test_states.size())
# Prediction
model = CoverNet(K_SIZE, EPSILON, TRAJ_LINK, TRAJ_DIR, device='cuda:0')
traj_logits = model((test_imgs, test_states))
# Output 5 and 10 most likely ... | _____no_output_____ | MIT | Trajectory_Prediction.ipynb | Gianfranco-98/Trajectory-Prediction-PyTorch |
OpenVisus Enabled Jupyter Notebook OpenViSUS: imports and utilities | %matplotlib notebook
import os,sys
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import *
import OpenVisus as ov
# Enable I/O component of OpenVisus
ov.DbModule.attach()
# function to plot the image data with matplotlib
# optional parameters: colormap, existing plot to reuse (for more interacti... | _____no_output_____ | MIT | jupyter/OpenVisus-Template.ipynb | ComputingElevatedLab/sciviscourse |
Computo concurrente Multiprocessing El modulo 'multiprocessing' de Python permite la manipulacion y sincronizacion de procesos, tambien ofrece concurrencia local como remota.Ejemplo de motivacion... | import time
def calc_cuad(numeros):
print('Calcula el cuadrado:')
for n in numeros:
time.sleep(0.2)
print('cuadrado:', n*n)
def calc_cubo(numeros):
print('Calcula el cubo:')
for n in numeros:
time.sleep(0.2)
print('cubo:', n*n*n)
nums = range(10)
t = time.time()... | Calcula el cuadrado:
cuadrado: 0
cuadrado: 1
cuadrado: 4
cuadrado: 9
cuadrado: 16
cuadrado: 25
cuadrado: 36
cuadrado: 49
cuadrado: 64
cuadrado: 81
Calcula el cubo:
cubo: 0
cubo: 1
cubo: 8
cubo: 27
cubo: 64
cubo: 125
cubo: 216
cubo: 343
cubo: 512
cubo: 729
Finaliza la ejecucion
Tiempo de ejecucion 4.024327278137207
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Una manera sencilla de generar procesos en Python es por medio de la creacion del objeto `Process` y llamarlo por medio del metodo `start()`. | import multiprocessing as mp
def tarea(nombre):
print('Hola', nombre)
for n in range(10000):
n**(1/(n+1))
if __name__ == '__main__': # Esta condicion se interpreta como una verificacion de si este proceso es el principal
p = mp.Process(target=tarea, args=('Saul', )) ## Ejecuta la funcion tare... | Calcula el cuadrado:
Calcula el cubo:
cuadrado: cubo:0
0
cuadrado: cubo:1
1
cuadrado:cubo: 48
cuadrado:cubo: 927
cuadrado: cubo:16
64
cuadrado: cubo:25
125
cuadrado: 36
cubo: 216
cuadrado: 49
cubo: 343
cuadrado: 64
cubo: 512
cuadrado: 81
cubo: 729
Tiempo de ejecucion 2.1406450271606445
Finaliza la ejecucion
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Tarea Investiga en la documentacion del modulo `Multiprocessing` cual es su funcionamiento y todos los metodos o funciones que estan implementados en el. Identificadores PID, PPID | import multiprocessing as mp
import os
print('Nombre del proceso:', __name__)
print('Proceso padre:', os.getppid())
print('Proceso actual:', os.getpid())
import multiprocessing as mp
import os
def info(titulo):
print(titulo)
print('Nombre del proceso:', __name__)
print('Proceso padre:', os.getppid())
... | Inicio
Nombre del proceso: __main__
Proceso padre: 7448
Proceso actual: 8016
Funcion f
Nombre del proceso: __main__
Proceso padre: 8016
Proceso actual: 9690
Hola Valeriano
------------
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
EjercicioCrea 3 procesos hijos, donde:- El primero multiplique 3 numeros (a,b,c)- El segundo sume (a,b,c)- El tercero haga (a+b)/c- Todos devolveran el valor calculado, el nombre de cada proceso hijo y el id del proceso padre. | import multiprocessing as mp
import os
def info(titulo):
print(titulo)
print('Nombre del proceso:', __name__)
print('Proceso actual:', os.getpid())
print('Proceso padre:', os.getppid())
def primero(a,b,c):
info('a*b*c =')
print(a*b*c)
def segundo(a,b,c):
info('a+b+c =')
print... | Cuadrado: 0
Cuadrado: 1
Cuadrado: 4
Cuadrado: 9
Cuadrado: 16
Cuadrado: 25
Cuadrado: 36
Cuadrado: 49
Cuadrado: 64
Cuadrado: 81
Tiempo de ejecucion: 0.04141974449157715
Resultado del proceso: []
Finaliza ejecucion
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
2020-10-27 Nombres y terminaciรณn de procesos | import multiprocessing
multiprocessing.cpu_count() | _____no_output_____ | MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Con el mรฉtodo `cpu_count() | import time
def TareaHijo():
print("Proceso HIJO con PID: {}".format(multiprocessing.current_process().pid))
time.sleep(3)
print("Fin del proceso hijo")
def main():
print("Proceso Padre PID: {}".format(multiprocessing.current_process().pid))
myProcess = multiprocessing.Process(target=TareaHijo) # De... | Proceso Padre PID: 6703
Proceso HIJO con PID: 7714
Fin del proceso hijo
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Es posible asignar un nombre a un proceso hijo que ha sido creado, por medio del medio del argumento `name` se asigna el nombre del proceso hijo. | def myProcess():
print("Proceso con nombre: {}".format(multiprocessing.current_process().name)) ## Metodo current process para obtener el nombre del proceso
def main():
childProcess = multiprocessing.Process(target=myProcess, name='Proceso-LCD-cc')
childProcess.start()
childProcess.join()
mai... | _____no_output_____ | MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Ejercicio:1. Vamos a crear 3 procesos los cuales tendrรกn nombre y cรณdigo definido como funP1, funP2, funP3. Cada hijo escribirรก su nombre, su PID y el PID del padre, ademรกs de hacer un cรกlculo sobre tres valores a, b y c.2. El proceso 1 calcula a*b + c, el proceso 2 calcula a*b*c y el proceso 3 calcula (a*b)/c3. Cre... | import multiprocessing as mp
import os
import random
def info(titulo):
pname = current_process().name
print('Nombre del proceso: %s...' % pname)
print(titulo)
print('Proceso actual:', os.getpid())
print('Proceso padre:', os.getppid())
def funP1(a,b,c):
info('a*b + c =')
print(a*b + c)... | Nombre del proceso: funP2...
a*b*c =
Proceso actual: 15004
Proceso padre: 6703
15
Nombre del proceso: funP1...
a*b + c =
Proceso actual: 15003
Proceso padre: 6703
16
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
No obstante , a veces se requiere crear procesos que corran en silencio (*background*) y no bloquear el proceso principal al finalizarlos. Esta especificaciรณn es comunmente utilizada cuando el proceso principal no tiene la certeza de interrumpir un proceso despuรฉs de esperar cierto tiempo o finalizar sin que haya termi... | from multiprocessing import Process, current_process
import time
def f1():
p = current_process()
print('Starting process %s, ID %s....' %(p.name, p.pid))
time.sleep(8)
print('Starting process %s, ID, %s....' %(p.name, p.pid))
def f2():
p = current_process()
print('Starting process %s, ID %... | Starting process Worker 1, ID 15700....
Starting process Worker 2, ID 15705....
Starting process Worker 2, ID 15705....
Starting process Worker 1, ID, 15700....
| MIT | T2.ProcHilosPy/T2-MultiprocessingPython.ipynb | patoba/ComputacionConcurrente |
Sentiment Classification & How To "Frame Problems" for a Neural Networkby Andrew Trask- **Twitter**: @iamtrask- **Blog**: http://iamtrask.github.io What You Should Already Know- neural networks, forward and back-propagation- stochastic gradient descent- mean squared error- and train/test splits Where to Get Help if Y... | def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines()))
g.close() | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
**Note:** The data in `reviews.txt` we're using has already been preprocessed a bit and contains only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like `The`,... | len(reviews)
reviews[0]
labels[0] | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Lesson: Develop a Predictive Theory | print("labels.txt \t : \t reviews.txt\n")
pretty_print_review_and_label(2137)
pretty_print_review_and_label(12816)
pretty_print_review_and_label(6267)
pretty_print_review_and_label(21934)
pretty_print_review_and_label(5297)
pretty_print_review_and_label(4998) | labels.txt : reviews.txt
NEGATIVE : this movie is terrible but it has some good effects . ...
POSITIVE : adrian pasdar is excellent is this film . he makes a fascinating woman . ...
NEGATIVE : comment this movie is impossible . is terrible very improbable bad interpretat...
POSITIVE : excellent episode movie a... | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Project 1: Quick Theory ValidationThere are multiple ways to implement these projects, but in order to get your code closer to what Andrew shows in his solutions, we've provided some hints and starter code throughout this notebook.You'll find the [Counter](https://docs.python.org/2/library/collections.htmlcollections.... | from collections import Counter
import numpy as np | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
We'll create three `Counter` objects, one for words from postive reviews, one for words from negative reviews, and one for all the words. | # Create three Counter objects to store positive, negative and total counts
positive_counts = Counter()
negative_counts = Counter()
total_counts = Counter() | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
**TODO:** Examine all the reviews. For each word in a positive review, increase the count for that word in both your positive counter and the total words counter; likewise, for each word in a negative review, increase the count for that word in both your negative counter and the total words counter.**Note:** Throughout... | for i in range(len(reviews)):
if(labels[i] == 'POSITIVE'):
for word in reviews[i].split(" "):
positive_counts[word] += 1
total_counts[word] += 1
else:
for word in reviews[i].split(" "):
negative_counts[word] += 1
total_counts[word] += 1 | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following two cells to list the words used in positive reviews and negative reviews, respectively, ordered from most to least commonly used. | # Examine the counts of the most common words in positive reviews
positive_counts.most_common()
# Examine the counts of the most common words in negative reviews
negative_counts.most_common() | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
As you can see, common words like "the" appear very often in both positive and negative reviews. Instead of finding the most common words in positive or negative reviews, what you really want are the words found in positive reviews more often than in negative reviews, and vice versa. To accomplish this, you'll need to ... | # Create Counter object to store positive/negative ratios
pos_neg_ratios = Counter()
# TODO: Calculate the ratios of positive and negative uses of the most common words
# Consider words to be "common" if they've been used at least 100 times
# for word, count in total_counts.most_common():
# if count > 100:
#... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Examine the ratios you've calculated for a few words: | print("Pos-to-neg ratio for 'the' = {}".format(pos_neg_ratios["the"]))
print("Pos-to-neg ratio for 'amazing' = {}".format(pos_neg_ratios["amazing"]))
print("Pos-to-neg ratio for 'terrible' = {}".format(pos_neg_ratios["terrible"])) | Pos-to-neg ratio for 'the' = 1.0607993145235326
Pos-to-neg ratio for 'amazing' = 4.022813688212928
Pos-to-neg ratio for 'terrible' = 0.17744252873563218
| MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Looking closely at the values you just calculated, we see the following:* Words that you would expect to see more often in positive reviews โ like "amazing"ย โ have a ratio greater than 1. The more skewed a word is toward postive, the farther from 1 its positive-to-negative ratio will be.* Words that you would expect t... | # TODO: Convert ratios to logs
for word, ratio in pos_neg_ratios.most_common():
pos_neg_ratios[word] = np.log(ratio) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Examine the new ratios you've calculated for the same words from before: | print("Pos-to-neg ratio for 'the' = {}".format(pos_neg_ratios["the"]))
print("Pos-to-neg ratio for 'amazing' = {}".format(pos_neg_ratios["amazing"]))
print("Pos-to-neg ratio for 'terrible' = {}".format(pos_neg_ratios["terrible"])) | Pos-to-neg ratio for 'the' = 0.05902269426102881
Pos-to-neg ratio for 'amazing' = 1.3919815802404802
Pos-to-neg ratio for 'terrible' = -1.7291085042663878
| MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
If everything worked, now you should see neutral words with values close to zero. In this case, "the" is near zero but slightly positive, so it was probably used in more positive reviews than negative reviews. But look at "amazing"'s ratio - it's above `1`, showing it is clearly a word with positive sentiment. And "ter... | # words most frequently seen in a review with a "POSITIVE" label
pos_neg_ratios.most_common()
# words most frequently seen in a review with a "NEGATIVE" label
list(reversed(pos_neg_ratios.most_common()))[0:30]
# Note: Above is the code Andrew uses in his solution video,
# so we've included it here to avoid conf... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
End of Project 1. Watch the next video to see Andrew's solution, then continue on to the next lesson. Transforming Text into NumbersThe cells here include code Andrew shows in the next video. We've included it so you can run the code along with the video without having to type in everything. | from IPython.display import Image
review = "This was a horrible, terrible movie."
Image(filename='sentiment_network.png')
review = "The movie was excellent"
Image(filename='sentiment_network_pos.png') | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Project 2: Creating the Input/Output Data**TODO:** Create a [set](https://docs.python.org/3/tutorial/datastructures.htmlsets) named `vocab` that contains every word in the vocabulary. | # TODO: Create set named "vocab" containing all of the words from all of the reviews
vocab = list(total_counts) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to check your vocabulary size. If everything worked correctly, it should print **74074** | vocab_size = len(vocab)
print(vocab_size) | 74074
| MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Take a look at the following image. It represents the layers of the neural network you'll be building throughout this notebook. `layer_0` is the input layer, `layer_1` is a hidden layer, and `layer_2` is the output layer. | from IPython.display import Image
Image(filename='sentiment_network_2.png') | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
**TODO:** Create a numpy array called `layer_0` and initialize it to all zeros. You will find the [zeros](https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html) function particularly helpful here. Be sure you create `layer_0` as a 2-dimensional matrix with 1 row and `vocab_size` columns. | # TODO: Create layer_0 matrix with dimensions 1 by vocab_size, initially filled with zeros
layer_0 = np.zeros((1, vocab_size)) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell. It should display `(1, 74074)` | layer_0.shape
from IPython.display import Image
Image(filename='sentiment_network.png') | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
`layer_0` contains one entry for every word in the vocabulary, as shown in the above image. We need to make sure we know the index of each word, so run the following cell to create a lookup table that stores the index of every word. | # Create a dictionary of words in the vocabulary mapped to index positions
# (to be used in layer_0)
word2index = {}
for i, word in enumerate(vocab):
word2index[word] = i
# display the map of words to indices
word2index | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
**TODO:** Complete the implementation of `update_input_layer`. It should count how many times each word is used in the given review, and then store those counts at the appropriate indices inside `layer_0`. | def update_input_layer(review):
""" Modify the global layer_0 to represent the vector form of review.
The element at a given index of layer_0 should represent
how many times the given word occurs in the review.
Args:
review(string) - the string of the review
Returns:
None
"""
... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to test updating the input layer with the first review. The indices assigned may not be the same as in the solution, but hopefully you'll see some non-zero values in `layer_0`. | update_input_layer(reviews[0])
layer_0 | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
**TODO:** Complete the implementation of `get_target_for_labels`. It should return `0` or `1`, depending on whether the given label is `NEGATIVE` or `POSITIVE`, respectively. | def get_target_for_label(label):
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if label == 'POSITIVE':
return 1
return 0
# TODO: Your code here | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following two cells. They should print out`'POSITIVE'` and `1`, respectively. | labels[0]
get_target_for_label(labels[0]) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following two cells. They should print out `'NEGATIVE'` and `0`, respectively. | labels[1]
get_target_for_label(labels[1]) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
End of Project 2. Watch the next video to see Andrew's solution, then continue on to the next lesson. Project 3: Building a Neural Network **TODO:** We've included the framework of a class called `SentimentNetork`. Implement all of the items marked `TODO` in the code. These include doing the following:- Create a bas... | import time
import sys
import numpy as np
# Encapsulate our neural network in a class
class SentimentNetwork:
def __init__(self, reviews, labels, hidden_nodes = 10, learning_rate = 0.001):
"""Create a SentimenNetwork with the given settings
Args:
reviews(list) - List of reviews used for... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to create a `SentimentNetwork` that will train on all but the last 1000 reviews (we're saving those for testing). Here we use a learning rate of `0.1`. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.1) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to test the network's performance against the last 1000 reviews (the ones we held out from our training set). **We have not trained the model yet, so the results should be about 50% as it will just be guessing and there are only two possible values to choose from.** | mlp.test(reviews[-1000:],labels[-1000:]) | Progress:48.8% Speed(reviews/sec):800.1 #Correct:245 #Tested:489 Testing Accuracy:50.1%Progress:99.9% Speed(reviews/sec):777.5 #Correct:500 #Tested:1000 Testing Accuracy:50.0% | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to actually train the network. During training, it will display the model's accuracy repeatedly as it trains so you can see how well it's doing. | mlp.train(reviews[:-1000],labels[:-1000]) | Progress:0.0% Speed(reviews/sec):0.0 #Correct:1 #Trained:1 Training Accuracy:100.%
Progress:10.4% Speed(reviews/sec):246.6 #Correct:1251 #Trained:2501 Training Accuracy:50.0%
Progress:11.4% Speed(reviews/sec):247.1 #Correct:1369 #Trained:2737 Training Accuracy:50.0% | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
That most likely didn't train very well. Part of the reason may be because the learning rate is too high. Run the following cell to recreate the network with a smaller learning rate, `0.01`, and then train the new network. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.01)
mlp.train(reviews[:-1000],labels[:-1000]) | Progress:0.0% Speed(reviews/sec):0.0 #Correct:1 #Trained:1 Training Accuracy:100.%
Progress:9.72% Speed(reviews/sec):239.4 #Correct:1165 #Trained:2334 Training Accuracy:49.9% | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
That probably wasn't much different. Run the following cell to recreate the network one more time with an even smaller learning rate, `0.001`, and then train the new network. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.001)
mlp.train(reviews[:-1000],labels[:-1000]) | Progress:0.0% Speed(reviews/sec):0.0 #Correct:1 #Trained:1 Training Accuracy:100.%
Progress:10.4% Speed(reviews/sec):249.0 #Correct:1267 #Trained:2501 Training Accuracy:50.6%
Progress:20.8% Speed(reviews/sec):248.8 #Correct:2655 #Trained:5001 Training Accuracy:53.0%
Progress:31.2% Speed(reviews/sec):249.5 #Correct:4087... | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
With a learning rate of `0.001`, the network should finall have started to improve during training. It's still not very good, but it shows that this solution has potential. We will improve it in the next lesson. End of Project 3. Watch the next video to see Andrew's solution, then continue on to the next lesson. Und... | from IPython.display import Image
Image(filename='sentiment_network.png')
def update_input_layer(review):
global layer_0
# clear out previous state, reset the layer to be all 0s
layer_0 *= 0
for word in review.split(" "):
layer_0[0][word2index[word]] += 1
update_input_layer(reviews[0]... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Project 4: Reducing Noise in Our Input Data**TODO:** Attempt to reduce the noise in the input data like Andrew did in the previous video. Specifically, do the following:* Copy the `SentimentNetwork` class you created earlier into the following cell.* Modify `update_input_layer` so it does not count how many times each... | # TODO: -Copy the SentimentNetwork class from Projet 3 lesson
# -Modify it to reduce noise, like in the video
import time
import sys
import numpy as np
# Encapsulate our neural network in a class
class SentimentNetwork:
def __init__(self, reviews, labels, hidden_nodes = 10, learning_rate = 0.001):
"... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to recreate the network and train it. Notice we've gone back to the higher learning rate of `0.1`. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.1)
mlp.train(reviews[:-1000],labels[:-1000]) | Progress:0.0% Speed(reviews/sec):0.0 #Correct:1 #Trained:1 Training Accuracy:100.%
Progress:10.4% Speed(reviews/sec):83.64 #Correct:1838 #Trained:2501 Training Accuracy:73.4%
Progress:20.8% Speed(reviews/sec):83.27 #Correct:3820 #Trained:5001 Training Accuracy:76.3%
Progress:31.2% Speed(reviews/sec):83.09 #Correct:5911... | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
That should have trained much better than the earlier attempts. It's still not wonderful, but it should have improved dramatically. Run the following cell to test your model with 1000 predictions. | mlp.test(reviews[-1000:],labels[-1000:]) | Progress:99.9% Speed(reviews/sec):942.5 #Correct:849 #Tested:1000 Testing Accuracy:84.9% | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
End of Project 4. Andrew's solution was actually in the previous video, so rewatch that video if you had any problems with that project. Then continue on to the next lesson. Analyzing Inefficiencies in our NetworkThe following cells include the code Andrew shows in the next video. We've included it here so you can ru... | Image(filename='sentiment_network_sparse.png')
layer_0 = np.zeros(10)
layer_0
layer_0[4] = 1
layer_0[9] = 1
layer_0
weights_0_1 = np.random.randn(10,5)
layer_0.dot(weights_0_1)
indices = [4,9]
layer_1 = np.zeros(5)
for index in indices:
layer_1 += (1 * weights_0_1[index])
layer_1
Image(filename='sentiment_network_s... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Project 5: Making our Network More Efficient**TODO:** Make the `SentimentNetwork` class more efficient by eliminating unnecessary multiplications and additions that occur during forward and backward propagation. To do that, you can do the following:* Copy the `SentimentNetwork` class from the previous project into the... | import time
import sys
import numpy as np
# Encapsulate our neural network in a class
class SentimentNetwork:
def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1):
"""Create a SentimenNetwork with the given settings
Args:
reviews(list) - List of reviews used for tra... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to recreate the network and train it once again. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.1)
mlp.train(reviews[:-1000],labels[:-1000]) | Progress:0.0% Speed(reviews/sec):0.0 #Correct:1 #Trained:1 Training Accuracy:100.%
Progress:10.4% Speed(reviews/sec):1756. #Correct:1823 #Trained:2501 Training Accuracy:72.8%
Progress:20.8% Speed(reviews/sec):1710. #Correct:3810 #Trained:5001 Training Accuracy:76.1%
Progress:31.2% Speed(reviews/sec):1707. #Correct:5884... | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
That should have trained much better than the earlier attempts. Run the following cell to test your model with 1000 predictions. | mlp.test(reviews[-1000:],labels[-1000:]) | Progress:99.9% Speed(reviews/sec):1970. #Correct:853 #Tested:1000 Testing Accuracy:85.3% | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
End of Project 5. Watch the next video to see Andrew's solution, then continue on to the next lesson. Further Noise Reduction | Image(filename='sentiment_network_sparse_2.png')
# words most frequently seen in a review with a "POSITIVE" label
pos_neg_ratios.most_common()
# words most frequently seen in a review with a "NEGATIVE" label
list(reversed(pos_neg_ratios.most_common()))[0:30]
from bokeh.models import ColumnDataSource, LabelSet
from boke... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Project 6: Reducing Noise by Strategically Reducing the Vocabulary**TODO:** Improve `SentimentNetwork`'s performance by reducing more noise in the vocabulary. Specifically, do the following:* Copy the `SentimentNetwork` class from the previous project into the following cell.* Modify `pre_process_data`:>* Add two addi... | import time
import sys
import numpy as np
from collections import Counter
# Encapsulate our neural network in a class
class SentimentNetwork:
def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1, min_count = 10, polarity_cutoff = 0.1):
"""Create a SentimenNetwork with the given settings... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to train your network with a small polarity cutoff. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000],min_count=20,polarity_cutoff=0.05,learning_rate=0.01)
mlp.train(reviews[:-1000],labels[:-1000]) | /opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:51: RuntimeWarning: divide by zero encountered in log
| MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
And run the following cell to test it's performance. It should be | mlp.test(reviews[-1000:],labels[-1000:]) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Run the following cell to train your network with a much larger polarity cutoff. | mlp = SentimentNetwork(reviews[:-1000],labels[:-1000],min_count=20,polarity_cutoff=0.8,learning_rate=0.01)
mlp.train(reviews[:-1000],labels[:-1000]) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
And run the following cell to test it's performance. | mlp.test(reviews[-1000:],labels[-1000:]) | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
End of Project 6. Watch the next video to see Andrew's solution, then continue on to the next lesson. Analysis: What's Going on in the Weights? | mlp_full = SentimentNetwork(reviews[:-1000],labels[:-1000],min_count=0,polarity_cutoff=0,learning_rate=0.01)
mlp_full.train(reviews[:-1000],labels[:-1000])
Image(filename='sentiment_network_sparse.png')
def get_most_similar_words(focus = "horrible"):
most_similar = Counter()
for word in mlp_full.word2index.key... | _____no_output_____ | MIT | sentiment-network/sentiment-classification-project.ipynb | eugli/udacity-deep-learning |
Advanced usageThis notebook replicates what was done in the *simple_usage* notebooks, but this time with the advanced API. The advanced API is required if we want to use non-standard affinity methods that better preserve global structure.If you are comfortable with the advanced API, please refer to the *preserving_glo... | from openTSNE import TSNEEmbedding
from openTSNE import affinity
from openTSNE import initialization
from examples import utils
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt | _____no_output_____ | BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
Load data | import gzip
import pickle
with gzip.open("data/macosko_2015.pkl.gz", "rb") as f:
data = pickle.load(f)
x = data["pca_50"]
y = data["CellType1"].astype(str)
print("Data set contains %d samples with %d features" % x.shape) | Data set contains 44808 samples with 50 features
| BSD-3-Clause | examples/02_advanced_usage.ipynb | gavehan/openTSNE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.