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 |
|---|---|---|---|---|---|
10ステップ後の姿勢のばらつき | path = []
for j in range(100):
x = np.array([0,0,0])
u = np.array([0.1,10/180*math.pi]) # 毎回0.1だけ進めて10[deg]向きを変える
for i in range(10):
x = f(x,u)
path.append(x)
fig = plt.figure(i,figsize=(8, 8))
sp = fig.add_subplot(111, aspect='equal')
sp.set_xlim(-1.0,1.0)
sp.set_ylim(-0.5,1.5)
... | _____no_output_____ | MIT | state_equations/with_noise.ipynb | ryuichiueda/probrobo_practice |
Create Spark Session for application | spark = SparkSession.\
builder.\
master("local[*]").\
appName("Demo-app").\
config("spark.serializer", KryoSerializer.getName).\
config("spark.kryo.registrator", SedonaKryoRegistrator.getName) .\
config("spark.jars.packages", "org.apache.sedona:sedona-python-adapter-3.0_2.12:1.1.0-incubating,org... | 21/10/08 19:55:41 WARN UDTRegistration: Cannot register UDT for org.locationtech.jts.geom.Geometry, which is already registered.
21/10/08 19:55:41 WARN UDTRegistration: Cannot register UDT for org.locationtech.jts.index.SpatialIndex, which is already registered.
21/10/08 19:55:41 WARN SimpleFunctionRegistry: The functi... | Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
Geotiff Loader 1. Loader takes as input a path to directory which contains geotiff files or a parth to particular geotiff file2. Loader will read geotiff image in a struct named image which contains multiple fields as shown in the schema below which can be extracted using spark SQL | # Path to directory of geotiff images
DATA_DIR = "./data/raster/"
df = spark.read.format("geotiff").option("dropInvalid",True).load(DATA_DIR)
df.printSchema()
df = df.selectExpr("image.origin as origin","ST_GeomFromWkt(image.wkt) as Geom", "image.height as height", "image.width as width", "image.data as data", "image.... | +--------------------+--------------------+------+-----+--------------------+-----+
| origin| Geom|height|width| data|bands|
+--------------------+--------------------+------+-----+--------------------+-----+
|file:///Users/jia...|POLYGON ((-58.702...| 32| 32|[1081.0, 106... | Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
Extract a particular band from geotiff dataframe using RS_GetBand() | ''' RS_GetBand() will fetch a particular band from given data array which is the concatination of all the bands'''
df = df.selectExpr("Geom","RS_GetBand(data, 1,bands) as Band1","RS_GetBand(data, 2,bands) as Band2","RS_GetBand(data, 3,bands) as Band3", "RS_GetBand(data, 4,bands) as Band4")
df.createOrReplaceTempView("... | +--------------------+--------------------+--------------------+--------------------+--------------------+
| Geom| Band1| Band2| Band3| Band4|
+--------------------+--------------------+--------------------+--------------------+--------------------+... | Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
Map Algebra operations on band values | ''' RS_NormalizedDifference can be used to calculate NDVI for a particular geotiff image since it uses same computational formula as ndvi'''
NomalizedDifference = df.selectExpr("RS_NormalizedDifference(Band1, Band2) as normDiff")
NomalizedDifference.show(5)
''' RS_Mean() can used to calculate mean of piel values in a ... | +--------------------+
| logicalOver|
+--------------------+
|[865.0, 1084.0, 1...|
|[1197.0, 1163.0, ...|
+--------------------+
| Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
Visualising Geotiff Images1. Normalize the bands in range [0-255] if values are greater than 2552. Process image using RS_Base64() which converts in into a base64 string3. Embedd results of RS_Base64() in RS_HTML() to embedd into IPython notebook4. Process results of RS_HTML() as below: | ''' Plotting images as a dataframe using geotiff Dataframe.'''
df = spark.read.format("geotiff").option("dropInvalid",True).load(DATA_DIR)
df = df.selectExpr("image.origin as origin","ST_GeomFromWkt(image.wkt) as Geom", "image.height as height", "image.width as width", "image.data as data", "image.nBands as bands")
d... | _____no_output_____ | Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
User can also create some UDF manually to manipulate Geotiff dataframes | ''' Sample UDF calculates sum of all the values in a band which are greater than 1000.0 '''
def SumOfValues(band):
total = 0.0
for num in band:
if num>1000.0:
total+=1
return total
calculateSum = udf(SumOfValues, DoubleType())
spark.udf.register("RS_Sum", calculateSum)
sumDF = df.... | 21/10/08 19:55:44 WARN SimpleFunctionRegistry: The function rs_maskvalues replaced a previously registered function.
| Apache-2.0 | binder/ApacheSedonaRaster.ipynb | aggunr/incubator-sedona |
Stepper Motors* [How to use a stepper motor with the Raspberry Pi Pico](https://www.youngwonks.com/blog/How-to-use-a-stepper-motor-with-the-Raspberry-Pi-Pico)* [Control 28BYJ-48 Stepper Motor with ULN2003 Driver & Arduino](https://lastminuteengineers.com/28byj48-stepper-motor-arduino-tutorial/) Description of the 27BY... | %serialconnect
from machine import Pin
import time
class Stepper(object):
step_seq = [[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0,... | Found serial ports: /dev/cu.usbmodem14401, /dev/cu.Bluetooth-Incoming-Port
[34mConnecting to --port=/dev/cu.usbmodem14401 --baud=115200 [0m
[34mReady.
[0m.0
| MIT | Raspberry_Pi_Pico/notebooks/C.08-Stepper-Motors.ipynb | jckantor/cbe61622 |
Discussion:* What class methods should we build to support the syringe pump project?* Should we simplify and stick with half-step sequence?* How will be integrate motor operation with UI buttons and other controls? Programmable Input/Ouput (PIO)* MicroPython (https://datasheets.raspberrypi.org/pico/raspberry-pi-pico-p... | %serialconnect
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
from time import sleep
import sys
@asm_pio(set_init=(PIO.OUT_LOW,) * 4)
def prog():
wrap_target()
set(pins, 8) [31] # 8
nop() [31]
nop() [31]
nop() [31]
nop() [31]
nop() [31]
nop() [31]
set(pins, 4) [... | Found serial ports: /dev/cu.usbmodem14201, /dev/cu.Bluetooth-Incoming-Port
[34mConnecting to --port=/dev/cu.usbmodem14201 --baud=115200 [0m
[34mReady.
[0m256
512
256
512
256
512
256
512
256
512
256
512
256
512
256
| MIT | Raspberry_Pi_Pico/notebooks/C.08-Stepper-Motors.ipynb | jckantor/cbe61622 |
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](http... | import subprocess
try:
import geehydro
except ImportError:
print('geehydro package not installed. Installing ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geehydro']) | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Import libraries | import ee
import folium
import geehydro | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. | try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize() | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `... | Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID') | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Add Earth Engine Python script | image = ee.Image('srtm90_v4')
smoothed = image.reduceNeighborhood(**{
'reducer': ee.Reducer.mean(),
'kernel': ee.Kernel.square(3),
})
# vis_params = {'min': 0, 'max': 3000}
# Map.addLayer(image, vis_params, 'SRTM original')
# Map.addLayer(smooth, vis_params, 'SRTM smoothed')
Map.setCenter(-112.40, 42.53, 12)
... | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Display Earth Engine data layers | Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map | _____no_output_____ | MIT | Image/image_smoothing.ipynb | pberezina/earthengine-py-notebooks |
Run Sampling Experiment (Land Surface Temperature) | %%time
start_time = '2010-06-06T00:00:00.000000000' #'2010-06'
end_time = '2010-06-06T00:00:00.000000000'#'2010-08'
num_training = 2000
variables = ['land_surface_temperature']
window_sizes = [3] #, 15] #[3, 5, 7, 9, 11, 13, 15]
save_names = 'test'
sampling_exp = SamplingExp(
variables=variables,
window_size... | Extracting minicubes...
3
No data fitted...extracting datacube
/media/disk/databases/BACI-CABLAB/low_res_data/land_surface_temperature
Variable: land_surface_temperature
Window Size: 3
Initialize data class
Load minicubes
Extract datacube for plots...
/media/disk/databases/BACI-CABLAB/low_res_data/land_surface_temperat... | MIT | notebooks/regression/esdc_application/old/app_sample_3_experiment.ipynb | IPL-UV/sakame |
Run Sampling Experiment (Gross Primary Productivity) Load Results | ## Run Sampling Experiment (Land Surface Temperature) | _____no_output_____ | MIT | notebooks/regression/esdc_application/old/app_sample_3_experiment.ipynb | IPL-UV/sakame |
Self-Driving Car Engineer Nanodegree Deep Learning Project: Build a Traffic Sign Recognition ClassifierIn this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the noteb... | import pickle
import numpy as np
import pandas as pd
import random
from sklearn.utils import shuffle
import tensorflow as tf
from tensorflow.contrib.layers import flatten
import cv2
import glob
import os
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
--- Step 0: Load The Data | # TODO: Fill this in based on where you saved the training and testing data
training_file = "../data/train.p"
validation_file= "../data/valid.p"
testing_file = "../data/test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
w... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
--- Step 1: Dataset Summary & ExplorationThe pickled data is a dictionary with 4 key/value pairs:- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.cs... | ### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = len(X_train)
# TODO: Number of validation examples
n_validation = len(X_valid)
# TODO: Number of testing examples.
n_test = len(X_test)... | Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index... | ### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
index = random.randint(0, len(X_train))
image = X_train[index].squeeze()
plt.figure(figsize=(1,1))
plt.imshow(image)
print(y_train[index]) | 10
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
---- Step 2: Design and Test a Model ArchitectureDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).The LeNet-5 implementation shown in the [classroom](https://cl... | ### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
#Convert to gray
X_train_gry = np.sum(X_train/3, axis=3, keepdims=True)
X_valid_gry = np.sum(X_valid/3, axis=3, keepdims=Tru... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Model Architecture | ### Define your architecture here.
### Feel free to use as many code cells as needed.
def LeNet(x):
#HyperParameters
mu = 0
sigma = 0.1
keep_prob = 0.5
# SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Train, Validate and Test the Model A validation set can be used to assess how well the model is performing. A low accuracy on the training and validationsets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting. | ### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
x = tf.placeholder(tf.float32, (None, 32, ... | INFO:tensorflow:Restoring parameters from ./lenet
Test Accuracy = 0.921
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
--- Step 3: Test a Model on New ImagesTo give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.You may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actu... | ### Load the images and plot them here.
### Feel free to use as many code cells as needed.
#fig, axs = plt.subplots(2,4, figsize=(4, 2))
#fig.subplots_adjust(hspace = .2, wspace=.001)
#axs = axs.ravel()
#../data/Images/traffic*.png
fig, axes = plt.subplots(1, 5, figsize=(18,4))
new_images = []
for i, img in enumerate(... | (32, 32, 1)
(32, 32, 1)
(32, 32, 1)
(32, 32, 1)
(32, 32, 1)
(5, 32, 32, 1)
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Predict the Sign Type for Each Image | ### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
#my_labels = [35, 12, 11, 24, 16, 14, 1, 4]
keep_prob = tf.placeholder(tf.float32)
with ... | INFO:tensorflow:Restoring parameters from ./lenet
Test Accuracy = 0.600
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Analyze Performance | ### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
sess = tf.get_default_session()
prediction = sess.run(logits, ... | INFO:tensorflow:Restoring parameters from ./lenet
[12 18 12 18 3]
| MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Output Top 5 Softmax Probabilities For Each Image Found on the Web For each of the new images, print out the model's softmax probabilities to show the **certainty** of the model's predictions (limit the output to the top 5 probabilities for each image). [`tf.nn.top_k`](https://www.tensorflow.org/versions/r0.12/api_doc... | ### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
print(sess.run(tf.nn.top_k(tf.nn.softmax(prediction), k=5))) | TopKV2(values=array([[ 0.13296957, 0.09634399, 0.08997886, 0.06783284, 0.06598242],
[ 0.13137311, 0.07682533, 0.07135586, 0.06071901, 0.05829126],
[ 0.16518918, 0.12350544, 0.0783048 , 0.07044089, 0.06533803],
[ 0.18929006, 0.11967038, 0.07411727, 0.06745335, 0.04894404],
[ 0... | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Project WriteupOnce you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. > **Note**: Once you have complet... | ### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific we... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | Ansheel9/Traffic-Sign-Classifier |
Advanced Lane Finding ProjectThe goals / steps of this project are the following:* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.* Apply a distortion correction to raw images.* Use color transforms, gradients, etc., to create a thresholded binary image.* Apply a per... | import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
%matplotlib qt
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoi... | _____no_output_____ | MIT | examples/example.ipynb | VamshiK-Kasula/CarND-Advanced-Lane-Lines |
Broadcasting the Value**Numpy arrays differ from normal python list due to their ability to broadcast.** | arr[0:5] = 100 # Broacasts the value 100 to first 5 digits.
arr
# Reset the array
arr = np.arange(0,11)
arr
slice_of_arr = arr[0:6]
slice_of_arr
# To grab everything in the slice
slice_of_arr[:]
# Broadcasting after grabbing everything in the array
slice_of_arr[:] = 99
slice_of_arr
arr
# Notice above how not only s... | _____no_output_____ | BSD-3-Clause | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas |
2D Array/Matrix | arr_2d = np.array([[5,10,15],[20,25,30],[35,40,45]])
arr_2d # REMEMBER If having confusion regarding dimensions of the matrix just call shape.
arr_2d.shape # 3 rows, 3 columns
# Two general formats for grabbing elements from a 2D array or matrix format :
# (i) Double Bracket Format (ii) Single Bracket Format with comm... | _____no_output_____ | BSD-3-Clause | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas |
Conditional Selection | arr = np.arange(1,11)
arr
# Taking the array arr and comapring it using comparison operators to get a full boolean array out of this.
bool_arr = arr > 5
'''
1. Getting the array and using a comparison operator on it will actually return a boolean array.
2. An array with boolean values in response to our condition.
3. N... | _____no_output_____ | BSD-3-Clause | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas |
Exercise1. Create a new 2d array np.arange(50).reshape(5,10).2. Grab any 2sub matrices from the 5x10 chunk. | arr_2d = np.arange(50).reshape(5,10)
arr_2d
# Selecting 11 to 35
arr_2d[1:4,1:6]# Keep in mind it is exclusive for the end value in the start:end format of indexing.
# Selecting 5-49
arr_2d[0:,5:] | _____no_output_____ | BSD-3-Clause | 05. Python for Data Analysis - NumPy/5.19 indexing_selection_np_array.ipynb | shrey-c/DSC-ML-numpy-pandas |
NumPy, Pandas and Matplotlib with ICESat UW Geospatial Data Analysis CEE498/CEWA599 David Shean Objectives1. Solidify basic skills with NumPy, Pandas, and Matplotlib2. Learn basic data manipulation, exploration, and visualizatioin with a relatively small, clean point dataset (65K points)3. Learn a bit more about t... | #Use shorter names (np, pd, plt) instead of full (numpy, pandas, matplotlib.pylot) for convenience
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Magic function to enable interactive plotting (zoom/pan) in Jupyter notebook
#If running locally, this would be `%matplotlib notebook`, but since we'... | _____no_output_____ | MIT | modules/03_NumPy_Pandas_Matplotlib/03_NumPy_Pandas_Matplotlib_ICESat_exercises.ipynb | UW-GDA/gda_course_2021 |
Define relative path to the GLAS data csv from week 01 | glas_fn = '../01_Shell_Github/data/GLAH14_tllz_conus_lulcfilt_demfilt.csv' | _____no_output_____ | MIT | modules/03_NumPy_Pandas_Matplotlib/03_NumPy_Pandas_Matplotlib_ICESat_exercises.ipynb | UW-GDA/gda_course_2021 |
This notebook just defines `bar` | def bar(x):
return "bar" * x | _____no_output_____ | BSD-3-Clause | 001-Jupyter/001-Tutorials/003-IPython-in-Depth/examples/IPython Kernel/nbpackage/nbs/other.ipynb | willirath/jupyter-jsc-notebooks |
Data Preprocessing | # drop the following columns as they are only available in training data
# click_time, clicked, open_time, unsubscribe_time, unsubscribed
training_data.drop(['click_time','clicked', 'open_time', 'unsubscribe_time', 'unsubscribed'], axis=1, inplace=True) | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Missing Values | training_data.isnull().sum()
training_data['mail_category'].fillna(training_data['mail_category'].value_counts().index[0], inplace=True)
training_data['mail_type'].fillna(training_data['mail_type'].value_counts().index[0],inplace=True)
training_data['hacker_timezone'].fillna(training_data['hacker_timezone'].value_count... | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Outliers | training_data.describe().T
min_threshold, max_threshold = training_data.sent_time.quantile([0.001, 0.999])
training_data = training_data[(training_data['sent_time'] > min_threshold) & (training_data['sent_time'] < max_threshold)]
min_threshold, max_threshold = training_data.last_online.quantile([0.001, 0.999])
training... | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Encoding Categorical Attributes | from sklearn.preprocessing import LabelEncoder
encode = LabelEncoder()
# Extract Categorical Attributes
#cat_training_data = training_data.select_dtypes(include=['object']).copy()
# encode the categorical attributes of training_data
training_data = training_data.apply(encode.fit_transform)
# encode the categorical at... | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Seperate the Label Column from training_data | label = training_data['opened']
training_data.drop('opened', inplace=True, axis=1) | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Scaling Numerical Features | from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# extract numerical attributes and scale it to have zero mean and unit variance
train_cols = training_data.select_dtypes(include=['float64', 'int64']).columns
training_data = scaler.fit_transform(training_data.select_dtypes(include=['float64','i... | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Split the training_data into training and validaiton data | from sklearn.model_selection import train_test_split
x_train, x_val, y_train, y_val = train_test_split(training_data, label, test_size = 0.2, random_state=2) | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Models Training Decision Tree | from sklearn import tree
from sklearn import metrics
DT_Classifier = tree.DecisionTreeClassifier(criterion='entropy', random_state=0)
DT_Classifier.fit(x_train, y_train) | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Accuracy and Confusion Matrix | accuracy = metrics.accuracy_score(y_val, DT_Classifier.predict(x_val))
confustion_matrix = metrics.confusion_matrix(y_val, DT_Classifier.predict(x_val))
accuracy
confustion_matrix | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
K-Nearest Neighbour | from sklearn.neighbors import KNeighborsClassifier
KNN_Classifier = KNeighborsClassifier(n_jobs=-1)
KNN_Classifier.fit(x_train, y_train)
accuracy = metrics.accuracy_score(y_val, KNN_Classifier.predict(x_val))
confusion_matrix = metrics.confusion_matrix(y_val, KNN_Classifier.predict(x_val))
accuracy
confusion_matrix | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Prediction on test data | predicted = DT_Classifier.predict(testing_data)
predicted.shape
prediction_df = pd.DataFrame(predicted, columns=['Prediction'])
prediction_df.to_csv('prediction.csv')
import pickle
pkl_filename = "Decision_Tree_model.pkl"
with open(pkl_filename, 'wb') as file:
pickle.dump(DT_Classifier, file) | _____no_output_____ | CC0-1.0 | Source Code.ipynb | ericblanco/fictional-happiness |
Implement Sliding Windows and Fit a PolynomialThis notebook displays how to create a sliding windows on a image using Histogram we did in an earlier notebook.we can use the two highest peaks from our histogram as a starting point for determining where the lane lines are, and then use sliding windows moving upward in t... |
# Assuming you have created a warped binary image called "binary_warped"
# Take a histogram of the bottom half of the image
histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((binary_warped, binary_warped, binary_w... | _____no_output_____ | MIT | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving |
2. Set up windows and window hyper parameters.Our next step is to set a few hyper parameters related to our sliding windows, and set them up to iterate across the binary activations in the image. I have some base hyper parameters below, but don't forget to try out different values in your own implementation to see wha... | # HYPERPARAMETERS
# Choose the number of sliding windows
nwindows = 9
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Set height of windows - based on nwindows above and image shape
window_height = np.int(binary_warped.shape[0]//nwindows)
# I... | _____no_output_____ | MIT | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving |
3. Iterate through number of sliding windows to track curvaturenow that we've set up what the windows look like and have a starting point, we'll want to loop for `nwindows`, with the given window sliding left or right if it finds the mean position of activated pixels within the window to have shifted.Let's approach th... | # Concatenate the arrays of indices (previously was a list of lists of pixels)
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_... | _____no_output_____ | MIT | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving |
5. VisualizeWe will use subplots to visualize the output.Lets get to coding then. | import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import cv2
# Load our image
binary_warped = mpimg.imread('./img/warped-example.jpg')
def find_lane_pixels(binary_warped):
# Take a histogram of the bottom half of the image
histogram = np.sum(binary_warped[binary_warped.shape[... | [ 2.23090058e-04 -3.90812851e-01 4.78139852e+02]
[ 4.19709859e-04 -4.79568379e-01 1.11522544e+03]
| MIT | 04-Advanced-Computer-Vision/02-Implement-Sliding-Windows-and-Fit-a-Polynomial.ipynb | vyasparthm/AutonomousDriving |
Loading Files Alright, let's start with some basics. Before we do anything, we will need to load a snapshot. You can do this using the ```load_sample``` convenience function. yt will autodetect that you want a tipsy snapshot and download it from the yt hub. | import yt | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
We will be looking at a fairly low resolution dataset. >This dataset is available for download at https://yt-project.org/data/TipsyGalaxy.tar.gz (10 MB). | ds = yt.load_sample("TipsyGalaxy") | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
We now have a `TipsyDataset` object called `ds`. Let's see what fields it has. | ds.field_list | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
yt also defines so-called "derived" fields. These fields are functions of the on-disk fields that live in the `field_list`. There is a `derived_field_list` attribute attached to the `Dataset` object - let's take look at the derived fields in this dataset: | ds.derived_field_list | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
All of the field in the `field_list` are arrays containing the values for the associated particles. These haven't been smoothed or gridded in any way. We can grab the array-data for these particles using `ds.all_data()`. For example, let's take a look at a temperature-colored scatterplot of the gas particles in this o... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
ad = ds.all_data()
xcoord = ad["Gas", "Coordinates"][:, 0].v
ycoord = ad["Gas", "Coordinates"][:, 1].v
logT = np.log10(ad["Gas", "Temperature"])
plt.scatter(
xcoord, ycoord, c=logT, s=2 * logT, marker="o", edgecolor="none", vmin=2, vmax=6
)
plt.x... | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
Making Smoothed Images yt will automatically generate smoothed versions of these fields that you can use to plot. Let's make a temperature slice and a density projection. | yt.SlicePlot(ds, "z", ("gas", "density"), width=(40, "kpc"), center="m")
yt.ProjectionPlot(ds, "z", ("gas", "density"), width=(40, "kpc"), center="m") | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
Not only are the values in the tipsy snapshot read and automatically smoothed, the auxiliary files that have physical significance are also smoothed. Let's look at a slice of Iron mass fraction. | yt.SlicePlot(ds, "z", ("gas", "Fe_fraction"), width=(40, "kpc"), center="m") | _____no_output_____ | BSD-3-Clause-Clear | doc/source/cookbook/tipsy_and_yt.ipynb | Kiradorn/yt |
Natural Language Processing, a look at distinguishing subreddit categories by analyzing the text of the comments and posts**Matt Paterson, hello@hiremattpaterson.com**General Assembly Data Science Immersive, July 2020 Abstract**HireMattPaterson.com has been (fictionally) contracted by Virgin Galactic’s marketing team... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import nltk
import lebowski as dude
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Read in the data. In the data_file_creation.ipynb found in this directory, we have already gone to the 'https://api.pushshift.io/reddit/search/' api and pulled subreddit posts and comments from SpaceX, Boeing, BlueOrigin, and VirginGalactic; four specific companies venturing into the outer space exploration business w... | spacex = pd.read_csv('./data/spacex.csv')
boeing = pd.read_csv('./data/boeing.csv')
spacex.head() | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
We have already done a lot of cleaning up, but as we see there are still many NaN values and other meaningless values in our data. We'll create a function to remove these values using mapping in our dataframe. Before we get there, let's convert our target column into a binary selector. | spacex['subreddit'] = spacex['subreddit'].map({'spacex': 1, 'boeing': 0})
boeing['subreddit'] = boeing['subreddit'].map({'spacex': 1, 'boeing': 0}) | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
And drop the null values right off too. | print(f"spacex df has {spacex.isna().sum()} null values not including extraneous words")
print(f"boeing df has {boeing.isna().sum()} null values not including extraneous words") | spacex df has subreddit 0
body 37
permalink 0
dtype: int64 null values not including extraneous words
boeing df has subreddit 0
body 24
permalink 0
dtype: int64 null values not including extraneous words
| CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
we can remove these 61 rows right off | spacex = spacex.dropna()
boeing = boeing.dropna()
spacex.shape
boeing.shape | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Merge into one dataframe | space_wars = pd.concat([spacex, boeing])
space_wars.shape | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Use TF to break up the dataframes into numbers and then drop the unneeded words | tvec = TfidfVectorizer(stop_words = 'english') | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
We will only put the 'body' column in to the count vectorizer | X_list = space_wars.body
nums_df = pd.DataFrame(tvec.fit_transform(X_list).toarray(),
columns=tvec.get_feature_names())
nums_df.head() | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
And with credit to Noelle Brown, let's graph the resulting top words: | # get count of top-occurring words
top_words_tf = {}
for i in nums_df.columns:
top_words_tf[i] = nums_df[i].sum()
# top_words to dataframe sorted by highest occurance
most_freq_tf = pd.DataFrame(sorted(top_words_tf.items(), key = lambda x: x[1], reverse = True))
plt.figure(figsize = (10, 5))
# visualize top... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
We can see that if we remove 'replace_me', 'removed', and 'deleted', then we'll be dealing with a much more useful dataset. For the words dataframe, we can just add these words to our stop_words library. For the numeric dataframe we'll drop them here, as well as a few more. | dropwords = ['replace_me', 'removed', 'deleted', 'https', 'com', 'don', 'www']
nums_df = nums_df.drop(columns=dropwords) | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
And we can re-run the graph above for a better look. | # get count of top-occurring words
top_words_tf = {}
for i in nums_df.columns:
top_words_tf[i] = nums_df[i].sum()
# top_words to dataframe sorted by highest occurance
most_freq_tf = pd.DataFrame(sorted(top_words_tf.items(), key = lambda x: x[1], reverse = True))
plt.figure(figsize = (18, 6))
dude.graph_words... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
If I had more time I'd like to graph the words used most in each company. I can go ahead and try to display which company is more verbose, wordy that is, and which one uses longer words (Credit to Hovanes Gasparian). | nums_df = pd.concat([space_wars['subreddit'], nums_df])
space_wars['word_count'] = space_wars['body'].apply(dude.word_count)
space_wars['post_length'] = space_wars['body'].apply(dude.count_chars)
space_wars[['word_count', 'post_length']].describe().T
space_wars.groupby(['word_count']).size().sort_values(ascending=False... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Trouble in parsing-diseIt appears that I'm having some issues with manipulating this portion of the data. I will clean this up before final pull request. Create test_train_split with word data Find the baseline: | baseline = space_wars.subreddit.value_counts(normalize=True)[1]
all_scores = {}
all_scores['baseline'] = baseline
all_scores['baseline']
X_words = space_wars['body']
y_words = space_wars['subreddit']
X_train_w, X_test_w, y_train_w, y_test_w = train_test_split(X_words,
... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Now it's time to train some models! | # Modify our stopwords list from the nltk.'english'
stopwords = nltk.corpus.stopwords.words('english')
# Above we created a list called dropwords
for i in dropwords:
stopwords.append(i)
param_cv = {
'stop_words' : stopwords,
'ngram_range' : (1, 2),
'analyzer' : 'word',
'max_df' : 0.8,
'min_df' :... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Logistic Regression | lr = LogisticRegression( max_iter = 10_000)
lr.fit(train_data_features, y_train_w)
lr.score(train_data_features, y_train_w)
all_scores['Logistic Regression'] = lr.score(test_data_features, y_test_w)
all_scores['Logistic Regression'] | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
***Using a simple Logistic regression with very little tweaking, a set of stopwords, we created a model that while slightly overfit, is more than 22 points more accurate than the baseline.*** What does the confusion matrix look like? Is 80% accuracy even good?Perhaps I can get some help making a confusion matrix with ... | pipe = Pipeline([
('count_v', CountVectorizer()),
('nb', MultinomialNB())
])
pipe_params = {
'count_v__max_features': [2000, 5000, 9000],
'count_v__stop_words': [stopwords],
'count_v__min_df': [2, 3, 10],
'count_v__max_df': [.9, .8, .7],
'count_v__ngram_range': [(1, 1), (1, 2)]
}
gs = Grid... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
We see that our Naive Bayes model yields an accuracy score just shy of our Logistic Regression model, 79.7%**What does the confusion matrix look like?** | # Get predictions and true/false pos/neg
preds = gs.predict(X_test_w)
tn, fp, fn, tp = confusion_matrix(y_test_w, preds).ravel()
# View confusion matrix
dude.graph_words('black')
plot_confusion_matrix(gs, X_test_w, y_test_w, cmap='Blues', values_format='d');
sensitivity = tp / (tp + fp)
sensitivity
specificity = tn / ... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Naive Bayes using the TFID Vectorizer | pipe_tvec = Pipeline([
('tvec', TfidfVectorizer()),
('nb', MultinomialNB())
])
pipe_params_tvec = {
'tvec__max_features': [2000, 9000],
'tvec__stop_words' : [None, stopwords],
'tvec__ngram_range': [(1, 1), (1, 2)]
}
gs_tvec = GridSearchCV(pipe_tvec, pipe_params_tvec, cv = 5)
%%time
gs_tvec.fit(X_t... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Here, the specificity is 4 points higher than the NB using Count Vectorizer, but the sensitity and overall accuracy are about the same. Random Cut Forest and Extra Trees | pipe_rf = Pipeline([
('count_v', CountVectorizer()),
('rf', RandomForestClassifier()),
])
pipe_ef = Pipeline([
('count_v', CountVectorizer()),
('ef', ExtraTreesClassifier()),
])
pipe_params = {
'count_v__max_features': [2000, 5000, 9000],
'count_v__stop_words': [stopwords],
'count_v__min_d... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Our original Logistic Regression model is still the winner. What does the matchup look like? | score_df = pd.DataFrame([all_scores])
score_df.shape
score_df.head() | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Create a Count Vecotorized datasetSince the below cells have been troublesome, we'll create a dataset using only the count vectorizer and then use that data in the model as we did above. | # Re-establish the subsets using Noelle's starter script again
train_data_features = cntv.fit_transform(X_train_w, y_train_w)
test_data_features = cntv.transform(X_test_w)
pipe_params_tvec = {
'tvec__max_features': [2000, 9000],
'tvec__stop_words' : [None, stopwords],
'tvec__ngram_range': [(1, 1), (1, 2)]
}... | _____no_output_____ | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
Irreconcilable Error:At this time there are still structural issues that are not allowing this last block of code to complete the final model attempts (user error).***In the next few days, prior to publication, this notebook will be revamped and this final cell will execute.*** | %%time
vote = VotingClassifier([
('ada', AdaBoostClassifier(base_estimator=DecisionTreeClassifier())),
('grad_boost', GradientBoostingClassifier()),
('tree', DecisionTreeClassifier()),
('knn_pipe', knn_pipe)
])
params = {
'ada__n_estimators': [50, 51], # since HPO names are common, use dunder fr... | C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:
ValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation... | CC0-1.0 | NLP_subreddits_Spacex_v_Boeing.ipynb | MattPat1981/new_space_race_nlp |
%matplotlib inline
import os
import re
import urllib.request
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import itertools
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pack_padded_se... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises | |
In this notebook you will work with a deep generative language model that maps words from a discrete (bit-vector-valued) latent space. We will use text data (we will work on the character level) in Spanish and pytorch. The first section concerns data manipulation and data loading classes necessary for our implementatio... | url = "https://raw.githubusercontent.com/ryancotterell/sigmorphon2016/master/data/"
train_file = "spanish-task1-train"
val_file = "spanish-task1-dev"
test_file = "spanish-task1-test"
print("Downloading data files...")
if not os.path.isfile(train_file):
urllib.request.urlretrieve(url + train_file, filename=train_fi... | Downloading data files...
Download complete.
| MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
DataIn order to work with text data, we need to transform the text into something that our algorithms can work with. The first step of this process is converting words into word ids. We do this by constructing a vocabulary from the data, assigning a new word id to each new word it encounters. | UNK_TOKEN = "?"
PAD_TOKEN = "_"
SOW_TOKEN = ">"
EOW_TOKEN = "."
def extract_inflected_word(s):
"""
Extracts the inflected words in the SIGMORPHON dataset.
"""
return s.split()[-1]
class Vocabulary:
def __init__(self):
self.idx_to_char = {0: UNK_TOKEN, 1: PAD_TOKEN, 2: SOW_TOKEN, 3: EO... | e 8
é 24
ș 0
| MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
We also need to load the data files into memory. We create a simple class `TextDataset` that stores the data as a list of words: | class TextDataset(Dataset):
"""
A simple class that loads a list of words into memory from a text file,
split by newlines. This does not do any memory optimisation,
so if your dataset is very large, you might want to use an alternative
class.
"""
def __init__(self, tex... | Sample from training data: "compiláramos"
Sample from validation data: "debutara"
Sample from test data: "paginabas"
| MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Now it's time to write a function that converts a word into a list of character ids using the vocabulary we created before. This function is `create_batch` in the code cell below. This function creates a batch from a list of words, and makes sure that each word starts with a start-of-word symbol and ends with an end-of... | def create_batch(words, vocab, device, word_dropout=0.):
"""
Converts a list of words to a padded batch of word ids. Returns
an input batch, an output batch shifted by one, a sequence mask over
the input batch, and a tensor containing the sequence length of each
batch element.
:param words: a li... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
In PyTorch the RNN functions expect inputs to be sorted from long words to shorter ones. Therefore we create a simple wrapper class for the DataLoader class that sorts words from long to short: | class SortingTextDataLoader:
"""
A wrapper for the DataLoader class that sorts a list of words by their
lengths in descending order.
"""
def __init__(self, dataloader):
self.dataloader = dataloader
self.it = iter(dataloader)
def __iter__(self):
return self
... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Model Deterministic language modelIn language modelling, we model a word $x = \langle x_1, \ldots, x_n \rangle$ of length $n = |x|$ as a sequence of categorical draws:\begin{align}X_i|x_{<i} & \sim \text{Cat}(f(x_{<i}; \theta)) & i = 1, \ldots, n \\\end{align}where we use $x_{<i}$ to denote a (possibly empty) prefix ... | def bernoulli_log_probs_from_logits(logits):
"""
Let p be the Bernoulli parameter and q = 1 - p.
This function is a stable computation of p and q from logit = log(p/q).
:param logit: log (p/q)
:return: log_p, log_q
"""
return - F.softplus(-logits), - F.softplus(logits) | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
We start with the implementation of a product of Bernoulli distributions where the parameters are *given* at construction time. That is, for some vector $b_1, \ldots, b_K$ we have\begin{equation} Z_k \sim \text{Bernoulli}(b_k)\end{equation}and thus the joint probability of $z_1, \ldots, z_K$ is given by $\prod_{k=1}... | class ProductOfBernoullis:
"""
This is class models a product of independent Bernoulli distributions.
Each product of Bernoulli is defined by a D-dimensional vector of logits
for each independent Bernoulli variable.
"""
def __init__(self, logits):
"""
:param p: a tensor... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Then we should implement the inference model $Q(z | x, \lambda)$, that is, a module that uses a neural network to map from a data point $x$ to the parameters of a product of Bernoullis.You might want to consult the documentation of * `torch.nn.Embedding`* `torch.nn.LSTM`* `torch.nn.Linear`* and of our own `ProductOfBer... | class InferenceModel(nn.Module):
def __init__(self, vocab_size, embedder, hidden_size,
latent_size, pad_idx, bidirectional=False):
"""
Implement the layers in the inference model.
:param vocab_size: size of the vocabulary of the language
:param embedder: em... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Then we should implement the generative latent factor model. The decoder is a sequence of correlated Categorical draws that condition on a latent factor assignment. We will be parameterising categorical distributions, so you might want to check the documentation of `torch.distributions.categorical.Categorical`. | from torch.distributions import Categorical
class LatentFactorModel(nn.Module):
def __init__(self, vocab_size, emb_size, hidden_size, latent_size,
pad_idx, dropout=0.):
"""
:param vocab_size: size of the vocabulary of the language
:param emb_size: dimensionality of emb... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
The code below is used to assess the model and also investigate what it learned. We implemented it for you, so that you can focus on the VAE part. It's useful however to learn from this example: we do interesting things like computing perplexity and sampling novel words! Evaluation metricsDuring training we'd like to ... | def eval_elbo(model, inference_model, eval_dataset, vocab, device, batch_size=128):
"""
Computes a single sample estimate of the ELBO on a given dataset.
This returns both the average ELBO and the average KL (for inspection).
"""
dl = DataLoader(eval_dataset, batch_size=batch_size)
sorted_dl = S... | tensor(-37.6747, device='cuda:0') tensor(0.5302, device='cuda:0')
| MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
A common metric to evaluate language models is the perplexity per word. The perplexity per word for a dataset is defined as:\begin{align} \text{ppl}(\mathcal{D}|\theta, \lambda) = \exp\left(-\frac{1}{\sum_{k=1}^{|\mathcal D|} n^{(k)}} \sum_{k=1}^{|\mathcal{D}|} \log P(x^{(k)}|\theta, \lambda)\right) \end{align}where... | def eval_perplexity(model, inference_model, eval_dataset, vocab, device,
n_samples, batch_size=128):
"""
Estimates the per-word perplexity using importance sampling with the
given number of samples.
"""
dl = DataLoader(eval_dataset, batch_size=batch_size)
sorted_dl = So... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Lastly, we want to occasionally qualitatively see the performance of the model during training, by letting it reconstruct a given word from the latent space. This gives us an idea of whether the model is using the latent space to encode some semantics about the data. For this we use a deterministic greedy decoding algo... | def greedy_decode(model, z, vocab, max_len=50):
"""
Greedily decodes a word from a given z, by picking the word with
maximum probability at each time step.
"""
# Disable dropout.
model.eval()
# Don't compute gradients.
with torch.no_grad():
batch_size = z.size(0)
... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
TrainingNow it's time to train the model. We use early stopping on the validation perplexity for model selection. | # Define the model hyperparameters.
emb_size = 256
hidden_size = 256
latent_size = 16
bidirectional_encoder = True
free_nats = 0 # 5.
annealing_steps = 0 # 11400
dropout = 0.6
word_dropout = 0 # 0.75
batch_size = 64
learning_rate = 0.001
num_epochs = 20
n_importance_samples = 3 # 50
# Create the training data loader.... | (1) step 0: training ELBO (KL) = -39.02 (0.43) -- KL weight = 1.00 -- validation ELBO (KL) = -38.29 (0.43)
(1) step 100: training ELBO (KL) = -27.68 (1.20) -- KL weight = 1.00 -- validation ELBO (KL) = -23.76 (1.28)
Finished epoch 1
Evaluation epoch 1:
- validation perplexity: 7.88
- validation NLL: 21.97
- validati... | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Let's plot the training and validation statistics: | steps, training_ELBO = list(zip(*train_ELBOs))
_, training_KL = list(zip(*train_KLs))
_, val_ELBO = list(zip(*val_ELBOs))
_, val_KL = list(zip(*val_KLs))
epochs, val_ppl = list(zip(*val_perplexities))
_, val_NLL = list(zip(*val_NLLs))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 5))
# Plot training ELBO and KL
a... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Let's load the best model according to validation perplexity and compute its perplexity on the test data: | # Load the best model from disk.
model = LatentFactorModel(vocab_size=vocab.size(),
emb_size=emb_size,
hidden_size=hidden_size,
latent_size=latent_size,
pad_idx=vocab[PAD_TOKEN],
dropout=dropout)
model.load_state_dict(torch.load(be... | test ELBO (KL) = -25.34 (5.46) -- test perplexity = 9.56 -- test NLL = 24.05
| MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Qualitative analysisLet's have a look at what how our trained model interacts with the learned latent space. First let's greedily decode some samples from the prior to assess the diversity of the model: | # Generate 10 samples from the standard normal prior.
num_prior_samples = 10
pz = ProductOfBernoullis(torch.ones(num_prior_samples, latent_size) * 0.5)
z = pz.sample()
z = z.to(device)
# Use the greedy decoding algorithm to generate words.
predictions = greedy_decode(model, z, vocab)
predictions = batch_to_words(predi... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Let's now have a look how good the model is at reconstructing words from the test dataset using the approximate posterior mean and a couple of samples: | # Pick a random test word.
test_word = test_dataset[np.random.choice(len(test_dataset))]
# Infer q(z|x).
x_in, _, seq_mask, seq_len = create_batch([test_word], vocab, device)
qz = inference_model(x_in, seq_mask, seq_len)
# Decode using the mean.
z_mean = qz.mean()
mean_reconstruction = greedy_decode(model, z_mean, vo... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
We can also qualitatively assess the smoothness of the learned latent space by interpolating between two words in the test set: | # Pick a random test word.
test_word_1 = test_dataset[np.random.choice(len(test_dataset))]
# Infer q(z|x).
x_in, _, seq_mask, seq_len = create_batch([test_word_1], vocab, device)
qz = inference_model(x_in, seq_mask, seq_len)
qz_1 = qz.mean()
# Pick a random second test word.
test_word_2 = test_dataset[np.random.choic... | _____no_output_____ | MIT | LatentFactorModel/LatentFactorModel.ipynb | vitutorial/exercises |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.