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
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(white_output))
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de...
yellow_output = 'test_videos_output/solidYellowLeft.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start an...
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat...
challenge_output = 'test_videos_output/challenge.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and e...
_____no_output_____
MIT
P1.ipynb
owennottank/CarND-LaneLines-P1
In-Class Coding Lab: Data Analysis with PandasIn this lab, we will perform a data analysis on the **RMS Titanic** passenger list. The RMS Titanic is one of the most famous ocean liners in history. On April 15, 1912 it sank after colliding with an iceberg in the North Atlantic Ocean. To learn more, read here: https://e...
import pandas as pd import numpy as np # this turns off warning messages import warnings warnings.filterwarnings('ignore') passengers = pd.read_csv('CCL-titanic.csv') passengers.sample(10)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
How many survived?One of the first things we should do is figure out how many of the passengers in this data set survived. Let's start with isolating just the `'Survivied'` column into a series:
passengers['Survived'].sample(10)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
There's too many to display so we just display a random sample of 10 passengers. - 1 means the passenger survivied- 0 means the passenger diedWhat we really want is to count the number of survivors and deaths. We do this by querying the `value_counts()` of the `['Survived']` column, which returns a `Series` of counts, ...
passengers['Survived'].value_counts()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
Only 342 passengers survived, and 549 perished. Let's observe this same data as percentages of the whole. We do this by adding the `normalize=True` named argument to the `value_counts()` method.
passengers['Survived'].value_counts(normalize=True)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
**Just 38% of passengers in this dataset survived.** Now you Try it!**FIRST** Write a Pandas expression to display counts of males and female passengers using the `Sex` variable:
passengers['Sex'].value_counts()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
**NEXT** Write a Pandas expression to display male /female passenger counts as a percentage of the whole number of passengers in the data set.
passengers['Sex'].value_counts(normalize=True)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
If you got things working, you now know that **35% of passengers were female**. Who survivies? Men or Women?We now know that 35% of the passengers were female, and 65% we male. **The next think to think about is how do survivial rates affect these numbers? **If the ratio is about the same for surviviors only, then we ...
survivors = passengers[passengers['Survived'] ==1] survivors['PassengerId'].count()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
Still **342** like we discovered originally. Now let's check the **Sex** split among survivors only:
survivors['Sex'].value_counts()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
WOW! That is a huge difference! But you probably can't see it easily. Let's represent it in a `DataFrame`, so that it's easier to visualize:
sex_all_series = passengers['Sex'].value_counts() sex_survivor_series = survivors['Sex'].value_counts() sex_comparision_df = pd.DataFrame({ 'AllPassengers' : sex_all_series, 'Survivors' : sex_survivor_series }) sex_comparision_df['SexSurvivialRate'] = sex_comparision_df['Survivors'] / sex_comparision_df['AllPassengers...
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
**So, females had a 74% survival rate. Much better than the overall rate of 38%** We should probably briefly explain the code above. - The first two lines get a series count of all passengers by Sex (male / female) and count of survivors by sex- The third line creates DataFrame. Recall a pandas dataframe is just a dic...
passengers['AgeCat'] = np.nan # Not a number passengers['AgeCat'][ passengers['Age'] <=18 ] = 'Child' passengers['AgeCat'][ passengers['Age'] > 18 ] = 'Adult' passengers.sample(5)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
Let's get the count and distrubutions of Adults and Children on the passenger list.
passengers['AgeCat'].value_counts()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
And here's the percentage as a whole:
passengers['AgeCat'].value_counts(normalize=True)
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
So close to **80%** of the passengers were adults. Once again let's look at the ratio of `AgeCat` for survivors only. If your age has no bearing of survivial, then the rates should be the same. Here's the counts of Adult / Children among the survivors only:
survivors = passengers[passengers['Survived'] ==1] survivors['AgeCat'].value_counts()
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
Now You Try it!Calculate the `AgeCat` survival rate, similar to how we did for the `SexSurvivalRate`.
agecat_all_series = passengers['AgeCat'].value_counts() agecat_survivor_series = survivors['AgeCat'].value_counts() # todo make a data frame, add AgeCatSurvivialRate column, display dataframe agecat_comparision_df = pd.DataFrame({ 'AllPassengers' : agecat_all_series, 'Survivors' : agecat_survivor_series }) agecat_com...
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
**So, children had a 50% survival rate, better than the overall rate of 38%** So, women and children first?It looks like the RMS really did have the motto: "Women and Children First."Here's our insights. We know:- If you were a passenger, you had a 38% chance of survival.- If you were a female passenger, you had a 74% ...
# todo: repeat the analysis in the previous cell for Pclass pclass_all_series = passengers['Pclass'].value_counts() pclass_survivor_series = survivors['Pclass'].value_counts() pclass_comparision_df = pd.DataFrame({ 'AllPassengers' : pclass_all_series, 'Survivors' : pclass_survivor_series }) pclass_comparision_df['Pcl...
_____no_output_____
MIT
content/lessons/12/Class-Coding-Lab/CCL-Data-Analysis-With-Pandas.ipynb
MahopacHS/spring2019-DavisGrimm
Generate small plot
cells = make_spheroids.generate_artificial_spheroid(10)['cells'] spheroid = {} spheroid['cells'] = cells G = graph_generation_func.generate_voronoi_graph(spheroid, dCells = 0.6) for ind in G.nodes(): if ind % 2 == 0: G.add_node(ind, color = 'r') else: G.add_node(ind, co...
_____no_output_____
MIT
Examples/.ipynb_checkpoints/Example-checkpoint.ipynb
microfluidix/HMRF
Batch analyze the data
spheroid_path = './utility/spheroid_sample_1.csv' spheroid_data = pandas.read_csv(spheroid_path) spheroid = pr.single_spheroid_process(spheroid_data[spheroid_data['area'] > 200]) G = graph.generate_voronoi_graph(spheroid, zRatio = 2, dCells = 35) import glob from collections import defaultdict degree_frame_Vor = p...
_____no_output_____
MIT
Examples/.ipynb_checkpoints/Example-checkpoint.ipynb
microfluidix/HMRF
Model Explainer Example![architecture](architecture.png)In this example we will: * [Describe the project structure](Project-Structure) * [Train some models](Train-Models) * [Create Tempo artifacts](Create-Tempo-Artifacts) * [Run unit tests](Unit-Tests) * [Save python environment for our classifier](Save-Classifie...
!tree -P "*.py" -I "__init__.py|__pycache__" -L 2
. ├── artifacts │   ├── explainer │   └── model ├── k8s │   └── rbac └── src ├── constants.py ├── data.py ├── explainer.py ├── model.py └── tempo.py 6 directories, 5 files
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Train Models * This section is where as a data scientist you do your work of training models and creating artfacts. * For this example we train sklearn and xgboost classification models for the iris dataset.
import os import logging import numpy as np import json import tempo from tempo.utils import logger from src.constants import ARTIFACTS_FOLDER logger.setLevel(logging.ERROR) logging.basicConfig(level=logging.ERROR) from src.data import AdultData data = AdultData() from src.model import train_model adult_model = tr...
_____no_output_____
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Create Tempo Artifacts
from src.tempo import create_explainer, create_adult_model sklearn_model = create_adult_model() Explainer = create_explainer(sklearn_model) explainer = Explainer() # %load src/tempo.py import os import dill import numpy as np from alibi.utils.wrappers import ArgmaxTransformer from src.constants import ARTIFACTS_FOLDE...
_____no_output_____
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Save Explainer
!ls artifacts/explainer/conda.yaml tempo.save(Explainer)
Collecting packages... Packing environment at '/home/clive/anaconda3/envs/tempo-d87b2b65-e7d9-4e82-9c0d-0f83f48c07a3' to '/home/clive/work/mlops/fork-tempo/docs/examples/explainer/artifacts/explainer/environment.tar.gz' [########################################] | 100% Completed | 1min 13.1s
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Test Locally on DockerHere we test our models using production images but running locally on Docker. This allows us to ensure the final production deployed model will behave as expected when deployed.
from tempo import deploy_local remote_model = deploy_local(explainer) r = json.loads(remote_model.predict(payload=data.X_test[0:1], parameters={"threshold":0.90})) print(r["data"]["anchor"]) r = json.loads(remote_model.predict(payload=data.X_test[0:1], parameters={"threshold":0.99})) print(r["data"]["anchor"]) remote_m...
_____no_output_____
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Production Option 1 (Deploy to Kubernetes with Tempo) * Here we illustrate how to run the final models in "production" on Kubernetes by using Tempo to deploy Prerequisites Create a Kind Kubernetes cluster with Minio and Seldon Core installed using Ansible as described [here](https://tempo.readthedocs.io/en/latest/ove...
!kubectl apply -f k8s/rbac -n production from tempo.examples.minio import create_minio_rclone import os create_minio_rclone(os.getcwd()+"/rclone-minio.conf") tempo.upload(sklearn_model) tempo.upload(explainer) from tempo.serve.metadata import SeldonCoreOptions runtime_options = SeldonCoreOptions(**{ "remote_opt...
_____no_output_____
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Production Option 2 (Gitops) * We create yaml to provide to our DevOps team to deploy to a production cluster * We add Kustomize patches to modify the base Kubernetes yaml created by Tempo
from tempo import manifest from tempo.serve.metadata import SeldonCoreOptions runtime_options = SeldonCoreOptions(**{ "remote_options": { "namespace": "production", "authSecretName": "minio-secret" } }) yaml_str = manifest(explainer, options=runtime_options) with open(os.getc...
apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: annotations: seldon.io/tempo-description: "" seldon.io/tempo-model: '{"model_details": {"name": "income-explainer", "local_folder": "/home/clive/work/mlops/fork-tempo/docs/examples/explainer/artifacts/explainer", "uri...
Apache-2.0
docs/examples/explainer/README.ipynb
outerbounds/tempo
Copyright 2018 The TensorFlow Authors.Licensed under the Apache License, Version 2.0 (the "License"). Neural Machine Translation with Attention Run in Google Colab View source on GitHub This notebook is still under construction! Please come back later.This notebook trains a sequence to...
import collections import io import itertools import os import random import re import time import unicodedata import numpy as np import tensorflow as tf assert tf.__version__.startswith('2') import matplotlib.pyplot as plt print(tf.__version__)
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Download and prepare the datasetWe'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format:```May I borrow this book? ¿Puedo tomar prestado este libro?```There are a variety of languages available, but we'll use the English-Spanish dataset. ...
# TODO(brianklee): This preprocessing should ideally be implemented in TF # because preprocessing should be exported as part of the SavedModel. # Converts the unicode file to ascii # https://stackoverflow.com/a/518232/2809427 def unicode_to_ascii(s): return ''.join(c for c in unicodedata.normalize('NFD', s) ...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Training on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset (of course, translation quality degrades with less data).
def load_anki_data(num_examples=None): # Download the file path_to_zip = tf.keras.utils.get_file( 'spa-eng.zip', origin='http://download.tensorflow.org/data/spa-eng.zip', extract=True) path_to_file = os.path.dirname(path_to_zip) + '/spa-eng/spa.txt' with io.open(path_to_file, 'rb') as f: lines ...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Write the encoder and decoder modelHere, we'll implement an encoder-decoder model with attention. The following diagram shows that each input word is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence.The input is put through an encoder model which g...
ENCODER_SIZE = DECODER_SIZE = 1024 EMBEDDING_DIM = 256 MAX_OUTPUT_LENGTH = train_ds.output_shapes[1][1] def gru(units): return tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_activation='sigmoid', ...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
For the decoder, we're using *Bahdanau attention*. Here are the equations that are implemented:Lets decide on notation before writing the simplified form:* FC = Fully connected (dense) layer* EO = Encoder output* H = hidden state* X = input to the decoderAnd the pseudo-code:* `score = FC(tanh(FC(EO) + FC(H)))`* `attent...
class BahdanauAttention(tf.keras.Model): def __init__(self, units): super(BahdanauAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) def call(self, hidden_state, enc_output): # enc_output shape = (batch_s...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Define a translate functionNow, let's put the encoder and decoder halves together. The encoder step is fairly straightforward; we'll just reuse Keras's dynamic unroll. For the decoder, we have to make some choices about how to feed the decoder RNN. Overall the process goes as follows:1. Pass the *input* through the *e...
class NmtTranslator(tf.keras.Model): def __init__(self, encoder, decoder, start_token_id, end_token_id): super(NmtTranslator, self).__init__() self.encoder = encoder self.decoder = decoder # (The token_id should match the decoder's language.) # Uses start_token_id to initialize the decoder. se...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Define the loss functionOur loss function is a word-for-word comparison between true answer and model prediction. real = [, 'This', 'is', 'the', 'correct', 'answer', '.', '', ''] pred = ['This', 'is', 'what', 'the', 'model', 'emitted', '.', '']results in comparing This/This, is/is, the/what, correct/the, an...
def loss_fn(real, pred): # The prediction doesn't include the <start> token. real = real[:, 1:] # Cut down the prediction to the correct shape (We ignore extra words). pred = pred[:, :real.shape[1]] # If real == <OOV>, then mask out the loss. mask = 1 - np.equal(real, 0) loss_ = tf.nn.sparse_softmax_cross...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Configure model directoryWe'll use one directory to save all of our relevant artifacts (summary logs, checkpoints, SavedModel exports, etc.)
# Where to save checkpoints, tensorboard summaries, etc. MODEL_DIR = '/tmp/tensorflow/nmt_attention' def apply_clean(): if tf.io.gfile.exists(MODEL_DIR): print('Removing existing model dir: {}'.format(MODEL_DIR)) tf.io.gfile.rmtree(MODEL_DIR) # Optional: remove existing data apply_clean() # Summary writers ...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Visualize the model's outputLet's visualize our model's output. (It hasn't been trained yet, so it will output gibberish.)We'll use this visualization to check on the model's progress.
def plot_attention(attention, sentence, predicted_sentence): fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1) ax.matshow(attention, cmap='viridis') fontdict = {'fontsize': 14} ax.set_xticklabels([''] + sentence.split(), fontdict=fontdict, rotation=90) ax.set_yticklabels(...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Train the model
def train(model, optimizer, dataset): """Trains model on `dataset` using `optimizer`.""" start = time.time() avg_loss = tf.keras.metrics.Mean('loss', dtype=tf.float32) for inp, target in dataset: with tf.GradientTape() as tape: predictions, _ = model(inp, target=target) loss = loss_fn(target, pr...
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
Next steps* [Download a different dataset](http://www.manythings.org/anki/) to experiment with translations, for example, English to German, or English to French.* Experiment with training on a larger dataset, or using more epochs
_____no_output_____
Apache-2.0
community/en/nmt.ipynb
thezwick/examples
OpenAI GymWe're gonna spend several next weeks learning algorithms that solve decision processes. We are then in need of some interesting decision problems to test our algorithms.That's where OpenAI gym comes into play. It's a python library that wraps many classical decision problems including robot control, videogam...
import gym env = gym.make("MountainCar-v0") plt.imshow(env.render('rgb_array')) print("Observation space:", env.observation_space) print("Action space:", env.action_space)
Observation space: Box(2,) Action space: Discrete(3)
MIT
gym_basics_mountain_car_v0.ipynb
PratikSavla/Reinformemt-Learning-Examples
Note: if you're running this on your local machine, you'll see a window pop up with the image above. Don't close it, just alt-tab away. Gym interfaceThe three main methods of an environment are* __reset()__ - reset environment to initial state, _return first observation_* __render()__ - show current environment state ...
obs0 = env.reset() print("initial observation code:", obs0) # Note: in MountainCar, observation is just two numbers: car position and velocity print("taking action 2 (right)") new_obs, reward, is_done, _ = env.step(2) print("new observation code:", new_obs) print("reward:", reward) print("is game over?:", is_done) #...
taking action 2 (right) new observation code: [ -4.02551631e-01 1.12759220e-04] reward: -1.0 is game over?: False
MIT
gym_basics_mountain_car_v0.ipynb
PratikSavla/Reinformemt-Learning-Examples
Play with itBelow is the code that drives the car to the right. However, it doesn't reach the flag at the far right due to gravity. __Your task__ is to fix it. Find a strategy that reaches the flag. You're not required to build any sophisticated algorithms for now, feel free to hard-code :)_Hint: your action at each s...
# create env manually to set time limit. Please don't change this. TIME_LIMIT = 250 env = gym.wrappers.TimeLimit(gym.envs.classic_control.MountainCarEnv(), max_episode_steps=TIME_LIMIT + 1) s = env.reset() actions = {'left': 0, 'stop': 1, 'right': 2} # prepare "display" %matplotlib notebo...
WARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.
MIT
gym_basics_mountain_car_v0.ipynb
PratikSavla/Reinformemt-Learning-Examples
Submit to coursera
from submit import submit_interface submit_interface(policy, "pratik_mukesh@srmuniv.edu.in", "IT3M0zwksnBtCJXV")
WARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype. Submitted to Coursera platform. See results on assignment page!
MIT
gym_basics_mountain_car_v0.ipynb
PratikSavla/Reinformemt-Learning-Examples
Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli
%matplotlib inline import numpy import matplotlib.pyplot as plt
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
Boundary Value Problems: Discretization Model Problems The simplest boundary value problem (BVP) we will run into is the one-dimensional version of Poisson's equation$$ u''(x) = f(x).$$ Usually we solve this equation on a finite interval with either Dirichlet or Neumann boundary condtions. Because there are two ...
# Problem setup a = 0.0 b = 1.0 u_a = 0.0 u_b = 3.0 f = lambda x: numpy.exp(x) u_true = lambda x: (4.0 - numpy.exp(1.0)) * x - 1.0 + numpy.exp(x) # Descretization m = 10 x_bc = numpy.linspace(a, b, m + 2) x = x_bc[1:-1] delta_x = (b - a) / (m + 1) # Construct matrix A A = numpy.zeros((m, m)) diagonal = numpy.ones(m) ...
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
Error AnalysisA natural question to ask given our approximation $U_i$ is how close this is to the true solution $u(x)$ at the grid points $x_i$. To address this we will define the error $E$ as$$ E = U - \hat{U}$$where $U$ is the vector of the approximate solution and $\hat{U}$ is the vector composed of the $u(x_i)...
def solve_mixed_1st_order_one_sided(m): # Problem setup a = -1.0 b = 1.0 alpha = 3.0 sigma = -5.0 f = lambda x: numpy.exp(x) # Descretization x_bc = numpy.linspace(a, b, m + 2) x = x_bc[1:-1] delta_x = (b - a) / (m + 1) # Construct matrix A A = numpy.zeros((m + 2, m + 2...
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
Existance and UniquenessOne question that should be asked before embarking upon a numerical solution to any equation is whether the original is *well-posed*. Well-posedness is defined as a problem that has a unique solution and depends continuously on the input data (inital condition and boundary conditions are examp...
# Problem setup a = -1.0 b = 1.0 alpha = 3.0 sigma = -5.0 f = lambda x: numpy.exp(x) # Descretization m = 50 x_bc = numpy.linspace(a, b, m + 2) x = x_bc[1:-1] delta_x = (b - a) / (m + 1) # Construct matrix A A = numpy.zeros((m + 2, m + 2)) diagonal = numpy.ones(m + 2) / delta_x**2 A += numpy.diag(diagonal * -2.0, 0) ...
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
We can see why $A$ is singular, the constant vector $e = [1, 1, 1, 1, 1,\ldots, 1]^T$ is in fact in the null-space of $A$. Our numerical method has actually demonstrated this problem is *ill-posed*! Indeed, since the boundary conditions are only on the derivatives there are an infinite number of solutions to the BVP ...
# Simple linear pendulum solutions def linear_pendulum(t, alpha=0.01, beta=0.01, T=1.0): C_1 = alpha C_2 = (beta - alpha * numpy.cos(T)) / numpy.sin(T) return C_1 * numpy.cos(t) + C_2 * numpy.sin(t) alpha = [0.1, -0.1, -1.0] beta = [0.1, 0.1, 0.0] T = [1.0, 1.0, 1.0] t = numpy.linspace(0, 10.0, 100) fig =...
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
But how would we go about handling the fully non-linear problem? First let's discretize using our approach to date with the second order, centered second derivative finite difference approximation to find$$ \frac{1}{\Delta t^2}(\theta_{i+1} - 2 \theta_i + \theta_{i-1}) + \sin (\theta_i) = 0.$$ The most common appro...
def solve_nonlinear_pendulum(m, alpha, beta, T, max_iterations=100, tolerance=1e-3, verbose=False): # Discretization t_bc = numpy.linspace(0.0, T, m + 2) t = t_bc[1:-1] delta_t = T / (m + 1) diagonal = numpy.ones(t.shape) G = numpy.empty(t_bc.shape) # Initial guess theta = 0.7 ...
_____no_output_____
CC0-1.0
04_BVP_problems.ipynb
lihu8918/numerical-methods-pdes
Many to Many ClassificationSimple example for Many to Many Classification (Simple pos tagger) by Recurrent Neural Networks- Creating the **data pipeline** with `tf.data`- Preprocessing word sequences (variable input sequence length) using `padding technique` by `user function (pad_seq)`- Using `tf.nn.embedding_lookup`...
import os, sys import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import string %matplotlib inline slim = tf.contrib.slim print(tf.__version__)
1.10.0
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Prepare example data
sentences = [['I', 'feel', 'hungry'], ['tensorflow', 'is', 'very', 'difficult'], ['tensorflow', 'is', 'a', 'framework', 'for', 'deep', 'learning'], ['tensorflow', 'is', 'very', 'fast', 'changing']] pos = [['pronoun', 'verb', 'adjective'], ['noun', 'verb', 'adverb', 'adjective'], ['noun', 'verb'...
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Create pad_seq function
def pad_seq(sequences, max_len, dic): seq_len, seq_indices = [], [] for seq in sequences: seq_len.append(len(seq)) seq_idx = [dic.get(char) for char in seq] seq_idx += (max_len - len(seq_idx)) * [dic.get('<pad>')] # 0 is idx of meaningless token "<pad>" seq_indices.append(seq_idx...
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Pre-process data
max_length = 10 X_length, X_indices = pad_seq(sequences = sentences, max_len = max_length, dic = word_dic) print(X_length, np.shape(X_indices)) y = [elm + ['<pad>'] * (max_length - len(elm)) for elm in pos] y = [list(map(lambda el : pos_dic.get(el), elm)) for elm in y] print(np.shape(y)) y
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Define SimPosRNN
class SimPosRNN: def __init__(self, X_length, X_indices, y, n_of_classes, hidden_dim, max_len, word_dic): # Data pipeline with tf.variable_scope('input_layer'): # input layer를 구현해보세요 # tf.get_variable을 사용하세요 # tf.nn.embedding_lookup을 사용하세요 sel...
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Create a model of SimPosRNN
# hyper-parameter# lr = .003 epochs = 100 batch_size = 2 total_step = int(np.shape(X_indices)[0] / batch_size) print(total_step) ## create data pipeline with tf.data # tf.data를 이용해서 직접 구현해보세요 # 최종적으로 model은 아래의 코드를 통해서 생성됩니다. sim_pos_rnn = SimPosRNN(X_length = X_length_mb, X_indices = X_indices_mb, y = y_mb, ...
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Creat training op and train model
## create training op opt = tf.train.AdamOptimizer(learning_rate = lr) training_op = opt.minimize(loss = sim_pos_rnn.seq2seq_loss) sess = tf.Session() sess.run(tf.global_variables_initializer()) tr_loss_hist = [] for epoch in range(epochs): avg_tr_loss = 0 tr_step = 0 sess.run(tr_iterator.initializer...
_____no_output_____
Apache-2.0
week07/02_many_to_many_classification_exercise.ipynb
modulabs/modu-tensorflow
Check the distribution of the true and false trials
mu, sigma = 0, 0.1 # mean and standard deviation s = np.random.normal(mu, sigma, 1000) k2_test, p_test = sc.stats.normaltest(s, axis=0, nan_policy='omit') print("p = {:g}".format(p_test)) if p_test < 0.05: # null hypothesis - the distribution is normally distributed; less than alpha - reject null hypothesis print...
L0.1_c-3_m10_MothInOut.csv L0.1_c-3_m12_MothInOut.csv L0.1_c-3_m20_MothInOut.csv L0.1_c-3_m21_MothInOut.csv L0.1_c-3_m22_MothInOut.csv L0.1_c-3_m23_MothInOut.csv L0.1_c-3_m24_MothInOut.csv L0.1_c-3_m25_MothInOut.csv L0.1_c-3_m27_MothInOut.csv L0.1_c-3_m2_MothInOut.csv L0.1_c-3_m32_MothInOut.csv L0.1_c-3_m34_MothInOut.c...
MIT
Step3_SVM-ClassifierTo-LabelVideoData.ipynb
itsMahad/MothAbdominalRestriction
Infocomparison of vhgpr and sgpr
import sys sys.path.append("../../") import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import WhiteKernel, RBF, ConstantKernel as C from core import VHGPR plt.rcParams.update({'font.size': 16})
_____no_output_____
MIT
HGPextreme/examples/motorcycle/func_prediction.ipynb
umbrellagong/HGPextreme
data and test points
Data = sio.loadmat('motorcycle.mat') DX = Data['X'] DY = Data['y'].flatten() x = np.atleast_2d(np.linspace(0,60,100)).T # Test points
_____no_output_____
MIT
HGPextreme/examples/motorcycle/func_prediction.ipynb
umbrellagong/HGPextreme
VHGPR
kernelf = C(10.0, (1e-1, 5*1e3)) * RBF(5, (1e-1, 1e2)) # mean kernel kernelg = C(10.0, (1e-1, 1e2)) * RBF(5, (1e-1, 1e2)) # variance kernel model_v = VHGPR(kernelf, kernelg) results_v = model_v.fit(DX, DY).predict(x)
_____no_output_____
MIT
HGPextreme/examples/motorcycle/func_prediction.ipynb
umbrellagong/HGPextreme
Standard GPR
kernel = C(1e1, (1e-1, 1e4)) * RBF(1e1, (1e-1, 1e2)) + WhiteKernel(1e1, (1e-1, 1e4)) model_s = GaussianProcessRegressor(kernel, n_restarts_optimizer = 5) results_s = model_s.fit(DX, DY).predict(x, return_std = True)
_____no_output_____
MIT
HGPextreme/examples/motorcycle/func_prediction.ipynb
umbrellagong/HGPextreme
Comparison
plt.figure(figsize = (6,4)) plt.plot(DX,DY,"o") plt.plot(x, results_v[0],'r', label='vhgpr') plt.plot(x, results_v[0] + 2 * np.sqrt(np.exp(results_v[2])), 'r--') plt.plot(x, results_v[0] - 2 * np.sqrt(np.exp(results_v[2])),'r--') plt.plot(x, results_s[0],'k', label='sgpr') plt.plot(x, results_s[0] + 2* np.sqr...
_____no_output_____
MIT
HGPextreme/examples/motorcycle/func_prediction.ipynb
umbrellagong/HGPextreme
$EXERCISE_PREAMBLE$As always, run the setup code below before working on the questions (and if you leave this notebook and come back later, remember to run the setup code again).
from learntools.core import binder; binder.bind(globals()) from learntools.python.ex5 import * print('Setup complete.')
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
Exercises 1.Have you ever felt debugging involved a bit of luck? The following program has a bug. Try to identify the bug and fix it.
def has_lucky_number(nums): """Return whether the given list of numbers is lucky. A lucky list contains at least one number divisible by 7. """ for num in nums: if num % 7 == 0: return True else: return False
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
Try to identify the bug and fix it in the cell below:
def has_lucky_number(nums): """Return whether the given list of numbers is lucky. A lucky list contains at least one number divisible by 7. """ for num in nums: if num % 7 == 0: return True else: return False q1.check() #_COMMENT_IF(PROD)_ q1.hint() #_COMMENT_IF(...
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
2. a.Look at the Python expression below. What do you think we'll get when we run it? When you've made your prediction, uncomment the code and run the cell to see if you were right.
#[1, 2, 3, 4] > 2
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
bR and Python have some libraries (like numpy and pandas) compare each element of the list to 2 (i.e. do an 'element-wise' comparison) and give us a list of booleans like `[False, False, True, True]`. Implement a function that reproduces this behaviour, returning a list of booleans corresponding to whether the corresp...
def elementwise_greater_than(L, thresh): """Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise. >>> elementwise_greater_than([1, 2, 3, 4], 2) [False, False, True, True] """ pass q2.check() #_COMMENT_IF(PROD)_ q2....
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
3.Complete the body of the function below according to its docstring
def menu_is_boring(meals): """Given a list of meals served over some period of time, return True if the same meal has ever been served two days in a row, and False otherwise. """ pass q3.check() #_COMMENT_IF(PROD)_ q3.hint() #_COMMENT_IF(PROD)_ q3.solution()
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
4. 🌶️Next to the Blackjack table, the Python Challenge Casino has a slot machine. You can get a result from the slot machine by calling `play_slot_machine()`. The number it returns is your winnings in dollars. Usually it returns 0. But sometimes you'll get lucky and get a big payday. Try running it below:
play_slot_machine()
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
By the way, did we mention that each play costs $1? Don't worry, we'll send you the bill later.On average, how much money can you expect to gain (or lose) every time you play the machine? The casino keeps it a secret, but you can estimate the average value of each pull using a technique called the **Monte Carlo method...
def estimate_average_slot_payout(n_runs): """Run the slot machine n_runs times and return the average net profit per run. Example calls (note that return value is nondeterministic!): >>> estimate_average_slot_payout(1) -1 >>> estimate_average_slot_payout(1) 0.5 """ pass
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
When you think you know the expected value per spin, uncomment the line below to see how close you were.
#_COMMENT_IF(PROD)_ q4.solution()
_____no_output_____
Apache-2.0
notebooks/python/raw/ex_5.ipynb
NeuroLaunch/learntools
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th...
%matplotlib inline %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!
data_path = "Bike-Sharing-Dataset/hour.csv" rides = pd.read_csv(data_path) rides.head()
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov...
rides[: 24 * 10].plot(x="dteday", y="cnt")
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`.
dummy_fields = ["season", "weathersit", "mnth", "hr", "weekday"] for each in dummy_fields: dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False) rides = pd.concat([rides, dummies], axis=1) fields_to_drop = [ "instant", "dteday", "season", "weathersit", "weekday", "atemp",...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions.
quant_features = ["casual", "registered", "cnt", "temp", "hum", "windspeed"] # Store scalings in a dictionary so we can convert back later scaled_features = {} for each in quant_features: mean, std = data[each].mean(), data[each].std() scaled_features[each] = [mean, std] data.loc[:, each] = (data[each] - me...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.
# Save data for approximately the last 21 days test_data = data[-21 * 24 :] # Now remove the test data from the data set data = data[: -21 * 24] # Separate the data into features and targets target_fields = ["cnt", "casual", "registered"] features, targets = data.drop(target_fields, axis=1), data[target_fields] test_...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).
# Hold out the last 60 days or so of the remaining data as a validation set train_features, train_targets = features[: -60 * 24], targets[: -60 * 24] val_features, val_targets = features[-60 * 24 :], targets[-60 * 24 :]
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Time to build the networkBelow you'll build your network. We've built out the structure. You'll implement both the forward pass and backwards pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hid...
############# # In the my_answers.py file, fill out the TODO sections as specified ############# from my_answers import NeuralNetwork def MSE(y, Y): return np.mean((y - Y) ** 2)
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Unit testsRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly before you starting trying to train it. These tests must all be successful to pass the project.
import unittest inputs = np.array([[0.5, -0.2, 0.1]]) targets = np.array([[0.4]]) test_w_i_h = np.array([[0.1, -0.2], [0.4, 0.5], [-0.3, 0.2]]) test_w_h_o = np.array([[0.3], [-0.1]]) class TestMethods(unittest.TestCase): ########## # Unit tests for data loading ########## def test_data_path(self): ...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Training the networkHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys #################### ### Set the hyperparameters in you myanswers.py file ### #################### from my_answers import iterations, learning_rate, hidden_nodes, output_nodes N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {"train": [], "va...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Check out your predictionsHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.
fig, ax = plt.subplots(figsize=(8, 4)) mean, std = scaled_features["cnt"] predictions = np.array(network.run(test_features)).T * std + mean ax.plot(predictions[0], label="Prediction") ax.plot((test_targets["cnt"] * std + mean).values, label="Data") ax.set_xlim(right=len(predictions)) ax.legend() dates = pd.to_datetim...
_____no_output_____
Apache-2.0
deep_learning_v2_pytorch/project-bikesharing/Predicting_bike_sharing_data.ipynb
TeoZosa/deep-learning-v2-pytorch
Introduction to![picture](https://raw.githubusercontent.com/rlberry-py/rlberry/main/assets/logo_wide.svg) Colab setup
# install rlberry library !git clone https://github.com/rlberry-py/rlberry.git !cd rlberry && git pull && pip install -e . > /dev/null 2>&1 # install ffmpeg-python for saving videos !pip install ffmpeg-python > /dev/null 2>&1 # install optuna for hyperparameter optimization !pip install optuna > /dev/null 2>&1 # pa...
_____no_output_____
MIT
notebooks/introduction_to_rlberry.ipynb
antoine-moulin/rlberry
Interacting with a simple environment
from rlberry.envs import GridWorld # A grid world is a simple environment with finite states and actions, on which # we can test simple algorithms. # -> The reward function can be accessed by: env.R[state, action] # -> And the transitions: env.P[state, action, next_state] env = GridWorld(nrows=3, ncols=10, ...
videos/gw.mp4
MIT
notebooks/introduction_to_rlberry.ipynb
antoine-moulin/rlberry
Creating an agentLet's create an agent that runs value iteration to find a near-optimal policy.This is possible in our GridWorld, because we have access to the transitions `env.P` and the rewards `env.R`.An Agent must implement at least two methods, **fit()** and **policy()**.It can also implement **sample_parameters(...
import numpy as np from rlberry.agents import Agent class ValueIterationAgent(Agent): name = 'ValueIterationAgent' def __init__(self, env, gamma=0.99, epsilon=1e-5, **kwargs): # it's important to put **kwargs to ensure compatibility with the base class """ gamma: discount factor epis...
videos/gw.mp4
MIT
notebooks/introduction_to_rlberry.ipynb
antoine-moulin/rlberry
`AgentStats`: A powerfull class for hyperparameter optimization, training and evaluating agents.
# Create random agent as a baseline class RandomAgent(Agent): name = 'RandomAgent' def __init__(self, env, gamma=0.99, epsilon=1e-5, **kwargs): # it's important to put **kwargs to ensure compatibility with the base class """ gamma: discount factor episilon: precision of value iteratio...
[I 2020-11-22 15:33:24,381] A new study created in memory with name: no-name-853cb971-a1ac-45a3-8d33-82ccd07b32c1 [I 2020-11-22 15:33:24,406] Trial 0 finished with value: 0.9 and parameters: {'gamma': 0.25}. Best is trial 0 with value: 0.9. [I 2020-11-22 15:33:24,427] Trial 1 finished...
MIT
notebooks/introduction_to_rlberry.ipynb
antoine-moulin/rlberry
Setup Imports
import sys sys.path.append('../') del sys %reload_ext autoreload %autoreload 2 from toolbox.parsers import standard_parser, add_task_arguments, add_model_arguments from toolbox.utils import load_task, get_pretrained_model, to_class_name import modeling.models as models
_____no_output_____
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Notebook functions
from numpy import argmax, mean def run_models(model_names, word2vec, bart, args, train=False): args.word2vec = word2vec args.bart = bart pretrained_model = get_pretrained_model(args) for model_name in model_names: args.model = model_name print(model_name) model = geta...
_____no_output_____
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Parameters
ap = standard_parser() add_task_arguments(ap) add_model_arguments(ap) args = ap.parse_args(["-m", "", "--root", ".."])
_____no_output_____
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Load the data
task = load_task(args)
Task loaded from ../results/modeling_task/context-dependent-same-type_50-25-25_rs24_bs4_cf-v0_tf-v0.pkl.
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Basic baselines
run_models(model_names=["random", "frequency"], word2vec=False, bart=False, args=args)
random Evaluation on the valid loader...
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Basic baselines
run_models(model_names=["summaries-count", "summaries-unique-count", "summaries-overlap", "activated-summaries", "context-count", "context-unique-count", "summaries-context-cou...
summaries-count Evaluation on the valid loader...
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Embedding baselines
run_models(model_names=["summaries-average-embedding", "summaries-overlap-average-embedding", "context-average-embedding", "summaries-context-average-embedding", "summaries-context-overlap-average-embedding"], wor...
Word2Vec embedding loaded. summaries-average-embedding Evaluation on the valid loader...
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
Custom classifier
run_models(model_names=["custom-classifier"], word2vec=True, bart=False, args=args, train=True)
Word2Vec embedding loaded. custom-classifier Learning answers counts...
Apache-2.0
notebooks/run_model.ipynb
clementjumel/master_thesis
CountVectorizer with Mulinomial Naive Bayes (Benchmark Model)
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer from sklearn.naive_bayes import BernoulliNB, MultinomialNB countVect = CountVectorizer() X_train_countVect = countVect.fit_transform(X_train_cleaned) print("Number of features : %d \n" %len(countVect.get_feature_names())) #6378 print("Sh...
_____no_output_____
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
TfidfVectorizer with Logistic Regression
from sklearn.linear_model import LogisticRegression tfidf = TfidfVectorizer(min_df=5) #minimum document frequency of 5 X_train_tfidf = tfidf.fit_transform(X_train) print("Number of features : %d \n" %len(tfidf.get_feature_names())) #1722 print("Show some feature names : \n", tfidf.get_feature_names()[::1000]) # ...
The best paramenter set is : {'lr__C': 10, 'tfidf__max_features': None, 'tfidf__min_df': 3, 'tfidf__ngram_range': (1, 2), 'tfidf__stop_words': None} Accuracy on validation set: 0.8720 AUC score : 0.8720 Classification report : precision recall f1-score support 0 0.87 0....
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
Word2Vec**Step 1 : Parse review text to sentences (Word2Vec model takes a list of sentences as inputs)****Step 2 : Create volcabulary list using Word2Vec model.****Step 3 : Transform each review into numerical representation by computing average feature vectors of words therein.****Step 4 : Fit the average feature vec...
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') def parseSent(review, tokenizer, remove_stopwords=False): raw_sentences = tokenizer.tokenize(review.strip()) sentences = [] for raw_sentence in raw_sentences: if len(raw_sentence) > 0: sentences.append(cleanText(raw_...
4500 parsed sentence in the training set Show a parsed sentence in the training set : ['the', 'crimson', 'rivers', 'is', 'one', 'of', 'the', 'most', 'over', 'directed', 'over', 'the', 'top', 'over', 'everything', 'mess', 'i', 've', 'ever', 'seen', 'come', 'out', 'of', 'france', 'there', 's', 'nothing', 'worse', 'tha...
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
Creating Volcabulary List usinhg Word2Vec Model
from wordcloud import WordCloud from gensim.models import word2vec from gensim.models.keyedvectors import KeyedVectors num_features = 300 #embedding dimension min_word_count = 10 num_workers = 4 context = 10 ...
Training Word2Vec model ...
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
Averaging Feature Vectors
def makeFeatureVec(review, model, num_features): ''' Transform a review to a feature vector by averaging feature vectors of words appeared in that review and in the volcabulary list created ''' featureVec = np.zeros((num_features,),dtype="float32") nwords = 0. index2word_set = set(mo...
_____no_output_____
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
Random Forest Classifer
from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_estimators=1000) rf.fit(trainVector, y_train) predictions = rf.predict(testVector) modelEvaluation(predictions)
_____no_output_____
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
LSTM**Step 1 : Prepare X_train and X_test to 2D tensor.** **Step 2 : Train a simple LSTM (embeddign layer => LSTM layer => dense layer).** **Step 3 : Compile and fit the model using log loss function and ADAM optimizer.**
from keras.preprocessing import sequence from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Lambda from keras.layers.embeddings import Embedding from keras.layers.recurrent import LSTM, SimpleRNN, GRU from keras.preprocessing.text import ...
_____no_output_____
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis