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 |
|---|---|---|---|---|---|
Checkpoint callback optionsThe callback provides several options to give the resulting checkpoints unique names, and adjust the checkpointing frequency.Train a new model, and save uniquely named checkpoints once every 5-epochs: | # include the epoch in the file name. (uses `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
checkpoint_path, verbose=1, save_weights_only=True,
# Save weights, every 5-epochs.
period=5)
mod... | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Now, look at the resulting checkpoints and choose the latest one: | ! ls {checkpoint_dir}
latest = tf.train.latest_checkpoint(checkpoint_dir)
latest | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Note: the default tensorflow format only saves the 5 most recent checkpoints.To test, reset the model and load the latest checkpoint: | model = create_model()
model.load_weights(latest)
loss, acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
What are these files? The above code stores the weights to a collection of [checkpoint](https://www.tensorflow.org/guide/saved_modelsave_and_restore_variables)-formatted files that contain only the trained weights in a binary format. Checkpoints contain:* One or more shards that contain your model's weights. * An inde... | # Save the weights
model.save_weights('./checkpoints/my_checkpoint')
# Restore the weights
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Save the entire modelThe entire model can be saved to a file that contains the weight values, the model's configuration, and even the optimizer's configuration (depends on set up). This allows you to checkpoint a model and resume training later—from the exact same state—without access to the original code.Saving a ful... | model = create_model()
# You need to use a keras.optimizer to restore the optimizer state from an HDF5 file.
model.compile(optimizer='adam',
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
# Save entire model to ... | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Now recreate the model from that file: | # Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('my_model.h5')
new_model.summary() | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Check its accuracy: | loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) | _____no_output_____ | Apache-2.0 | site/en/2/tutorials/keras/save_and_restore_models.ipynb | allenlavoie/docs |
Stream Analytics TutorialOverviewWelcome to the stream analytics tutorial for EpiData. In this tutorial we will perform near real-time stream analytics on sample weather data acquired from a simulated wireless sensor network. Package and Module ImportsAs a first step, we will import packages and modules required for th... | #from epidata.context import ec
from epidata.analytics import *
%matplotlib inline
from datetime import datetime, timedelta
import pandas as pd
import time
import pylab as pl
from IPython import display
import json | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Stream AnalysisFunction DefinitionEpiData supports development and deployment of custom algorithms via Jupyter Notebook. Below, we define python functions for substituting extreme outliers and aggregating temperature measurements. These functions can be operated on near real-time and historic data. In this tutorial, we... | import pandas as pd
import math, numbers
def substitute_demo(df, meas_names, method="rolling", size=3):
"""
Substitute missing measurement values within a data frame, using the specified method.
"""
df["meas_value"].replace(250, np.nan, inplace=True)
for meas_name in meas_names:
if (... | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Transformations and StreamsThe analytics algorithms are executed on near real-time data through transformations. A transformation specifies the function, its parameters and destination. The destination can be one of the database tables, namely 'measurements_cleansed' or 'measurements_summary', or another Kafka topic.On... | #Stop current near real-time processing
ec.stop_streaming()
# Define tranformations and steam operations
op1 = ec.create_transformation(substitute_demo, [["Temperature", "Wind_Speed"], "rolling", 3], "measurements_substituted")
ec.create_stream([op1], "measurements")
op2 = ec.create_transformation(identity, [], "meas... | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Data IngestionWe can now start data ingestion from simulated wireless sensor network. To do so, you can download and run the sensor_data_with_outliers.py example shown in the image below. Data Query and VisualizationWe query the original and processed data from Kafka queue using Kafka Consumer. The data obtained from t... | from bokeh.io import push_notebook, show, output_notebook
from bokeh.layouts import row, column
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from kafka import KafkaConsumer
import json
from pandas.io.json import json_normalize
output_notebook()
plot1 = figure(plot_width=750, plot_height... | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Another way to query and visualize processed data is using ec.query_measurements_cleansed(..) and ec.query_measurements_summary(..) functions. For our example, we specify paramaters that match sample data set, and query the aggregated values using ec.query_measurements_summary(..) function call. | # QUERY MEASUREMENTS_CLEANSED TABLE
primary_key={"company": "EpiData", "site": "San_Jose", "station":"WSN-1",
"sensor": ["Temperature_Probe", "RH_Probe", "Anemometer"]}
start_time = datetime.strptime('8/19/2017 00:00:00', '%m/%d/%Y %H:%M:%S')
stop_time = datetime.strptime('8/20/2017 00:00:00', '%m/%d/%Y ... | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Stop Stream AnalyticsThe transformations can be stopped at any time via ec.stop_streaming() function call | #Stop current near real-time processing
ec.stop_streaming() | _____no_output_____ | Apache-2.0 | ipython/home/tutorials/3. Stream Analytics Tutorial.ipynb | samarth-bhutani/epidata-community |
Update the geemap packageIf you run into errors with this notebook, please uncomment the line below to update the [geemap](https://github.com/giswqs/geemapinstallation) package to the latest version from GitHub. Restart the Kernel (Menu -> Kernel -> Restart) to take effect. | # geemap.update_package() | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Create an interactive map Use the Drawing tool to draw a rectangle on the map | Map = geemap.Map()
Map | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Generate a Landsat timelapse animation | import os
out_dir = os.path.join(os.path.expanduser("~"), 'Downloads')
if not os.path.exists(out_dir):
os.makedirs(out_dir)
label = 'Urban Growth in Las Vegas'
Map.add_landsat_ts_gif(label=label, start_year=1985, bands=['Red', 'Green', 'Blue'], font_color='white', frames_per_second=10, progress_bar_color='blue') | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Create Landsat timeseries | import os
import ee
import geemap
Map = geemap.Map()
Map | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
You and define an roi or draw a rectangle on the map | roi = ee.Geometry.Polygon(
[[[-115.471773, 35.892718],
[-115.471773, 36.409454],
[-114.271283, 36.409454],
[-114.271283, 35.892718],
[-115.471773, 35.892718]]], None, False)
# roi = Map.draw_last_feature
collection = geemap.landsat_timeseries(roi=roi, start_year=1985, end_year=2019, st... | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Download ImageCollection as a GIF | # Define arguments for animation function parameters.
video_args = {
'dimensions': 768,
'region': roi,
'framesPerSecond': 10,
'bands': ['NIR', 'Red', 'Green'],
'min': 0,
'max': 4000,
'gamma': [1, 1, 1]
}
work_dir = os.path.join(os.path.expanduser("~"), 'Downloads')
if not os.path.exists(work_dir):
os.... | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Add animated text to GIF | geemap.show_image(out_gif)
texted_gif = os.path.join(work_dir, "landsat_ts_text.gif")
geemap.add_text_to_gif(out_gif, texted_gif, xy=('3%', '5%'), text_sequence=1985, font_size=30, font_color='#ffffff', add_progress_bar=False)
label = 'Urban Growth in Las Vegas'
geemap.add_text_to_gif(texted_gif, texted_gif, xy=('2%', ... | _____no_output_____ | MIT | examples/notebooks/18_create_landsat_timelapse.ipynb | jitendra-kumar/geemap |
Copyright 2019 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License"); | # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
Multilingual Universal Sentence Encoder Q&A Retrieval View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This is a demo for using [Univeral Encoder Multilingual Q&A model](https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3) for question-an... | %%capture
#@title Setup Environment
# Install the latest Tensorflow version.
!pip install -q tensorflow_text
!pip install -q simpleneighbors[annoy]
!pip install -q nltk
!pip install -q tqdm
#@title Setup common imports and functions
import json
import nltk
import os
import pprint
import random
import simpleneighbors
im... | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
Run the following code block to download and extract the SQuAD dataset into:* **sentences** is a list of (text, context) tuples - each paragraph from the SQuAD dataset are splitted into sentences using nltk library and the sentence and paragraph text forms the (text, context) tuple.* **questions** is a list of (questio... | #@title Download and extract SQuAD data
squad_url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json' #@param ["https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json", "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json", "https://rajpurkar.github.io/SQuAD-explorer/dataset/tr... | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
The following code block setup the tensorflow graph **g** and **session** with the [Univeral Encoder Multilingual Q&A model](https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3)'s **question_encoder** and **response_encoder** signatures. | #@title Load model from tensorflow hub
module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3" #@param ["https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3", "https://tfhub.dev/google/universal-sentence-encoder-qa/3"]
model = hub.load(module_url)
| _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
The following code block compute the embeddings for all the text, context tuples and store them in a [simpleneighbors](https://pypi.org/project/simpleneighbors/) index using the **response_encoder**. | #@title Compute embeddings and build simpleneighbors index
batch_size = 100
encodings = model.signatures['response_encoder'](
input=tf.constant([sentences[0][0]]),
context=tf.constant([sentences[0][1]]))
index = simpleneighbors.SimpleNeighbors(
len(encodings['outputs'][0]), metric='angular')
print('Computing ... | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
On retrieval, the question is encoded using the **question_encoder** and the question embedding is used to query the simpleneighbors index. | #@title Retrieve nearest neighbors for a random question from SQuAD
num_results = 25 #@param {type:"slider", min:5, max:40, step:1}
query = random.choice(questions)
display_nearest_neighbors(query[0], query[1]) | _____no_output_____ | Apache-2.0 | site/en-snapshot/hub/tutorials/retrieval_with_tf_hub_universal_encoder_qa.ipynb | ilyaspiridonov/docs-l10n |
COPYRIGHT © 2018 Kiran Arun Setup | # install dependencies
!rm -r Neural_Networks-101-demo
!git clone -b explanations https://github.com/KiranArun/Neural_Networks-101-demo.git
!python3 /content/Neural_Networks-101-demo/scripts/setup.py helper_funcs tensorboard
# run tensorboard
get_ipython().system_raw('tensorboard --logdir=/content/logdir/ --host=0.0.0.... | Tensorboard Link: http://bdb495ac.ngrok.io
| MIT | tb_models/Basic_MNIST-tb.ipynb | KiranArun/Neural_Networks-demo |
MNIST Handwriten Digits Classifier | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
from math import ceil,floor
import helper_funcs as helper
# this is the directory where we will keep and external files, eg. data, logs
model_root_dir = '/content/'
# get data
mnist = helper.MNIST_data(model_root_dir+'MNIST_data/',sh... | _____no_output_____ | MIT | tb_models/Basic_MNIST-tb.ipynb | KiranArun/Neural_Networks-demo |
**Chapter 16 – Reinforcement Learning** This notebook contains all the sample code and solutions to the exercices in chapter 16. Setup First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures: | # To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import numpy.random as rnd
import os
import sys
# to make this notebook's output stable across runs
rnd.seed(42)
# To plot pretty figures and animations
%matplotlib nbagg
impo... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Introduction to OpenAI gym In this notebook we will be using [OpenAI gym](https://gym.openai.com/), a great toolkit for developing and comparing Reinforcement Learning algorithms. It provides many environments for your learning *agents* to interact with. Let's start by importing `gym`: | import gym | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Next we will load the MsPacman environment, version 0. | env = gym.make('MsPacman-v0') | [2017-02-17 10:57:41,836] Making new env: MsPacman-v0
| Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Let's initialize the environment by calling is `reset()` method. This returns an observation: | obs = env.reset() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Observations vary depending on the environment. In this case it is an RGB image represented as a 3D NumPy array of shape [width, height, channels] (with 3 channels: Red, Green and Blue). In other environments it may return different objects, as we will see later. | obs.shape | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
An environment can be visualized by calling its `render()` method, and you can pick the rendering mode (the rendering options depend on the environment). In this example we will set `mode="rgb_array"` to get an image of the environment as a NumPy array: | img = env.render(mode="rgb_array") | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Let's plot this image: | plt.figure(figsize=(5,4))
plt.imshow(img)
plt.axis("off")
save_fig("MsPacman")
plt.show() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Welcome back to the 1980s! :) In this environment, the rendered image is simply equal to the observation (but in many environments this is not the case): | (img == obs).all() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Let's create a little helper function to plot an environment: | def plot_environment(env, figsize=(5,4)):
plt.close() # or else nbagg sometimes plots in the previous cell
plt.figure(figsize=figsize)
img = env.render(mode="rgb_array")
plt.imshow(img)
plt.axis("off")
plt.show() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Let's see how to interact with an environment. Your agent will need to select an action from an "action space" (the set of possible actions). Let's see what this environment's action space looks like: | env.action_space | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
`Discrete(9)` means that the possible actions are integers 0 through 8, which represents the 9 possible positions of the joystick (0=center, 1=up, 2=right, 3=left, 4=down, 5=upper-right, 6=upper-left, 7=lower-right, 8=lower-left). Next we need to tell the environment which action to play, and it will compute the next s... | env.reset()
for step in range(110):
env.step(3) #left
for step in range(40):
env.step(8) #lower-left | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Where are we now? | plot_environment(env) | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
The `step()` function actually returns several important objects: | obs, reward, done, info = env.step(0) | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
The observation tells the agent what the environment looks like, as discussed earlier. This is a 210x160 RGB image: | obs.shape | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
The environment also tells the agent how much reward it got during the last step: | reward | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
When the game is over, the environment returns `done=True`: | done | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Finally, `info` is an environment-specific dictionary that can provide some extra information about the internal state of the environment. This is useful for debugging, but your agent should not use this information for learning (it would be cheating). | info | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Let's play one full game (with 3 lives), by moving in random directions for 10 steps at a time, recording each frame: | frames = []
n_max_steps = 1000
n_change_steps = 10
obs = env.reset()
for step in range(n_max_steps):
img = env.render(mode="rgb_array")
frames.append(img)
if step % n_change_steps == 0:
action = env.action_space.sample() # play randomly
obs, reward, done, info = env.step(action)
if done:
... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Now show the animation (it's a bit jittery within Jupyter): | def update_scene(num, frames, patch):
patch.set_data(frames[num])
return patch,
def plot_animation(frames, repeat=False, interval=40):
plt.close() # or else nbagg sometimes plots in the previous cell
fig = plt.figure()
patch = plt.imshow(frames[0])
plt.axis('off')
return animation.FuncAnim... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Once you have finished playing with an environment, you should close it to free up resources: | env.close() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
To code our first learning agent, we will be using a simpler environment: the Cart-Pole. A simple environment: the Cart-Pole The Cart-Pole is a very simple environment composed of a cart that can move left or right, and pole placed vertically on top of it. The agent must move the cart left or right to keep the pole u... | env = gym.make("CartPole-v0")
obs = env.reset()
obs | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
The observation is a 1D NumPy array composed of 4 floats: they represent the cart's horizontal position, its velocity, the angle of the pole (0 = vertical), and the angular velocity. Let's render the environment... unfortunately we need to fix an annoying rendering issue first. Fixing the rendering issue Some environm... | from PIL import Image, ImageDraw
try:
from pyglet.gl import gl_info
openai_cart_pole_rendering = True # no problem, let's use OpenAI gym's rendering function
except Exception:
openai_cart_pole_rendering = False # probably no X server available, let's use our own rendering function
def render_cart_pole(... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Now let's look at the action space: | env.action_space | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Yep, just two possible actions: accelerate towards the left or towards the right. Let's push the cart left until the pole falls: | obs = env.reset()
while True:
obs, reward, done, info = env.step(0)
if done:
break
plt.close() # or else nbagg sometimes plots in the previous cell
img = render_cart_pole(env, obs)
plt.imshow(img)
plt.axis("off")
save_fig("cart_pole_plot") | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Notice that the game is over when the pole tilts too much, not when it actually falls. Now let's reset the environment and push the cart to right instead: | obs = env.reset()
while True:
obs, reward, done, info = env.step(1)
if done:
break
plot_cart_pole(env, obs) | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Looks like it's doing what we're telling it to do. Now how can we make the poll remain upright? We will need to define a _policy_ for that. This is the strategy that the agent will use to select an action at each step. It can use all the past actions and observations to decide what to do. A simple hard-coded policy Le... | frames = []
n_max_steps = 1000
n_change_steps = 10
obs = env.reset()
for step in range(n_max_steps):
img = render_cart_pole(env, obs)
frames.append(img)
# hard-coded policy
position, velocity, angle, angular_velocity = obs
if angle < 0:
action = 0
else:
action = 1
obs, re... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Nope, the system is unstable and after just a few wobbles, the pole ends up too tilted: game over. We will need to be smarter than that! Neural Network Policies Let's create a neural network that will take observations as inputs, and output the action to take for each observation. To choose an action, the network will... | import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
# 1. Specify the network architecture
n_inputs = 4 # == env.observation_space.shape[0]
n_hidden = 4 # it's a simple task, we don't need more than this
n_outputs = 1 # only outputs the probability of accelerating left
initializer = tf.contr... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
In this particular environment, the past actions and observations can safely be ignored, since each observation contains the environment's full state. If there were some hidden state then you may need to consider past actions and observations in order to try to infer the hidden state of the environment. For example, if... | n_max_steps = 1000
frames = []
with tf.Session() as sess:
init.run()
obs = env.reset()
for step in range(n_max_steps):
img = render_cart_pole(env, obs)
frames.append(img)
action_val = action.eval(feed_dict={X: obs.reshape(1, n_inputs)})
obs, reward, done, info = env.step(act... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Now let's look at how well this randomly initialized policy network performed: | video = plot_animation(frames)
plt.show() | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Yeah... pretty bad. The neural network will have to learn to do better. First let's see if it is capable of learning the basic policy we used earlier: go left if the pole is tilting left, and go right if it is tilting right. The following code defines the same neural network but we add the target probabilities `y`, and... | import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
tf.reset_default_graph()
n_inputs = 4
n_hidden = 4
n_outputs = 1
learning_rate = 0.01
initializer = tf.contrib.layers.variance_scaling_initializer()
X = tf.placeholder(tf.float32, shape=[None, n_inputs])
y = tf.placeholder(tf.float32, sh... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
We can make the same net play in 10 different environments in parallel, and train for 1000 iterations. We also reset environments when they are done. | n_environments = 10
n_iterations = 1000
envs = [gym.make("CartPole-v0") for _ in range(n_environments)]
observations = [env.reset() for env in envs]
with tf.Session() as sess:
init.run()
for iteration in range(n_iterations):
target_probas = np.array([([1.] if obs[2] < 0 else [0.]) for obs in observati... | [2017-02-17 10:58:55,704] Making new env: CartPole-v0
| Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Looks like it learned the policy correctly. Now let's see if it can learn a better policy on its own. Policy Gradients To train this neural network we will need to define the target probabilities `y`. If an action is good we should increase its probability, and conversely if it is bad we should reduce it. But how do w... | import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
tf.reset_default_graph()
n_inputs = 4
n_hidden = 4
n_outputs = 1
learning_rate = 0.01
initializer = tf.contrib.layers.variance_scaling_initializer()
X = tf.placeholder(tf.float32, shape=[None, n_inputs])
hidden = fully_connected(X, n_hi... | [2017-02-17 11:06:16,047] Making new env: CartPole-v0
| Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Markov Chains | transition_probabilities = [
[0.7, 0.2, 0.0, 0.1], # from s0 to s0, s1, s2, s3
[0.0, 0.0, 0.9, 0.1], # from s1 to ...
[0.0, 1.0, 0.0, 0.0], # from s2 to ...
[0.0, 0.0, 0.0, 1.0], # from s3 to ...
]
n_max_steps = 50
def print_sequence(start_state=0):
current_state = start_st... | States: 0 0 3
States: 0 1 2 1 2 1 2 1 2 1 3
States: 0 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 3
States: 0 3
States: 0 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 3
States: 0 1 3
States: 0 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 ...
States: 0 0 3
States: 0 0 0 1 2 1 2... | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Markov Decision Process | transition_probabilities = [
[[0.7, 0.3, 0.0], [1.0, 0.0, 0.0], [0.8, 0.2, 0.0]], # in s0, if action a0 then proba 0.7 to state s0 and 0.3 to state s1, etc.
[[0.0, 1.0, 0.0], None, [0.0, 0.0, 1.0]],
[None, [0.8, 0.1, 0.1], None],
]
rewards = [
[[+10, 0, 0], [0, 0, 0], [0, 0, 0]],
... | policy_fire
States (+rewards): 0 (10) 0 (10) 0 1 (-50) 2 2 2 (40) 0 (10) 0 (10) 0 (10) ... Total rewards = 210
States (+rewards): 0 1 (-50) 2 (40) 0 (10) 0 (10) 0 1 (-50) 2 2 (40) 0 (10) ... Total rewards = 70
States (+rewards): 0 (10) 0 1 (-50) 2 (40) 0 (10) 0 (10) 0 (10) 0 (10) 0 (10) 0 (10) ... Total rewards = 70
St... | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Q-Learning Q-Learning will learn the optimal policy by watching the random policy play. | n_states = 3
n_actions = 3
n_steps = 20000
alpha = 0.01
gamma = 0.99
exploration_policy = policy_random
q_values = np.full((n_states, n_actions), -np.inf)
for state, actions in enumerate(possible_actions):
q_values[state][actions]=0
env = MDPEnvironment()
for step in range(n_steps):
action = exploration_policy... | States (+rewards): 0 (10) 0 (10) 0 1 (-50) 2 (40) 0 (10) 0 1 (-50) 2 (40) 0 (10) ... Total rewards = 230
States (+rewards): 0 (10) 0 (10) 0 (10) 0 1 (-50) 2 2 1 (-50) 2 (40) 0 (10) ... Total rewards = 90
States (+rewards): 0 1 (-50) 2 (40) 0 (10) 0 (10) 0 (10) 0 (10) 0 (10) 0 (10) 0 (10) ... Total rewards = 170
States ... | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Learning to play MsPacman using Deep Q-Learning | env = gym.make("MsPacman-v0")
obs = env.reset()
obs.shape
env.action_space | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Preprocessing Preprocessing the images is optional but greatly speeds up training. | mspacman_color = np.array([210, 164, 74]).mean()
def preprocess_observation(obs):
img = obs[1:176:2, ::2] # crop and downsize
img = img.mean(axis=2) # to greyscale
img[img==mspacman_color] = 0 # Improve contrast
img = (img - 128) / 128 - 1 # normalize from -1. to 1.
return img.reshape(88, 80, 1)
i... | _____no_output_____ | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
Build DQN | tf.reset_default_graph()
from tensorflow.contrib.layers import convolution2d, fully_connected
input_height = 88
input_width = 80
input_channels = 1
conv_n_maps = [32, 64, 64]
conv_kernel_sizes = [(8,8), (4,4), (3,3)]
conv_strides = [4, 2, 1]
conv_paddings = ["SAME"]*3
conv_activation = [tf.nn.relu]*3
n_hidden_inputs... | Iteration 328653 Training step 100000/100000 (100.0%) | Apache-2.0 | 16_reinforcement_learning.ipynb | fsv20/Sergey |
[](http://rpi.analyticsdojo.com)Basic Text Feature Creation in Pythonrpi.analyticsdojo.com Basic Text Feature Creation in Python | !wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/train.csv
!wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/test.csv
import numpy as np
import pandas as pd
import pandas as pd
train= pd.read_csv('train.csv')
test = pd.read_csv(... | /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reinde... | MIT | site/_build/jupyter_execute/notebooks/08-intro-nlp/01-titanic-features.ipynb | rpi-techfundamentals/spring2020_website |
Warding Tied to Objectives Repear previous exercise but add status of towers at time of ward.Code here is incorporated into a class to make things smoother | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import matplotlib.patches as patches
import os
data_path = os.path.join('data_obj', 'data_April_09_to_May_01.json')
df = pd.read_json(data_path)
df.head()
os.listdir('data_obj')
df.shape
df['match_id'].nunique() | _____no_output_____ | MIT | 04_Extract_Organize_Objectives.ipynb | NadimKawwa/DOTAWardFinder |
We have more entries that number of unique match IDs. We can reduce work and avoid redundancy by parsing through unique match IDs to extract objectives | df['match_id'][52]
#look inside a obs log column
df['objectives'][52]
for item in df['objectives'][52]:
print(item['type'])
for item in df['objectives'][0]:
if item['type']== 'building_kill':
print(item['key'])
arr = [{'bot1': 999, 'bot2': 55}, {'bot2': 100, 'bot3': 300}]
pd.DataFrame(arr)
def getObject... | _____no_output_____ | MIT | 04_Extract_Organize_Objectives.ipynb | NadimKawwa/DOTAWardFinder |
Neuromatch Academy: Week 1, Day 5, Tutorial 3 Dimensionality Reduction and reconstruction__Content creators:__ Alex Cayco Gajic, John Murray__Content reviewers:__ Roozbeh Farhoudi, Matt Krause, Spiros Chavlis, Richard Gao, Michael Waskom --- Tutorial ObjectivesIn this notebook we'll learn to apply PCA for dimensional... | # @title Video 1: PCA for dimensionality reduction
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="oO0bbInoO_0", width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=oO0bbInoO_0
| CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
--- SetupRun these cells to get the tutorial started. | # Imports
import numpy as np
import matplotlib.pyplot as plt
# @title Figure Settings
import ipywidgets as widgets # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
# @title Helper Functions
de... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
--- Section 1: Perform PCA on MNISTThe MNIST dataset consists of a 70,000 images of individual handwritten digits. Each image is a 28x28 pixel grayscale image. For convenience, each 28x28 pixel image is often unravelled into a single 784 (=28*28) element vector, so that the whole dataset is represented as a 70,000 x 78... | from sklearn.datasets import fetch_openml
mnist = fetch_openml(name='mnist_784')
X = mnist.data
plot_MNIST_sample(X) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
The MNIST dataset has an extrinsic dimensionality of 784, much higher than the 2-dimensional examples used in the previous tutorials! To make sense of this data, we'll use dimensionality reduction. But first, we need to determine the intrinsic dimensionality $K$ of the data. One way to do this is to look for an "elbow"... | help(pca)
help(plot_eigenvalues)
#################################################
## TO DO for students: perform PCA and plot the eigenvalues
#################################################
# perform PCA
# score, evectors, evals = ...
# plot the eigenvalues
# plot_eigenvalues(evals, limit=False)
# plt.xlim(...) # ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
--- Section 2: Calculate the variance explainedThe scree plot suggests that most of the eigenvalues are near zero, with fewer than 100 having large values. Another common way to determine the intrinsic dimensionality is by considering the variance explained. This can be examined with a cumulative plot of the fraction o... | help(plot_variance_explained)
def get_variance_explained(evals):
"""
Calculates variance explained from the eigenvalues.
Args:
evals (numpy array of floats) : Vector of eigenvalues
Returns:
(numpy array of floats) : Vector of variance explained
"""
#########################################... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
--- Section 3: Reconstruct data with different numbers of PCs Now we have seen that the top 100 or so principal components of the data can explain most of the variance. We can use this fact to perform *dimensionality reduction*, i.e., by storing the data using only 100 components rather than the samples of all 784 pixe... | help(plot_MNIST_reconstruction)
def reconstruct_data(score, evectors, X_mean, K):
"""
Reconstruct the data based on the top K components.
Args:
score (numpy array of floats) : Score matrix
evectors (numpy array of floats) : Matrix of eigenvectors
X_mean (numpy array of floats) : Vector correspon... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
Interactive Demo: Reconstruct the data matrix using different numbers of PCsNow run the code below and experiment with the slider to reconstruct the data matrix using different numbers of principal components.**Steps*** How many principal components are necessary to reconstruct the numbers (by eye)? How does this rela... | # @title
# @markdown Make sure you execute this cell to enable the widget!
def refresh(K=100):
X_reconstructed = reconstruct_data(score, evectors, X_mean, K)
plot_MNIST_reconstruction(X, X_reconstructed)
plt.title('Reconstructed, K={}'.format(K))
_ = widgets.interact(refresh, K=(1, 784, 10)) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
Exercise 4: Visualization of the weightsNext, let's take a closer look at the first principal component by visualizing its corresponding weights. **Steps:*** Enter `plot_MNIST_weights` to visualize the weights of the first basis vector.* What structure do you see? Which pixels have a strong positive weighting? Which h... | help(plot_MNIST_weights)
#################################################
## TO DO for students: plot the weights calling the plot_MNIST_weights function
#################################################
# Plot the weights of the first principal component
# plot_MNIST_weights(...)
# to_remove solution
# Plot the weig... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
--- Summary* In this tutorial, we learned how to use PCA for dimensionality reduction by selecting the top principal components. This can be useful as the intrinsic dimensionality ($K$) is often less than the extrinsic dimensionality ($N$) in neural data. $K$ can be inferred by choosing the number of eigenvalues necess... | help(add_noise)
###################################################################
# Insert your code here to:
# Add noise to the data
# Plot noise-corrupted data
# Perform PCA on the noisy data
# Calculate and plot the variance explained
###################################################################
np.random.se... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
Exercise 6: DenoisingNext, use PCA to perform denoising by projecting the noise-corrupted data onto the basis vectors found from the original dataset. By taking the top K components of this projection, we can reduce noise in dimensions orthogonal to the K-dimensional latent space. **Steps:**- Subtract the mean of the ... | ###################################################################
# Insert your code here to:
# Subtract the mean of the noise-corrupted data
# Project onto the original basis vectors evectors
# Reconstruct the data using the top 50 components
# Plot the result
########################################################... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D5_DimensionalityReduction/W1D5_Tutorial3.ipynb | simpleParadox/course-content |
Quick Start **A tutorial on Renormalized Mutual Information**We describe in detail the implementation of RMI estimation in the very simple case of a Gaussian distribution.Of course, in this case the optimal feature is given by the Principal Component Analysis | import numpy as np
# parameters of the Gaussian distribution
mu = [0,0]
sigma = [[1, 0.5],[0.5,2]]
# extract the samples
N_samples = 100000
samples = np.random.multivariate_normal(mu, sigma, N_samples ) | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
Visualize the distribution with a 2D histogram | import matplotlib.pyplot as plt
plt.figure()
plt.hist2d(*samples.T, bins=100, cmap=plt.cm.binary)
plt.gca().set_aspect("equal")
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.title("$P_x(x)$")
plt.show() | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
Estimate Renormalized Mutual Information of a featureNow we would like to find a one-dimensional function $f(x_1,x_2)$ to describe this 2d distribution. Simplest featureFor example, we could consider ignoring one of the variables: | def f(x):
# feature
# shape [N_samples, N_features=1]
return x[:,0][...,None]
def grad_f(x):
# gradient
# shape [N_samples, N_features=1, N_x=2]
grad_f = np.zeros([len(x),1,2])
grad_f[...,0] = 1
return grad_f
def feat_and_grad(x):
return f(x), grad_f(x) | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
Let's plot it on top of the distribution | # Range of the plot
xmin = -4
xmax = 4
# Number of points in the grid
N = 100
# We evaluate the feature on a grid
x_linspace = np.linspace(xmin, xmax, N)
x1_grid, x2_grid = np.meshgrid(x_linspace, x_linspace, indexing='ij')
x_points = np.array([x1_grid.flatten(), x2_grid.flatten()]).T
feature = f(x_points)
gradient =... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
$f(x)=x_1$ is clearly a linear function that ignores $x_2$ and increases in the $x_1$ direction**How much information does it give us on $x$?**If we used common mutual information, it would be $\infty$, because $f$ is a deterministic function, and $H(y|x) = -\log \delta(0)$.Let's estimate the renormalized mutual inform... | import rmi.estimation as inf
samples = np.random.multivariate_normal(mu, sigma, N_samples )
feature = f(samples)
gradient = grad_f(samples)
RMI = inf.RenormalizedMutualInformation(feature, gradient)
print("Renormalized Mutual Information (x,f(x)): %2.2f" % RMI) | Renormalized Mutual Information (x,f(x)): 1.42
| MIT | quick-start.ipynb | XudongWang97/rmi |
Please note that we perform the plot by calculating the feature on a uniform grid. But, to estimate RMI, the feature should be calculated on x **sampled** from the $x$ distribution. In particular, we have | p_y, delta_y = inf.produce_P(feature)
entropy = inf.Entropy(p_y, delta_y)
fterm = inf.RegTerm(gradient)
print("Entropy\t %2.2f" % entropy)
print("Fterm\t %2.2f" % fterm)
print("Renormalized Mutual Information (x,f(x)): %2.2f" %
(entropy + fterm)) | Entropy 1.42
Fterm -0.00
Renormalized Mutual Information (x,f(x)): 1.42
| MIT | quick-start.ipynb | XudongWang97/rmi |
Renormalized Mutual Information is the sum of the two terms- Entropy- RegTerm Reparametrization invarianceDo we gain information if we increase the variance of the feature?For example, let's rescale our feature. Clearly the information on $x$ should remain the same | scale_factor = 4
feature *= scale_factor
gradient *= scale_factor
RMI = inf.RenormalizedMutualInformation(feature, gradient)
print("Renormalized Mutual Information (x,f(x)): %2.2f" % RMI)
p_y, delta_y = inf.produce_P(feature)
entropy = inf.Entropy(p_y, delta_y)
fterm = inf.RegTerm(gradient)
print("Entropy\t %2.2f" ... | Renormalized Mutual Information (x,f(x)): 1.42
Entropy 2.80
Fterm -1.39
| MIT | quick-start.ipynb | XudongWang97/rmi |
Let's try even a non-linear transformation. As long as it is invertible, we will get the same RMI | # For example
y_lin = np.linspace(-4,4,100)
f_lin = y_lin**3 + 5*y_lin
plt.figure()
plt.title("Reparametrization function")
plt.plot(y_lin, f_lin)
plt.show()
feature_new = feature**3 + 5*feature
gradient_new = 3*feature[...,None]**2*gradient +5*gradient# chain rule...
RMI = inf.RenormalizedMutualInformation(feature_ne... | Renormalized Mutual Information (x,f(x)): 1.42
Entropy 6.24
Fterm -4.70
| MIT | quick-start.ipynb | XudongWang97/rmi |
In this case, we have to increase the number of bins to calculate the Entropy with reasonable accuracy.The reason is that the feature now spans a quite larger range but changes very rapidly in the few bins around zero (but we use a uniform binning when estimating the entropy). | plt.hist(feature_new,1000)
plt.show() | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
And if we instead appliead a **non-invertible** transformation? The consequence is clear: we will **lose information**.Consider for example: | feature_new = feature**2
gradient_new = 2*feature[...,None]*gradient # chain rule...
RMI_2 = inf.RenormalizedMutualInformation(feature_new, gradient_new, 2000)
print("Renormalized Mutual Information (x,f(x)): %2.2f" % RMI_2)
p_y, delta_y = inf.produce_P(feature_new)
entropy = inf.Entropy(p_y, delta_y)
fterm = inf.Reg... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
The careful observer will be able to guess how much information we have lost in this case: our feature is centered in zero and we squared it. We lose the sign, and on average the half of the samples have one sign and the half the other sign. One bit of information is lost. The difference is $\log 2$! | deltaRMI = RMI - RMI_2
print("delta RMI %2.3f" %deltaRMI)
print("log 2 = %2.3f" % np.log(2)) | delta RMI 0.672
log 2 = 0.693
| MIT | quick-start.ipynb | XudongWang97/rmi |
Another featureLet's take another linear feature, for example, this time in the other direction | def f(x):
# feature
# shape [N_samples, N_features=1]
return x[:,1][...,None]
def grad_f(x):
# gradient
# shape [N_samples, N_features=1, N_x=2]
grad_f = np.zeros([len(x),1,2])
grad_f[...,1] = 1
return grad_f
def feat_and_grad(x):
return f(x), grad_f(x)
feature = f(x_points)
gradi... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
This feature seems to better describe our input. This is reasonable: it lies closer to the direction of larger fluctuation of the distribution. What is the best linear feature that we can take? | # Let's define a linear feature
def linear(x, th):
""" linear increasing in the direction given by angle th.
Args:
x (array_like): [N_samples, 2] array of samples
th (float): direction of the feature in which it increases
Returns:
feature (array_like): [N_samples, 1] feature
... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
Let's plot the feature with the parameter that gives the largest Renormalized Mutual Information |
feature, gradient = linear(x_points,best_theta)
plt.figure()
plt.title("Feature contours")
plt.xlabel(r"$x_1$")
plt.ylabel(r"$x_2$")
plt.gca().set_aspect('equal')
# Draw the input distribution on the background
samples = np.random.multivariate_normal(mu, sigma, N_samples )
plt.hist2d(*samples.T, bins=100, cmap=plt.... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
This is the same feature that we would get if we considered the first Principal Component of PCA. This is the only case in which this is possible: PCA can only extract linear features, and in particular, since it only takes into account the covariance matrix of the distribution, it can provide the best feature only for... | import rmi.pca
samples = np.random.multivariate_normal(mu, sigma, N_samples )
g_pca = rmi.pca.pca(samples,1)
eigenv = g_pca.w[0]
angle_pca = np.arctan(eigenv[1]/eigenv[0])
feature, gradient = linear(samples,angle_pca)
RMI = inf.RenormalizedMutualInformation(feature, gradient)
print("Renormalized Mutual Information (x,... | best found angle 1.19
pca direction 1.18
| MIT | quick-start.ipynb | XudongWang97/rmi |
We recall that in this very special case, and as long as the proposed feature is only rotated (without changing the scale), the simple maximization of the Feature Entropy would have given the same result.Again, this only holds for linear features, and in particular for those whose gradient vector is not affected by a c... | import rmi.neuralnets as nn
# Define the layout of the neural network
# The cost function is implicit when choosing the model RMIOptimizer
rmi_optimizer = nn.RMIOptimizer(
layers=[
nn.K.layers.Dense(30, activation="relu",input_shape=(2,)),
nn.K.layers.Dense(1)
])
# Compile the network === choose t... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
Calculate the feature on the input points: just apply the object `rmi_net`! | feature = rmi_net(x_points)
plt.figure()
plt.title("Feature contours")
plt.xlabel(r"$x_1$")
plt.ylabel(r"$x_2$")
plt.gca().set_aspect('equal')
# Draw the input distribution on the background
samples = np.random.multivariate_normal(mu, sigma, N_samples )
plt.hist2d(*samples.T, bins=100, cmap=plt.cm.binary)
# Draw th... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
To calculate also the gradient of the feature, one can use the function `get_feature_and_grad` | feature, gradient = rmi_net.get_feature_and_grad(samples)
RMI = inf.RenormalizedMutualInformation(feature, gradient)
print("Renormalized Mutual Information (x,f(x)): %2.2f" % RMI) | Renormalized Mutual Information (x,f(x)): 1.81
| MIT | quick-start.ipynb | XudongWang97/rmi |
Tradeoff between simplicity and compression When optimizing renormalized mutual information to obtain a **meaningful feature** (in the sense of representation learning), one should avoid to employ too powerful networks.A good feature should set a convenient tradeoff between its **"simplicity"** (i.e. number of paramet... | # Let's define a linear feature
def cheating_feature(x):
Feature = x[:, 0]*np.cos(best_theta) + x[:, 1]*np.sin(best_theta)
step_size = 3
step_width = 1/12
step_argument = x[:, 0]*np.cos(best_theta+np.pi/2) + x[:, 1]*np.sin(best_theta+np.pi/2)
Feature +=step_size*np.tanh(step_argument/step_widt... | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
This feature has a larger mutual information than the linear one. It is still increasing in the direction of largest variance of $x$.However, it contains a _jump_ in the orthogonal direction. This jump allows to encode a "bit" of additional information (about the orthogonal coordinate), allowing to unambiguously distin... | # Histogram of the feature
# The continuous value of x encodes one coordinate,
# the two peaks of the distribution provide additional information
# on the second coordinate!
plt.hist(feature,1000)
plt.show() | _____no_output_____ | MIT | quick-start.ipynb | XudongWang97/rmi |
UPDATEThis notebook is no longer being used. Please look at the most recent version, NLSS_V2 found in the same directory. My project looks at the Northernlion Live Super Show, a thrice a week Twitch stream which has been running since 2013. Unlike a video service like Youtube, the live nature of Twitch allows for a mo... | # Every returned Out[] is displayed, not just the last one.
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import nltk
import pandas as pd
import numpy as np | _____no_output_____ | MIT | OldFiles/NLSS.ipynb | AndrewRyan95/Twitch_Sentiment_Analysis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.