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
Load review dataset For this assignment, we will use a subset of the Amazon product review dataset. The subset was chosen to contain similar numbers of positive and negative reviews, as the original dataset consisted primarily of positive reviews.
products = turicreate.SFrame('../data/amazon_baby_subset.sframe/')
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
One column of this dataset is 'sentiment', corresponding to the class label with +1 indicating a review with positive sentiment and -1 indicating one with negative sentiment.
products['sentiment'][1:20]
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Let us quickly explore more of this dataset. The 'name' column indicates the name of the product. Here we list the first 10 products in the dataset. We then count the number of positive and negative reviews.
products.head(10)['name'] print('# of positive reviews =', len(products[products['sentiment'] == 1])) print('# of negative reviews =', len(products[products['sentiment'] == -1]))
# of positive reviews = 26579 # of negative reviews = 26493
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Note:** For this assignment, we eliminated class imbalance by choosing a subset of the data with a similar number of positive and negative reviews. Apply text cleaning on the review dataIn this section, we will perform some simple feature cleaning using **SFrames**. The last assignment used all words in building bag...
important_words = load_important_words() important_words[0:10], len(important_words)
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now, we will perform 2 simple data transformations:1. Remove punctuation using [Python's built-in](https://docs.python.org/2/library/string.html) string functionality.2. Compute word counts (only for **important_words**)We start with *Step 1* which can be done as follows:
import string def remove_punctuation(text): translator = text.maketrans('', '', string.punctuation) return text.translate(translator) products['review_clean'] = products['review'].apply(remove_punctuation)
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now we proceed with *Step 2*. For each word in **important_words**, we compute a count for the number of times the word occurs in the review. We will store this count in a separate column (one for each word). The result of this feature processing is a single column for each word in **important_words** which keeps a cou...
for word in important_words: products[word] = products['review_clean'].apply(lambda s: s.split().count(word)) products.column_names()[0:10], len(products.column_names())
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
The SFrame **products** now contains one column for each of the 193 **important_words**. As an example, the column **perfect** contains a count of the number of times the word **perfect** occurs in each of the reviews.
products['perfect'][0:10], len(products['perfect'])
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now, write some code to compute the number of product reviews that contain the word **perfect**.**Hint**: * First create a column called `contains_perfect` which is set to 1 if the count of the word **perfect** (stored in column **perfect**) is >= 1.* Sum the number of 1s in the column `contains_perfect`.
products['contains_perfect'] = products['perfect'].apply(lambda c: 1 if c >= 1 else 0) sum(products['contains_perfect']) sum(products['great'].apply(lambda c: 1 if c >= 1 else 0)), sum(products['quality'].apply(lambda c: 1 if c >= 1 else 0))
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question**. How many reviews contain the word **perfect**? - cf. above cell. Convert SFrame to NumPy arrayAs you have seen previously, NumPy is a powerful library for doing matrix manipulation. Let us convert our data to matrices and then implement our algorithms with matrices.First, make sure you can perform ...
import numpy as np
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
We now provide you with a function that extracts columns from an SFrame and converts them into a NumPy array. Two arrays are returned: one representing features and another representing class labels. Note that the feature matrix includes an additional column 'intercept' to take account of the intercept term. Let us con...
# Warning: This may take a few minutes... feature_matrix, sentiment = get_numpy_data(products, important_words, 'sentiment')
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Are you running this notebook on an Amazon EC2 t2.micro instance?** (If you are using your own machine, please skip this section)It has been reported that t2.micro instances do not provide sufficient power to complete the conversion in acceptable amount of time. For interest of time, please refrain from running `get_...
feature_matrix.shape, feature_matrix.shape[1] ## == number of features / number of important word + 1 (interept)
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question:** Assuming that the intercept is present, how does the number of features in **feature_matrix** relate to the number of features in the logistic regression model? Let x = [number of features in feature_matrix] and y = [number of features in logistic regression model]. - [ ] y = x - 1 - [x] y = x -...
sentiment
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Estimating conditional probability with link function Recall from lecture that the link function is given by:$$P(y_i = +1 | \mathbf{x}_i,\mathbf{w}) = \frac{1}{1 + \exp(-\mathbf{w}^T h(\mathbf{x}_i))},$$where the feature vector $h(\mathbf{x}_i)$ represents the word counts of **important_words** in the review $\mathbf...
''' produces probablistic estimate for P(y_i = +1 | x_i, w). estimate ranges between 0 and 1. ''' def predict_probability(feature_matrix, coefficients): score = np.dot(feature_matrix, coefficients) ## Take dot product of feature_matrix and coefficients return 1. / (1. + np.exp(-score)) # Compute P(y_i =...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Aside**. How the link function works with matrix algebraSince the word counts are stored as columns in **feature_matrix**, each $i$-th row of the matrix corresponds to the feature vector $h(\mathbf{x}_i)$:$$[\text{feature_matrix}] =\left[\begin{array}{c}h(\mathbf{x}_1)^T \\h(\mathbf{x}_2)^T \\\vdots \\h(\mathbf{x}_N)...
dummy_feature_matrix = np.array([[1., 2., 3.], [1., -1., -1]]) dummy_coefficients = np.array([1., 3., -1.]) correct_scores = np.array([1.*1. + 2.*3. + 3.*(-1.), 1.*1. + (-1.)*3. + (-1.)*(-1.)]) correct_preds = np.array([1. / (1 + np.exp(-correct_scores[0])), 1. / (1 + np.exp(-correct_scores[1]))]) eps = 1e-...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Compute derivative of log likelihood with respect to a single coefficientRecall from lecture:$$\frac{\partial\ell}{\partial w_j} = \sum_{i=1}^N h_j(\mathbf{x}_i)\left(\mathbf{1}[y_i = +1] - P(y_i = +1 | \mathbf{x}_i, \mathbf{w})\right)$$We will now write a function that computes the derivative of log likelihood with r...
def feature_derivative(errors, features): return np.dot(errors, features) # Compute the dot product...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
In the main lecture, our focus was on the likelihood. In the advanced optional video, however, we introduced a transformation of this likelihood---called the log likelihood---that simplifies the derivation of the gradient and is more numerically stable. Due to its numerical stability, we will use the log likelihood i...
def compute_log_likelihood(feature_matrix, sentiment, coefficients): indic = (sentiment == +1) scores = np.dot(feature_matrix, coefficients) logexp = np.log(1. + np.exp(-scores)) # Simple check to prevent overflow mask = np.isinf(logexp) logexp[mask] = -scores[mask] return np.sum((...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Checkpoint**Just to make sure we are on the same page, run the following code block and check that the outputs match.
dummy_feature_matrix = np.array([[1.,2.,3.], [1.,-1.,-1]]) dummy_coefficients = np.array([1., 3., -1.]) dummy_sentiment = np.array([-1, 1]) correct_indicators = np.array( [-1 == +1, 1 == +1]) correct_scores = np.array( [1.*1. + 2.*3. + 3.*(-1.), 1.*1. + (-1.)...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Taking gradient steps Now we are ready to implement our own logistic regression. All we have to do is to write a gradient ascent function that takes gradient steps towards the optimum. Complete the following function to solve the logistic regression model using gradient ascent:
from math import sqrt def logistic_regression(feature_matrix, sentiment, initial_coefficients, step_size, max_iter): coeffs = np.array(initial_coefficients) # make sure it's a numpy array for itr in range(max_iter): # Predict P(y_i = +1|x_i,w) using your predict_probability() function pred...
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now, let us run the logistic regression solver.
coefficients = logistic_regression(feature_matrix, sentiment, initial_coefficients=np.zeros(194), step_size=1e-7, max_iter=301)
iteration 0: log likelihood of observed labels = -36780.91768478 iteration 1: log likelihood of observed labels = -36775.13434712 iteration 2: log likelihood of observed labels = -36769.35713564 iteration 3: log likelihood of observed labels = -36763.58603240 iteration 4: log likelihood of observed labels = -...
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question:** As each iteration of gradient ascent passes, does the log likelihood increase or decrease? - increase Predicting sentiments Recall from lecture that class predictions for a data point $\mathbf{x}$ can be computed from the coefficients $\mathbf{w}$ using the following formula:$$\hat{y}_i = \left\{\b...
# Compute the scores as a dot product between feature_matrix and coefficients. scores = np.dot(feature_matrix, coefficients) len(scores), scores
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now, complete the following code block for **Step 2** to compute the class predictions using the **scores** obtained above:
preds = np.where(scores > 0., 1, -1) len(scores), scores
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question:** How many reviews were predicted to have positive sentiment?
n_pos = np.where(scores > 0., 1, 0).sum() n_neg = np.where(scores > 0., 0, 1).sum() assert n_pos + n_neg == len(scores) n_pos n_pos, n_neg = len(preds[preds == 1]), len(preds[preds == -1]) assert n_pos + n_neg == len(scores) n_pos
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Measuring accuracyWe will now measure the classification accuracy of the model. Recall from the lecture that the classification accuracy can be computed as follows:$$\mbox{accuracy} = \frac{\mbox{ correctly classified data points}}{\mbox{ total data points}}$$Complete the following code block to compute the accuracy o...
np.where(sentiment - preds != 0, 1, 0).sum() n = len(products) num_mistakes = np.where(sentiment - preds != 0, 1, 0).sum() accuracy = (n - num_mistakes) / n print("-----------------------------------------------------") print(f'# Reviews correctly classified = {n - num_mistakes}') print(f'# Reviews incorrectly clas...
----------------------------------------------------- # Reviews correctly classified = 39903 # Reviews incorrectly classified = 13169 # Reviews total = 53072 ----------------------------------------------------- Accuracy = 0.75
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question**: What is the accuracy of the model on predictions made above? (round to 2 digits of accuracy) Which words contribute most to positive & negative sentiments? Recall that in Module 2 assignment, we were able to compute the "**most positive words**". These are words that correspond most strongly with po...
def top_n(words=important_words, coeffs=list(coefficients[1:]), key='positive'): return sorted( [(word, coeff) for word, coeff in zip(words, coeffs)], key=lambda x: x[1], reverse=True if key == 'positive' else False )
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Now, **word_coefficient_tuples** contains a sorted list of (**word**, **coefficient_value**) tuples. The first 10 elements in this list correspond to the words that are most positive. Ten "most positive" wordsNow, we compute the 10 words that have the most positive coefficient values. These words are associated with p...
list(map(lambda t: t[0], top_n()[0:10]))
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
**Quiz Question:** Which word is **NOT** present in the top 10 "most positive" words?- [ ] love- [ ] easy- [ ] great- [ ] perfect- [x] cheap Ten "most negative" wordsNext, we repeat this exercise on the 10 most negative words. That is, we compute the 10 words that have the most negative coefficient values. These word...
list(map(lambda t: t[0], top_n(key='negative')[0:10]))
_____no_output_____
BSD-3-Clause
C03/w02/C03w02_nb_pa1.ipynb
pascal-p/ML_UW_Spec
Demo: MultiContainer feeder exampleThe basic steps to set up an OpenCLSim simulation are:* Import libraries* Initialise simpy environment* Define object classes* Create objects * Create sites * Create vessels * Create activities* Register processes and run simpy---- 0. Import libraries
import datetime, time import simpy import numpy as np import pandas as pd import shapely.geometry import openclsim.core as core import openclsim.model as model import openclsim.plot as plot
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
1. Initialise simpy environment
NR_BARGES = 3 TOTAL_AMOUNT = 100 BARGE_CAPACITY=10 # setup environment simulation_start = 0 my_env = simpy.Environment(initial_time=simulation_start) registry = {}
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
2. Define object classes
# create a Site object based on desired mixin classes Site = type( "Site", ( core.Identifiable, core.Log, core.Locatable, core.HasMultiContainer, core.HasResource, ), {}, ) # create a TransportProcessingResource object based on desired mixin classes TransportProc...
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
3. Create objects 3.1. Create site object(s)
location_from_site = shapely.geometry.Point(4.18055556, 52.18664444) data_from_site = {"env": my_env, "name": "from_site", "geometry": location_from_site, "store_capacity": 4, "nr_resources": 1, "initials": [ {...
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
3.2. Create vessel object(s)
vessels = {} for i in range(NR_BARGES): vessels[f"vessel{i}"] = TransportProcessingResource( env=my_env, name=f"vessel{i}", geometry=location_from_site, store_capacity=4, nr_resources=1, compute_v=lambda x: 10, initials=[ { "id": "...
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
3.3 Create activity/activities
processes = [] for i in range(NR_BARGES): vessel = vessels[f"vessel{i}"] requested_resources={} processes.append( model.WhileActivity( env=my_env, name=f"while {vessel.name}", registry=registry, sub_processes=[ model.SequentialActi...
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
4. Register processes and run simpy
model.register_processes([install_process, *processes]) my_env.run() def extend_id_map(activity, id_map): if hasattr(activity, "sub_processes"): for sub_process in activity.sub_processes: id_map = extend_id_map(sub_process, id_map) return {**id_map, activity.id: activity } activity_map...
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
5. Inspect results 5.1 Inspect logs
plot.get_log_dataframe(installer01, list(activity_map.values())).head()
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
5.2 Visualise gantt charts
acts = [] for proc in processes: acts.extend(proc.sub_processes[0].sub_processes) plot.get_gantt_chart([*install_process.sub_processes, *acts]) plot.get_gantt_chart( [installer01], id_map=id_map )
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
5.3 Visualise step charts
fig = plot.get_step_chart([installer01]) fig = plot.get_step_chart([from_site, *vessels.values(), installer01, to_site])
_____no_output_____
MIT
notebooks/23_Simple_feeder_process_MC.ipynb
VanOord/OpenCLSim
Setting Up Authentication WH Authentication1. get API key by going to https://db.wealthawk.com/docs 2. click authorize in the upper right3. click 'try it out' on `/api/user` and then click excecute4. copy the code in the `curl` box that corrosponds to 'Authorazation'
WH_API_KEY = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjY5NGNmYTAxOTgyMDNlMjgwN2Q4MzRkYmE2MjBlZjczZjI4ZTRlMmMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vd2gtbWFpbi0zMDc3MjIiLCJhdWQiOiJ3aC1tYWluLTMwNzcyMiIsImF1dGhfdGltZSI6MTYzNjIyMzA5MywidXNlcl9pZCI6Ik1zc0FpNzFOcUZkMXkySk5GT2tpaXRrSjRJZjIiLCJzdWIi...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/Model_Examples-checkpoint.ipynb
WealtHawk-prod/WH_Utils
Coresignal AuthenticationJust like above but the whole company shares one API key so I won't be writing in down here UserThis is the model for working with our users i.e. the wealth managers. Creating Users From json / dict
with open('tests/test_data/user.json', 'r') as f: user_dict = json.load(f) user_dict user_example = WH_Utils.User(data_dict = user_dict) user_example.__dict__ user_example
_____no_output_____
Apache-2.0
.ipynb_checkpoints/Model_Examples-checkpoint.ipynb
WealtHawk-prod/WH_Utils
From WH API
user_id = "6091f72d-9b4c-4af9-9b25-e75811a2667e" example_client2 = WH_Utils.User(WH_ID= user_id, auth_header = WH_auth_dict) example_client2
_____no_output_____
Apache-2.0
.ipynb_checkpoints/Model_Examples-checkpoint.ipynb
WealtHawk-prod/WH_Utils
Parameterized machine learning algo: tanh(Z) = (a exp(Z) - b exp(-Z)) / (c exp(Z) + d exp(-Z)) with parameters a,b,c,d s.t. ad - bc = 1 Sequential iteration of difference equation: Z =
import warnings warnings.filterwarnings('ignore') import os import sys import numpy as np import time from IPython.display import display sys.path.insert(1, '../src'); import z_plane as zp import graphic_utility as gu; import itergataters as ig import numcolorpy as ncp def rnd_lambda(s=1): """ random paramete...
One Unescaped Vector: V = 2.26 135.0 degrees 38490 total unescaped points points near V (plane units) 15466 within V/ 1 (2.263) 3964 within V/ 2 (1.131) 1774 within V/ 3 (0.754) 1009 within V/ 4 (0.566) 648 within V/ 5 (0.453) 459 within V/ 6 (0.377) 339 withi...
MIT
fig_notebooks/explore_tanh.ipynb
dlanier/FlyingMachineFractal
Hashtags
from nltk.tokenize import TweetTokenizer import os import pandas as pd import re import sys from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation from IPython.display import clear_output def squeal(text=None): clear_output(wait=True) if not text ...
202101 #coronamaatregelen #coronavirus #corona #avondklok #coronadebat #COVID19 #lockdown #Corona #FVD #coronavaccin #COVID19NL #coronaprotest #Rutte #covid19nl #vaccin #covid19 #avondklokrellen #persconferentie #vaccinatie #Covid19 #coronabeleid #Vaccinatie #rellen #museumplein #avondklokdebat #covid #stopdelockdown #...
Apache-2.0
hashtags.ipynb
puregome/notebooks
Lecture 11, Solution methods for multiobjective optimization Reminder: Mathematical formulation of multiobjective optimization problemsMultiobjective optimization problems are often formulated as$$\begin{align} \\min \quad &\{f_1(x),\ldots,f_k(x)\}\\\text{s.t.} \quad & g_j(x) \geq 0\text{ for all }j=1,\ldots,J\\& h...
#Let us define a Python function which returns the value of this import math def car_problem(c,p,v): # import pdb; pdb.set_trace() return [#Objective function values c,-p, (math.sqrt((p-50.)/50.)+((p-50.)/50.)**2+ 0.3*(10.-c)+0.00001*(v-(1000.+3000.*(p-50.)/150.))**2)*10000. +5000...
Car with 3 l/100km consumption, 50kW and 1000cm^3 engine would cost 26000.0€ Car with 3 l/100km consumption, 100kW and 2000cm^3 engine would cost 46000.0€ Car with 3 l/100km consumption, 100kW and 1000cm^3 engine would cost 146000.0€
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
Normalization of the objectives **In many of the methods, the normalization of the objectives is necessary.**We can normalize the objectives using the nadir and ideal and setting the normalized objective as$$ \tilde f_i = \frac{f_i-z_i^{ideal}}{z_i^{nadir}-z_i^{ideal}}$$ Calculating the ideal **Finding the ideal for ...
#Calculating the ideal from scipy.optimize import minimize import ad def calc_ideal(f): ideal = [0]*3 #Because three objectives solutions = [] #list for storing the actual solutions, which give the ideal bounds = ((3,10),(50,200),(1000,4000)) #Bounds of the problem starting_point = [3,50,1000] for i...
Optimization terminated successfully (Exit mode 0) Current function value: 3.0 Iterations: 1 Function evaluations: 4 Gradient evaluations: 1 Optimization terminated successfully (Exit mode 0) Current function value: -200.0 Iterations: 5 ...
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
Pay-off table method**Finding the nadir value is however, usually much harder.**Usually, the nadir value is estimated using the so-called pay-off table method.The pay-off table method does not guarantee to find the exact nadir for problems with more than two objectives. The method is, however, a generally accepted wa...
for solution in solutions: print(solution)
[3.0, -50.0, 26000.0] [3.0, -200.0, 1033320.5080756888] [10.0, -50.0, 5000.0]
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
Thus, the esimation of the nadir vector is $$(10,-50,1033320.5080756888)$$This is actually the real Nadir vector for this problem. Normalized car problem
#Let us define a Python function which returns the value of this import math def car_problem_normalized(c,p,v): z_ideal = [3.0, -200.0, 5000] z_nadir = [10,-50,1033320.5080756888] z = car_problem(c,p,v) return [(zi-zideali)/(znadiri-zideali) for (zi,zideali,znadiri) in zip(z,z_ideal,z_nadi...
_____no_output_____
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
the zip function in Python
print("Normalized value of the car problem at (3,50,1000) is " +str(car_problem_normalized(3,50,1000))) print("Normalized value of the car problem at (3,125,2500) is " +str(car_problem_normalized(3,125,2500))) print("Normalized value of the car problem at (10,100,1000) is " +str(car_problem_normalized...
Normalized value of the car problem at (3,50,1000) is [0.0, 1.0, 0.020421648537670038] Normalized value of the car problem at (3,125,2500) is [0.0, 0.5, 0.054212133547970276] Normalized value of the car problem at (10,100,1000) is [1.0, 0.6666666666666666, 0.11669513450097163]
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
**So, value 1 now indicates the worst value on the Pareto frontier and value 0 indicates the best values** Let's set the ideal and nadir for later reference:
z_ideal = [3.0, -200.0, 5000] z_nadir = [10.,-50,1033320.5080756888]
_____no_output_____
MIT
Lecture 11, Methods for multiobjective optimization.ipynb
bshavazipour/TIES483-2022
All those moments will be los(s)t in time, like tears in rain.> I am completely operational, and all my circuits are functioning perfectly.- toc: true - badges: true- comments: true- categories: [jupyter]- image: images/posts/2020-12-10-Tears-In-Rain/Tears-In-Rain.jpg
#hide !pip install -Uqq fastbook import fastbook fastbook.setup_book() #hide from fastai.vision.all import * from fastbook import * matplotlib.rc('image', cmap='Greys')
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Under the Hood: Training a Digit Classifier This one is the big one. Now we have made it past the introduction of the course it is time to get under the hood and start implementing some of the functionality for ourselves. I am going to be taking quite thorough notes as I want to make sure I understand everything befor...
path = untar_data(URLs.MNIST_SAMPLE) #hide Path.BASE_PATH = path
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
The have also added the UNIX [ls()](https://en.wikipedia.org/wiki/Ls) function to Python [path](https://docs.python.org/3/library/pathlib.html) to give a handy way to see what is in our directory. Here you can see we have our training and validation directory along with a label.csv file.
path.ls()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Inside each of the training and validation directories we have a folder which contains all of our **3's** and **7's** respectively
(path/'train').ls()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Now we can create a list of the file paths and store them in variables
threes = (path/'train'/'3').ls().sorted() sevens = (path/'train'/'7').ls().sorted() threes
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Let's take a look at what we are working with. By indexing into the above **threes** list we can retrive the first path in the list. Using [PIL](https://pillow.readthedocs.io/en/stable/) the Python Imaging Library, we can display the data at that path.
im3_path = threes[1] im3 = Image.open(im3_path) im3
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
At this point it may not be entirely intuative what image information is. It is just an array of values for 0 to 255 for an 8-bit grayscale image like we have above. By casting into a Numpy array and taking a slice we can se what that might look like.
array(im3)[4:10,4:10]
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
As we have seen earlier in the course the PyTorch tensors have very similar functionality to Numpy arrays, but have the added benefit of being pushed to the GPU, this is a optimization and can be used in replacement of standard Numpy arrays. As a huge fan of Numpy my natural propensity is to use them all the time. But ...
tensor(im3)[4:10,4:10]
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
By loading the tensor into a Pandas Dataframe we are able to see what the pixel values look like by using the .background_gradients method
im3_t = tensor(im3) df = pd.DataFrame(im3_t[4:15,4:22]) df.style.set_properties(**{'font-size':'6pt'}).background_gradient('Greys')
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
![](2020-12-10-Tears-In-Rain/Datatable.jpg) First Try: Pixel Similarity Before we start building our model we should consider if there are feasible alternatives to our problem. Working with Deep Learning is like weilding a very large hammer and every problem can appear to us as a nail. But for small self contained pro...
seven_tensors = [tensor(Image.open(o)) for o in sevens] three_tensors = [tensor(Image.open(o)) for o in threes] len(three_tensors),len(seven_tensors)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
In a similar way to the method above to cast our image to an array or tensor, we can use the fastai `show_image` method to take a tensor and display it as an image, this will be useful for debugging
show_image(three_tensors[1]);
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Our next operation is to normalize the values of the images between 0 and 1, first we stack the images on top of one another using `torch.stack`, convert the integer values in the tensor stack to a float to ensure that values aren't rounded after our division operation, and then we divide the image by 255. By looking ...
stacked_sevens = torch.stack(seven_tensors).float()/255 stacked_threes = torch.stack(three_tensors).float()/255 stacked_threes.shape
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
The length of the tensor.shape is the same as the tensor rank or number of dimensions, we can see that below by using the `ndim` method. This is a fast way of checking that your tensors have the correct rank before moving forward building your model or baseline
len(stacked_threes.shape) stacked_threes.ndim
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Now that we have all of our image tensors stack on top of one another and normalized, we can use the `mean` method to find the average. By passing in the argument 0, we are telling the operation to take the `mean` across the first axis. In this example this is the `mean` of the 6131 images.
mean3 = stacked_threes.mean(0) show_image(mean3); mean7 = stacked_sevens.mean(0) show_image(mean7);
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Now that we have our `mean` images, we can compare one of the images against them to see what the `pixel similarity` is and determine if the image is either a **3** or a **7**
a_3 = stacked_threes[1] show_image(a_3);
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
L1 and L2 norm - Take the mean of the absolute value of differences (absolute value is the function that replaces negative values with positive values). This is called the mean absolute difference or L1 norm- Take the mean of the square of differences (which makes everything positive) and then take the square root (wh...
dist_3_abs = (a_3 - mean3).abs().mean() dist_3_sqr = ((a_3 - mean3)**2).mean().sqrt() dist_3_abs,dist_3_sqr dist_7_abs = (a_3 - mean7).abs().mean() dist_7_sqr = ((a_3 - mean7)**2).mean().sqrt() dist_7_abs,dist_7_sqr
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we can see by using the `l1_loss` and the `mse_loss` methods we are getting the same answers our implementations above
F.l1_loss(a_3.float(),mean7), F.mse_loss(a_3,mean7).sqrt()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Computing Metrics Using Broadcasting At this point we could simply use a loop and iterate through each of the images in the validation set, calculate the `L1` loss for each image and determine whether or not our baseline application determines the number to be a **3** or a **7**, check the prediction against and deter...
valid_3_tens = torch.stack([tensor(Image.open(o)) for o in (path/'valid'/'3').ls()]) valid_3_tens = valid_3_tens.float()/255 valid_7_tens = torch.stack([tensor(Image.open(o)) for o in (path/'valid'/'7').ls()]) valid_7_tens = valid_7_tens.float()/255 valid_3_tens...
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we are going to write our `L1 Norm` in the form of a function, here taking the mean across the rows and columns of the absolute difference of the tow images.
def mnist_distance(a,b): return (a-b).abs().mean((-1,-2)) mnist_distance(a_3, mean3)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
But by using `Broadcasting`, we can instead use our entire tensor stack and compare it against the `mean` image of the **3** all at once. What is happening under the hood is that PyTorch is making a "virtual" copy of the mean image tensor for every image tensor in the validation stack so it can determine the `pixel sim...
valid_3_dist = mnist_distance(valid_3_tens, mean3) valid_3_dist, valid_3_dist.shape
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Now lets create a simple definition to determine if the prediction is a **3** if the result is `False` then we assume that the image is classified as a **7** If the `mnist_distance` measured againt the `mean` **3** is lower than the `mean` **7** then the function will return `True`
def is_3(x): return mnist_distance(x,mean3) < mnist_distance(x,mean7)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here by passing in our test image we can see that it returns `True`, but by casting it to a float we can get a value instead
is_3(a_3), is_3(a_3).float()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Taking advantage of `Broadcasting` we can pass the entire tensor stack to the function and we get back an array of predictions
is_3(valid_3_tens)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Lets check the accuracy of our classification application. We are expecting every image tensor in the `valid_3_tens` tensor to return true and all the image tensors in the `valid_7_tens` tensor to return false. We can convert them to a floating point value and take the `mean` to determine the accuracy
accuracy_3s = is_3(valid_3_tens).float() .mean() accuracy_7s = (1 - is_3(valid_7_tens).float()).mean() accuracy_3s,accuracy_7s,(accuracy_3s+accuracy_7s)/2
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Wow! It looks like our naive `pixel similarity` application gives us a **95%** accuracy on this task! We have only used PyTorch for its power tensor operations in this task and proven that with a simple baseline we can determine a highly accurate classifier. Let's see if making a Deep Learning model we can improve the...
gv(''' init->predict->loss->gradient->step->stop step->predict[label=repeat] ''')
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
![](2020-12-10-Tears-In-Rain/SGD.jpg) To understand `SGD` a little better lets start with a simpler example using this quadratic function:
def f(x): return x**2
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Let's plot what that function looks like:
plot_function(f, 'x', 'x**2')
/opt/conda/envs/fastai/lib/python3.8/site-packages/fastbook/__init__.py:73: UserWarning: Not providing a value for linspace's steps is deprecated and will throw a runtime error in a future release. This warning will appear only once per process. (Triggered internally at /opt/conda/conda-bld/pytorch_1603729096996/work/...
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
The sequence of steps we described earlier starts by picking some random value for a parameter, and calculating the value of the loss:
plot_function(f, 'x', 'x**2') plt.scatter(-1.5, f(-1.5), color='red');
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Now we look to see what would happen if we increased or decreased our parameter by a little bit—the adjustment. This is simply the slope at a particular point: ![](2020-12-10-Tears-In-Rain/Slope.jpg) We can change our weight by a little in the direction of the slope, calculate our loss and adjustment again, and repeat ...
xt = tensor(3.).requires_grad_()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Notice the special method requires_grad_? That's the magical incantation we use to tell PyTorch that we want to calculate gradients with respect to that variable at that value. It is essentially tagging the variable, so PyTorch will remember to keep track of how to compute gradients of the other, direct calculations on...
yt = f(xt) yt
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Calculating the derivative value of our function at this input tensor is simple, we just call the `backward` method.
yt.backward()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
The "backward" here refers to backpropagation, which is the name given to the process of calculating the derivative of each layer. We can now view the gradients by checking the grad attribute of our tensor:
xt.grad
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
If you remember your high school calculus rules, the derivative of x***2 is 2*x, and we have x=3, so the gradients should be 2*3=6, which is what PyTorch calculated for us!Now we'll repeat the preceding steps, but with a vector argument for our function:
xt = tensor([3.,4.,10.]).requires_grad_() xt
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
And we'll add sum to our function so it can take a vector (i.e., a rank-1 tensor), and return a scalar (i.e., a rank-0 tensor):
def f(x): return (x**2).sum() yt = f(xt) yt
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Our gradients are 2*xt, as we'd expect!
yt.backward() xt.grad
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
The gradients only tell us the slope of our function, they don't actually tell us exactly how far to adjust the parameters. But it gives us some idea of how far; if the slope is very large, then that may suggest that we have more adjustments to do, whereas if the slope is very small, that may suggest that we are close ...
w -= gradient(w) * lr
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
If you pick a learning rate that's too low, it can mean having to do a lot of steps ![](2020-12-10-Tears-In-Rain/Small_Step.jpg) But picking a learning rate that's too high is even worse—it can actually result in the loss getting worse ![](2020-12-10-Tears-In-Rain/Large_Step.jpg) If the learning rate is too high, it ma...
time = torch.arange(0,20).float(); time
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we create a quadratic function, a function of the form a*(time***2)+(b*time)+c, and add some noiose to simulate realworld measurments
speed = torch.randn(20)*3 + 0.75*(time-9.5)**2 + 1 plt.scatter(time,speed);
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
We want to distinguish clearly between the function's input (the time when we are measuring the coaster's speed) and its parameters (the values that define which quadratic we're trying). So, let's collect the parameters in one argument and thus separate the input, t, and the parameters, params, in the function's signat...
def f(t, params): a,b,c = params return a*(t**2) + (b*t) + c
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
We need to determine which loss function we would like to use. For continuous data, it's common to use mean squared error:
def mse(preds, targets): return ((preds-targets)**2).mean().sqrt()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 1: Initialize the parameters First thing we want to do is create a tensor for our parameters and to tell PyTorch that this tensor `requires_grad_()`.
params = torch.randn(3).requires_grad_() #hide orig_params = params.clone()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 2: Calculate the predictions Lets pass our time tensor and our params into our function
preds = f(time, params)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we are creating a small matplotlib function to show a comparison between our predictions and our observations
def show_preds(preds, ax=None): if ax is None: ax=plt.subplots()[1] ax.scatter(time, speed) ax.scatter(time, to_np(preds), color='red') ax.set_ylim(-300,100) show_preds(preds)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 3: Calculate the loss Now we can use our `L2` or `RMSE` function to determine our loss
loss = mse(preds, speed) loss
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 4: Calculate the gradients By performing `Back Propogation` with our `backward()` method on the loss, we can calculate the slope of our gradient and which direction the we need to move in to improve our loss
loss.backward() params.grad
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we use a small learning rate and multiply that to our parameter's gradient to make sure we move towards the optimal solution over each iteration
params.grad * 1e-5 params
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 5: Step the weights.
lr = 1e-5 params.data -= lr * params.grad.data params.grad = None
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
**Understanding this bit depends on remembering recent history. To calculate the gradients we call backward on the loss. But this loss was itself calculated by mse, which in turn took preds as an input, which was calculated using f taking as an input params, which was the object on which we originally called required_g...
preds = f(time,params) mse(preds, speed) show_preds(preds)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Here we simply wrap our previous steps into a function - Make a prediction- Calculate the loss- Perform back propogation on the loss, see above for details- Apply the learning rate - Zero our gradients- Return our predictions
def apply_step(params, prn=True): preds = f(time, params) loss = mse(preds, speed) loss.backward() params.data -= lr * params.grad.data params.grad = None if prn: print(loss.item()) return preds
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 6: Repeat the process Now we simply call our `apply_step` function a number of times, as we can see our loss improves each iteration
for i in range(10): apply_step(params) #hide params = orig_params.detach().requires_grad_() _,axs = plt.subplots(1,4,figsize=(12,3)) for ax in axs: show_preds(apply_step(params, False), ax) plt.tight_layout()
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
Step 7: stop Either we can stop after a certain accuracy or simply after a number of iterations Summarizing Gradient Descent
gv(''' init->predict->loss->gradient->step->stop step->predict[label=repeat] ''')
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
![](2020-12-10-Tears-In-Rain/SGD.jpg) - Initialize the weights.- For each image, use these weights to predict whether it appears to be a 3 or a 7.- Based on these predictions, calculate how good the model is (its loss).- Calculate the gradient, which measures for each weight, how changing that weight would change the l...
train_x = torch.cat([stacked_threes, stacked_sevens]).view(-1, 28*28)
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave
We also need a label for each of the images, here we can simply create a tensor by combining an array of 1's of length of the number of **3's** and an array of 0's the length of the number of **7's**. We use the PyTorch function `unsqueeze` to transpose the tensor from a vector with 123396 elements into a tensor with 1...
train_y = tensor([1]*len(threes) + [0]*len(sevens)).unsqueeze(1) train_x.shape,train_y.shape
_____no_output_____
Apache-2.0
_notebooks/2020-12-10-Tears-In-Rain.ipynb
bailey-deep-learning/im_sorry_dave